<?php

namespace App\Filament\Resources\UserResource\Pages;

use App\Filament\Resources\UserResource;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;

class EditUser extends EditRecord
{
    protected static string $resource = UserResource::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(__('User 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(__('User 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();
        }
    }
}
