<?php

namespace App\Filament\Resources\GuardPatrolEntryResource\Pages;

use App\Filament\Resources\GuardPatrolEntryResource;
use App\Models\CheckPointName;
use App\Models\CheckPointTime;
use App\Models\GuardName;
use App\Models\GuardPatrolEntry;
use Filament\Actions;
use Filament\Facades\Filament;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;

class CreateGuardPatrolEntry extends CreateRecord
{
    protected static string $resource = GuardPatrolEntryResource::class;

    public $plantId;
    public $pallet_number;
    public $palletNo;
    public $pendingPallet;
    public $snoCount = 0;

    public $pallet_number_locked = false;

    public $serial_number;
    //protected static string $view = 'filament.resources.pallet-validation-resource.pages.create-pallet-validation';

    // protected $listeners = [
    //     'updateSnoQuantity' => 'handleUpdateSnoQuantity',
    // ];

    // public ?array $data = null;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $guardId = GuardName::where(
            'name',
            Filament::auth()->user()?->name
        )->value('id');

        if (! $guardId) {

            Notification::make()
                ->title('Guard Name Not Matched')
                ->body('Logged-in user name was not found in Guard Name Master.')
                ->danger()
                ->send();
            $this->halt();
        }

        $data['guard_name_id'] = $guardId;

        $checkPoint = CheckPointName::where('plant_id', $data['plant_id'])
            ->where('name', trim($data['check_point_name']))
            ->value('id');

        if (! $checkPoint) {
            Notification::make()
                ->title('Invalid Check Point')
                ->body('The entered check point name does not exist.')
                ->danger()
                ->send();
            $this->halt();
        }

        // $lastScan = GuardPatrolEntry::where('plant_id', $data['plant_id'])
        //     ->where('guard_name_id', $guardId)
        //     ->latest('id')
        //     ->first();

        // if ($lastScan) {

        //     $previousPoint = $lastScan->check_point_name_id;

        //     $route = CheckPointTime::where('plant_id', $data['plant_id'])
        //         ->where('check_point1_id', $previousPoint)
        //         ->where('check_point2_id', $checkPoint->id)
        //         ->first();


        //     if (! $route) {

        //         Notification::make()
        //             ->title('Wrong Check Point Order')
        //             ->body('This checkpoint is not the next allowed point.')
        //             ->danger()
        //             ->send();

        //         $this->halt();
        //     }


        // } else {


        //     // First scan must start from sequence 1

        //     $firstRoute = CheckPointTime::where('plant_id', $data['plant_id'])
        //         ->where('check_point2_id', $checkPoint->id)
        //         ->where('sequence_number', 1)
        //         ->first();


        //     if (! $firstRoute) {

        //         Notification::make()
        //             ->title('Invalid Starting Point')
        //             ->body('Patrol must start from the first checkpoint.')
        //             ->danger()
        //             ->send();

        //         $this->halt();
        //     }

        // }



        $data['check_point_name_id'] = $checkPoint;


        unset($data['check_point_name']);


        return $data;
    }


    public function processCheckPointName()
    {
        // $plantId = $this->form->getState()['plant_id'];

        // $plantId = trim($plantId) ?? null;

        // $pendingPallet = $this->form->getState()['pending_pallet_list'];

        // $palletNumber = trim($this->form->getState()['pallet_number'])?? null;

        // $palletNumber = trim($palletNumber) ?? null;

        // $serialNumber = trim($this->form->getState()['serial_number'])?? null;

        // $serialNumber = trim($serialNumber) ?? null;

        // $operatorName = Filament::auth()->user()?->name;

        // $clickedAt = session('pallet_clicked_time');

        // $clickedBy = session('pallet_created_by');


        // if(!$palletNumber)
        // {
        //     Notification::make()
        //     ->title('Pallet number cannot be empty')
        //     ->danger()
        //     ->send();
        //     $this->form->fill([
        //         'serial_number' => null,
        //         'plant_id' => $plantId,
        //         'pallet_number' => $palletNumber,
        //         'pending_pallet_list' => $pendingPallet,
        //         'Sno_quantity' => 0,
        //         'created_by'    => $operatorName,
        //         'scanned_by'    => $operatorName,
        //     ]);
        //     return;
        // }


        // $count = PalletValidation::where('plant_id', $plantId)
        // ->where('pallet_number', $palletNumber)
        // ->count('pallet_number');


        // if(!$serialNumber)
        // {
        //     Notification::make()
        //     ->title('Serial number cannot be empty')
        //     ->danger()
        //     ->send();
        //     $this->dispatch('loadData', $palletNumber, $plantId);
        //     $this->form->fill([
        //         'serial_number' => null,
        //         'plant_id' => $plantId,
        //         'pallet_number' => $palletNumber,
        //         'pending_pallet_list' => $pendingPallet,
        //         'Sno_quantity' => $count,
        //         'created_by'    => $operatorName,
        //         'scanned_by'    => $operatorName,
        //     ]);
        //     return;
        // }
        // if(strlen($serialNumber) < 13)
        // {
        //     Notification::make()
        //     ->title('Serial number should contain minimum 13 digits.')
        //     ->danger()
        //     ->send();
        //     $this->dispatch('loadData', $palletNumber, $plantId);
        //     $this->form->fill([
        //         'serial_number' => null,
        //         'plant_id' => $plantId,
        //         'pallet_number' => $palletNumber,
        //         'pending_pallet_list' => $pendingPallet,
        //         'Sno_quantity' => $count,
        //         'created_by'    => $operatorName,
        //         'scanned_by'    => $operatorName,
        //     ]);
        //     return;
        // }
        // if (!ctype_alnum($serialNumber))
        // {
        //     Notification::make()
        //     ->title('Serial number must contain alpha-numeric values only.')
        //     ->danger()
        //     ->send();
        //     $this->dispatch('loadData', $palletNumber, $plantId);
        //     $this->form->fill([
        //         'serial_number' => null,
        //         'plant_id' => $plantId,
        //         'pallet_number' => $palletNumber,
        //         'pending_pallet_list' => $pendingPallet,
        //         'Sno_quantity' => $count,
        //         'created_by'    => $operatorName,
        //         'scanned_by'    => $operatorName,
        //     ]);
        //     return;
        // }

        // $existInvoiceSno = LocatorInvoiceValidation::where('serial_number', $serialNumber)
        // ->where('plant_id', $plantId)
        // ->where('scanned_status', '=', 'Scanned')
        // ->first();

        // $invoiceNumber = $existInvoiceSno?->invoice_number;
        // if($existInvoiceSno)
        // {
        //     Notification::make()
        //     ->title("Scanned serial number '{$serialNumber}' already completed the scanning process and exist in invoice number : {$invoiceNumber}.<br>Scan the new serial number to add!")
        //     ->danger()
        //     ->send();
        //     $this->dispatch('loadData', $palletNumber, $plantId);
        //     $this->form->fill([
        //         'serial_number' => null,
        //         'plant_id' => $plantId,
        //         'pallet_number' => $palletNumber,
        //         'pending_pallet_list' => $pendingPallet,
        //         'Sno_quantity' => $count,
        //         'created_by'    => $operatorName,
        //         'scanned_by'    => $operatorName,
        //     ]);
        //     return;
        // }

        // $existingRecord = PalletValidation::where('serial_number', $serialNumber)
        // ->where('plant_id', $plantId)
        // ->first();

        // if ($existingRecord)
        // {

        //     if ($existingRecord && $existingRecord->pallet_number == $palletNumber)
        //     {
        //         Notification::make()
        //             ->title("Scanned serial number '{$serialNumber}' is already exists in pallet number '{$palletNumber}'.<br>Scan the new serial number to proceed.")
        //             ->danger()
        //             ->send();
        //     }
        //     else if ($existingRecord && $existingRecord->pallet_number && $existingRecord->pallet_number != $palletNumber)
        //     {
        //         Notification::make()
        //             ->title("Scanned serial number '{$serialNumber}' already exists in pallet number '{$existingRecord->pallet_number}'.<br>Scan the new serial number to proceed.")
        //             ->danger()
        //             ->send();
        //     }
        //     else if ($existingRecord && $existingRecord->locator_number)
        //     {
        //         Notification::make()
        //             ->title("Scanned serial number '{$serialNumber}' is already exists in locator number '{$existingRecord->locator_number}'.<br>Scan the new serial number to proceed.")
        //             ->danger()
        //             ->send();
        //     }
        //     $this->dispatch('loadData', $palletNumber, $plantId);
        //     $this->form->fill([
        //         'serial_number' => null,
        //         'plant_id' => $plantId,
        //         'pallet_number' => $palletNumber,
        //         'pending_pallet_list' => $pendingPallet,
        //         'Sno_quantity' => $count,
        //         'created_by'    => $operatorName,
        //         'scanned_by'    => $operatorName,
        //     ]);
        //     return;
        // }

        // try
        // {

        //     $existingPallet = PalletValidation::where('plant_id', $plantId)
        //     ->where('pallet_number', $palletNumber)
        //     ->first();

        //     $createdAt = $existingPallet ? $existingPallet->created_at : $clickedAt ?? now();

        //     $createdBy = $existingPallet ? $existingPallet->created_by : $clickedBy ?? $operatorName;

        //     $record = PalletValidation::create([
        //         'plant_id'       => $plantId,
        //         'pallet_number'  => $palletNumber,
        //         'serial_number'  => $serialNumber,
        //         'created_by'     => $createdBy,
        //         'scanned_by'     => $operatorName,
        //         'created_at'     => $createdAt,
        //         'scanned_at'     => now(),
        //         'updated_by'     => $operatorName,
        //     ]);

        //     $count = PalletValidation::where('plant_id', $plantId)
        //     ->where('pallet_number', $palletNumber)
        //     ->count('pallet_number');

        //     if ($record)
        //     {
        //         Notification::make()
        //             ->title("Scanned serial number : '{$serialNumber}' successfully inserted into pallet table!<br>Scan the next new serial number to proceed...")
        //             ->success()
        //             ->send();

        //         $this->snoCount = PalletValidation::where('plant_id', $plantId)
        //             ->where('pallet_number', $palletNumber)
        //             ->count();

        //         $this->form->fill([
        //             'plant_id'      => $plantId,
        //             'pallet_number' => $palletNumber,
        //             'serial_number' => null,
        //             'pending_pallet_list' => $pendingPallet,
        //             'Sno_quantity' => $count,
        //             'created_by'    => $operatorName,
        //             'scanned_by'    => $operatorName,
        //         ]);

        //         $this->dispatch('loadData', $palletNumber, $plantId);
        //     }
        //     else
        //     {
        //         Notification::make()
        //             ->title('Pallet validation not inserted.')
        //             ->danger()
        //             ->send();
        //             $this->dispatch('loadData', $palletNumber, $plantId);
        //             $this->form->fill([
        //                 'plant_id'      => $plantId,
        //                 'pallet_number' => $palletNumber,
        //                 'serial_number' => null,
        //                 'pending_pallet_list' => $pendingPallet,
        //                 'Sno_quantity' => $count,
        //                 'scanned_by'    => $operatorName,
        //             ]);
        //             return;
        //     }
        // }
        // catch (\Exception $e)
        // {
        //     Notification::make()
        //         ->title('Error: Pallet validation not inserted.')
        //         ->body("Something went wrong while inserting serial number : '{$serialNumber}' into pallet table!\nScan the new serial number to proceed...")
        //         ->danger()
        //         ->send();
        //         $this->dispatch('loadData', $palletNumber, $plantId);
        //         $this->form->fill([
        //             'plant_id'      => $plantId,
        //             'pallet_number' => $palletNumber,
        //             'serial_number' => null,
        //             'pending_pallet_list' => $pendingPallet,
        //             'Sno_quantity' => $count,
        //             'created_by'    => $operatorName,
        //             'scanned_by'    => $operatorName,
        //         ]);
        //         return;
        // }
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('create'); // Stay on Create Page after saving
    }
}
