<?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\Actions\Action;
use Filament\Forms\Components\FileUpload;
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\Get;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;
use Livewire\Features\SupportFileUploads\WithFileUploads;
use Maatwebsite\Excel\Facades\Excel;
use Storage;

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

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

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

    protected static ?int $navigationSort = 3;

    public $upload_serial_locator;

    public $scan_locator = '';
    public $plant_id = null;

    public $filters =
    [
        'plant_id' => null,
        'scan_serial_number' => null,
        'scan_locator' => null,
        'upload_serial_locator' => null,
    ];

    public function form(Form $form): Form
    {
        return $form
            ->statePath('filters')
            ->schema([
                Section::make('') // You can give your section a title or leave it blank
                    ->schema([
                        Select::make('plant_id')
                            ->label('Plant')
                            ->reactive()
                            ->required()
                            //->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('scan_serial_number') || $get('scan_locator')) //!empty($get('scan_serial_number'))
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('scan_serial_number', null);
                                $set('scan_locator', null);
                                $set('upload_serial_locator', null);
                            })
                            ->columnSpan(1),
                        TextInput::make('scan_serial_number')
                            ->label('Scan Serial Number')
                            ->reactive()
                            ->minLength(9)
                            ->readOnly(fn (callable $get) => !$get('plant_id'))
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $plantId = $get('plant_id');
                                if (!$plantId) {
                                    $set('scan_serial_number', null);
                                    $set('scan_locator', null);
                                }
                                $set('upload_serial_locator', null);
                            })
                            ->columnSpan(1),
                        TextInput::make('scan_locator')
                            ->label('Scan Locator Number')
                            ->reactive()
                            ->minLength(7)
                            ->readOnly(fn (callable $get) => !$get('plant_id'))
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $plantId = $get('plant_id');
                                if (!$plantId) {
                                    $set('scan_serial_number', null);
                                    $set('scan_locator', null);
                                }
                                $set('upload_serial_locator', null);
                            })
                            ->columnSpan(1),
                        FileUpload::make('upload_serial_locator')
                            ->label('Choose Serial-Locator Master file')
                            ->preserveFilenames()
                            ->storeFiles(false)
                            ->reactive()
                            ->disabled(fn (Get $get) => $get('scan_serial_number') || $get('scan_locator'))//!$get('plant_id') ||
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $plantId = $get('plant_id');
                                if (!$plantId) {
                                    $set('scan_serial_number', null);
                                    $set('scan_locator', null);
                                    $set('upload_serial_locator', null);
                                }
                                $set('scan_serial_number', null);
                                $set('scan_locator', null);
                            })
                            ->directory('uploads/temp')
                            ->disk('local')
                            ->columnSpan('full')
                    ])
                    ->columns(3)
            ]);
    }

    public function masterFileUpload()
    {
        $plantId = $this->filters['plant_id'] ?? null;

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

        if ($plantId == '' || $plantId == null)
        {
            Notification::make()
                ->title('Please select a plant first.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => null,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        $fileArray = $this->filters['upload_serial_locator'];

        $file = is_array($fileArray) ? reset($fileArray) : $fileArray; // Get the first file

        if (!$file) {
            Notification::make()
                ->title('Please upload a file!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        $originalName = $file->getClientOriginalName();

        $extension = $file->getClientOriginalExtension();

        if (!in_array(strtolower($extension), ['xlsx', 'xls', 'csv']))
        {
            Notification::make()
                ->title('Choose a proper Excel file')
                ->body('The file must be an Excel file (xlsx, xls, csv).')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        $path = $file->storeAs('uploads/temp', $originalName, 'local');

        $fullPath = Storage::disk('local')->path($path);

       if (!file_exists($fullPath)) {
            Notification::make()
                ->title('File not found after upload!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        $data = Excel::toArray([], $fullPath);

        $rows = $data[0];

        $insertedCount = 0;

        $plantId = $this->filters['plant_id'];

        $existingSerials = [];

        $excelSerials = [];
        $excelLocators = [];

        $invalidSerial = [];
        $invalidLocator = [];

        foreach (array_slice($rows, 1) as $row) {
            $serialNumber = $row[0] ?? null;
            $locator = $row[1] ?? null;

            if ($serialNumber)
            {
                $excelSerials[] = $serialNumber;
                if (strlen($serialNumber) < 9 || strlen($serialNumber) > 20) {
                    $invalidSerial[] = $serialNumber;
                } elseif (!ctype_alnum($serialNumber)) {
                    $invalidSerial[] = $serialNumber;
                }
            }

            if ($locator) {
                $excelLocators[] = $locator;
                if (strlen($locator) < 7) {
                    $invalidLocator[] = $locator;
                }
            }
        }

        $uniqueInvalidSerial = array_unique($invalidSerial);
        if (count($uniqueInvalidSerial) > 0) {
            Notification::make()
                ->title('Invalid Serial Numbers Found')
                ->body('The following serial numbers are invalid, length should contain minimum of 9 digits (and maximum 20 digits) alpha numeric values:<br>' . implode(', ', $uniqueInvalidSerial))
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        $uniqueInvalidLocator = array_unique($invalidLocator);
        if (count($uniqueInvalidLocator) > 0) {
            Notification::make()
                ->title('Invalid Locator Numbers Found')
                ->body('The following locator numbers are invalid, length should contain minimum of 7 digits alpha numeric values:<br>' . implode(', ', $uniqueInvalidLocator))
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        // foreach (array_slice($rows, 1) as $row)
        // {
        //     $serialNumber = $row[0] ?? null;
        //     $locator = $row[1] ?? null;
        //     if ($serialNumber) {
        //         $excelSerials[] = $serialNumber;
        //     }
        //     if ($locator) {
        //         $excelLocators[] = $locator;
        //     }
        // }

       // dd($excelSerials);

        if (count($excelSerials) !== count(array_unique($excelSerials))) {
            $duplicates = array_diff_assoc($excelSerials, array_unique($excelSerials));
            $duplicates = array_values(array_unique($duplicates));
            Notification::make()
                ->title('Duplicate Serial Numbers in Excel')
                ->body('The following serial numbers are duplicated in the file:<br>' . implode(', ', $duplicates))
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        $excelLocators = array_unique($excelLocators);
        $locatorsWithQuantityTwo = Locator::whereIn('locator_number', $excelLocators)
            ->where('plant_id',$plantId)
            ->where('locator_quantity', '>=', 2)
            ->pluck('locator_number')
            ->toArray();

        if (count($locatorsWithQuantityTwo) > 0) {
            Notification::make()
                ->title('Locators with Insufficient Space')
                ->body('The following locators does not have space:<br>' . implode(', ', $locatorsWithQuantityTwo))
                ->warning()
                ->duration(5000)
                ->send();

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

        $excelSerials = array_unique($excelSerials);

        $palletSerials = PalletValidation::whereIn('serial_number', $excelSerials)->where('plant_id',$plantId)->pluck('serial_number')->toArray();
        $invoiceSerials = LocatorInvoiceValidation::whereIn('serial_number', $excelSerials)->where('plant_id',$plantId)->where('scanned_status','!=','')->where('scanned_status','!=',null)->pluck('serial_number')->toArray();

        $existingSerials = array_unique(array_merge($palletSerials, $invoiceSerials));

        if (count($existingSerials) > 0)
        {
            Notification::make()
                ->title('Duplicate Serial Numbers Found')
                ->body('The following serial numbers already exist and cannot be imported:<br>' . implode(', ', $existingSerials))
                ->danger()
                ->duration(5000)
                ->send();

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

        $insertedCount = 0;

        foreach (array_slice($rows, 1) as $row)
        {
            $serialNumber = $row[0] ?? null;
            $locator_num = $row[1] ?? null;

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

            if (empty($row[0]) && empty($row[1])) {
                continue;
            }

            if (!in_array($serialNumber, $existingSerials) && $serialNumber && $locator_num)
            {
                PalletValidation::create([
                    'plant_id' => $plantId,
                    'pallet_number' => null,
                    'serial_number' => $serialNumber,
                    'locator_number' => $locator_num,
                    'locator_quantity' => $locatorQuantity->locator_quantity,
                    'created_by' => $userName,
                    'updated_by' => $userName,
                    'scanned_by' => $userName,
                    'scanned_at' => now(),
                ]);
                $insertedCount++;
            }
        }

        Storage::delete($fullPath);

        if ($insertedCount > 0) {
            Notification::make()
                ->title('Serial Locators imported successfully!')
                ->body("'{$insertedCount}' locator serial number(s) have been imported.")
                ->success()
                ->duration(1000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }
        else
        {
            Notification::make()
                ->title('Serial Locators imported Failed!')
                ->body('No new serial number(s) found in the uploaded excel file..!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }
    }

    public function skipLocatorsQuestion()
    {
        $plantId = $this->filters['plant_id'] ?? null;

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

        if ($plantId == '' || $plantId == null)
        {
            Notification::make()
                ->title('Please select a plant first.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => null,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        $fileArray = $this->filters['upload_serial_locator'];

        $file = is_array($fileArray) ? reset($fileArray) : $fileArray;

        if (!$file) {
            Notification::make()
                ->title('Please upload a file!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        $originalName = $file->getClientOriginalName();

        $extension = $file->getClientOriginalExtension();

        if (!in_array(strtolower($extension), ['xlsx', 'xls', 'csv']))
        {
            Notification::make()
                ->title('Choose a proper Excel file')
                ->body('The file must be an Excel file (xlsx, xls, csv).')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        $path = $file->storeAs('uploads/temp', $originalName, 'local');

        $fullPath = Storage::disk('local')->path($path);

       if (!file_exists($fullPath)) {
            Notification::make()
                ->title('File not found after upload!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => null,
                'scan_locator' => null,
                'upload_serial_locator' => null,
            ]);
            return;
        }

        $data = Excel::toArray([], $fullPath);

        $rows = $data[0];

        $plantId = $this->filters['plant_id'];

        $existingSerials = [];

        $excelSerials = [];
        $excelLocators = [];

        foreach (array_slice($rows, 1) as $row)
        {
            $serialNumber = $row[0] ?? null;
            $locator = $row[1] ?? null;
            if ($serialNumber) {
                $excelSerials[] = $serialNumber;
            }
            if ($locator) {
                $excelLocators[] = $locator;
            }
        }

        $excelSerials = array_unique($excelSerials);

        $palletSerials = PalletValidation::whereIn('serial_number', $excelSerials)->where('plant_id',$plantId)->pluck('serial_number')->toArray();
        $invoiceSerials = LocatorInvoiceValidation::whereIn('serial_number', $excelSerials)->where('scanned_status','!=','')->where('scanned_status','!=',null)->where('plant_id',$plantId)->pluck('serial_number')->toArray();
        $existingSerials = array_unique(array_merge($palletSerials, $invoiceSerials));


        $excelLocators = array_unique($excelLocators);
        $locatorsWithQuantityTwo = Locator::whereIn('locator_number', $excelLocators)
            ->where('plant_id',$plantId)
            ->where('locator_quantity', '>=', 2)
            ->pluck('locator_number')
            ->toArray();


        if (count($existingSerials) > 0)
        {
            Notification::make()
                ->title('Duplicate Serial Numbers Found')
                ->body('The following serial numbers already exist and cannot be imported: ' . implode(', ', $existingSerials))
                ->danger()
                ->duration(5000)
                ->send();

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

        $insertedCount = 0;

        foreach (array_slice($rows, 1) as $row) {
            $serialNumber = $row[0] ?? null;
            $locator_num = $row[1] ?? null;


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

            if (empty($row[0]) && empty($row[1])) {
                continue;
            }

            if ($serialNumber && $locator_num && !in_array($locator_num, $locatorsWithQuantityTwo)) {
                PalletValidation::create([
                    'plant_id' => $plantId,
                    'pallet_number' => null,
                    'serial_number' => $serialNumber,
                    'locator_number' => $locator_num,
                    'locator_quantity' => $locatorQuantity->locator_quantity,
                    'created_by' => $userName,
                    'updated_by' => $userName,
                    'scanned_by' => $userName,
                    'scanned_at' => now(),
                ]);
                $insertedCount++;
            }
        }

        Storage::delete($fullPath);

        if ($insertedCount > 0) {
            Notification::make()
                ->title('Serial Locators imported successfully!')
                ->body("'{$insertedCount}' locator serial number(s) have been imported.")
                ->success()
                ->duration(1000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }
        else
        {
            Notification::make()
                ->title('Serial Locators imported Failed!')
                ->body('No new serial number(s) found in the uploaded excel file..!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }
    }

    public function cancelLocatorsQuestion()
    {
        $plantId = $this->filters['plant_id'] ?? null;
        $this->dispatch('loadData', '', '', 0);
        $this->form->fill
           ([
               'plant_id' => $plantId,
               'scan_serial_number' => null,
               'scan_locator' => null,
               'upload_serial_locator' => null,
           ]);
    }

    public function skipSerialQuestion()
    {
        $plantId = $this->filters['plant_id'] ?? null;

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

        if ($plantId == '' || $plantId == null)
        {
            Notification::make()
                ->title('Please select a plant first.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => null,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        $fileArray = $this->filters['upload_serial_locator'];

        $file = is_array($fileArray) ? reset($fileArray) : $fileArray; // Get the first file

        if (!$file) {
            Notification::make()
                ->title('Please upload a file!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        $originalName = $file->getClientOriginalName();

        $extension = $file->getClientOriginalExtension();

        if (!in_array(strtolower($extension), ['xlsx', 'xls', 'csv']))
        {
            Notification::make()
                ->title('Choose a proper Excel file')
                ->body('The file must be an Excel file (xlsx, xls, csv).')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        $path = $file->storeAs('uploads/temp', $originalName, 'local');

        $fullPath = Storage::disk('local')->path($path);

       if (!file_exists($fullPath)) {
            Notification::make()
                ->title('File not found after upload!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        $data = Excel::toArray([], $fullPath);

        $rows = $data[0];

        $plantId = $this->filters['plant_id'];

        $existingSerials = [];

        $excelSerials = [];

        foreach (array_slice($rows, 1) as $row)
        {
            $serialNumber = $row[0] ?? null;
            $locator = $row[1] ?? null;
            if ($serialNumber) {
                $excelSerials[] = $serialNumber;
            }
            if ($locator) {
                $excelLocators[] = $locator;
            }
        }

        $excelSerials = array_unique($excelSerials);

        $palletSerials = PalletValidation::whereIn('serial_number', $excelSerials)->where('plant_id',$plantId)->pluck('serial_number')->toArray();
        $invoiceSerials = LocatorInvoiceValidation::whereIn('serial_number', $excelSerials)->where('scanned_status','!=','')->where('scanned_status','!=',null)->where('plant_id',$plantId)->pluck('serial_number')->toArray();
        $existingSerials = array_unique(array_merge($palletSerials, $invoiceSerials));
        $excelLocators = array_unique($excelLocators);
        $locatorsWithQuantityTwo = Locator::whereIn('locator_number', $excelLocators)
            ->where('plant_id',$plantId)
            ->where('locator_quantity', '>=', 2)
            ->pluck('locator_number')
            ->toArray();


        $skipSerials = array_unique(array_merge(
            $existingSerials
        ));

        $insertedCount = 0;
        foreach (array_slice($rows, 1) as $row) {
            $serialNumber = $row[0] ?? null;
            $locator_num = $row[1] ?? null;

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

            if (empty($row[0]) && empty($row[1])) {
                continue;
            }

            if ($serialNumber && $locator_num && !in_array($serialNumber, $existingSerials) && !in_array($locator_num, $locatorsWithQuantityTwo)) {
                PalletValidation::create([
                    'plant_id' => $plantId,
                    'pallet_number' => null,
                    'serial_number' => $serialNumber,
                    'locator_number' => $locator_num,
                    'locator_quantity' => $locatorQuantity->locator_quantity,
                    'created_by' => $userName,
                    'updated_by' => $userName,
                    'scanned_by' => $userName,
                    'scanned_at' => now(),
                ]);
                $insertedCount++;
            }
        }

        Storage::delete($fullPath);

        if ($insertedCount > 0) {
            Notification::make()
                ->title('Serial Locators imported successfully!')
                ->body("'{$insertedCount}' locator serial number(s) have been imported.")
                ->success()
                ->duration(1000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        } else {
            Notification::make()
                ->title('Serial Locators imported Failed!')
                ->body('No new serial number(s) found in the uploaded excel file..!')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }
    }

    public function cancelSerialQuestion()
    {
        $plantId = $this->filters['plant_id'] ?? null;
        $this->dispatch('loadData', '', '', 0);
        $this->form->fill
        ([
            'plant_id' => $plantId,
            'scan_serial_number' => null,
            'scan_locator' => null,
            'upload_serial_locator' => null,
        ]);
    }

    public function addLocator()
    {
        $plantId = $this->filters['plant_id'] ?? null;
        $scanLocator = $this->filters['scan_locator'] ?? null;
        $scanSno = $this->filters['scan_serial_number'] ?? null;

        if ($plantId == '' || $plantId == null)
        {
            Notification::make()
                ->title('Please select a plant first.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
            ([
                'plant_id' => null,
                'scan_serial_number' => null,
                'scan_locator' => null,
                'upload_serial_locator' => null,
            ]);
            return;
        }

        if (!$scanSno && !$scanLocator)
        {
            Notification::make()
                ->title('Please enter serial number and locator number to add data.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => null,
                'scan_locator' => null,
                'upload_serial_locator' => null,
            ]);
            return;
        }

        if (!$scanSno)
        {
            Notification::make()
                ->title('Please enter serial number to add data.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => null,
                'scan_locator' => $scanLocator,
                'upload_serial_locator' => null,
            ]);
            return;
        }
        else if (strlen($scanSno) < 9 || strlen($scanSno) > 20)
        {
            Notification::make()
                ->title("Serial number should contain minimum 9 digits and maximum 20 digits.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => null,
                'scan_locator' => $scanLocator,
                'upload_serial_locator' => null,
            ]);
            return;
        }
        else if (!ctype_alnum($scanSno))
        {
            Notification::make()
                ->title('Serial number must contain alpha-numeric values only.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => null,
                'scan_locator' => $scanLocator,
                'upload_serial_locator' => null,
            ]);
            return;
        }

        if (!$scanLocator)
        {
            Notification::make()
                ->title('Please enter locator number to add data.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => $scanSno,
                'scan_locator' => null,
                'upload_serial_locator' => null,
            ]);
            return;
        }
        else if (strlen($scanLocator) < 7) {
            Notification::make()
                ->title("Locator number '$scanLocator' must be at least 7 digits.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => $scanSno,
                'scan_locator' => null,
                'upload_serial_locator' => null,
            ]);
            return;
        }

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

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

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => $scanSno,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

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

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => $scanSno,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

        if ($scanSno && $scanLocator)
        {
            $palletRecord = PalletValidation::where('serial_number', $scanSno)
                ->where('plant_id', $plantId)
                ->first();

            if ($palletRecord)
            {
                if ($palletRecord->pallet_number == null || $palletRecord->pallet_number == '')
                {
                    Notification::make()
                        ->title("Serial number '$scanSno' already exists in locator number '$palletRecord->locator_number'.")
                        ->danger()
                        ->duration(5000)
                        ->send();

                    $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                    $this->form->fill
                        ([
                            'plant_id' => $plantId,
                            'scan_serial_number' => null,
                            'scan_locator' => $scanLocator,
                            'upload_serial_locator' => null,
                        ]);
                    return;
                }
                else if ($palletRecord->locator_number == null || $palletRecord->locator_number == '')
                {
                    Notification::make()
                        ->title("Serial number '$scanSno' already exists in pallet number '$palletRecord->pallet_number'.")
                        ->danger()
                        ->duration(5000)
                        ->send();

                    $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                    $this->form->fill
                        ([
                            'plant_id' => $plantId,
                            'scan_serial_number' => null,
                            'scan_locator' => $scanLocator,
                            'upload_serial_locator' => null,
                        ]);
                    return;
                }
                else
                {
                    Notification::make()
                        ->title("Serial number '$scanSno' already exists in pallet number '$palletRecord->pallet_number' with locator number '$palletRecord->locator_number'.")
                        ->warning()
                        ->duration(5000)
                        ->send();

                    $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                    $this->form->fill
                        ([
                            'plant_id' => $plantId,
                            'scan_serial_number' => null,
                            'scan_locator' => $scanLocator,
                            'upload_serial_locator' => null,
                        ]);
                    return;
                }
            }
            else
            {
                $invoicesnoexists = LocatorInvoiceValidation::where('plant_id', $plantId)
                    ->where('serial_number', $scanSno)
                    ->where('scanned_status', '=', 'Scanned')
                    ->first();

                $invoiceNo = $invoicesnoexists?->invoice_number;

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

                    $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                    $this->form->fill
                        ([
                            'plant_id' => $plantId,
                            'scan_serial_number' => null,
                            'scan_locator' => $scanLocator,
                            'upload_serial_locator' => null,
                        ]);
                    return;
                }
            }
        }

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

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

        $created = PalletValidation::create([
            'plant_id'       => $plantId,
            'locator_number' => $scanLocator,
            'serial_number'  => $scanSno,
            'locator_quantity'  => $locatorQuantity->locator_quantity,
            'created_at' => now(),
            'created_by' => $userName,
            'scanned_at' => now(),
            'scanned_by' => $userName,
            'updated_at' => now(),
            'updated_by' => $userName,
        ]);

        if ($created)
        {
            Notification::make()
                ->title("Serial number '$scanSno' added into locator number '$scanLocator' successfully!")
                ->success()
                ->duration(1000)
                ->send();

            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => null,
                'scan_locator' => null,
                'upload_serial_locator' => null,
            ]);
        }
        else
        {
            Notification::make()
                ->title("Failed to add serial number '$scanSno' into locator number '$scanLocator'!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => $scanSno,
                'scan_locator' => $scanLocator,
                'upload_serial_locator' => null,
            ]);
        }

        // Refresh the table to show the new record
        $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
    }

    public function viewLocator()
    {
        $plantId = $this->filters['plant_id'] ?? null;
        $scanLocator = $this->filters['scan_locator'] ?? null;
        $scanSno = $this->filters['scan_serial_number'] ?? null;

        if ($plantId == '' || $plantId == null)
        {
            Notification::make()
                ->title('Please select a plant first.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
            ([
                'plant_id' => null,
                'scan_serial_number' => null,
                'scan_locator' => null,
                'upload_serial_locator' => null,
            ]);
            return;
        }

        if (!$scanSno && !$scanLocator)
        {
            Notification::make()
                ->title('Please enter atleast a serial number or locator number to view data.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => null,
                'scan_locator' => null,
                'upload_serial_locator' => null,
            ]);
            return;
        }
        else if ($scanSno && $scanLocator)
        {
            if (strlen($scanSno) < 9 || strlen($scanSno) > 20) {
                Notification::make()
                    ->title("Serial number should contain minimum 9 digits and maximum 20 digits.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                $this->form->fill
                    ([
                        'plant_id' => $plantId,
                        'scan_serial_number' => null,
                        'scan_locator' => $scanLocator,
                        'upload_serial_locator' => null,
                    ]);
                return;
            }
            else if (!ctype_alnum($scanSno))
            {
                Notification::make()
                    ->title('Serial number must contain alpha-numeric values only.')
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                $this->form->fill
                    ([
                        'plant_id' => $plantId,
                        'scan_serial_number' => null,
                        'scan_locator' => $scanLocator,
                        'upload_serial_locator' => null,
                    ]);
                return;
            }
            else if (strlen($scanLocator) < 7)
            {
                Notification::make()
                    ->title("Locator number '$scanLocator' must be at least 7 digits.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                $this->form->fill
                    ([
                        'plant_id' => $plantId,
                        'scan_serial_number' => $scanSno,
                        'scan_locator' => null,
                        'upload_serial_locator' => null,
                    ]);
                return;
            }

            $locator = Locator::where('locator_number', $scanLocator)
                ->where('plant_id', $plantId)
                ->first();
            if (!$locator)
            {
                Notification::make()
                    ->title("Locator number '$scanLocator' does not exist in the master.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                $this->form->fill
                    ([
                        'plant_id' => $plantId,
                        'scan_serial_number' => $scanSno,
                        'scan_locator' => null,
                        'upload_serial_locator' => null,
                    ]);
                return;
            }

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

            $invoiceNo = $invoicesnoexists?->invoice_number;

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

                $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                $this->form->fill
                    ([
                        'plant_id' => $plantId,
                        'scan_serial_number' => null,
                        'scan_locator' => $scanLocator,
                        'upload_serial_locator' => null,
                    ]);
                return;
            }

            $serialNumberExists = PalletValidation::where('serial_number', $scanSno)
                ->where('plant_id', $plantId)
                ->where('locator_number', $scanLocator)
                ->first();
            if (!$serialNumberExists)
            {
                Notification::make()
                    ->title("Serial number '$scanSno' and locator number '$scanLocator' does not exist in pallet table.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                $this->form->fill
                    ([
                        'plant_id' => $plantId,
                        'scan_serial_number' => null,
                        'scan_locator' => null,
                        'upload_serial_locator' => null,
                    ]);
                return;
            }
            else
            {
                if ($serialNumberExists->pallet_number != null && $serialNumberExists->pallet_number != '')
                {
                    Notification::make()
                        ->title("Serial number '$scanSno' already exists in pallet number '$serialNumberExists->pallet_number' with locator number '$serialNumberExists->locator_number'.")
                        ->danger()
                        ->duration(5000)
                        ->send();

                    $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                    $this->form->fill
                        ([
                            'plant_id' => $plantId,
                            'scan_serial_number' => null,
                            'scan_locator' => null,
                            'upload_serial_locator' => null,
                        ]);
                    return;
                }
                else
                {
                    Notification::make()
                        ->title("Serial number '$scanSno' exists in locator number '$serialNumberExists->locator_number'.")
                        ->success()
                        ->duration(1000)
                        ->send();

                    $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                    $this->form->fill
                        ([
                            'plant_id' => $plantId,
                            'scan_serial_number' => null,
                            'scan_locator' => null,
                            'upload_serial_locator' => null,
                        ]);
                    return;
                }
            }
        }
        else if ($scanSno)
        {
            if (strlen($scanSno) < 9 || strlen($scanSno) > 20) {
                Notification::make()
                    ->title("Serial number should contain minimum 9 digits and maximum 20 digits.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                $this->form->fill
                    ([
                        'plant_id' => $plantId,
                        'scan_serial_number' => null,
                        'scan_locator' => $scanLocator,
                        'upload_serial_locator' => null,
                    ]);
                return;
            }
            else if (!ctype_alnum($scanSno))
            {
                Notification::make()
                    ->title('Serial number must contain alpha-numeric values only.')
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                $this->form->fill
                    ([
                        'plant_id' => $plantId,
                        'scan_serial_number' => null,
                        'scan_locator' => $scanLocator,
                        'upload_serial_locator' => null,
                    ]);
                return;
            }

            // Check if the serial number exists in pallet or locator or invoice
            $palletRecord = PalletValidation::where('serial_number', $scanSno)
                ->where('plant_id', $plantId)
                ->first();

            if ($palletRecord)
            {
                if ($palletRecord->pallet_number == null || $palletRecord->pallet_number == '')
                {
                    Notification::make()
                        ->title("Serial number '$scanSno' exists in locator number '$palletRecord->locator_number'.")
                        ->success()
                        ->duration(1000)
                        ->send();

                    $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                    $this->form->fill
                        ([
                            'plant_id' => $plantId,
                            'scan_serial_number' => null,
                            'scan_locator' => null,
                            'upload_serial_locator' => null,
                        ]);
                    return;
                }
                else if ($palletRecord->locator_number == null || $palletRecord->locator_number == '')
                {
                    Notification::make()
                        ->title("Serial number '$scanSno' already exists in pallet number '$palletRecord->pallet_number'.")
                        ->danger()
                        ->duration(5000)
                        ->send();

                    $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                    $this->form->fill
                        ([
                            'plant_id' => $plantId,
                            'scan_serial_number' => null,
                            'scan_locator' => null,
                            'upload_serial_locator' => null,
                        ]);
                    return;
                }
                else
                {
                    Notification::make()
                        ->title("Serial number '$scanSno' already exists in pallet number '$palletRecord->pallet_number' with locator number '$palletRecord->locator_number'.")
                        ->danger()
                        ->duration(5000)
                        ->send();

                    $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                    $this->form->fill
                        ([
                            'plant_id' => $plantId,
                            'scan_serial_number' => null,
                            'scan_locator' => null,
                            'upload_serial_locator' => null,
                        ]);
                    return;
                }
            }
            else
            {
                $invoicesnoexists = LocatorInvoiceValidation::where('plant_id', $plantId)
                    ->where('serial_number', $scanSno)
                    ->where('scanned_status', '=', 'Scanned')
                    ->first();

                $invoiceNo = $invoicesnoexists?->invoice_number;

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

                    $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                    $this->form->fill
                        ([
                            'plant_id' => $plantId,
                            'scan_serial_number' => null,
                            'scan_locator' => $scanLocator,
                            'upload_serial_locator' => null,
                        ]);
                    return;
                }
                else
                {
                    Notification::make()
                        ->title("Serial number '$scanSno' does not exist in pallet table.")
                        ->danger()
                        ->duration(5000)
                        ->send();

                    $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                    $this->form->fill
                        ([
                            'plant_id' => $plantId,
                            'scan_serial_number' => null,
                            'scan_locator' => $scanLocator,
                            'upload_serial_locator' => null,
                        ]);
                    return;
                }
            }
        }
        else if ($scanLocator)
        {
            if (strlen($scanLocator) < 7) {
                Notification::make()
                    ->title("Locator number '$scanLocator' must be at least 7 digits.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                $this->form->fill
                    ([
                        'plant_id' => $plantId,
                        'scan_serial_number' => $scanSno,
                        'scan_locator' => null,
                        'upload_serial_locator' => null,
                    ]);
                return;
            }

            $locator = Locator::where('locator_number', $scanLocator)
                ->where('plant_id', $plantId)
                ->first();
            if (!$locator)
            {
                Notification::make()
                    ->title("Locator number '$scanLocator' does not exist in the master.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                $this->form->fill
                    ([
                        'plant_id' => $plantId,
                        'scan_serial_number' => $scanSno,
                        'scan_locator' => null,
                        'upload_serial_locator' => null,
                    ]);
                return;
            }

            $serialNumbernExists = PalletValidation::where('locator_number', $scanLocator)
                ->where('plant_id', $plantId)
                ->first();
            if (!$serialNumbernExists) {
                Notification::make()
                    ->title("Locator number '$scanLocator' does not exist in pallet table.")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                $this->form->fill
                    ([
                        'plant_id' => $plantId,
                        'scan_serial_number' => $scanSno,
                        'scan_locator' => null,
                        'upload_serial_locator' => null,
                    ]);
                return;
            }
            else
            {
                Notification::make()
                    ->title("Locator number '$scanLocator' exist in pallet table.")
                    ->success()
                    ->duration(1000)
                    ->send();

                $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
                $this->form->fill
                    ([
                        'plant_id' => $plantId,
                        'scan_serial_number' => null,
                        'scan_locator' => null,
                        'upload_serial_locator' => null,
                    ]);
                return;
            }
        }
        $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
    }

    public function deleteLocator()
    {
        $plantId = $this->filters['plant_id'] ?? null;
        $scanLocator = $this->filters['scan_locator'] ?? null;
        $scanSno = $this->filters['scan_serial_number'] ?? null;

        if ($plantId == '' || $plantId == null)
        {
            Notification::make()
                ->title('Please select a plant first.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', '', 0);
            $this->form->fill
            ([
                'plant_id' => null,
                'scan_serial_number' => null,
                'scan_locator' => null,
                'upload_serial_locator' => null,
            ]);
            return;
        }

        if (!$scanSno && !$scanLocator)
        {
            Notification::make()
                ->title('Please enter serial number and locator number to delete data.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }
        else if (!$scanSno)
        {
            Notification::make()
                ->title('Please enter serial number to delete data.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => $scanLocator,
                    'upload_serial_locator' => null,
                ]);
            return;
        }
        else if (strlen($scanSno) < 9 || strlen($scanSno) > 20) {
            Notification::make()
                ->title("Serial number should contain minimum 9 digits and maximum 20 digits.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => $scanLocator,
                    'upload_serial_locator' => null,
                ]);
            return;
        }
        else if (!ctype_alnum($scanSno))
        {
            Notification::make()
                ->title('Serial number must contain alpha-numeric values only.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => null,
                    'scan_locator' => $scanLocator,
                    'upload_serial_locator' => null,
                ]);
            return;
        }
        else if (!$scanLocator)
        {
            Notification::make()
                ->title('Please enter locator number to delete data.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => $scanSno,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }
        else if (strlen($scanLocator) < 7)
        {
            Notification::make()
                ->title("Locator number '$scanLocator' must be at least 7 digits.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => $scanSno,
                'scan_locator' => null,
                'upload_serial_locator' => null,
            ]);
            return;
        }

        $locator = Locator::where('locator_number', $scanLocator)->where('plant_id',$plantId)->first();
        if (!$locator)
        {
            Notification::make()
                ->title("Locator number '$scanLocator' does not exist in the master.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
                ([
                    'plant_id' => $plantId,
                    'scan_serial_number' => $scanSno,
                    'scan_locator' => null,
                    'upload_serial_locator' => null,
                ]);
            return;
        }

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

        $invoiceNo = $invoicesnoexists?->invoice_number;

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

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => null,
                'scan_locator' => $scanLocator,
                'upload_serial_locator' => null,
            ]);
            return;
        }

        $palletExists = PalletValidation::where('plant_id', $plantId)
            ->where('serial_number', $scanSno)
            ->where('locator_number', $scanLocator)
            ->where('pallet_number', '!=','')
            ->where('pallet_number', '!=',null)
            ->first();

        if ($palletExists)
        {
            Notification::make()
                ->title("Serial number '$scanSno' already exists in pallet number '$palletExists->pallet_number'!<br>Please enter locator serial number to remove data.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => null,
                'scan_locator' => $scanLocator,
                'upload_serial_locator' => null,
            ]);
            return;
        }

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

        $deleted = $query->forceDelete();

        if ($deleted)
        {
            Notification::make()
                ->title("Serial number '$scanSno' removed from locator number '$scanLocator' successfully.")
                ->success()
                ->duration(1000)
                ->send();

            $this->dispatch('loadData', '', '', $plantId);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => null,
                'scan_locator' => null,
                'upload_serial_locator' => null,
            ]);
            return;
        }
        else
        {
            Notification::make()
                ->title("Failed to remove serial number '$scanSno' from locator number '$scanLocator'!")
                //->title("Serial number '{$scanSno}' and Locator number '{$scanLocator}' does not exist in pallet table.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $scanLocator, $scanSno, $plantId);
            $this->form->fill
            ([
                'plant_id' => $plantId,
                'scan_serial_number' => $scanSno,
                'scan_locator' => $scanLocator,
                'upload_serial_locator' => null,
            ]);
            return;
        }
    }

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