<?php

namespace App\Components\Claim;

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

class KeyDatesManager extends Component {
    public Claim $claim;
    public $dates = [];

    public function mount() {
        $this->dates = $this->claim->keyDates()
            ->get()
            ->pluck('pivot.date', 'id')
            ->map(fn($date) => $date ? \Carbon\Carbon::parse($date)->format('Y-m-d') : null)
            ->toArray();
    }

    public function updateDate($dateTypeId, HistoryService $history) {
        $value = $this->dates[$dateTypeId] ?? null;
        $dateType = KeyDate::find($dateTypeId);

        $client = $this->claim->client;

        try {
            if (empty($value)) {
                $this->claim->keyDates()->detach($dateTypeId);
                $history->add($client, 'Key date "' . ($dateType->display_name ?? 'Unknown') . '" cleared', [
                    'claim_id'    => $this->claim->id,
                    'key_date_id' => $dateTypeId,
                ]);
            } else {
                $this->claim->keyDates()->syncWithoutDetaching([
                    $dateTypeId => ['date' => $value]
                ]);

                if($dateTypeId == 23) {
                    $this->claim->keyDates()->syncWithoutDetaching([
                        24 => ['date' => date("Y-m-d", strtotime($value . "+14 day"))]
                    ]);
                }

                $history->add($client, 'Key date "' . ($dateType->display_name ?? 'Unknown') . '" set to ' . $value, [
                    'claim_id'    => $this->claim->id,
                    'key_date_id' => $dateTypeId,
                    'date'        => $value,
                ]);
            }

            $this->dispatch('toast', message: 'Date updated successfully.', type: 'success');
        } catch (\Exception $e) {
            $this->dispatch('toast', message: 'Failed to update date. Please try again.', type: 'error');
        }
    }

    public function render() {
        return view('components.claim.key-dates-manager', ['keyDates' => KeyDate::get()]);
    }
}