<?php

namespace App\Filament\Resources\LocatorInvoiceValidationResource\Pages;

use App\Filament\Resources\LocatorInvoiceValidationResource;
use App\Models\Configuration;
use App\Models\Locator;
use App\Models\LocatorInvoiceValidation;
use App\Models\PalletValidation;
use Filament\Facades\Filament;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
use Maatwebsite\Excel\Facades\Excel;
use Storage;
use Str;

class CreateLocatorInvoiceValidation extends CreateRecord
{
    protected static string $resource = LocatorInvoiceValidationResource::class;

    protected static string $view = 'filament.resources.pallet-validation-resource.pages.create-locator-invoice-validation';

    public $plantId;

    public $invoice_number;

    public $pallet_number;

    public $serial_number;

    public $snoCount;

    public $locator_number;

    public array $matchedSerialNumbersForRemoval = [];

    public bool $showRemoveSerialsModal = false;

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('create');
    }

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

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

        $palletNumber = $this->form->getState()['pallet_number'];

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

        $serialNumber = $this->form->getState()['serial_number'];

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

        $invoiceNumber = $this->form->getState()['invoice_number'];

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

        $updateStatus = $this->form->getState()['update_invoice'] ?? null;

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

        $operatorName = $user->name;

        if (! $plantId) {
            Notification::make()
                ->title('Plant Not Found')
                ->body("Plant can't be empty!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', '', $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'serial_number' => null,
                'sno_quantity' => 0,
                'scan_quantity' => 0,
                'pend_quantity' => 0,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        }

        $filename = $invoiceNumber.'.xlsx';

        $folderPath = 'ExportDispatch'; // Configuration::where('c_name', 'INVOICE_FOLDER_PATH')->where('plant_id', $plantId)->value('c_value');

        $fullFolderPath = "uploads/$folderPath";

        $directory = $fullFolderPath;
        $disk = Storage::disk('local');
        $filePath = $directory.'/'.$filename;

        try {
            // $record1 = LocatorInvoiceValidation::query()
            // ->where('plant_id', $plantId)
            // ->where('invoice_number', $invoiceNumber)
            // ->first();

            $records = LocatorInvoiceValidation::where('plant_id', $plantId)
                ->where('invoice_number', $invoiceNumber)
                ->get();

            $allScanned = true;

            foreach ($records as $record) {
                if (($record->scanned_status == null) || trim($record->scanned_status) == '') {
                    $allScanned = false;
                    break;
                }
            }

            if (count($records) > 0 && $allScanned) {
                Notification::make()
                    ->title('Completed: Locator Invoice')
                    ->body("Locator invoice '$invoiceNumber' completed the scanning process.<br>Scan the next 'Locator Invoice' to proceed..!")
                    ->info()
                    ->duration(5000)
                    ->send();

                if ($disk->exists($filePath)) {
                    $disk->delete($filePath);
                }
                $this->dispatch('loadData', '', $plantId);
                $this->form->fill([
                    'plant_id' => $plantId,
                    'plant' => $plantId,
                    'invoice_number' => null,
                    'pallet_number' => null,
                    'serial_number' => null,
                    'sno_quantity' => 0,
                    'scan_quantity' => 0,
                    'pend_quantity' => 0,
                    'created_by' => $operatorName,
                    'scanned_by' => $operatorName,
                ]);

                return;
            }

            $invoiceExist = LocatorInvoiceValidation::where('plant_id', $plantId)
                ->where('invoice_number', $invoiceNumber)
                ->count('invoice_number');

            if ($invoiceExist <= 0) {
                $filename = $invoiceNumber.'.xlsx';

                $folderPath = 'ExportDispatch'; // Configuration::where('c_name', 'INVOICE_FOLDER_PATH')->where('plant_id', $plantId)->value('c_value');

                $fullFolderPath = "uploads/$folderPath";

                $directory = $fullFolderPath;
                $disk = Storage::disk('local');
                $filePath = $directory.'/'.$filename;
                $fullPath = $disk->path($filePath);

                if ($disk->exists($filePath)) {
                    $fullPath = $disk->path($filePath);
                } else {
                    Notification::make()
                        ->title('Invoice File Not Found')
                        ->body("Import the scanned 'Invoice' file to proceed..!")
                        ->danger()
                        ->duration(5000)
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'plant' => $plantId,
                        'invoice_number' => null,
                        'pallet_number' => null,
                        'serial_number' => null,
                        'sno_quantity' => 0,
                        'scan_quantity' => 0,
                        'pend_quantity' => 0,
                        'created_by' => $operatorName,
                        'scanned_by' => $operatorName,
                    ]);
                    $this->dispatch('loadData', '', $plantId);

                    return;
                }

                if ($fullPath && file_exists($fullPath)) {
                    $rows = Excel::toArray(null, $fullPath)[0];

                    if ((count($rows) - 1) <= 0) {
                        Notification::make()
                            // ->title('Records Not Found')
                            // ->body("Import the valid 'Serial Invoice' file to proceed..!")
                            ->title('Invalid Locator Invoice Found')
                            ->body('Uploaded excel sheet is empty or<br>contains no valid data.')
                            ->danger()
                            ->duration(5000)
                            ->send();

                        if ($disk->exists($filePath)) {
                            $disk->delete($filePath);
                        }
                        $this->dispatch('loadData', '', $plantId);
                        $this->form->fill([
                            'plant_id' => $plantId,
                            'plant' => $plantId,
                            'invoice_number' => null,
                            'pallet_number' => null,
                            'serial_number' => null,
                            'sno_quantity' => 0,
                            'scan_quantity' => 0,
                            'pend_quantity' => 0,
                            'created_by' => $operatorName,
                            'scanned_by' => $operatorName,
                        ]);

                        return;
                    }

                    $invalidSerialCodes = [];
                    $duplicateSerials = [];
                    $seenSerialNumbers = [];
                    $validRowsFound = false;

                    foreach ($rows as $index => $row) {
                        if ($index === 0) {
                            continue;
                        }  // Skip header

                        $serialNumber = trim((string) ($row[0] ?? ''));

                        if (empty($serialNumber)) {
                            continue;
                        } else {
                            if (Str::length($serialNumber) < 9 || Str::length($serialNumber) > 20 || ! ctype_alnum($serialNumber)) {
                                $invalidSerialCodes[] = $serialNumber;
                            } else {
                                if (in_array($serialNumber, $seenSerialNumbers)) {
                                    $duplicateSerials[] = $serialNumber;
                                } else {
                                    $seenSerialNumbers[] = $serialNumber;
                                    $validRowsFound = true;
                                }
                            }
                        }
                    }

                    $uniqueSerialCodes = array_unique($invalidSerialCodes);

                    if (! empty($uniqueSerialCodes)) {
                        Notification::make()
                            ->title('Invalid Serial Numbers Found')
                            ->body('The following serial numbers should contain minimum 9 digit (and maximum 20 digit) alpha numeric values:<br>'.implode(', ', $uniqueSerialCodes))
                            ->danger()
                            ->duration(5000)
                            ->send();

                        // if ($disk->exists($filePath)) {
                        //     $disk->delete($filePath);
                        // }
                        $this->dispatch('loadData', '', $plantId);
                        $this->form->fill([
                            'plant_id' => $plantId,
                            'plant' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'pallet_number' => null,
                            'serial_number' => null,
                            'sno_quantity' => 0,
                            'scan_quantity' => 0,
                            'pend_quantity' => 0,
                            'created_by' => $operatorName,
                            'scanned_by' => $operatorName,
                        ]);

                        return;
                    }

                    $duplicateSerialCodes = array_unique($duplicateSerials);

                    if (! empty($duplicateSerialCodes)) {
                        Notification::make()
                            ->title('Duplicate Serial Numbers Found')
                            ->body('The following serial numbers are already exist in imported excel:<br>'.implode(', ', $duplicateSerialCodes))
                            ->danger()
                            ->duration(5000)
                            ->send();

                        // if ($disk->exists($filePath)) {
                        //     $disk->delete($filePath);
                        // }
                        $this->dispatch('loadData', '', $plantId);
                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'pallet_number' => null,
                            'serial_number' => null,
                            'sno_quantity' => 0,
                            'scan_quantity' => 0,
                            'pend_quantity' => 0,
                            'created_by' => $operatorName,
                            'scanned_by' => $operatorName,
                        ]);

                        return;
                    }

                    if (! $validRowsFound) {
                        Notification::make()
                            ->title('Invalid Locator Invoice Found')
                            ->body('Uploaded excel sheet is empty or<br>contains no valid data.')
                            ->danger()
                            ->duration(5000)
                            ->send();

                        if ($disk->exists($filePath)) {
                            $disk->delete($filePath);
                        }
                        $this->dispatch('loadData', '', $plantId);
                        $this->form->fill([
                            'plant_id' => $plantId,
                            'plant' => $plantId,
                            'invoice_number' => null,
                            'pallet_number' => null,
                            'serial_number' => null,
                            'sno_quantity' => 0,
                            'scan_quantity' => 0,
                            'pend_quantity' => 0,
                            'created_by' => $operatorName,
                            'scanned_by' => $operatorName,
                        ]);

                        return;
                    }

                    $serialsToCheck = $seenSerialNumbers;

                    $existingSerials = LocatorInvoiceValidation::whereIn('serial_number', $serialsToCheck)
                        ->where('invoice_number', '!=', $invoiceNumber)
                        ->where('plant_id', $plantId)
                        ->pluck('serial_number')
                        ->toArray();

                    if (! empty($existingSerials)) {
                        Notification::make()
                            ->title('Duplicate Serial Numbers Found')
                            ->body('The following serial numbers already exist with a different invoice number:<br>'.implode(', ', $existingSerials))
                            ->danger()
                            ->duration(5000)
                            ->send();

                        // if ($disk->exists($filePath))
                        // {
                        //     $disk->delete($filePath);
                        // }
                        $this->dispatch('loadData', '', $plantId);
                        $this->form->fill([
                            'plant_id' => $plantId,
                            'plant' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'pallet_number' => null,
                            'serial_number' => null,
                            'sno_quantity' => 0,
                            'scan_quantity' => 0,
                            'pend_quantity' => 0,
                            'created_by' => $operatorName,
                            'scanned_by' => $operatorName,
                        ]);

                        return;
                    } else {
                        $createdAny = false;
                        foreach ($seenSerialNumbers as $serialNumber) {
                            // $deleted = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)
                            // ->where('serial_number', $serialNumber)
                            // ->where('plant_id', $plantId)
                            // ->where(function($query) {
                            //     $query->whereNull('scanned_status')
                            //           ->orWhere('scanned_status', '');
                            // })
                            // ->forceDelete();

                            // if ($deleted)
                            // {
                            //     LocatorInvoiceValidation::create([
                            //         'plant_id' => $plantId,
                            //         'invoice_number' => $invoiceNumber,
                            //         'serial_number' => $serialNumber,
                            //         'created_by' => $operatorName,

                            //     ]);
                            //     $createdAny = true;

                            //     $this->form->fill([
                            //         'plant_id'      => $plantId,
                            //         'plant'      => $plantId,
                            //         'invoice_number' => $invoiceNumber,
                            //         'serial_number' => null,
                            //         'sno_quantity' => $this->snoCount,
                            //         'created_by'    => $operatorName,
                            //         'scanned_by'    => $operatorName,
                            //     ]);

                            //     $this->dispatch('loadData', $invoiceNumber, $plantId);
                            // }

                            LocatorInvoiceValidation::create([
                                'plant_id' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'serial_number' => $serialNumber,
                                'created_by' => $operatorName,
                            ]);

                            $createdAny = true;

                        }

                        if ($createdAny) {
                            Notification::make()
                                ->title('Success: Invoice inserted successfully.')
                                ->success()
                                ->duration(500)
                                ->send();
                            Notification::make()
                                ->title("Start the scanning process for imported invoice number '$invoiceNumber'!")
                                ->info()
                                ->duration(800)
                                ->send();

                            // if ($disk->exists($filePath))
                            // {
                            //     $disk->delete($filePath);
                            // }

                            $snoCount = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->count();

                            $pendingCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->whereNull('scanned_status')->orWhere('scanned_status', '=', '')->count();

                            $scannedCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('scanned_status', '=', 'Scanned')->count();

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'plant' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'update_invoice' => 0,
                                'pallet_number' => null,
                                'serial_number' => null,
                                'sno_quantity' => $snoCount,
                                'scan_quantity' => $scannedCount,
                                'pend_quantity' => $pendingCount,
                                'created_by' => $operatorName,
                                'scanned_by' => $operatorName,
                            ]);

                            $this->dispatch('loadData', $invoiceNumber, $plantId);
                        }
                    }
                }
            } elseif ($updateStatus == 1) {
                $filename = $invoiceNumber.'.xlsx';

                $folderPath = 'ExportDispatch'; // Configuration::where('c_name', 'INVOICE_FOLDER_PATH')->where('plant_id', $plantId)->value('c_value');

                $fullFolderPath = "uploads/$folderPath";

                $directory = $fullFolderPath;
                $disk = Storage::disk('local');
                $filePath = $directory.'/'.$filename;
                $fullPath = $disk->path($filePath);

                if ($disk->exists($filePath)) {
                    $fullPath = $disk->path($filePath);
                } else {
                    Notification::make()
                        ->title('Updated Invoice File Not Found')
                        ->body("Import the updated 'Invoice' file to proceed..!")
                        ->danger()
                        ->duration(5000)
                        ->send();

                    $this->dispatch('loadData', '', $plantId);
                    $this->form->fill([
                        'plant_id' => $plantId,
                        'plant' => $plantId,
                        'invoice_number' => null,
                        'pallet_number' => null,
                        'serial_number' => null,
                        'sno_quantity' => 0,
                        'scan_quantity' => 0,
                        'pend_quantity' => 0,
                        'created_by' => $operatorName,
                        'scanned_by' => $operatorName,
                    ]);

                    return;
                }

                // session()->flash('invoice_valid', true);

                if ($fullPath && file_exists($fullPath)) {
                    $rows = Excel::toArray(null, $fullPath)[0];

                    if ((count($rows) - 1) <= 0) {
                        Notification::make()
                            ->title('Invalid Updated Locator Invoice Found')
                            ->body('Uploaded excel sheet is empty or<br>contains no valid data.')
                            ->danger()
                            ->duration(5000)
                            ->send();

                        if ($disk->exists($filePath)) {
                            $disk->delete($filePath);
                        }
                        $this->dispatch('loadData', '', $plantId);
                        $this->form->fill([
                            'plant_id' => $plantId,
                            'plant' => $plantId,
                            'invoice_number' => null,
                            'pallet_number' => null,
                            'serial_number' => null,
                            'sno_quantity' => 0,
                            'scan_quantity' => 0,
                            'pend_quantity' => 0,
                            'created_by' => $operatorName,
                            'scanned_by' => $operatorName,
                        ]);

                        return;
                    }

                    $invalidSerialCodes = [];
                    $duplicateSerials = [];
                    $seenSerialNumbers = [];
                    $validRowsFound = false;

                    foreach ($rows as $index => $row) {
                        if ($index === 0) {
                            continue;
                        }  // Skip header

                        $serialNumber = trim((string) ($row[0] ?? ''));

                        if (empty($serialNumber)) {
                            continue;
                        } else {
                            if (Str::length($serialNumber) < 9 || Str::length($serialNumber) > 20 || ! ctype_alnum($serialNumber)) {
                                $invalidSerialCodes[] = $serialNumber;
                            } else {
                                if (in_array($serialNumber, $seenSerialNumbers)) {
                                    $duplicateSerials[] = $serialNumber;
                                } else {
                                    $seenSerialNumbers[] = $serialNumber;
                                    $validRowsFound = true;
                                }
                            }
                        }
                    }

                    $uniqueSerialCodes = array_unique($invalidSerialCodes);

                    if (! empty($uniqueSerialCodes)) {
                        Notification::make()
                            ->title('Invalid Serial Numbers Found')
                            ->body('The following serial numbers should contain minimum 9 digit (and maximum 20 digit) alpha numeric values:<br>'.implode(', ', $uniqueSerialCodes))
                            ->danger()
                            ->duration(5000)
                            ->send();

                        // if ($disk->exists($filePath)) {
                        //     $disk->delete($filePath);
                        // }
                        $this->dispatch('loadData', '', $plantId);
                        $this->form->fill([
                            'plant_id' => $plantId,
                            'plant' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'pallet_number' => null,
                            'serial_number' => null,
                            'sno_quantity' => 0,
                            'scan_quantity' => 0,
                            'pend_quantity' => 0,
                            'created_by' => $operatorName,
                            'scanned_by' => $operatorName,
                        ]);

                        return;
                    }

                    $duplicateSerialCodes = array_unique($duplicateSerials);

                    if (! empty($duplicateSerialCodes)) {
                        Notification::make()
                            ->title('Duplicate Serial Numbers Found')
                            ->body('The following serial numbers are already exist in imported excel:<br>'.implode(', ', $duplicateSerialCodes))
                            ->danger()
                            ->duration(5000)
                            ->send();

                        // if ($disk->exists($filePath))
                        // {
                        //     $disk->delete($filePath);
                        // }
                        $this->dispatch('loadData', '', $plantId);
                        $this->form->fill([
                            'plant_id' => $plantId,
                            'plant' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'pallet_number' => null,
                            'serial_number' => null,
                            'sno_quantity' => 0,
                            'scan_quantity' => 0,
                            'pend_quantity' => 0,
                            'created_by' => $operatorName,
                            'scanned_by' => $operatorName,
                        ]);

                        return;
                    }

                    if (! $validRowsFound) {
                        Notification::make()
                            ->title('Invalid Updated Locator Invoice Found')
                            ->body('Uploaded excel sheet is empty or<br>contains no valid data.')
                            ->danger()
                            ->duration(5000)
                            ->send();

                        if ($disk->exists($filePath)) {
                            $disk->delete($filePath);
                        }
                        $this->dispatch('loadData', '', $plantId);
                        $this->form->fill([
                            'plant_id' => $plantId,
                            'plant' => $plantId,
                            'invoice_number' => null,
                            'pallet_number' => null,
                            'serial_number' => null,
                            'sno_quantity' => 0,
                            'scan_quantity' => 0,
                            'pend_quantity' => 0,
                            'created_by' => $operatorName,
                            'scanned_by' => $operatorName,
                        ]);

                        return;
                    }

                    $serialsToCheck = $seenSerialNumbers;

                    $existingSerials = LocatorInvoiceValidation::whereIn('serial_number', $serialsToCheck)
                        ->where('invoice_number', '!=', $invoiceNumber)
                        ->where('plant_id', $plantId)
                        ->pluck('serial_number')
                        ->toArray();

                    if (! empty($existingSerials)) {
                        Notification::make()
                            ->title('Duplicate Serial Numbers Found')
                            ->body('The following serial numbers already exist with a different invoice number:<br>'.implode(', ', $existingSerials))
                            ->danger()
                            ->duration(5000)
                            ->send();

                        // if ($disk->exists($filePath)) {
                        //     $disk->delete($filePath);
                        // }
                        $this->dispatch('loadData', '', $plantId);
                        $this->form->fill([
                            'plant_id' => $plantId,
                            'plant' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'pallet_number' => null,
                            'serial_number' => null,
                            'sno_quantity' => 0,
                            'scan_quantity' => 0,
                            'pend_quantity' => 0,
                            'created_by' => $operatorName,
                            'scanned_by' => $operatorName,
                        ]);

                        return;
                    } else {
                        $createdAny = false;
                        foreach ($seenSerialNumbers as $serialNumber) {
                            $existingRecord = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)
                                ->where('serial_number', $serialNumber)
                                ->where('plant_id', $plantId)
                                ->first();

                            if ($existingRecord) {
                                if ($existingRecord->scanned_status != null && $existingRecord->scanned_status != '') {
                                    continue;
                                }
                                $existingRecord->forceDelete();
                            }

                            LocatorInvoiceValidation::create([
                                'plant_id' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'serial_number' => $serialNumber,
                                'created_by' => $operatorName,
                                'updated_by' => $operatorName,
                            ]);

                            $createdAny = true;
                        }

                        if ($createdAny) {
                            Notification::make()
                                ->title('Success: Invoice updated successfully.')
                                ->success()
                                ->duration(500)
                                ->send();
                            Notification::make()
                                ->title("Start the scanning process for updated invoice number '$invoiceNumber'!")
                                ->info()
                                ->duration(800)
                                ->send();

                            // if ($disk->exists($filePath))
                            // {
                            //     $disk->delete($filePath);
                            // }

                            $snoCount = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->count();

                            $pendingCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->whereNull('scanned_status')->orWhere('scanned_status', '=', '')->count();

                            $scannedCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('scanned_status', '=', 'Scanned')->count();

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'plant' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'update_invoice' => 0,
                                'pallet_number' => null,
                                'serial_number' => null,
                                'sno_quantity' => $snoCount,
                                'scan_quantity' => $scannedCount,
                                'pend_quantity' => $pendingCount,
                                'created_by' => $operatorName,
                                'scanned_by' => $operatorName,
                            ]);
                        }

                        $this->dispatch('loadData', $invoiceNumber, $plantId);
                    }
                }
            } else {
                Notification::make()
                    ->title("Start the scanning process for scanned invoice number '$invoiceNumber'!")
                    ->info()
                    ->duration(1000)
                    ->send();

                $snoCount = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->count();

                $pendingCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->whereNull('scanned_status')->orWhere('scanned_status', '=', '')->count();

                $scannedCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('scanned_status', '=', 'Scanned')->count();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'plant' => $plantId,
                    'invoice_number' => $invoiceNumber,
                    'pallet_number' => null,
                    'serial_number' => null,
                    'sno_quantity' => $snoCount,
                    'scan_quantity' => $scannedCount,
                    'pend_quantity' => $pendingCount,
                    'created_by' => $operatorName,
                    'scanned_by' => $operatorName,
                ]);

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

        } catch (\Exception $e) {
            Notification::make()
                ->title('Error: Locator invoice insertion (or updation).')
                ->body($e->getMessage())
                ->danger()
                ->duration(5000)
                ->send();

            $snoCount = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->count();

            $pendingCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->whereNull('scanned_status')->orWhere('scanned_status', '=', '')->count();

            $scannedCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('scanned_status', '=', 'Scanned')->count();

            $this->dispatch('loadData', $invoiceNumber, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'serial_number' => null,
                'sno_quantity' => $snoCount,
                'scan_quantity' => $scannedCount,
                'pend_quantity' => $pendingCount,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);
        }
    }

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

        $this->plantId = $plantId;

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

        $this->pallet_number = $palletNumber;

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

        $this->serial_number = $serialNumber;

        $invoiceNumber = trim($this->form->getState()['invoice_number']);

        $this->invoice_number = $invoiceNumber;

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

        $updateLocatorStatus = $this->form->getState()['update_locator_invoice'] ?? null;

        $PalletSerialNumbers = [];

        $InvoiceSerialNumbers = [];

        $matchedSerialNumbers = [];

        $UnknownSerialNumbers = [];

        $filename = $invoiceNumber.'.xlsx';

        $folderPath = 'ExportDispatch'; // Configuration::where('c_name', 'INVOICE_FOLDER_PATH')->where('plant_id', $plantId)->value('c_value');

        $fullFolderPath = "uploads/$folderPath";

        $directory = $fullFolderPath;
        $disk = Storage::disk('local');
        $filePath = $directory.'/'.$filename;

        $invExist = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->first();
        if (! $invExist) {
            Notification::make()
                ->title('Invoice Not Found')
                ->body("Scanned invoice number '$invoiceNumber' does not exist in invoice table!<br>Import the scanned 'Invoice' file to proceed..!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $invoiceNumber, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => null,
                'pallet_number' => null,
                'serial_number' => null,
                'sno_quantity' => 0,
                'scan_quantity' => 0,
                'pend_quantity' => 0,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        } else {
            $records = LocatorInvoiceValidation::where('plant_id', $plantId)
                ->where('invoice_number', $invoiceNumber)
                ->get();

            $allScanned = true;

            foreach ($records as $record) {
                if (($record->scanned_status == null) || trim($record->scanned_status) == '') {
                    $allScanned = false;
                    break;
                }
            }

            if (count($records) > 0 && $allScanned) {
                Notification::make()
                    ->title('Completed: Locator Invoice')
                    ->body("Invoice number '$invoiceNumber' completed the scanning process.<br>Scan the next 'Locator Invoice' to proceed..!")
                    ->info()
                    ->duration(1000)
                    ->send();

                if ($disk->exists($filePath)) {
                    $disk->delete($filePath);
                }
                $this->dispatch('loadData', '', $plantId);
                $this->form->fill([
                    'plant_id' => $plantId,
                    'plant' => $plantId,
                    'invoice_number' => null,
                    'pallet_number' => null,
                    'serial_number' => null,
                    'sno_quantity' => 0,
                    'scan_quantity' => 0,
                    'pend_quantity' => 0,
                    'created_by' => $operatorName,
                    'scanned_by' => $operatorName,
                ]);

                return;
            }
        }

        $snoCount = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->count();

        $pendingCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->whereNull('scanned_status')->orWhere('scanned_status', '=', '')->count();

        $scannedCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('scanned_status', '=', 'Scanned')->count();

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

            $this->dispatch('loadData', $invoiceNumber, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'update_invoice' => 0,
                'serial_number' => null,
                'sno_quantity' => $snoCount,
                'scan_quantity' => $scannedCount,
                'pend_quantity' => $pendingCount,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        }

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

            $this->dispatch('loadData', $invoiceNumber, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'update_invoice' => 0,
                'serial_number' => null,
                'sno_quantity' => $snoCount,
                'scan_quantity' => $scannedCount,
                'pend_quantity' => $pendingCount,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        }

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

        if (! $palletRecord) {
            Notification::make()
                ->title("Pallet number '{$palletNumber}' does not exist in pallet table.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $invoiceNumber, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'update_invoice' => 0,
                'serial_number' => null,
                'sno_quantity' => $snoCount,
                'scan_quantity' => $scannedCount,
                'pend_quantity' => $pendingCount,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        }

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

        $allCompleted = true;
        foreach ($palletRecords as $record) {
            if ($record->pallet_status != 'Completed') {
                $allCompleted = false;
                break;
            }
        }

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

            $this->dispatch('loadData', $invoiceNumber, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'update_invoice' => 0,
                'serial_number' => null,
                'sno_quantity' => $snoCount,
                'scan_quantity' => $scannedCount,
                'pend_quantity' => $pendingCount,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        }

        if ($allCompleted) {
            $PalletSerialNumbers = $palletRecords->pluck('serial_number')
                ->map(function ($serial) {
                    return trim($serial);
                })
                ->all();

            $InvoiceSerialNumbers = LocatorInvoiceValidation::where('plant_id', $plantId)
                ->where('invoice_number', $invoiceNumber)
                ->where(function ($query) {
                    $query->where('scanned_status', '=', '')
                        ->orWhereNull('scanned_status');
                })
                ->pluck('serial_number')
                ->all();

            $matchedSerialNumbers = array_intersect($PalletSerialNumbers, $InvoiceSerialNumbers);

            if (empty($matchedSerialNumbers)) {
                Notification::make()
                    ->title("Scanned pallet number '$palletNumber' does not have invoice serial numbers.<br>Scan the valid exist pallet number to start the scanning process..!")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadData', $invoiceNumber, $plantId);
                $this->form->fill([
                    'plant_id' => $plantId,
                    'plant' => $plantId,
                    'invoice_number' => $invoiceNumber,
                    'pallet_number' => null,
                    'update_invoice' => 0,
                    'serial_number' => null,
                    'sno_quantity' => $snoCount,
                    'scan_quantity' => $scannedCount,
                    'pend_quantity' => $pendingCount,
                    'created_by' => $operatorName,
                    'scanned_by' => $operatorName,
                ]);

                return;
            }

            $UnknownSerialNumbers = array_diff($PalletSerialNumbers, $InvoiceSerialNumbers);
            // $matchedSerialNumbers = array_unique(array_merge($InvoiceSerialNumbers, $PalletSerialNumbers));

            if (! empty($UnknownSerialNumbers)) {
                // hereToContinue...
                if ($updateLocatorStatus == null || $updateLocatorStatus == 0) {
                    // $missingSerialsString = "Missing serial numbers:\n" . implode(",\n", $missingSerialNumbers);
                    $missingSerialsString = "Scanned pallet number '$palletNumber' has '".count($PalletSerialNumbers)."' serial numbers.<br><br>But, below mentioned '".count($matchedSerialNumbers)."' serial numbers only exist in invoice,<br>".implode(', ', $matchedSerialNumbers)."<br><br>Press 'Yes' and Click 'Enter' in the pallet text box to proceed with existing serial number!<br><br>Press 'No' to cancel the scanning process!";

                    if (count($matchedSerialNumbers) > 10) {
                        // $missingSerialsString = "Missing serial numbers: " . count($missingSerialNumbers);
                        $missingSerialsString = "Scanned pallet number '$palletNumber' has '".count($PalletSerialNumbers)."' serial numbers.<br><br>But, '".count($matchedSerialNumbers)."' serial numbers only exist in invoice,<br><br>Press 'Yes' and Click 'Enter' in the pallet text box to proceed with existing serial number!<br><br>Press 'No' to cancel the scanning process!";
                    }

                    // $body = "Scanned pallet number '$palletNumber' has ".$missingSerialsString."<br>Do you want to skip missing serial numbers?<br>Then Press 'Yes' and Click 'Enter'.";

                    Notification::make()
                        ->title('Partial Pallet Serial Numbers Found')
                        ->body($missingSerialsString)
                        ->danger()
                        ->duration(5000)
                        ->send();

                    $this->dispatch('loadData', $invoiceNumber, $plantId);
                    $this->form->fill([
                        'plant_id' => $plantId,
                        'plant' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'pallet_number' => $palletNumber,
                        'update_invoice' => 0,
                        'serial_number' => null,
                        'sno_quantity' => $snoCount,
                        'scan_quantity' => $scannedCount,
                        'pend_quantity' => $pendingCount,
                        'created_by' => $operatorName,
                        'scanned_by' => $operatorName,
                    ]);
                }
            } else {
                $updLocNam = '';
                foreach ($matchedSerialNumbers as $serial) {
                    $palletRecord = PalletValidation::where('plant_id', $plantId)->where('pallet_number', $palletNumber)->where('serial_number', $serial)->first();
                    $invoiceRecord = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->where('serial_number', $serial)->first();

                    if ($invoiceRecord) {
                        $invoiceRecord->scanned_status = 'Scanned';
                        $invoiceRecord->pallet_number = $palletNumber;
                        $invoiceRecord->locator_number = $palletRecord->locator_number;
                        $invoiceRecord->scanned_at = now();
                        $invoiceRecord->scanned_by = $operatorName;
                        $invoiceRecord->save();
                    }

                    if ($updLocNam == '' || $updLocNam == null) {
                        $updLocNam = $palletRecord->locator_number;
                    }

                    // PalletValidation::where('plant_id', $plantId)->where('pallet_number', $palletNumber)->where('serial_number', $serial)->forceDelete();
                    $palletRecord->forceDelete();
                }

                if ($updLocNam != '' && $updLocNam != null) {
                    $locator = Locator::where('locator_number', $updLocNam)->where('plant_id', $plantId)
                        ->first();

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

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

                Notification::make()
                    ->title("All Serial numbers are moved into invoice from the pallet number '$palletNumber'.<br>Scan the next exist pallet number to start the scanning process..!")
                    ->success()
                    ->duration(500)
                    ->send();

                $records = LocatorInvoiceValidation::where('plant_id', $plantId)
                    ->where('invoice_number', $invoiceNumber)
                    ->get();

                $allScanned = true;
                foreach ($records as $record) {
                    if (($record->scanned_status == null) || trim($record->scanned_status) == '') {
                        $allScanned = false;
                        break;
                    }
                }

                if (count($records) > 0 && $allScanned) {
                    Notification::make()
                        ->title('Completed: Locator Invoice')
                        ->body("Invoice number '$invoiceNumber' completed the scanning process.<br>Scan the next 'Locator Invoice' to proceed..!")
                        ->info()
                        ->duration(1000)
                        ->send();

                    if ($disk->exists($filePath)) {
                        $disk->delete($filePath);
                    }

                    $this->dispatch('loadData', '', $plantId);
                    $this->form->fill([
                        'plant_id' => $plantId,
                        'plant' => $plantId,
                        'invoice_number' => null,
                        'pallet_number' => null,
                        'update_invoice' => 0,
                        'serial_number' => null,
                        'sno_quantity' => 0,
                        'scan_quantity' => 0,
                        'pend_quantity' => 0,
                        'created_by' => $operatorName,
                        'scanned_by' => $operatorName,
                    ]);

                    return;
                } else {
                    $pendingCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->whereNull('scanned_status')->orWhere('scanned_status', '=', '')->count();

                    $scannedCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('scanned_status', '=', 'Scanned')->count();

                    $this->dispatch('loadData', $invoiceNumber, $plantId);
                    $this->form->fill([
                        'plant_id' => $plantId,
                        'plant' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'pallet_number' => null,
                        'update_invoice' => 0,
                        'serial_number' => null,
                        'sno_quantity' => $snoCount,
                        'scan_quantity' => $scannedCount,
                        'pend_quantity' => $pendingCount,
                        'created_by' => $operatorName,
                        'scanned_by' => $operatorName,
                    ]);

                    return;
                }
            }
        }

        if ($updateLocatorStatus == 1) {
            if ($allCompleted) {
                foreach ($matchedSerialNumbers as $serial) {
                    $palletRecord = PalletValidation::where('plant_id', $plantId)->where('pallet_number', $palletNumber)->where('serial_number', $serial)->first();
                    $invoiceRecord = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->where('serial_number', $serial)->first();

                    if ($invoiceRecord) {
                        $invoiceRecord->scanned_status = 'Scanned';
                        $invoiceRecord->pallet_number = $palletNumber;
                        $invoiceRecord->locator_number = $palletRecord->locator_number;
                        $invoiceRecord->scanned_at = now();
                        $invoiceRecord->scanned_by = $operatorName;
                        $invoiceRecord->save();
                    }

                    // PalletValidation::where('plant_id', $plantId)->where('pallet_number', $palletNumber)->where('serial_number', $serial)->forceDelete();
                    $palletRecord->forceDelete();
                }

                $succMsgStr = "Below mentioned '".count($matchedSerialNumbers)."' Serial numbers are moved into invoice from the pallet number '$palletNumber'.<br><br>".implode(', ', $matchedSerialNumbers).'<br><br>Scan the next exist pallet number to start the scanning process..!';

                if (count($matchedSerialNumbers) > 10) {
                    $succMsgStr = "'".count($matchedSerialNumbers)."' Serial numbers are moved into invoice from the pallet number '$palletNumber'.<br>Scan the next exist pallet number to start the scanning process..!";
                }

                Notification::make()
                    ->title($succMsgStr)
                    ->success()
                    ->duration(500)
                    ->send();

                $records = LocatorInvoiceValidation::where('plant_id', $plantId)
                    ->where('invoice_number', $invoiceNumber)
                    ->get();

                $allScanned = true;
                foreach ($records as $record) {
                    if (($record->scanned_status == null) || trim($record->scanned_status) == '') {
                        $allScanned = false;
                        break;
                    }
                }

                if (count($records) > 0 && $allScanned) {
                    Notification::make()
                        ->title('Completed: Locator Invoice')
                        ->body("Invoice number '$invoiceNumber' completed the scanning process.<br>Scan the next 'Locator Invoice' to proceed..!")
                        ->info()
                        ->duration(1000)
                        ->send();

                    if ($disk->exists($filePath)) {
                        $disk->delete($filePath);
                    }

                    $this->dispatch('loadData', '', $plantId);
                    $this->form->fill([
                        'plant_id' => $plantId,
                        'plant' => $plantId,
                        'invoice_number' => null,
                        'pallet_number' => null,
                        'update_invoice' => 0,
                        'serial_number' => null,
                        'sno_quantity' => 0,
                        'scan_quantity' => 0,
                        'pend_quantity' => 0,
                        'created_by' => $operatorName,
                        'scanned_by' => $operatorName,
                    ]);

                    return;
                } else {
                    $pendingCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->whereNull('scanned_status')->orWhere('scanned_status', '=', '')->count();

                    $scannedCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('scanned_status', '=', 'Scanned')->count();

                    $this->dispatch('loadData', $invoiceNumber, $plantId);
                    $this->form->fill([
                        'plant_id' => $plantId,
                        'plant' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'pallet_number' => null,
                        'update_invoice' => 0,
                        'serial_number' => null,
                        'sno_quantity' => $snoCount,
                        'scan_quantity' => $scannedCount,
                        'pend_quantity' => $pendingCount,
                        'created_by' => $operatorName,
                        'scanned_by' => $operatorName,
                    ]);

                    return;
                }
            } elseif ($updateLocatorStatus == 0) {
                $updateLocatorStatus == null;
            }
        }
    }

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

        $this->plantId = $plantId;

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

        $this->pallet_number = $palletNumber;

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

        $this->serial_number = $serialNumber;

        $invoiceNumber = trim($this->form->getState()['invoice_number']);

        $this->invoice_number = $invoiceNumber;

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

        $updateLocatorStatus = $this->form->getState()['update_locator_invoice'] ?? null;

        $existSerialNumber = '';

        $InvoiceSerialNumber = '';

        $filename = $invoiceNumber.'.xlsx';

        $folderPath = 'ExportDispatch'; // Configuration::where('c_name', 'INVOICE_FOLDER_PATH')->where('plant_id', $plantId)->value('c_value');

        $fullFolderPath = "uploads/$folderPath";

        $directory = $fullFolderPath;
        $disk = Storage::disk('local');
        $filePath = $directory.'/'.$filename;

        $invExist = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->first();
        if (! $invExist) {
            Notification::make()
                ->title('Invoice Not Found')
                ->body("Scanned invoice number '$invoiceNumber' does not exist in invoice table!<br>Import the scanned 'Invoice' file to proceed..!")
                ->danger()
                ->duration(5000)
                ->send();

            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'serial_number' => null,
                'sno_quantity' => 0,
                'scan_quantity' => 0,
                'pend_quantity' => 0,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        } else {
            $records = LocatorInvoiceValidation::where('plant_id', $plantId)
                ->where('invoice_number', $invoiceNumber)
                ->get();

            $allScanned = true;

            foreach ($records as $record) {
                if (($record->scanned_status == null) || trim($record->scanned_status) == '') {
                    $allScanned = false;
                    break;
                }
            }

            if (count($records) > 0 && $allScanned) {
                Notification::make()
                    ->title('Completed: Locator Invoice')
                    ->body("Invoice number '$invoiceNumber' completed the scanning process.<br>Scan the next 'Locator Invoice' to proceed..!")
                    ->info()
                    ->duration(1000)
                    ->send();

                if ($disk->exists($filePath)) {
                    $disk->delete($filePath);
                }

                $this->dispatch('loadData', '', $plantId);
                $this->form->fill([
                    'plant_id' => $plantId,
                    'plant' => $plantId,
                    'invoice_number' => null,
                    'pallet_number' => null,
                    'serial_number' => null,
                    'sno_quantity' => 0,
                    'scan_quantity' => 0,
                    'pend_quantity' => 0,
                    'created_by' => $operatorName,
                    'scanned_by' => $operatorName,
                ]);

                return;
            }
        }

        $snoCount = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->count();

        $pendingCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->whereNull('scanned_status')->orWhere('scanned_status', '=', '')->count();

        $scannedCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('scanned_status', '=', 'Scanned')->count();

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

            $this->dispatch('loadData', $invoiceNumber, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'update_invoice' => 0,
                'serial_number' => null,
                'sno_quantity' => $snoCount,
                'scan_quantity' => $scannedCount,
                'pend_quantity' => $pendingCount,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        } elseif (strlen($serialNumber) < 9 || strlen($serialNumber) > 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', $invoiceNumber, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'serial_number' => null,
                'sno_quantity' => $snoCount,
                'scan_quantity' => $scannedCount,
                'pend_quantity' => $pendingCount,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        } elseif (! ctype_alnum($serialNumber)) {
            Notification::make()
                ->title('Invalid: Serial Number')
                ->body('Serial number must contain alpha-numeric values only.')
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $invoiceNumber, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'serial_number' => null,
                'sno_quantity' => $snoCount,
                'scan_quantity' => $scannedCount,
                'pend_quantity' => $pendingCount,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        }

        $InvoiceSerialNumber = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->where('serial_number', $serialNumber)->first();

        if (! $InvoiceSerialNumber) {
            Notification::make()
                ->title('Unknown: Serial Number')
                ->body("Serial number '{$serialNumber}' does not exist in invoice number '$invoiceNumber'.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $invoiceNumber, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'serial_number' => null,
                'sno_quantity' => $snoCount,
                'scan_quantity' => $scannedCount,
                'pend_quantity' => $pendingCount,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        } elseif ($InvoiceSerialNumber->scanned_status != null && $InvoiceSerialNumber->scanned_status != '') {
            Notification::make()
                ->title('Completed: Serial Number')
                ->body("Serial number '{$serialNumber}' already completed the scanning process for the invoice number '$invoiceNumber'.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $invoiceNumber, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'serial_number' => null,
                'sno_quantity' => $snoCount,
                'scan_quantity' => $scannedCount,
                'pend_quantity' => $pendingCount,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        }

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

        $updLocQty = false;
        $succMsg = "Scanned serial number '{$serialNumber}' is moved into invoice.<br><br>Scan the next exist serial number to start the scanning process..!";
        $existPallNum = $existSerialNumber->pallet_number ?? null;
        $existPallStat = $existSerialNumber->pallet_status ?? null;
        $existLocatNum = $existSerialNumber->locator_number ?? null;
        if (! $existSerialNumber) {
            // skip update locator quantity
            $updLocQty = false;
            Notification::make()
                ->title('Unknown: Serial Number')
                ->body("Serial number '{$serialNumber}' does not exist in pallet table.")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $invoiceNumber, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'serial_number' => null,
                'sno_quantity' => $snoCount,
                'scan_quantity' => $scannedCount,
                'pend_quantity' => $pendingCount,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        } elseif ($existPallNum == null || $existPallNum == '') {
            // skip update locator quantity
            $updLocQty = false;
            $succMsg = "Scanned serial number '{$serialNumber}' is moved into invoice from the locator number '$existLocatNum'.<br><br>Scan the next exist serial number to start the scanning process..!";
        } elseif ($existLocatNum == null || $existLocatNum == '') {
            if ($existPallStat == null || $existPallStat == '') {
                // skip update locator quantity
                $updLocQty = false;
                $succMsg = "Scanned serial number '{$serialNumber}' is moved into invoice from the pallet number '$existPallNum'.<br><br>Scan the next exist serial number to start the scanning process..!";
                Notification::make()
                    ->title('Incompleted Pallet: Serial Number')// Pallet number '{$existPallNum}' does not completed the master packing!
                    ->body("Serial number '{$serialNumber}' exist in pallet number '$existPallNum' and it does not completed the master packing!")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->dispatch('loadData', $invoiceNumber, $plantId);
                $this->form->fill([
                    'plant_id' => $plantId,
                    'plant' => $plantId,
                    'invoice_number' => $invoiceNumber,
                    'pallet_number' => null,
                    'serial_number' => null,
                    'sno_quantity' => $snoCount,
                    'scan_quantity' => $scannedCount,
                    'pend_quantity' => $pendingCount,
                    'created_by' => $operatorName,
                    'scanned_by' => $operatorName,
                ]);

                return;
            } else {
                // skip update locator quantity
                $updLocQty = false;
                $succMsg = "Scanned serial number '{$serialNumber}' is moved into invoice from the pallet number '$existPallNum'.<br><br>Scan the next exist serial number to start the scanning process..!";
            }
        } elseif ($existPallNum != null && $existPallNum != '' && $existLocatNum != null && $existLocatNum != '') {
            // update locator quantity based on condition
            $snoCount = PalletValidation::where('plant_id', $plantId)->where('pallet_number', $existPallNum)->count();
            if ($snoCount > 0 && $snoCount == 1) {
                $updLocQty = true;
            } else {
                $updLocQty = false;
            }
            $succMsg = "Scanned serial number '{$serialNumber}' is moved into invoice from the pallet number '$existPallNum' in the locator number '$existLocatNum'.<br><br>Scan the next exist serial number to start the scanning process..!";
        }

        if ($InvoiceSerialNumber) {
            $InvoiceSerialNumber->pallet_number = $existPallNum;
            $InvoiceSerialNumber->locator_number = $existLocatNum;
            $InvoiceSerialNumber->scanned_status = 'Scanned';
            $InvoiceSerialNumber->scanned_at = now();
            $InvoiceSerialNumber->scanned_by = $operatorName;
            $InvoiceSerialNumber->save();
            $existSerialNumber->forceDelete();

            if ($updLocQty) {
                // hereToContinue
                $locator = Locator::where('locator_number', $existLocatNum)->where('plant_id', $plantId)->first();

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

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

            Notification::make()
                ->title($succMsg)
                ->success()
                ->duration(500)
                ->send();

            $records = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->get();

            $allScanned = true;
            foreach ($records as $record) {
                if (($record->scanned_status == null) || trim($record->scanned_status) == '') {
                    $allScanned = false;
                    break;
                }
            }

            if (count($records) > 0 && $allScanned) {
                Notification::make()
                    ->title('Completed: Locator Invoice')
                    ->body("Invoice number '$invoiceNumber' completed the scanning process.<br>Scan the next 'Locator Invoice' to proceed..!")
                    ->info()
                    ->duration(1000)
                    ->send();

                if ($disk->exists($filePath)) {
                    $disk->delete($filePath);
                }

                $this->dispatch('loadData', '', $plantId);
                $this->form->fill([
                    'plant_id' => $plantId,
                    'plant' => $plantId,
                    'invoice_number' => null,
                    'pallet_number' => null,
                    'update_invoice' => 0,
                    'serial_number' => null,
                    'sno_quantity' => 0,
                    'scan_quantity' => 0,
                    'pend_quantity' => 0,
                    'created_by' => $operatorName,
                    'scanned_by' => $operatorName,
                ]);

                return;
            } else {
                $pendingCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->whereNull('scanned_status')->orWhere('scanned_status', '=', '')->count();

                $scannedCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('scanned_status', '=', 'Scanned')->count();

                $this->dispatch('loadData', $invoiceNumber, $plantId);
                $this->form->fill([
                    'plant_id' => $plantId,
                    'plant' => $plantId,
                    'invoice_number' => $invoiceNumber,
                    'pallet_number' => null,
                    'update_invoice' => 0,
                    'serial_number' => null,
                    'sno_quantity' => $snoCount,
                    'scan_quantity' => $scannedCount,
                    'pend_quantity' => $pendingCount,
                    'created_by' => $operatorName,
                    'scanned_by' => $operatorName,
                ]);

                return;
            }
        } else {
            Notification::make()
                ->title("Failed to check Serial number '{$serialNumber}' existence.<br>Scan the valid serial number to proceed...")
                ->danger()
                ->duration(5000)
                ->send();

            $this->dispatch('loadData', $invoiceNumber, $plantId);
            $this->form->fill([
                'plant_id' => $plantId,
                'plant' => $plantId,
                'invoice_number' => $invoiceNumber,
                'pallet_number' => null,
                'update_invoice' => 0,
                'serial_number' => null,
                'sno_quantity' => $snoCount,
                'scan_quantity' => $scannedCount,
                'pend_quantity' => $pendingCount,
                'created_by' => $operatorName,
                'scanned_by' => $operatorName,
            ]);

            return;
        }
    }

    public function getFormActions(): array
    {
        return [];
    }
}
