<?php

namespace App\Components\Client;

use App\Models\Client\Client;
use App\Models\OptIn;
use Livewire\Component;

class UpdateContactPreferences extends Component {

    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($optInId) {
        $status = $this->optIns[$optInId] ?? false;

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

            $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
        ]);
    }
}
