<?php

namespace App\Filament\Resources\ProjectCharterResource\Pages;

use App\Filament\Resources\ProjectCharterResource;
use App\Models\ProjectCharter;
use Filament\Resources\Pages\CreateRecord;

class CreateProjectCharter extends CreateRecord
{
    protected static string $resource = ProjectCharterResource::class;

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

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

        $projectCharter = new ProjectCharter;
        $projectCharter->initiative_project_id = $data['initiative_project_id'];

        $validation = $projectCharter->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();
        }
    }
}
