<?php

namespace App\Components\Claim\Application;

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

class RedressType extends Component {
    use AuthorizesRequests;
    public Claim $claim;

    public ?string $redress_type = null;

    public function mount(Claim $claim) {
        $this->claim = $claim;
        $this->redress_type = $claim->redress_type;
    }

    public function save(HistoryService $service) {
        $this->authorize('claims.edit');
        $data = $this->validate([
            'redress_type' => 'required|in:FIXED,INDIVIDUAL',
        ]);

        $old = $this->claim->redress_type;

        $this->claim->update([
            'redress_type' => $data['redress_type'],
        ]);

        $service->add($this->claim->client, 'Redress type updated.', [
            'claim_id' => $this->claim->id,
            'from' => $old,
            'to' => $data['redress_type'],
        ]);

        $this->dispatch('toast',
            title: 'Saved',
            message: 'Successfully saved redress payment type.',
            type: 'success'
        );
    }

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