<?php

namespace App\Components\WillsCase;

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

class StatusToggle extends Component {
    public WillsCase $willsCase;

    public function mount(WillsCase $willsCase): void {
        $this->willsCase = $willsCase;
    }

    public function open(HistoryService $history): void {
        $this->willsCase->update([
            'is_open'   => true,
            'is_closed' => false,
            'closed_at' => null,
        ]);

        $history->add($this->willsCase, 'Case reopened');

        $this->willsCase = $this->willsCase->fresh();
        $this->dispatch('toast', type: 'success', message: 'Case marked as open.');
    }

    public function close(HistoryService $history): void {
        $this->willsCase->update([
            'is_open'   => false,
            'is_closed' => true,
            'closed_at' => now(),
        ]);

        $history->add($this->willsCase, 'Case closed', [
            'closed_at' => now()->toDateTimeString(),
        ]);

        $this->willsCase = $this->willsCase->fresh();
        $this->dispatch('toast', type: 'success', message: 'Case marked as closed.');
    }

    public function render(): \Illuminate\View\View {
        return view('components.wills-case.status-toggle');
    }
}
