<?php

namespace App\Components\Claim;

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

class CreateClaim extends Component {
    use AuthorizesRequests;

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

    public $redress_type = '';
    public $case_number = '';
    public $client;

    public function mount(Client $client) {
        $this->authorize('create', Claim::class);

        $this->client = $client;
    }

    public function createClaim(HistoryService $history): void {
        $this->authorize('create', Claim::class);

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

        $claim = $this->client->claim()->create([
            'redress_type' => $data['redress_type'],
            'case_number'  => $data['case_number'],
            'status_id'    => 1
        ]);

        $history->add($this->client, 'Claim created' . ($data['case_number'] ? ' — case number: "' . $data['case_number'] . '"' : ''), [
            'claim_id'     => $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.create-claim');
    }
}