<?php

namespace App\Components\Claim\Application;

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

class ImpactFactors extends Component {
    public Claim $claim;
    public $has_received_relevant_payment;
    public $has_criminal_conviction;
    public $payment_date;
    public $paying_organisation;
    public $payment_amount;

    public function mount() {
        $details = $this->claim->impactDetail;

        if ($details) {
            $this->has_received_relevant_payment = $details->has_received_relevant_payment;
            $this->has_criminal_conviction = $details->has_criminal_conviction;
            $this->payment_date = $details->payment_date;
            $this->paying_organisation = $details->paying_organisation;
            $this->payment_amount = $details->payment_amount;
        }
    }

    public function saveImpactDetails(HistoryService $history) {
        $this->validate();

        $this->claim->impactDetail()->updateOrCreate(
            ['claim_id' => $this->claim->id],
            [
                'has_received_relevant_payment' => $this->has_received_relevant_payment,
                'has_criminal_conviction' => $this->has_criminal_conviction,
                'payment_date' => $this->payment_date,
                'paying_organisation' => $this->paying_organisation,
                'payment_amount' => $this->payment_amount,
            ]
        );

        $history->add($this->claim->client, 'Impact factors updated.', [
            'claim_id' => $this->claim->id,
            'has_received_relevant_payment' => $this->has_received_relevant_payment,
            'has_criminal_conviction' => $this->has_criminal_conviction,
        ]);

        $this->dispatch('toast', message: 'Impact details saved successfully!', type: 'success');
    }

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

    protected function rules() {
        return [
            'has_received_relevant_payment' => 'required|boolean',
            'has_criminal_conviction' => 'required|boolean',
            'payment_date' => 'nullable|required_if:has_received_relevant_payment,true|date',
            'paying_organisation' => 'nullable|required_if:has_received_relevant_payment,true|string|max:255',
            'payment_amount' => 'nullable|required_if:has_received_relevant_payment,true|string|max:50',
        ];
    }
}
