<?php

namespace App\Filament\Resources\ServiceProviderResource\Pages;

use App\Filament\Resources\ServiceProviderResource;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;

class EditServiceProvider extends EditRecord
{
    protected static string $resource = ServiceProviderResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\DeleteAction::make()
                ->before(function (Actions\DeleteAction $action) {
                    $this->record->load('upcomingBookingItems');
                    if ($this->record->upcomingBookingItems->isNotEmpty()) {
                        $lastBookingDate = $this->record->upcomingBookingItems->max('service_date');
                        Notification::make()
                            ->title(__('Provider Deletion Failed'))
                            ->body(__(':name could not be deleted. They have :count upcoming bookings, with the last one on :date.', [
                                'name' => $this->record->name,
                                'count' => $this->record->upcomingBookingItems->count(),
                                'date' => $lastBookingDate,
                            ]))
                            ->danger()
                            ->send();
                        $action->cancel();
                    }
                }),
        ];
    }

    protected function beforeSave(): void
    {
        $this->record->load('upcomingBookingItems');
        if ($this->record->is_active && !$this->data['is_active'] && $this->record->upcomingBookingItems->isNotEmpty()) {
            $lastBookingDate = $this->record->upcomingBookingItems->max('service_date');
            Notification::make()
                ->title(__('Provider Deactivation Failed'))
                ->body(__(':name could not be deactivated. They have :count upcoming bookings, with the last one on :date.', [
                    'name' => $this->record->name,
                    'count' => $this->record->upcomingBookingItems->count(),
                    'date' => $lastBookingDate,
                ]))
                ->danger()
                ->send();
            $this->halt();
        }
    }
}
