<?php

namespace App\Components\Claim\Application;

use App\Models\Claim\Claim;
use App\Services\HistoryService;
use Livewire\Component;

class FurtherInformation extends Component {

    public Claim $claim;

    public $aps = false;
    public $confirm_aps = false;
    public $name_in_care = null;
    public $legal_name_change = null;
    public $supporting_documents = null;

    public function mount(): void {
        if ($this->claim->furtherInformation()->exists()) {
            $fi = $this->claim->furtherInformation;
            $this->aps = $fi->apply_aps;
            $this->confirm_aps = $fi->confirm_care_setting;
            $this->name_in_care = $fi->name_in_care;
            $this->legal_name_change = $fi->legal_name_change;
            // Fixed typo: Ensure column name matches the one used in save()
            $this->supporting_documents = $fi->supporting_docs_provision;
        }
    }

    public function save(HistoryService $history) {
        $this->validate([
            'aps' => 'required|boolean',
            'confirm_aps' => 'required|boolean',
            'name_in_care' => 'nullable|string',
            'legal_name_change' => 'nullable|string',
            'supporting_documents' => 'required|in:NA,Help,Provided',
        ]);

        try {
            $this->claim->furtherInformation()->updateOrCreate([
                'claim_id' => $this->claim->id,
            ], [
                'apply_aps' => $this->aps,
                'confirm_care_setting' => $this->confirm_aps,
                'name_in_care' => $this->name_in_care,
                'legal_name_change' => $this->legal_name_change,
                'supporting_docs_provision' => $this->supporting_documents,
            ]);

            $history->add($this->claim->client, 'Further information updated.', [
                'claim_id' => $this->claim->id,
                'apply_aps' => $this->aps,
                'supporting_docs_provision' => $this->supporting_documents,
            ]);

            $this->dispatch('toast', message: 'Further information saved successfully.', type: 'success');

        } catch (\Exception $exception) {
            $this->dispatch('toast', message: $exception->getMessage(), type: 'error');
        }
    }

    public function render() {
        return view('components.claim.application.further-information');
    }
}