<?php

namespace App\Filament\Pages;

use App\Models\Locator;
use App\Models\LocatorInvoiceValidation;
use App\Models\PalletValidation;
use App\Models\Plant;
use Barryvdh\DomPDF\Facade\Pdf;
use Filament\Facades\Filament;
use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Pages\Page;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Form;
use Filament\Forms\Components\Actions;
use Filament\Forms\Components\ViewField;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Mpdf\Mpdf;

class LocatorValidation extends Page implements HasForms
{
    protected static ?string $navigationIcon = 'heroicon-o-document-text';

    protected static string $view = 'filament.pages.locator-validation';

    protected static ?string $navigationGroup = 'Export Dispatch';

    protected static ?int $navigationSort = 2;

    use InteractsWithForms;

    public $pId, $palletNo, $serialNo;

    public bool $disableSerialNo = false;
    public bool $disablePalletNo = false;

    public $locatorNumber;
    public $state = [];

    public $plantId;

    public $scanLocator;

    public $locators;

    public array $filters = [];

    public function mount()
    {
        $this->form->fill([
            'plant_id'=>$this->plantId,
            'pallet_quantity' => 0,
        ]);
    }

    public function form(Form $form): Form
    {
        return $form
            ->statePath('filters')
            ->schema([
                Section::make('')
                    ->schema([
                        Select::make('plant_id')
                            ->label('Plant')
                            ->reactive()
                            //->options(Plant::pluck('name', 'id'))
                            ->options(function (callable $get) {
                                $userHas = Filament::auth()->user()->plant_id;
                                return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                            })
                            ->required(),
                        TextInput::make('scan_pallet_no')
                            ->label('Scan Pallet No')
                            ->minLength(10)
                            ->reactive()
                            // ->readonly(fn () => $this->disablePalletNo)
                            ->readOnly(fn (callable $get) => !$get('plant_id') || !empty($get('scan_serial_no')) || !empty($get('scan_locator_no')))
                            ->extraAttributes([
                                'wire:keydown.enter' => 'processPalletNo($event.target.value)',
                            ]),
                        TextInput::make('scan_serial_no')
                            ->label('Scan Serial No')
                            ->minLength(9)
                            ->reactive()
                            // ->readOnly(fn () => $this->disableSerialNo)
                            ->readOnly(fn (callable $get) => !$get('plant_id') || !empty($get('scan_pallet_no')) || !empty($get('scan_locator_no')))
                            ->extraAttributes([
                                'wire:keydown.enter' => 'processSerialNo($event.target.value)',
                            ]),
                        TextInput::make('scan_locator_no')
                            ->label('Scan Locator No')
                            ->minLength(7)
                            ->reactive()
                            ->readOnly(fn (callable $get) => !$get('plant_id') || (!$get('scan_pallet_no') && !$get('scan_serial_no')))
                            ->extraAttributes([
                                'id' => 'scan_locator_no',
                                'wire:keydown.enter' => 'processLocatorNo($event.target.value)',
                            ]),
                        TextInput::make('pallet_quantity')
                            ->label('Pallet Quantity')
                            ->reactive()
                            ->default('0')
                            ->readOnly(),
                    ])
                    ->columns(5)
            ]);
    }

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

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

        $palletNo= $this->form->getState()['scan_pallet_no'];

        $palletNo = trim($palletNo) ?? null;

        $serialNo = $this->form->getState()['scan_serial_no'] ?? null;

        $serialNo = trim($serialNo) ?? null;

        $scanLocator = $this->form->getState()['scan_locator_no'];

        $scanLocator = trim($scanLocator) ?? null;

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

        if ($serialNo && $scanLocator)
        {
            return;
        }

        if ($palletNo == null || $palletNo == '')
        {
            Notification::make()
                ->title("Pallet number can't be empty!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
            ([
                'plant_id'      => $plantId,
                'scan_serial_no' => null,
                'scan_pallet_no' => null,
                'scan_locator_no' => null,
                'pallet_quantity' => 0,
                'created_by'    => $operatorName,
                'scanned_by'    => $operatorName,
            ]);
            return;
        }
        else if (strlen($palletNo) < 10)
        {
            Notification::make()
                ->title("Pallet number '$palletNo' must be at least 10 digits.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
            return;
        }

        $Palletexists = PalletValidation::where('pallet_number', $palletNo)
        ->where('plant_id',  $plantId)->first();
        if(!$Palletexists)
        {
            Notification::make()
                ->title("Pallet number '$palletNo' does not found in pallet table.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
            ([
                'plant_id'      => $plantId,
                'scan_serial_no' => null,
                'scan_pallet_no' => null,
                'scan_locator_no' => null,
                'pallet_quantity' => 0,
                'created_by'    => $operatorName,
                'scanned_by'    => $operatorName,
            ]);
             return;
        }

        $locators = PalletValidation::where('plant_id', $plantId)
        ->where('pallet_number', $palletNo)
        ->get();

        $query  = PalletValidation::where('plant_id', $plantId)
        ->where('pallet_number', $palletNo);

        $palletRow = PalletValidation::where('plant_id', $plantId)
        ->where('pallet_number', $palletNo)
        ->first();

        $locatorNumber = $palletRow->locator_number;

        // $allRows = PalletValidation::where('plant_id', $plantId)
        // ->where(function ($query) use ($palletNo, $locatorNumber) {
        //     $query->where('pallet_number', $palletNo)
        //         ->orWhere('locator_number', $locatorNumber);
        // })
        // ->get();

        // $count = $allRows
        // ->filter(function ($row) {
        //     return !empty($row->pallet_number);
        // })
        // ->unique('pallet_number')
        // ->count();

        // $hasAnyLocator = $allRows->contains(function ($row)
        // {
        //     return !empty($row->locator_number);
        // });
        // if (!$hasAnyLocator)
        // {
        //     $count = 0;
        // }
        $count = PalletValidation::where('plant_id', $plantId)
        ->where('locator_number', $locatorNumber)
        ->count('locator_number');

        $pallets = $query->first();

        if ($pallets)
        {
            $this->locatorNumber = $pallets->locator_number;
        }
        else
        {
            $this->locatorNumber = '';
        }

        $allCompleted = $locators->every(function ($pallet)
        {
            return $pallet->pallet_status == 'Completed';
        });

        $notAlreadyCompleted = PalletValidation::where('plant_id', $plantId)
            ->where('pallet_number', $palletNo)
            ->whereNull('pallet_status')
            ->orWhere('pallet_status', '=','')
            // ->where('locator_number', $this->scanLocator)
            ->first();

        if($notAlreadyCompleted)
        {
            Notification::make()
                ->title("Pallet number '{$palletNo}' does not completed the master packing.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
            ([
                'plant_id'      => $plantId,
                'scan_serial_no' => null,
                'scan_pallet_no' => null,
                'scan_locator_no' => null,
                'pallet_quantity' => 0,
                'created_by'    => $operatorName,
                'scanned_by'    => $operatorName,
            ]);
            return;
        }

        if ($allCompleted && $locators->count() > 0) {
            $this->disableSerialNo = true;
            $this->disablePalletNo = true;
            $this->dispatch('focus-scan-locator-no');
            // $this->form->fill([
            //     'plant_id'  => $plantId,
            //     'scan_pallet_no'  => $palletNo,
            //     'pallet_quantity'  => $count,
            //     'scan_locator_no' => $locatorNumber,
            // ]);

             $this->form->fill([
                'plant_id'      => $plantId,
                'scan_serial_no' => null,
                'scan_pallet_no' => $palletNo,
                'scan_locator_no' => $locatorNumber,
                'pallet_quantity' => $count,
                'created_by'    => $operatorName,
                'scanned_by'    => $operatorName,
            ]);

            if ($this->locatorNumber)
            {
                Notification::make()
                    ->title("Press 'Remove Pallet' button to remove Pallet number : '$palletNo' from Locator number : '$locatorNumber'..!")
                    ->info()
                    ->duration(2000)
                    ->send();
            }

            $this->dispatch('loadData' ,$palletNo,$locatorNumber,$plantId);
        }
    }

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

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

        $this->plantId = $plantId;

        $palletNo = $this->form->getState()['scan_pallet_no'];

        $scanLocator = $this->form->getState()['scan_locator_no'];

        $this->disablePalletNo = true;

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

        if ($palletNo && $scanLocator)
        {
            return;
        }
        else if ($palletNo)
        {
            return;
        }

        if ($serialNo == null || $serialNo == '')
        {
            Notification::make()
                ->title("Serial number can't be empty!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
            return;
        }
        else if (strlen($serialNo) < 9 || strlen($serialNo) > 20)
        {
            Notification::make()
                ->title("Serial number should contain minimum 9 digits and maximum 20 digits.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
            return;
        }
        else if (!ctype_alnum($serialNo))
        {
            Notification::make()
                ->title("Serial number '$serialNo' must contain alpha-numeric values only.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
            return;
        }

        $invoicesnoexists = LocatorInvoiceValidation::where('plant_id', $plantId)
        ->where('serial_number', $serialNo)
        ->where('scanned_status', '=','Scanned')
        ->first();

        $invoiceNo = $invoicesnoexists?->invoice_number;

        if ($invoicesnoexists)
        {
            Notification::make()
                ->title("Serial number '$serialNo' already exists in invoice number '$invoiceNo' and completed the scanning process..!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
            ([
                'plant_id'      => $plantId,
                'scan_serial_no' => null,
                'scan_pallet_no' => null,
                'scan_locator_no' => null,
                'pallet_quantity' => 0,
                'created_by'    => $operatorName,
                'scanned_by'    => $operatorName,
            ]);
            return;
        }

        $existingRecord = PalletValidation::where('plant_id', $plantId)
        ->where('serial_number', $serialNo)
        ->where(function ($query) {
            $query->where('pallet_number', '!=', '')
                ->whereNotNull('pallet_number');
        })
        ->first();

        $existingLocator = PalletValidation::where('plant_id', $plantId)
        ->where('serial_number', $serialNo)
        ->first();

        $palletnumber = $existingRecord?->pallet_number;

        $locatorNo = $existingLocator?->locator_number;

        if ($existingRecord)
        {
            Notification::make()
                ->title("Scanned serial number '$serialNo' already exist in pallet number '$palletnumber'!<br>Scan the valid new serial number to proceed...")
                ->danger()
                ->duration(5000)
                ->send();

            // $this->form->fill([
            //     'plant_id'      => $plantId,
            //     'scan_serial_no' => null,
            //     'created_by'    => $operatorName,
            //     'scanned_by'    => $operatorName,
            // ]);

            $this->form->fill
            ([
                'plant_id'      => $plantId,
                'scan_serial_no' => null,
                'scan_pallet_no' => null,
                'scan_locator_no' => null,
                'pallet_quantity' => 0,
                'created_by'    => $operatorName,
                'scanned_by'    => $operatorName,
            ]);

            $this->dispatch('loadLocator' ,'',$plantId);

            return;
        }
        else
        {
            $this->disableSerialNo = true;

            if ($locatorNo) {
                Notification::make()
                    ->title("Press 'Remove Serial Number' button to remove Serial number : '$serialNo' from Locator number : '$locatorNo'..!")
                    ->info()
                    ->duration(2000)
                    ->send();
            }

            $count = PalletValidation::where('plant_id', $plantId)
            ->where('locator_number', $locatorNo)
            ->count('locator_number');

            $this->form->fill([
                'plant_id'      => $plantId,
                'scan_serial_no' => $serialNo,
                'scan_pallet_no' => null,
                'scan_locator_no' => $locatorNo,
                'pallet_quantity' => $count,
                'created_by'    => $operatorName,
                'scanned_by'    => $operatorName,
            ]);


            $this->dispatch('focus-scan-locator-no');

            $this->dispatch('loadserialNo' ,$serialNo,$plantId);

        }
    }

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

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

        $this->plantId = $plantId;

        $palletNo= $this->form->getState()['scan_pallet_no'];

        $palletNo = trim($palletNo) ?? null;

        $serialNo = $this->form->getState()['scan_serial_no'] ?? null;

        $serialNo = trim($serialNo) ?? null;

        $scanLocator = $this->form->getState()['scan_locator_no'];

        $scanLocator = trim($scanLocator) ?? null;

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

        $this->locators = PalletValidation::where('plant_id', $plantId)->where('locator_number', '11111')->get();

        if (!$palletNo && !$serialNo)
        {
            return;
        }

        if ($scanLocator == null || $scanLocator == '')
        {
            Notification::make()
                ->title("Locator number can't be empty!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => $serialNo,
                    'scan_pallet_no' => $palletNo,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
            return;
        }
        else if (strlen($scanLocator) < 7)
        {
            Notification::make()
                ->title("Locator number '$scanLocator' must be at least 7 digits.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => $serialNo,
                    'scan_pallet_no' => $palletNo,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
            return;
        }

        $exists = Locator::where('plant_id', $plantId)
        ->where('locator_number', $scanLocator)
        ->first();

        if(!$exists)
        {
            Notification::make()
                ->title("Locator number '{$scanLocator}' does not exist in the master.")
                ->danger()
                ->duration(5000)
                ->send();

            // $this->form->fill([
            //     'plant_id'      => $plantId,
            //     'scan_serial_no' => null,
            //     'scan_pallet_no' => null,
            //     'pallet_quantity' => 0,
            // ]);

            $this->form->fill
            ([
                'plant_id'      => $plantId,
                'scan_serial_no' => $serialNo,
                'scan_pallet_no' => $palletNo,
                'scan_locator_no' => null,
                'pallet_quantity' => 0,
                'created_by'    => $operatorName,
                'scanned_by'    => $operatorName,
            ]);

            $this->dispatch('loadLocator' ,'',$plantId);
            return;
        }

        $locator = Locator::where('locator_number', $scanLocator)
        ->where('plant_id', $plantId)
        ->first();

        if ($locator->locator_quantity >= 2) { // Use >= for simplicity
            Notification::make()
                ->title("No space available for locator number '{$scanLocator}'.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);

            $this->form->fill
            ([
                'plant_id'      => $plantId,
                'scan_serial_no' => $serialNo,
                'scan_pallet_no' => $palletNo,
                'scan_locator_no' => null,
                'pallet_quantity' => 0,
                'created_by'    => $operatorName,
                'scanned_by'    => $operatorName,
            ]);
            return;
        }

        $this->locators = PalletValidation::where('plant_id', $plantId)
        ->where('locator_number', $scanLocator)
        ->get();

        if ($palletNo)
        {
            if (strlen($palletNo) < 10)
            {
                Notification::make()
                    ->title("Pallet number '$palletNo' must be at least 10 digits.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                    ([
                        'plant_id'      => $plantId,
                        'scan_serial_no' => null,
                        'scan_pallet_no' => null,
                        'scan_locator_no' => null,
                        'pallet_quantity' => 0,
                        'created_by'    => $operatorName,
                        'scanned_by'    => $operatorName,
                    ]);
                return;
            }

            $notAlreadyCompleted = PalletValidation::where('plant_id', $plantId)
                ->where('pallet_number', $palletNo)
                ->whereNull('pallet_status')
                ->orWhere('pallet_status', '=','')
                // ->where('locator_number', $this->scanLocator)
                ->first();

            if($notAlreadyCompleted)
            {
                Notification::make()
                    ->title("Pallet number '{$palletNo}' does not completed the master packing.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $locatorExist = PalletValidation::where('pallet_number', $palletNo)
                ->where('plant_id', $plantId)
                ->first();

            if ($locatorExist && $locatorExist->locator_number && $locatorExist->locator_number != $scanLocator)
            {
                Notification::make()
                    ->title("Pallet number '$palletNo' is already assigned to locator number '{$locatorExist->locator_number}'.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => $palletNo,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);

                return;
            }

            if ($locatorExist && $locatorExist->locator_number == $scanLocator)
            {
                Notification::make()
                    ->title("Press 'Remove Pallet' button to remove Pallet number : '$palletNo' from Locator number : '$scanLocator'..!")
                    ->info()
                    ->duration(2000)
                    ->send();
            }
            else
            {
                Notification::make()
                    ->title("Press 'Add Pallet' button to add Pallet number : '$palletNo' into Locator number : '$scanLocator'..!")
                    ->info()
                    ->duration(2000)
                    ->send();
            }
        }
        else
        {
            if ($serialNo == '' || $serialNo == null) {
                Notification::make()
                    ->title("Serial number is required to add or remove when pallet number is empty.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                    ([
                        'plant_id'      => $plantId,
                        'scan_serial_no' => $serialNo,
                        'scan_pallet_no' => null,
                        'scan_locator_no' => $scanLocator,
                        'pallet_quantity' => 0,
                        'created_by'    => $operatorName,
                        'scanned_by'    => $operatorName,
                    ]);
                return;
            }
            else if (strlen($serialNo) < 9 || strlen($serialNo) > 20)
            {
                Notification::make()
                    ->title("Serial number should contain minimum 9 digits and maximum 20 digits.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                    ([
                        'plant_id'      => $plantId,
                        'scan_serial_no' => null,
                        'scan_pallet_no' => null,
                        'scan_locator_no' => null,
                        'pallet_quantity' => 0,
                        'created_by'    => $operatorName,
                        'scanned_by'    => $operatorName,
                    ]);
                return;
            }
            else if (!ctype_alnum($serialNo))
            {
                Notification::make()
                    ->title("Serial number '$serialNo' must contain alpha-numeric values only.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                    ([
                        'plant_id'      => $plantId,
                        'scan_serial_no' => null,
                        'scan_pallet_no' => null,
                        'scan_locator_no' => null,
                        'pallet_quantity' => 0,
                        'created_by'    => $operatorName,
                        'scanned_by'    => $operatorName,
                    ]);
                return;
            }

            $invoicesnoexists = LocatorInvoiceValidation::where('plant_id', $plantId)
                ->where('serial_number', $serialNo)
                ->where('scanned_status', '=','Scanned')
                ->first();

            $invoiceNo = $invoicesnoexists?->invoice_number;

            if ($invoicesnoexists)
            {
                Notification::make()
                    ->title("Serial number '$serialNo' already exists in invoice number '$invoiceNo' and completed the scanning process..!")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $serialExist = PalletValidation::where('serial_number', $serialNo)
                ->where('plant_id', $plantId)
                ->first();

            if ($serialExist && $serialExist->locator_number && $serialExist->locator_number != $scanLocator)
            {
                Notification::make()
                    ->title("Serial number '$serialNo' is already assigned to locator number '{$serialExist->locator_number}'.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }
            else if ($serialExist && $serialExist->pallet_number && $serialExist->pallet_number != null && $serialExist->pallet_number != '')
            {
                Notification::make()
                    ->title("Serial number '$serialNo' already exists in pallet number '{$serialExist->pallet_number}'.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                 return;
            }

            //heretocontinue

            if ($serialExist && $serialExist->locator_number == $scanLocator)
            {
                Notification::make()
                    ->title("Press 'Remove Serial Number' button to remove Serial number : '$serialNo' from Locator number : '$scanLocator'..!")
                    ->info()
                    ->duration(2000)
                    ->send();
            }
            else
            {
                Notification::make()
                    ->title("Press 'Add Serial Number' button to add Serial number : '$serialNo' into Locator number : '$scanLocator'..!")
                    ->info()
                    ->duration(2000)
                    ->send();
            }
        }

        $count = PalletValidation::where('plant_id', $plantId)
            ->where('locator_number', $scanLocator)
            ->count('locator_number');

        $this->form->fill([
            'plant_id'      => $plantId,
            'scan_serial_no' => $serialNo,
            'scan_pallet_no' => $palletNo,
            'scan_locator_no' => $scanLocator,
            'pallet_quantity' => $count,
            'created_by'    => $operatorName,
            'scanned_by'    => $operatorName,
        ]);

        $this->dispatch('loadLocator' ,$scanLocator,$plantId);
    }

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

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

        $this->plantId = $plantId;

        $palletNo= $this->form->getState()['scan_pallet_no'];

        $palletNo = trim($palletNo) ?? null;

        $serialNo = $this->form->getState()['scan_serial_no'] ?? null;

        $serialNo = trim($serialNo) ?? null;

        $scanLocator = $this->form->getState()['scan_locator_no'];

        $scanLocator = trim($scanLocator) ?? null;

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

        if (!$palletNo && !$serialNo)
        {
            return;
        }

        if ($scanLocator == null || $scanLocator == '') {
            Notification::make()
                ->title("Locator number can't be empty!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
            ([
                'plant_id'      => $plantId,
                'scan_serial_no' => $serialNo,
                'scan_pallet_no' => $palletNo,
                'scan_locator_no' => null,
                'pallet_quantity' => 0,
                'created_by'    => $operatorName,
                'scanned_by'    => $operatorName,
            ]);
            return;
        }
        else if (strlen($scanLocator) < 7)
        {
            Notification::make()
                ->title("Locator number '$scanLocator' must be at least 7 digits.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => $serialNo,
                    'scan_pallet_no' => $palletNo,
                    'scan_locator_no' => $scanLocator,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
            return;
        }

        $exists = Locator::where('locator_number', $scanLocator)
        ->where('plant_id', $plantId)
        ->first();

        if (!$exists)
        {
            Notification::make()
                ->title("Locator number '{$scanLocator}' does not exist in the master.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
            ([
                'plant_id'      => $plantId,
                'scan_serial_no' => $serialNo,
                'scan_pallet_no' => $palletNo,
                'scan_locator_no' => null,
                'pallet_quantity' => 0,
                'created_by'    => $operatorName,
                'scanned_by'    => $operatorName,
            ]);
            return;
        }

        $locator = Locator::where('locator_number', $scanLocator)
        ->where('plant_id', $plantId)
        ->first();

        if ($locator->locator_quantity >= 2) {
            Notification::make()
                ->title("No space available for locator number '{$scanLocator}'.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
            ([
                'plant_id'      => $plantId,
                'scan_serial_no' => $serialNo,
                'scan_pallet_no' => $palletNo,
                'scan_locator_no' => null,
                'pallet_quantity' => 0,
                'created_by'    => $operatorName,
                'scanned_by'    => $operatorName,
            ]);
            return;
        }

        if($palletNo)
        {
            if (strlen($palletNo) < 10)
            {
                Notification::make()
                    ->title("Pallet number '$palletNo' must be at least 10 digits.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                    ([
                        'plant_id'      => $plantId,
                        'scan_serial_no' => null,
                        'scan_pallet_no' => null,
                        'scan_locator_no' => null,
                        'pallet_quantity' => 0,
                        'created_by'    => $operatorName,
                        'scanned_by'    => $operatorName,
                    ]);
                return;
            }

            $Palletexists = PalletValidation::where('pallet_number', $palletNo)->where('plant_id',  $plantId)->first();

            if(!$Palletexists)
            {
                Notification::make()
                    ->title("Pallet number '$palletNo' does not found in pallet table.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $notAlreadyCompleted = PalletValidation::where('plant_id', $plantId)
            ->where('pallet_number', $palletNo)
            ->whereNull('pallet_status')
            ->orWhere('pallet_status', '=','')
            // ->where('locator_number', $this->scanLocator)
            ->first();

            if($notAlreadyCompleted)
            {
                Notification::make()
                    ->title("Pallet number '{$palletNo}' does not completed the master packing.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $alreadyAssigned = PalletValidation::where('plant_id', $plantId)
                ->where('pallet_number', $palletNo)
                ->where('locator_number', '!=', '')
                ->where('locator_number', '!=', null)
                // ->where('locator_number', $this->scanLocator)
                ->first();

            if ($alreadyAssigned)
            {
                Notification::make()
                    ->title("Pallet number '{$palletNo}' is already added into locator number '{$alreadyAssigned->locator_number}'.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $updatedRows = PalletValidation::where('plant_id', $plantId)
                ->where('pallet_number', $palletNo)
                ->update([
                    'locator_number' => $scanLocator,
                ]);

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

            if ($updatedRows > 0)
            {
                Notification::make()
                    ->title("Scanned pallet number '$palletNo' added into locator number '$scanLocator' successfully.")
                    ->success()
                    ->duration(500)
                    ->send();

                $locator = Locator::where('locator_number', $scanLocator)
                    ->where('plant_id', $plantId)->first();
                $locator->increment('locator_quantity');

                Locator::where('plant_id', $plantId)
                ->where('locator_number', $scanLocator)
                ->update(['updated_at' => now(), 'operator_id' => $operatorName]);

                PalletValidation::where('plant_id', $plantId)
                    ->where('pallet_number', $palletNo)
                    ->where('locator_number', $scanLocator)
                    ->update(['locator_quantity' => $locator->locator_quantity,'updated_at' => now(), 'updated_by' => $operatorName]);

                PalletValidation::where('plant_id', $plantId)
                    ->where('locator_number', $scanLocator)
                    ->update(['locator_quantity' => $locator->locator_quantity, 'updated_at' => now()]);

                    $this->form->fill([
                        'plant_id'      => $plantId,
                        'scan_serial_no' => null,
                        'scan_pallet_no' => null,
                        'scan_locator_no' => null,
                        'pallet_quantity' => null,
                        'created_by'    => $operatorName,
                        'updated_by'    => $operatorName,
                    ]);
                $this->dispatch('loadLocator' ,$scanLocator,$plantId);
                return;
            }
            else
            {
                Notification::make()
                    ->title("pallet number failed to add into locator number '$scanLocator'")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }
        }
        else
        {
            if ($serialNo == '' || $serialNo == null) {
                Notification::make()
                    ->title("Serial number is required to add when pallet number is empty.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                    ([
                        'plant_id'      => $plantId,
                        'scan_serial_no' => null,
                        'scan_pallet_no' => null,
                        'scan_locator_no' => null,
                        'pallet_quantity' => 0,
                        'created_by'    => $operatorName,
                        'scanned_by'    => $operatorName,
                    ]);
                return;
            }
            else if (strlen($serialNo) < 9 || strlen($serialNo) > 20)
            {
                Notification::make()
                    ->title("Serial number should contain minimum 9 digits and maximum 20 digits.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                    ([
                        'plant_id'      => $plantId,
                        'scan_serial_no' => null,
                        'scan_pallet_no' => null,
                        'scan_locator_no' => null,
                        'pallet_quantity' => 0,
                        'created_by'    => $operatorName,
                        'scanned_by'    => $operatorName,
                    ]);
                return;
            }
            else if (!ctype_alnum($serialNo))
            {
                Notification::make()
                    ->title("Serial number '$serialNo' must contain alpha-numeric values only.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                    ([
                        'plant_id'      => $plantId,
                        'scan_serial_no' => null,
                        'scan_pallet_no' => null,
                        'scan_locator_no' => null,
                        'pallet_quantity' => 0,
                        'created_by'    => $operatorName,
                        'scanned_by'    => $operatorName,
                    ]);
                return;
            }

            $invoicesnoexists = LocatorInvoiceValidation::where('plant_id', $plantId)
                ->where('serial_number', $serialNo)
                ->where('scanned_status', '=','Scanned')
                ->first();

            $invoiceNo = $invoicesnoexists?->invoice_number;

            if ($invoicesnoexists)
            {
                Notification::make()
                    ->title("Serial number '$serialNo' already exists in invoice number '$invoiceNo' and completed the scanning process..!")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $palletexists = PalletValidation::where('plant_id', $plantId)
                ->where('serial_number', $serialNo)
                ->where('pallet_number', '!=', '')
                ->where('pallet_number', '!=', null)
                ->first();

            if($palletexists)
            {
                Notification::make()
                    ->title("Serial number '$serialNo' already exists in pallet number '{$palletexists->pallet_number}'.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                 return;
            }

            $exists = PalletValidation::where('plant_id', $plantId)
                ->where('serial_number', $serialNo)
                ->where('locator_number', '!=', '')
                ->where('locator_number', '!=', null)
                ->first();

            if ($exists)
            {
                Notification::make()
                    ->title("Serial number '$serialNo' already exists in locator number '{$exists->locator_number}'.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            PalletValidation::create([
                'plant_id'        => $plantId,
                'pallet_number'   => null,
                'locator_number'  => $scanLocator,
                'serial_number'   => $serialNo,
                'locator_quantity'=> $locator->locator_quantity,
                'created_by'      => $operatorName,
                'scanned_by'      => $operatorName,
                'updated_by'      => $operatorName,
                'updated_at'      => now(),
                'scanned_at'      => now(),
            ]);

            Locator::where('plant_id', $plantId)
            ->where('locator_number', $scanLocator)
            ->update(['updated_at' => now(), 'operator_id' => $operatorName]);

            PalletValidation::where('plant_id', $plantId)
            ->where('locator_number', $scanLocator)
            ->update(['locator_quantity' => $locator->locator_quantity, 'updated_at' => now()]);


            Notification::make()
                ->title("Scanned serial number '$serialNo' added into locator number '$scanLocator' successfully.")
                ->success()
                ->duration(500)
                ->send();

            // $count = PalletValidation::where('plant_id', $plantId)
            // ->where('locator_number', $scanLocator)
            // ->count('locator_number');
                $this->form->fill([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => null,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);

            // $this->disableSerialNo = false;
            // $this->disablePalletNo = false;

            $this->dispatch('loadLocator' ,$scanLocator,$plantId);

        }
    }

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

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

        $this->plantId = $plantId;

        $palletNo = $this->form->getState()['scan_pallet_no'];

        $palletNo = trim($palletNo) ?? null;

        $serialNo = $this->form->getState()['scan_serial_no'] ?? null;

        $serialNo = trim($serialNo) ?? null;

        $scanLocator = $this->form->getState()['scan_locator_no'];

        $scanLocator = trim($scanLocator) ?? null;

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

        if (!$palletNo && !$serialNo)
        {
            return;
        }

        if ($scanLocator == null || $scanLocator == '') {
            Notification::make()
                ->title("Locator number can't be empty!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => $serialNo,
                    'scan_pallet_no' => $palletNo,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
            return;
        }
        else if (strlen($scanLocator) < 7)
        {
            Notification::make()
                ->title("Locator number '$scanLocator' must be at least 7 digits.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => $serialNo,
                    'scan_pallet_no' => $palletNo,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
            return;
        }

        $exists = Locator::where('locator_number', $scanLocator)
        ->where('plant_id', $plantId)
        ->first();

        if (!$exists)
        {
            Notification::make()
                ->title("Locator number '{$scanLocator}' does not exist in the master.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadLocator' ,'',$plantId);
            $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => $serialNo,
                    'scan_pallet_no' => $palletNo,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
            return;
        }

        if($palletNo)
        {
            if (strlen($palletNo) < 10)
            {
                Notification::make()
                    ->title("Pallet number '$palletNo' must be at least 10 digits.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                    ([
                        'plant_id'      => $plantId,
                        'scan_serial_no' => null,
                        'scan_pallet_no' => null,
                        'scan_locator_no' => null,
                        'pallet_quantity' => 0,
                        'created_by'    => $operatorName,
                        'scanned_by'    => $operatorName,
                    ]);
                return;
            }

            $Palletexists = PalletValidation::where('pallet_number', $palletNo)->where('plant_id',  $plantId)->first();
            if(!$Palletexists)
            {
                Notification::make()
                    ->title("Pallet number '$palletNo' does not found in pallet table.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $notAlreadyCompleted = PalletValidation::where('plant_id', $plantId)
                ->where('pallet_number', $palletNo)
                ->whereNull('pallet_status')
                ->orWhere('pallet_status', '=','')
                // ->where('locator_number', $this->scanLocator)
                ->first();

            if($notAlreadyCompleted)
            {
                Notification::make()
                    ->title("Pallet number '{$palletNo}' does not completed the master packing.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $palletValidation = PalletValidation::where('pallet_number', $palletNo)
                ->where('plant_id', $plantId)
                ->where('locator_number', '!=', '')
                ->where('locator_number', '!=',null)
                ->first();

            if ($palletValidation && $palletValidation->locator_number != $scanLocator)
            {
                Notification::make()
                    ->title("Pallet number '$palletNo' is exists in locator number '$palletValidation->locator_number'<br>Scan the valid locator number to remove pallet number.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator', '', $plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => $palletNo,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $palletRecord = PalletValidation::where('plant_id', $plantId)
            ->where('pallet_number', $palletNo)
            ->whereNotNull('locator_number')
            ->where('locator_number', '!=', '')
            ->first();

            if (!$palletRecord)
            {
                Notification::make()
                    ->title("Pallet number '{$palletNo}' doesn't exist in locator number.<br>Add locator number to proceed...")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => $palletNo,
                    'scan_locator_no' => $scanLocator,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $updatedRows = PalletValidation::where('plant_id', $plantId)
            ->where('pallet_number', $palletNo)
            ->update([
                'locator_number' => null,
                'locator_quantity' => 0,
                'updated_at' => now(),
                'updated_by' => $operatorName,
            ]);

            // if ($updatedRows > 0)
            // {
            //    // Locator::where('locator_number', $scanLocator)->decrement('locator_quantity');

            //    $locator = Locator::where('locator_number', $scanLocator)
            //    ->where('plant_id', $plantId)
            //    ->first();
            // //    $locator->decrement('locator_quantity');
            // $locator->locator_quantity;

            // $locator --;

            //     Locator::where('plant_id', $plantId)
            //     ->where('locator_number', $scanLocator)
            //     ->update(['updated_at' => now(), 'operator_id' => $operatorName]);

            //     PalletValidation::where('plant_id', $plantId)
            //         ->where('locator_number', $scanLocator)
            //         ->update(['locator_quantity' => $locator->locator_quantity, 'updated_at' => now()]);

            if ($updatedRows > 0)
            {

                $locator = Locator::where('locator_number', $scanLocator)
                    ->where('plant_id', $plantId)
                    ->first();

                    if ($locator && $locator->locator_quantity > 0) {
                        $locator->locator_quantity = $locator->locator_quantity - 1;
                        $locator->save();
                    }

                Locator::where('plant_id', $plantId)
                    ->where('locator_number', $scanLocator)
                    ->update([
                        'updated_at' => now(),
                        'operator_id' => $operatorName
                    ]);

                PalletValidation::where('plant_id', $plantId)
                    ->where('locator_number', $scanLocator)
                    ->update([
                        'locator_quantity' => $locator->locator_quantity,
                        'updated_at' => now()
                    ]);

                Notification::make()
                    ->title("Scanned pallet number '{$palletNo}' removed from locator number '$scanLocator' successfully.")
                    ->success()
                    ->duration(500)
                    ->send();

                $this->dispatch('loadLocator' ,$scanLocator,$plantId);
                $this->form->fill([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => null,
                    'created_by'    => $operatorName,
                    'updated_by'    => $operatorName,
                ]);
            }
            else
            {
                Notification::make()
                    ->title("No matching pallet found or locator number already empty.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => $palletNo,
                    'scan_locator_no' => $scanLocator,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

        }
        else
        {
            if ($serialNo == '' || $serialNo == null)
            {
                Notification::make()
                    ->title("Serial number is required to remove when pallet number is empty.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }
            else if (strlen($serialNo) < 9 || strlen($serialNo) > 20)
            {
                Notification::make()
                    ->title("Serial number should contain minimum 9 digits and maximum 20 digits.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                    ([
                        'plant_id'      => $plantId,
                        'scan_serial_no' => null,
                        'scan_pallet_no' => null,
                        'scan_locator_no' => null,
                        'pallet_quantity' => 0,
                        'created_by'    => $operatorName,
                        'scanned_by'    => $operatorName,
                    ]);
                return;
            }
            else if (!ctype_alnum($serialNo))
            {
                Notification::make()
                    ->title("Serial number '$serialNo' must contain alpha-numeric values only.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                    ([
                        'plant_id'      => $plantId,
                        'scan_serial_no' => null,
                        'scan_pallet_no' => null,
                        'scan_locator_no' => null,
                        'pallet_quantity' => 0,
                        'created_by'    => $operatorName,
                        'scanned_by'    => $operatorName,
                    ]);
                return;
            }

            $invoicesnoexists = LocatorInvoiceValidation::where('plant_id', $plantId)
            ->where('serial_number', $serialNo)
            ->where('scanned_status', '=','Scanned')
            ->first();

            $invoiceNo = $invoicesnoexists?->invoice_number;
            if ($invoicesnoexists)
            {
                Notification::make()
                    ->title("Serial number '$serialNo' already exists in invoice number '$invoiceNo' and completed the scanning process..!")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $exists = PalletValidation::where('serial_number', $serialNo)
            ->where('plant_id', $plantId)
            ->first();

            if (!$exists) {
                Notification::make()
                    ->title("Serial number '{$serialNo}' doesn't exist in the pallet table to remove.<br>Add serial number to proceed...")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => $serialNo,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => $scanLocator,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $existsInPallet = PalletValidation::where('serial_number', $serialNo)
            ->where('pallet_number', '!=', '')
            ->where('pallet_number', '!=',null)
            ->where('plant_id', $plantId)
            ->first();

            if ($existsInPallet) {
                Notification::make()
                    ->title("Serial number '{$serialNo}' already exists in pallet number '$existsInPallet->pallet_number'.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $existsInPallet = PalletValidation::where('serial_number', $serialNo)
            ->where('locator_number', '!=', '')
            ->where('locator_number', '!=',null)
            ->where('plant_id', $plantId)
            ->first();

            if ($existsInPallet && $existsInPallet->locator_number != $scanLocator) {
                Notification::make()
                    ->title("Serial number '{$serialNo}' exist in the locator number '$existsInPallet->locator_number'.<br>Scan the valid locator number to remove serial number.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => $serialNo,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }

            $deleted = PalletValidation::where('plant_id', $plantId)
                ->where('serial_number', $serialNo)
                ->forceDelete();

            if ($deleted > 0)
            {
                Locator::where('plant_id', $plantId)
                ->where('locator_number', $scanLocator)
                ->update(['updated_at' => now(), 'operator_id' => $operatorName]);

                Notification::make()
                    ->title("Scanned serial number '{$serialNo}' removed from locator number '$scanLocator' successfully.")
                    ->success()
                    ->duration(500)
                    ->send();

                $this->dispatch('loadLocator', $scanLocator, $plantId);
                $this->form->fill([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => null,
                    'created_by'    => $operatorName,
                    'updated_by'    => $operatorName,
                ]);
            }
            else
            {
                Notification::make()
                    ->title("Serial number failed to remove from locator number '$scanLocator'.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadLocator' ,'',$plantId);
                $this->form->fill
                ([
                    'plant_id'      => $plantId,
                    'scan_serial_no' => null,
                    'scan_pallet_no' => null,
                    'scan_locator_no' => null,
                    'pallet_quantity' => 0,
                    'created_by'    => $operatorName,
                    'scanned_by'    => $operatorName,
                ]);
                return;
            }
        }
    }

    public static function getNavigationLabel(): string
    {
        return 'Scan Locator';
    }

    public static function canAccess(): bool
    {
        return Auth::check() && Auth::user()->can('create locator validation page');
    }
}
