<?php

namespace App\Filament\Pages;

use App\Models\Locator;
use App\Models\LocatorInvoiceValidation;
use App\Models\PalletValidation;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Get;
use Filament\Pages\Page;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Form;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;

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

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

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

    protected static ?int $navigationSort = 4;

    public $plantId;

    public $locatorNo;

    protected $latestPalletNumber = null;

    public array $filters = [];

    public $Checking = [];

    public $records = [];

    // public $locatorSno = [];

    public function mount()
    {
        $this->Checking = [];
        // session()->forget('latestPalletSerials');
        session()->forget('latestPalletNumber');
        session()->forget('latestPalletDateTime');
        session()->forget('latestPalletCreatedBy');
    }

    // use InteractsWithForms;

    // public $form;

    public function form(Form $form): Form
    {
        return $form
            ->statePath('filters')
            ->schema([
                Section::make('')
                    ->schema([
                        Select::make('plant_id')
                            ->label('Plant')
                            ->reactive()
                            ->required()
                            ->columnSpan(1)
                            //->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();
                            })
                            ->disabled(fn (Get $get) => $get('plant_id'))
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $plantId = $get('plant_id');
                                if ($plantId)
                                {
                                    $set('plant', $plantId);
                                    $set('scan_locator_number', null);
                                    $set('scan_serial_number', null);
                                    $set('scan_remove_sno', null);
                                    $set('sno_quantity', 0);
                                }
                                else
                                {
                                    $set('plant', null);
                                    $set('scan_locator_number', null);
                                    $set('scan_serial_number', null);
                                    $set('scan_remove_sno', null);
                                    $set('sno_quantity', 0);
                                }
                            }),
                        Hidden::make('plant')
                            ->reactive(),
                        TextInput::make('scan_locator_number')
                            ->label('Scan Locator Number')
                            ->reactive()
                            ->minLength(7)
                            ->columnSpan(1)
                            ->readOnly(fn (callable $get) => !$get('plant') || $get('scan_serial_number') || $get('scan_remove_sno'))
                            ->extraAttributes([
                                'wire:keydown.enter' => 'processLocatorNo($event.target.value)',
                            ]),
                        TextInput::make('scan_serial_number')
                            ->label('Scan Serial Number')
                            ->reactive()
                            ->minLength(9)
                            ->columnSpan(1)
                            ->readOnly(fn (callable $get) => !$get('plant') || $get('scan_locator_number') || $get('scan_remove_sno'))
                            ->extraAttributes([
                                'wire:keydown.enter' => 'processSerialNo($event.target.value)',
                            ]),
                        TextInput::make('scan_remove_sno')
                            ->label('Remove Serial Number')
                            ->reactive()
                            ->minLength(9)
                            ->columnSpan(1)
                            ->readOnly(fn (callable $get) => !$get('plant') || $get('scan_locator_number') || $get('scan_serial_number') || count($this->records) <= 0)
                            ->extraAttributes([
                                'wire:keydown.enter' => 'processremoveSNo($event.target.value)',
                            ]),
                        TextInput::make('sno_quantity')
                            ->label('SNo. Quantity')
                            ->reactive()
                            ->readOnly()
                            ->columnSpan(1),
                    ])
                    ->columns(5)
            ]);
    }

    public function processLocatorNo($locatorNo)
    {
        $locatorNo = trim($locatorNo);
        $this->locatorNo = $locatorNo;

        $plantId = trim($this->form->getState()['plant']) ?? null;
        $this->plantId = $plantId;
        $serialNo = trim($this->form->getState()['scan_serial_number']) ?? null;
        $removeSerial = trim($this->form->getState()['scan_remove_sno']) ?? null;
        //$operatorName = Filament::auth()->user()->name;
        $count = count($this->records);

        if ($serialNo != null || $serialNo != '')
        {
            Notification::make()
                ->title('Press enter on "Scan Serial Number" field to proceed..!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => $serialNo,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }
        else if ($removeSerial != null || $removeSerial != '')
        {
            Notification::make()
                ->title('Press enter on "Remove Serial Number" field to proceed..!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => $removeSerial,
                'sno_quantity' => $count,
            ]);
            return;
        }

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

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }
        else if (strlen($locatorNo) < 7)
        {
            Notification::make()
                ->title('Invalid: Locator Number')
                ->body("Locator number '$locatorNo' must be at least 7 digits.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }

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

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

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }

        $serialLocator = PalletValidation::query()
            ->where('plant_id', $plantId)
            ->where('locator_number', $locatorNo)
            ->where(function($query) {
                    $query->whereNull('pallet_number')
                        ->orWhere('pallet_number', '');
                })
            ->get();

        //$locatorSno = $serialLocator->pluck('serial_number')->toArray();

        if ($serialLocator->count() <= 0)
        {
            Notification::make()
                ->title('Unknown: Serial Locator Number')
                ->body("Scanned locator number '$locatorNo' does not have any locator serial numbers to store into the pallet.<br>
                    Please scan a valid stored locator number to proceed.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }
        else
        {
            Notification::make()
                ->title('Add: Locator Serial Numbers')
                ->body("Scanned locator number '$locatorNo' has '".$serialLocator->count()."' locator serial numbers!<br>Do you want to store it into 'PALLET DATA' table?")
                ->info()
                ->duration(2000)
                ->send();

            $this->dispatch('open-confirm-modal', locatorNo: $locatorNo, plantId: $plantId);
        }
    }

    public function loadlocatorData($locatorNo, $serialNo, $removeserial, $plantId)
    {
        $operatorName = Filament::auth()->user()->name;

        if(count($this->records) <= 0)
        {
            session(['latestPalletDateTime' => now()->format('Y-m-d H:i:s')]);
            session(['latestPalletCreatedBy' => $operatorName]);
        }

        if ($locatorNo != null && $locatorNo != '')
        {
            $serialNumbers = PalletValidation::query()
                ->where('plant_id', $plantId)
                ->where(function($query) {
                        $query->whereNull('pallet_number')
                            ->orWhere('pallet_number', '');
                    })
                ->where('locator_number', $locatorNo)
                ->get()
                ->map(function ($record) use($operatorName) {
                    return [
                        'created_at' => session('latestPalletDateTime') ?? '',
                        'created_by' => session('latestPalletCreatedBy') ?? '',
                        // 'pallet_number' => '',
                        'serial_number' => $record->serial_number,
                        'scanned_at' => now()->format('Y-m-d H:i:s'),
                        'scanned_by' => $operatorName ?? '',
                    ];
                })
                ->toArray();

            if (count($this->records) > 0)
            {
                // $this->records = array_values(array_filter($this->records, function ($record) use ($serialNumbers) {
                //     return !in_array($record['serial_number'], $serialNumbers);
                // }));
                foreach ($serialNumbers as $serial)
                {
                    $serialNo = $serial['serial_number'];
                    $this->records = array_values(array_filter($this->records, function ($record) use ($serialNo) {
                        return $record['serial_number'] != $serialNo;
                    }));
                }
            }

            $newRecords = PalletValidation::query()
                ->where('plant_id', $plantId)
                ->where(function($query) {
                        $query->whereNull('pallet_number')
                            ->orWhere('pallet_number', '');
                    })
                ->where('locator_number', $locatorNo)
                ->orderBy('created_at', 'asc') //orderByDesc('created_at')
                ->get()
                ->map(function ($record) use($operatorName) {
                    return [
                        'created_at' => session('latestPalletDateTime') ?? '',
                        'created_by' => session('latestPalletCreatedBy') ?? '',
                        // 'pallet_number' => '',
                        'serial_number' => $record->serial_number,
                        'scanned_at' => now()->format('Y-m-d H:i:s'),
                        'scanned_by' => $operatorName ?? '',
                    ];
                })
                ->toArray();

            $this->records = array_merge($this->records, $newRecords);

            // $this->dispatch('loadData', $this->records, $plantId);
            // $this->form->fill([
            //     'plant_id' => $plantId,
            //     'plant' => $plantId,
            //     'scan_locator_number' => $locatorNo,
            //     'scan_serial_number' => null,
            //     'scan_remove_sno' => null,
            //     'sno_quantity' => count($this->records),
            // ]);
        }
        else if ($serialNo != null && $serialNo != '')
        {
            if (count($this->records) > 0)
            {
                $this->records = array_values(array_filter($this->records, function ($record) use ($serialNo) {
                    return $record['serial_number'] != $serialNo;
                }));
            }

            $newRecords = PalletValidation::query()
                ->where('plant_id', $plantId)
                ->where('serial_number', $serialNo)
                ->get()
                ->map(function ($record) use($operatorName) {
                    return [
                        'created_at' => session('latestPalletDateTime') ?? '',
                        'created_by' => session('latestPalletCreatedBy') ?? '',
                        // 'pallet_number' => '',
                        'serial_number' => $record->serial_number,
                        'scanned_at' => now()->format('Y-m-d H:i:s'),
                        'scanned_by' => $operatorName ?? '',
                    ];
                })
                ->toArray();

            $this->records = array_merge($this->records, $newRecords);

            Notification::make()
                ->title('Add: Locator Serial Number')
                ->body("Scanned locator serial number '$serialNo' successfully added into 'PALLET DATA' table.")
                ->success()
                ->duration(500)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => count($this->records),
            ]);
        }
        else if ($removeserial != null && $removeserial != '')
        {
            $this->records = array_values(array_filter($this->records, function ($record) use ($removeserial) {
                return $record['serial_number'] != $removeserial;
            }));

            Notification::make()
                ->title('Remove: Locator Serial Number')
                ->body("Scanned locator serial number '$removeserial' removed successfully from 'PALLET DATA' table.")
                ->success()
                ->duration(500)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => count($this->records),
            ]);
        }
    }

    public function addToPalletValidation()
    {
        $plantId = $this->form->getState()['plant'];
        $locatorNo = trim($this->form->getState()['scan_locator_number']) ?? null;
        $serial = trim($this->form->getState()['scan_serial_number']) ?? null;
        $removeSno = trim($this->form->getState()['scan_remove_sno']) ?? null;

        $serialLocator = PalletValidation::query()
            ->where('plant_id', $plantId)
            ->where('locator_number', $locatorNo)
            ->where(function($query) {
                    $query->whereNull('pallet_number')->orWhere('pallet_number', '');
                })
            ->get()
            ->count();

        $this->loadlocatorData($locatorNo, '', '', $plantId);

        $this->dispatch('close-modal', id: 'confirm-process-modal');

        Notification::make()
            ->title('Add: Locator Serial Numbers')
            ->body("Scanned locator number '$locatorNo' has '$serialLocator' locator serial numbers!<br>Successfully added into 'PALLET DATA' table.")
            ->success()
            ->duration(500)
            ->send();

        $this->dispatch('loadData', $this->records, $plantId);
        $this->form->fill([
            'plant_id' => $plantId,
            'plant' => $plantId,
            'scan_locator_number' => null,
            'scan_serial_number' => null,
            'scan_remove_sno' => null,
            'sno_quantity' => count($this->records),
        ]);
    }

    public function skipAddToPalletValidation()
    {
        $plantId = $this->form->getState()['plant'];
        Notification::make()
            ->title('Skipped: Locator Number')
            ->body('Scan the new locator number to proceed..!')
            ->info()
            ->duration(2000)
            ->send();

        $this->dispatch('loadData', $this->records, $plantId);
        $this->form->fill([
            'plant_id' => $plantId,
            'plant' => $plantId,
            'scan_locator_number' => null,
            'scan_serial_number' => null,
            'scan_remove_sno' => null,
            'sno_quantity' => count($this->records),
        ]);
    }

    public function processSerialNo($serialNo)
    {
        $serialNo = trim($serialNo);

        $plantId = $this->form->getState()['plant'];

        $locatorNo = trim($this->form->getState()['scan_locator_number']) ?? null;

        $removeSerial = trim($this->form->getState()['scan_remove_sno']) ?? null;
        //$operatorName = Filament::auth()->user()->name;
        $count = count($this->records);

        if ($locatorNo != null || $locatorNo != '')
        {
            Notification::make()
                ->title('Press enter on "Scan Locator Number" field to proceed..!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => $locatorNo,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }
        else if ($removeSerial != null || $removeSerial != '')
        {
            Notification::make()
                ->title('Press enter on "Remove Serial Number" field to proceed..!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => $removeSerial,
                'sno_quantity' => $count,
            ]);
            return;
        }

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

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }
        else if (strlen($serialNo) < 9 || strlen($serialNo) > 20)
        {
            Notification::make()
                ->title('Invalid: Serial Number')
                ->body("Serial number should contain minimum 9 digits and maximum 20 digits.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }
        else if (!ctype_alnum($serialNo))
        {
            Notification::make()
                ->title('Invalid: Serial Number')
                ->body("Serial number '$serialNo' must contain alpha-numeric values only.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }

        $serialLocator = PalletValidation::query()
        ->where('plant_id', $plantId)
        // ->where(function($query) {
        //         $query->whereNull('pallet_number')
        //               ->orWhere('pallet_number', '');
        //     })
        ->where('serial_number', $serialNo)
        ->first();

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

            $invoiceNo = $invoicesnoexists?->invoice_number;

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

                $this->dispatch('loadData', $this->records, $plantId);
                $this->form->fill([
                    'plant_id' => $plantId,
                    'plant' => $plantId,
                    'scan_locator_number' => null,
                    'scan_serial_number' => null,
                    'scan_remove_sno' => null,
                    'sno_quantity' => $count,
                ]);
                return;
            }
            else
            {
                Notification::make()
                    ->title('Unknown: Serial Number')
                    ->body("Scanned serial number: '$serialNo' doesn't exist in pallet table.<br>Scan the valid exist locator-serial number to proceed..!")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadData', $this->records, $plantId);
                $this->form->fill([
                    'plant_id' => $plantId,
                    'plant' => $plantId,
                    'scan_locator_number' => null,
                    'scan_serial_number' => null,
                    'scan_remove_sno' => null,
                    'sno_quantity' => $count,
                ]);
                return;
            }
        }
        elseif ($serialLocator->pallet_number != '' && $serialLocator->pallet_number != null)
        {
            Notification::make()
                ->title('Invalid: Serial Number')
                ->body("Scanned serial number: '$serialNo' already exist in pallet number '".$serialLocator->pallet_number."'.<br>Scan the valid locator-serial number to proceed..!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }

        $this->loadlocatorData('', $serialNo, '', $plantId);
    }

    public function generatePallet()
    {
        $plantId = $this->form->getState()['plant'];
        $locatorNo = trim($this->form->getState()['scan_locator_number']) ?? null;
        $serialNo = trim($this->form->getState()['scan_serial_number']) ?? null;
        $removeSerial = trim($this->form->getState()['scan_remove_sno']) ?? null;
        // $this->Checking = session('latestPalletSerials');
        $operatorName = Filament::auth()->user()->name;

        if (count($this->records) <= 0)
        {
            Notification::make()
                ->title('Locator Serials Not Found')
                ->body("Add some locator serial numbers to proceed generate pallet..!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => $locatorNo,
                'scan_serial_number' => $serialNo,
                'scan_remove_sno' => $removeSerial,
                'sno_quantity' => 0,
            ]);
            return;
        }

        $year = now()->format('y');
        $month = now()->format('m');
        $prefix = "EP-{$year}{$month}";

        $lastPallet1 = PalletValidation::where('pallet_number', 'like', "{$prefix}%")->orderByDesc('pallet_number')->first(); //->where('plant_id', $plantId)
        $lastPallet2 = LocatorInvoiceValidation::where('pallet_number', 'like', "{$prefix}%")->orderByDesc('pallet_number')->first();
        $newNumber = '001'; // $lastPallet ? str_pad(intval(substr($lastPallet->pallet_number, -3)) + 1, 3, '0', STR_PAD_LEFT) : '001';
        if ($lastPallet1 && $lastPallet2) {
            $serialPart1 = substr($lastPallet1->pallet_number, strlen($prefix));
            $serialPart2 = substr($lastPallet2->pallet_number, strlen($prefix));
            if (intval($serialPart1) > intval($serialPart2)) {
                $newNumber = str_pad(intval($serialPart1) + 1, strlen($serialPart1), '0', STR_PAD_LEFT);
            } else {
                $newNumber = str_pad(intval($serialPart2) + 1, strlen($serialPart2), '0', STR_PAD_LEFT);
            }
        }
        else if ($lastPallet1) {
            $serialPart1 = substr($lastPallet1->pallet_number, strlen($prefix));
            // OR
            // $serialPart = str_replace($prefix, '', $lastPallet->pallet_number);
            $newNumber = str_pad(intval($serialPart1) + 1, strlen($serialPart1), '0', STR_PAD_LEFT);
        }
        else if ($lastPallet2) {
            $serialPart2 = substr($lastPallet2->pallet_number, strlen($prefix));
            $newNumber = str_pad(intval($serialPart2) + 1, strlen($serialPart2), '0', STR_PAD_LEFT);
        }

        $newPalletNumber = "{$prefix}{$newNumber}";

        session(['latestPalletNumber' => $newPalletNumber]);
        $this->latestPalletNumber = session('latestPalletNumber');

        $url = route('download-qr-pdf', ['palletNo' => $newPalletNumber]);
        $this->js(<<<JS
            window.dispatchEvent(new CustomEvent('open-pdf', {
                detail: {
                    url: "{$url}"
                }
            }));
        JS);

        // $affected = PalletValidation::where('locator_number', $locatorNo)
        //     ->where('plant_id', $plantId)
        //     ->whereIn('serial_number', $this->Checking)
        //     ->update([
        //         'pallet_number' => $newPalletNumber,
        //         'locator_number' => null,
        //         'updated_at' => now()->format('Y-m-d H:i:s'),
        //         'updated_by' => $operatorName,
        //     ]);

        $newSerialNumbers = array_column($this->records, 'serial_number');

        PalletValidation::where('plant_id', $plantId)->whereIn('serial_number', $newSerialNumbers)->forceDelete();

        $rowsAdded = 0;

        foreach ($this->records as &$record) {
            $rowsAdded++;
            $record['plant_id'] = $plantId;
            // $record['pallet_number'] = $newPalletNumber;
            // $record['pallet_status'] = 'Completed';
            $record['updated_by'] = $operatorName;

            PalletValidation::updateOrCreate(
                [
                    'plant_id' => $plantId,
                    'serial_number' => $record['serial_number'],
                ],
                [
                    'pallet_number' => $newPalletNumber,
                    'pallet_status' => 'Completed',
                    'locator_number' => null,
                    'locator_quantity' => 0,
                    'created_at' => $record['created_at'],
                    'created_by' => $record['created_by'],
                    'scanned_at' => $record['scanned_at'],
                    'scanned_by' => $record['scanned_by'],
                    'updated_by' => $operatorName
                ]
            );
        }
        unset($record);

        // PalletValidation::insert($this->records);

        if ($rowsAdded > 0)
        {
            $this->records = [];
            Notification::make()
                ->title('Success: Pallet Generated')
                ->body("Pallet number '$newPalletNumber' completed the master packing successfully!")
                ->success()
                ->duration(600)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => 0,
            ]);
            return;
        }
        else
        {
            $this->records = [];
            Notification::make()
                ->title('Failed: Pallet Generated')
                ->body("No locator serial number records found to generate pallet..!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => 0,
            ]);
            return;
        }

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

        // if ($locator && $locator->locator_quantity > 0) {
        //     $locator->update([
        //         'locator_quantity' => $locator->locator_quantity - 1,
        //         'updated_at' => now()->format('Y-m-d H:i:s'),
        //         'updated_by' => $operatorName
        //     ]);
        // }

        // Notification::make()
        //     ->title('Pallet Generated')
        //     ->body("Pallet number {$this->latestPalletNumber} assigned to all serials for locator {$locatorNo}")
        //     ->success()
        //     ->duration(1000)
        //     ->send();
        // $this->dispatch('loadData', $this->records, $plantId);
        // $this->form->fill([
        //     'plant_id' => $plantId,
        //     'plant' => $plantId,
        //     'scan_locator_number' => null,
        //     'scan_serial_number' => null,
        //     'scan_remove_sno' => null,
        //     'sno_quantity' => null,
        // ]);
    }

    public function processremoveSNo($removeSno)
    {
        $plantId = $this->form->getState()['plant'];

        $locatorNo = trim($this->form->getState()['scan_locator_number']) ?? null;

        $removeSno = trim($removeSno);

        $serialNo = trim($this->form->getState()['scan_serial_number']) ?? null;
        $count = count($this->records);

        if ($locatorNo != null || $locatorNo != '')
        {
            Notification::make()
                ->title('Press enter on "Scan Locator Number" field to proceed..!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => $locatorNo,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }
        else if ($serialNo != null || $serialNo != '')
        {
            Notification::make()
                ->title('Press enter on "Scan Serial Number" field to proceed..!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => $serialNo,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }

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

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }
        else if (strlen($removeSno) < 9 || strlen($removeSno) > 20)
        {
            Notification::make()
                ->title('Invalid: Serial Number')
                ->body("Serial number should contain minimum 9 digits and maximum 20 digits.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }
        else if (!ctype_alnum($removeSno))
        {
            Notification::make()
                ->title('Invalid: Serial Number')
                ->body("Serial number '$removeSno' must contain alpha-numeric values only.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }

        // $serialLocator = PalletValidation::query()
        // ->where('plant_id', $plantId)
        // ->where(function($query) {
        //         $query->whereNull('pallet_number')
        //               ->orWhere('pallet_number', '');
        //     })
        // ->first();

        $serialNumbers = array_column($this->records, 'serial_number');

        $exists = in_array($removeSno, $serialNumbers);

        if (!$exists)
        {
            Notification::make()
                ->title('Unknown: Serial Number')
                ->body("Scanned serial number: '$removeSno' doesn't exist in 'PALLET DATA' table.<br>Scan the valid exist locator-serial number to proceed..!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $this->records, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'scan_locator_number' => null,
                'scan_serial_number' => null,
                'scan_remove_sno' => null,
                'sno_quantity' => $count,
            ]);
            return;
        }

        $this->loadlocatorData('', '', $removeSno, $plantId);

    }

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

}
