<?php

namespace App\Filament\Resources\ProjectCharterResource\Pages;

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

class EditProjectCharter extends EditRecord
{
    protected static string $resource = ProjectCharterResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\ViewAction::make(),
            Actions\DeleteAction::make(),
        ];
    }

    protected function authorizeAccess(): void
    {
        parent::authorizeAccess();

        $record = $this->getRecord();

        if (! $record->canEdit()) {
            Notification::make()
                ->title(__('project_charter.cannot_edit_non_draft'))
                ->danger()
                ->send();

            $this->redirect(ProjectCharterResource::getUrl('view', ['record' => $record]));
        }
    }

    protected function beforeSave(): void
    {
        // Server-side validation for initiative budget limit
        $data = $this->data;
        $record = $this->getRecord();

        if (! isset($data['estimated_cost'])) {
            return; // Skip validation if estimated_cost is missing
        }

        $validation = $record->validateEstimatedCostAgainstInitiative($data['estimated_cost']);

        if (! $validation['success']) {
            \Filament\Notifications\Notification::make()
                ->title(__('project_charter.initiative_cost_exceeded_title'))
                ->body($validation['message'])
                ->danger()
                ->send();

            $this->halt();
        }
    }
}
