<?php

namespace App\Components\Claim;

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

class CaseProgression extends Component {
    public Claim $claim;

    /**
     * The tick box items shown on the client overview page. Each defaults to
     * false (unticked) until a case worker marks the step complete.
     */
    public array $progress = [
        'aml_checks' => false,
        'id_certified' => false,
        'bank_statement' => false,
        'supporting_statement' => false,
        'initial_registration' => false,
        'dsars_sent_out' => false,
        'supplementary_statement' => false,
        'submitted' => false,
    ];

    /**
     * Human readable labels, in the order they should be displayed.
     */
    public array $labels = [
        'aml_checks' => 'AML Checks',
        'id_certified' => 'ID Certified',
        'bank_statement' => 'Bank Statement',
        'supporting_statement' => 'Supporting Statement',
        'initial_registration' => 'Initial Registration',
        'dsars_sent_out' => "DSAR's Sent Out",
        'supplementary_statement' => 'Supplementary Statement',
        'submitted' => 'Submitted',
    ];

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

        if ($progression = $claim->caseProgression) {
            foreach (array_keys($this->progress) as $key) {
                $this->progress[$key] = (bool) $progression->{$key};
            }
        }
    }

    public function updatedProgress($value, $key) {
        if (!array_key_exists($key, $this->labels)) {
            return;
        }

        $this->claim->caseProgression()->updateOrCreate([], $this->progress);

        app(HistoryService::class)->addForClaim(
            $this->claim,
            'Case progression "' . $this->labels[$key] . '" marked as ' . ($value ? 'complete' : 'incomplete'),
            [
                'field'    => $key,
                'value'    => (bool) $value,
            ]
        );

        $this->dispatch('toast', message: 'Case progression updated.', type: 'success');
    }

    public function render() {
        return view('components.claim.case-progression');
    }
}
