<?php

namespace App\Components\Client;

use App\Models\Client\Client;
use App\Models\OptIn;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class UpdateContactPreferences extends Component {
    use AuthorizesRequests;

    public Client $client;
    public $optIns = [];

    public function mount() {
        $this->optIns = $this->client->optIns()
            ->pluck('opt_ins.id')
            ->mapWithKeys(fn($id) => [$id => true])
            ->toArray();
    }

    public function updateOptIn(HistoryService $history, $optInId) {
        $this->authorize('clients.edit');
        $status = $this->optIns[$optInId] ?? false;
        $optIn = OptIn::find($optInId);

        try {
            if ($status) {
                $this->client->optIns()->syncWithoutDetaching($optInId);
            } else {
                $this->client->optIns()->detach($optInId);
            }

            $history->add($this->client, '"' . ($optIn?->display_name ?? 'Unknown') . '" opt-in ' . ($status ? 'enabled' : 'disabled'), [
                'opt_in_id' => $optInId,
                'opt_in' => $optIn?->display_name,
                'enabled' => $status,
            ]);

            $this->dispatch('toast',
                message: 'Opt-in preferences updated successfully.',
                type: 'success'
            );
        } catch (\Exception $e) {
            $this->dispatch('toast',
                message: 'Failed to update preference. Please try again.',
                type: 'error'
            );
        }
    }


    public function render() {
        $availableOptIns = OptIn::orderBy('display_name')->get();
        return view('components.client.update-contact-preferences', [
            'availableOptIns' => $availableOptIns
        ]);
    }
}
