<?php

namespace App\Filament\Resources\PanelGrMasterResource\Pages;

use App\Filament\Resources\PanelGrMasterResource;
use App\Models\PanelGrMaster;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Validation\ValidationException;

class CreatePanelGrMaster extends CreateRecord
{
    protected static string $resource = PanelGrMasterResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $exists = PanelGrMaster::where('plant_id', $data['plant_id'])
            ->where('item_id', $data['item_id'])
            ->where('document_number', $data['document_number'])
            ->where('invoice_number', $data['invoice_number'])
            ->where('supplier_number', $data['supplier_number'])
            ->where('inspection_lot_number', $data['inspection_lot_number'])
            ->first();

        if ($exists) {
            $message = 'Duplicate record found. '
                . 'Document Number: ' . $data['document_number']
                . ', Invoice Number: ' . $data['invoice_number']
                . ', Inspection Lot Number: ' . $data['inspection_lot_number'];

            Notification::make()
                ->title('Duplicate Record')
                ->body($message)
                ->danger()
                ->send();

            throw ValidationException::withMessages([
                'document_number' => $message,
            ]);
        }

        return $data;
    }
}
