<?php

namespace App\Filament\Resources\SpotRateTransportMasterResource\Pages;

use App\Filament\Resources\SpotRateTransportMasterResource;
use App\Models\SpotRateTransportMaster;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;

class EditSpotRateTransportMaster extends EditRecord
{
    protected static string $resource = SpotRateTransportMasterResource::class;

    protected function beforeSave(): void
    {
        $groupName = $this->data['group_name'] ?? null;
        $userNames = $this->data['user_name'] ?? [];
        $recordId = $this->record->id ?? null;

        foreach ($userNames as $userName) {

            $query = SpotRateTransportMaster::where('group_name', $groupName)
                ->whereJsonContains('user_name', $userName);

            // Exclude current record for update
            if ($recordId) {
                $query->where('id', '!=', $recordId);
            }

            if ($query->exists()) {

                Notification::make()
                    ->title('Duplicate User')
                    ->body("User {$userName} already exists in this group.")
                    ->danger()
                    ->persistent()
                    ->send();

                // Prevent save/update
                $this->halt();
                return;
            }
        }
    }

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