<?php

namespace App\Components\Claim;

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

class Edit extends Component {
    use AuthorizesRequests;

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

    public Claim $claim;
    public Client $client;
    public $redress_type;
    public $case_number;
    public $case_worker;
    public $case_worker_email;

    public function mount() {
        $this->authorize('edit', $this->client->claim);

        $this->redress_type = $this->client->claim->redress_type;
        $this->case_number = $this->client->claim->case_number;
        $this->case_worker = $this->client->claim->redress_case_worker;
        $this->case_worker_email = $this->client->claim->redress_case_worker_email;
    }

    public function updateClaim(HistoryService $history, AppMilestoneService $milestones): void {
        $this->authorize('edit', $this->client->claim);

        $data = $this->validate([
            'redress_type' => 'required|in:FIXED,INDIVIDUAL',
            'case_number'  => 'nullable|string|max:255',
            'case_worker'  => 'nullable|string|max:255',
            'case_worker_email' => 'nullable|email',
        ]);

        $claim = $this->client->claim;
        $appNumberReceived = blank($claim->case_number)
            && filled($data['case_number'])
            && blank($claim->app_receival_date);

        $claim->update([
            'redress_type' => $data['redress_type'],
            'case_number'  => $data['case_number'],
            'app_receival_date' => $appNumberReceived
                ? today()->toDateString()
                : $claim->app_receival_date,
            'redress_case_worker' => $data['case_worker'],
            'redress_case_worker_email' => $data['case_worker_email']
                ? strtolower(trim($data['case_worker_email']))
                : null,
        ]);

        if ($appNumberReceived) {
            $milestones->recordReceived($claim);
        }

        $history->add($this->client, 'Claim updated — case number: "' . ($data['case_number'] ?: 'N/A') . '"', [
            'claim_id'    => $this->client->claim->id,
            'case_number' => $data['case_number'],
            'redress_type' => $data['redress_type'],
        ]);

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

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