<?php

namespace App\Components\Claim;

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

class Edit extends Component {

    public $redress_types = [
        'FIXED' => 'Fixed Claim',
        'INDIVIDUAL' => 'Individual Claim',
    ];

    public $award_levels = Claim::AWARD_LEVELS;
    public $award_statuses = Claim::AWARD_STATUSES;

    public Claim $claim;
    public Client $client;
    public $redress_type;
    public $case_number;
    public $invoice_number;
    public $award_level;
    public $award_status;

    public function mount() {
        $this->redress_type = $this->client->claim->redress_type;
        $this->case_number = $this->client->claim->case_number;
        $this->invoice_number = $this->client->claim->invoice_number;
        $this->award_level = $this->client->claim->award_level;
        $this->award_status = $this->client->claim->award_status;
    }

    public function updateClaim(HistoryService $history): void {
        $data = $this->validate([
            'redress_type'   => 'required|in:FIXED,INDIVIDUAL',
            'case_number'    => 'nullable|string|max:255',
            'invoice_number' => 'nullable|string|max:255',
            'award_level'    => 'nullable|in:' . implode(',', array_keys(Claim::AWARD_LEVELS)),
            'award_status'   => 'nullable|in:' . implode(',', array_keys(Claim::AWARD_STATUSES)),
        ]);

        $claim = $this->client->claim;
        $before = $claim->only(array_keys($data));

        $claim->update($data);

        $changed = [];
        foreach ($claim->getChanges() as $field => $newValue) {
            if (in_array($field, ['updated_at', 'created_at'])) {
                continue;
            }
            $changed[$field] = ['from' => $before[$field] ?? null, 'to' => $newValue];
        }

        $history->addForClaim($claim, 'Claim updated - case number: "' . ($data['case_number'] ?: 'N/A') . '"', [
            'changed' => $changed,
        ]);

        $this->redirectRoute('clients.show', $this->client);
    }

    public function render() {
        return view('components.claim.edit');
    }
}