<?php

namespace App\Components\Client;

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

class UpdatePreferences extends Component {
    use AuthorizesRequests;
    public Client $client;
    public $prefs = [];

    protected $questions = [
        'diff_format' => 'Would the client wish to receive correspondence in a different format or language?',
        'braille' => 'Would the client wish to receive correspondence in braille (English Only)?',
        'large_print' => 'Would the client wish to receive correspondence in large print?',
        'audio' => 'Would the client wish to receive correspondence in audio?',
        'other_lang' => 'Would the client wish to receive correspondence in another language (please specify)?',
    ];

    public function mount() {
        // Fallback to an empty array if database column is null
        $this->prefs = $this->client->preferences ?? [];
    }

    public function save() {
        $this->authorize('clients.edit');
        // Clean up hidden preferences if the main question is 'No'
        if (($this->prefs['diff_format'] ?? '0') != '1') {
            $this->prefs['braille'] = null;
            $this->prefs['large_print'] = null;
            $this->prefs['audio'] = null;
            $this->prefs['other_lang'] = null;
            $this->prefs['language_required'] = null;
        }

        // Clean up language string if other_lang is 'No'
        if (($this->prefs['other_lang'] ?? '0') != '1') {
            $this->prefs['language_required'] = null;
        }

        $this->client->update(['preferences' => $this->prefs]);
        $this->dispatch('toast', type: 'success', message: 'Preferences updated.');
    }

    public function render() {
        return view('components.client.update-preferences', [
            'questions' => $this->questions
        ]);
    }
}