<?php

namespace App\Components\Claim\Application;

use App\Models\Claim\CareSetting;
use App\Models\Claim\CareSettingStatementHistory;
use App\Models\Client\Client;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class Statements extends Component
{
    use AuthorizesRequests;
    public Client $client;

    /** @var array<int, string> Statement text keyed by care_setting_id */
    public array $statements = [];

    public function mount(Client $client): void
    {
        $this->client = $client;
        $this->loadStatements();
    }

    protected function loadStatements(): void
    {
        if (!$this->client->claim) {
            return;
        }

        foreach ($this->client->claim->careSettings as $cs) {
            $this->statements[$cs->id] = $cs->statement ?? '';
        }
    }

    public function saveStatement(HistoryService $history, int $careSettingId): void
    {
        $this->authorize('claims.edit');
        $cs = CareSetting::findOrFail($careSettingId);

        $newStatement = $this->statements[$careSettingId] ?? '';
        $oldStatement = $cs->statement ?? '';

        if ($newStatement === $oldStatement) {
            $this->dispatch('toast', type: 'info', message: 'No changes to save.');
            return;
        }

        // Record the outgoing version before overwriting
        CareSettingStatementHistory::create([
            'care_setting_id' => $careSettingId,
            'statement'       => $oldStatement,
            'user_id'         => auth()->id(),
        ]);

        $cs->update(['statement' => $newStatement]);

        $history->add($this->client, 'Care setting statement updated for "' . ($cs->institution?->display_name ?? 'Unknown') . '"', [
            'claim_id' => $this->client->claim?->id,
            'care_setting_id' => $careSettingId,
            'institution' => $cs->institution?->display_name,
        ]);

        $this->dispatch('toast', type: 'success', message: 'Statement saved.');
    }

    public function render()
    {
        $careSettings = $this->client->claim
            ? $this->client->claim
                ->careSettings()
                ->with('institution', 'statementHistory.user')
                ->get()
            : collect();

        return view('components.claim.application.statements', [
            'careSettings' => $careSettings,
        ]);
    }
}
