<?php

namespace App\Components\PensionCase;

use App\Models\PensionCase\PensionCase;
use App\Models\PensionCase\PensionCaseInterim;
use App\Services\PensionCaseService;
use Livewire\Component;

class InterimManager extends Component {
    public PensionCase $pensionCase;

    public string $interim_date = '';
    public string $interim_amount = '';
    public string $interim_capped_amount = '';
    public string $net_to_client = '';
    public string $vat_amount = '';
    public string $cpf_fee_gross = '';
    public string $cpf_fee_gross_capped = '';
    public string $cpf_fee_net = '';
    public string $cpf_fee_net_capped = '';

    public bool $showForm = false;

    protected function rules(): array {
        return [
            'interim_date' => 'nullable|date',
            'interim_amount' => 'nullable|numeric|min:0',
            'interim_capped_amount' => 'nullable|numeric|min:0',
            'net_to_client' => 'nullable|numeric',
            'vat_amount' => 'nullable|numeric|min:0',
            'cpf_fee_gross' => 'nullable|numeric|min:0',
            'cpf_fee_gross_capped' => 'nullable|numeric|min:0',
            'cpf_fee_net' => 'nullable|numeric',
            'cpf_fee_net_capped' => 'nullable|numeric',
        ];
    }

    public function add(PensionCaseService $service): void {
        $this->validate();

        $data = array_map(fn($v) => $v === '' ? null : $v, [
            'interim_date' => $this->interim_date,
            'interim_amount' => $this->interim_amount,
            'interim_capped_amount' => $this->interim_capped_amount,
            'net_to_client' => $this->net_to_client,
            'vat_amount' => $this->vat_amount,
            'cpf_fee_gross' => $this->cpf_fee_gross,
            'cpf_fee_gross_capped' => $this->cpf_fee_gross_capped,
            'cpf_fee_net' => $this->cpf_fee_net,
            'cpf_fee_net_capped' => $this->cpf_fee_net_capped,
        ]);

        $service->addInterim($this->pensionCase, $data);

        $this->reset([
            'interim_date', 'interim_amount', 'interim_capped_amount', 'net_to_client',
            'vat_amount', 'cpf_fee_gross', 'cpf_fee_gross_capped', 'cpf_fee_net', 'cpf_fee_net_capped',
        ]);
        $this->showForm = false;

        $this->dispatch('toast', title: 'Interim added', type: 'success');
    }

    public function delete(int $id, PensionCaseService $service): void {
        $interim = PensionCaseInterim::findOrFail($id);
        $service->deleteInterim($interim);
        $this->dispatch('toast', title: 'Interim deleted', type: 'success');
    }

    public function render() {
        $interims = $this->pensionCase->interims()->get();
        return view('components.pension-case.interim-manager', compact('interims'));
    }
}
