<?php

namespace App\Filament\Resources\InvoiceValidationResource\Pages;

use App\Filament\Resources\InvoiceValidationResource;
use App\Imports\ExcelImport;
use App\Mail\InvalidSerialMail;
use App\Models\AlertMailRule;
use App\Models\InvoiceValidation;
use App\Models\Item;
use App\Models\Plant;
use App\Models\StickerMaster;
use App\Models\WireMasterPacking;
use DB;
use Filament\Facades\Filament;
use Filament\Notifications\Notification;
use Filament\Pages\Concerns\ExposesTableToWidgets;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Livewire\Attributes\On;
use Maatwebsite\Excel\Facades\Excel;
use Str;

class CreateInvoiceValidation extends CreateRecord
{
    // use ExposesTableToWidgets;
    protected static string $resource = InvoiceValidationResource::class;

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

    public $invoice_number;

    public $invoice_data;

    public $invoiceData = [];

    public $scanned_quantity;

    public $total_quantity;

    public string $currentItemCode = '';

    public string $currentSerialNumber = '';

    public $plantId;

    public $hasQuanTyp = false;

    public $invoiceNumber;

    public bool $hasSearched = false;

    public bool $showCapacitorInput = false;

    public $excel_file;

    public $mInvoiceNo;

    public function getFormActions(): array
    {
        return [
            $this->getCancelFormAction(),
        ];
    }

    protected $listeners = [
        'updateScannedQuantity' => 'updateScannedQuantity',
    ];

    public function updateScannedQuantity()
    {
        $totQuan = InvoiceValidation::where('invoice_number', $this->invoiceNumber)->where('plant_id', $this->plantId)->count();
        $scanSQuan = InvoiceValidation::where('invoice_number', $this->invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $this->plantId)->count();

        // $this->dispatch('playNotificationSound');
        if ($totQuan == $scanSQuan) {
            $this->form->fill([
                'plant_id' => $this->plantId,
                'invoice_number' => null,
                'serial_number' => null,
                'total_quantity' => 0,
                'update_invoice' => false,
                'scanned_quantity' => 0,
            ]);
            $this->dispatch('refreshCompletedInvoice', invoiceNumber: $this->invoiceNumber, plantId: $this->plantId, isSerial: true);
        } else {
            $this->form->fill([
                'plant_id' => $this->plantId,
                'invoice_number' => $this->invoiceNumber,
                'serial_number' => null,
                'total_quantity' => $totQuan,
                'update_invoice' => false,
                'scanned_quantity' => $scanSQuan,
            ]);
            $this->dispatch('refreshInvoiceData', invoiceNumber: $this->invoiceNumber, plantId: $this->plantId, onCapFocus: false);
        }
    }

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

    public function processInvoice($invoiceNumber)
    {
        $invoiceNumber = trim($invoiceNumber);

        $parts = explode('.', $invoiceNumber);

        $this->showCapacitorInput = false;

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

        $operatorName = $user->name;

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

        $this->plantId = $plantId;

        $plant = Plant::find($plantId);
        $plantCode = $plant?->code ?? null;

        // ..GET SERIAL INVOICE API

        if (strlen($invoiceNumber) > 15) {

            $payloadJson = base64_decode(strtr($parts[1], '-_', '+/'));

            if (empty($payloadJson)) {
                Notification::make()
                    ->title('Invalid payload for scanned qr code.')
                    ->danger()
                    ->seconds(1)
                    ->send();

                return;
            }

            $payload = json_decode($payloadJson, true);

            if (! isset($payload['data'])) {
                Notification::make()
                    ->title('Invalid payload for scanned qr code.')
                    ->info()
                    ->seconds(1)
                    ->send();

                return;
            }

            $documentData = $payload['data'];

            if ($documentData == '' || $documentData == '') {
                Notification::make()
                    ->title('Invalid payload for scanned qr code.')
                    ->info()
                    ->seconds(1)
                    ->send();

                return;
            }

            // Extract DocNo
            preg_match('/"DocNo"\s*:\s*"([^"]+)"/', $documentData, $matches);

            if (! isset($matches[1])) {
                Notification::make()
                    ->title('Invoice number not found.')
                    ->info()
                    ->seconds(1)
                    ->send();

                return;
            }

            if (isset($matches[1])) {
                $invoiceNumber = strtoupper($matches[1]);
            }
        } else {
            $invoiceNumber = strtoupper($invoiceNumber);
        }

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

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

        $invoiceType = null;
        // $this->invoiceNumber = $this->invoiceNumber ?? $invoiceNumber;

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

        if (! $invoiceExist) {
            Notification::make()
                ->title('New invoice detected.')
                ->info()
                ->seconds(1)
                ->send();
            $this->dispatch('playNotificationSound');

            $this->form->fill([
                'plant_id' => $plantId,
                'invoice_number' => $invoiceNumber,
                'serial_number' => null,
                'total_quantity' => 0,
                'scanned_quantity' => 0,
            ]);

            $this->dispatch('refreshEmptyInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId);
        } else {
            $totQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
            $scanSQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();

            $totMQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNotNull('quantity')->where('plant_id', $plantId)->count(); // ->where('quantity', '!=', '')
            $scanMQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNotNull('serial_number')->where('serial_number', '!=', '')->where('plant_id', $plantId)->count();

            if ($totMQuan > 0) {
                $checkMat = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->latest('updated_at')->first(); // ->where('quantity', '!=', '')
                if (($checkMat?->stickerMaster->material_type ?? 0) == 3) {
                    $totMatQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->invoice_quantity ?? 0;
                    $scanMatQuan = number_format($totMatQuan - (InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->quantity ?? 0), 3, '.', ''); // ('updated_at', 'desc')
                } else {
                    $totMatQuan = $totMQuan;
                    $scanMatQuan = $scanMQuan;
                }

                $this->form->fill([
                    'plant_id' => $plantId,
                    'invoice_number' => $invoiceNumber,
                    'serial_number' => null,
                    'total_quantity' => $totMatQuan,
                    'scanned_quantity' => $scanMatQuan,
                ]);

                if ($totQuan == $scanMQuan) {
                    Notification::make()
                        ->title('Completed: Material Invoice')
                        ->body("Material invoice '$invoiceNumber' completed the scanning process.<br>Scan the next 'Material Invoice' to proceed!")
                        ->warning()
                        ->seconds(2)
                        ->send();
                    $this->dispatch('playNotificationSound');

                    $filename = $invoiceNumber.'.xlsx';
                    $directory = "uploads/temp/{$plantCode}";
                    $disk = Storage::disk('local');
                    $filePath = $directory.'/'.$filename;
                    // $fullPath = null;
                    if ($disk->exists($filePath)) {
                        // $fullPath = $disk->path($filePath);
                        $disk->delete($filePath);
                    }

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => null,
                        'serial_number' => null,
                        'total_quantity' => 0,
                        'update_invoice' => false,
                        'scanned_quantity' => 0,
                    ]);

                    $this->dispatch('refreshCompletedInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId, isSerial: false);
                } else {
                    Notification::make()
                        ->title('Start the scanning process!')
                        ->info()
                        ->seconds(1)
                        ->send();
                    $this->dispatch('playNotificationSound');
                    // $hasRecords = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->first()->stickerMasterRelation->material_type ?? null;
                    // $this->dispatch( (!empty($hasRecords) && $hasRecords) ? 'refreshMaterialInvoiceData' : 'refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId, onCapFocus: false); //$this->invoiceNumber
                    $this->dispatch('refreshMaterialInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId);

                    if ($updateStatus == '1') {
                        // 'Material invoice update in progress...';
                        $filename = $invoiceNumber.'.xlsx';
                        $directory = "uploads/temp/{$plantCode}";
                        $disk = Storage::disk('local');
                        $filePath = $directory.'/'.$filename;
                        $fullPath = $disk->path($filePath);

                        if ($fullPath && file_exists($fullPath)) {
                            // Now you can read/process the file here
                            $rows = Excel::toArray(null, $fullPath)[0];

                            if ((count($rows) - 1) <= 0) {
                                Notification::make()
                                    ->title('Records Not Found')
                                    ->body("Import the valid updated 'Material Invoice' file to proceed..!")
                                    ->danger()
                                    ->seconds(2)
                                    ->send();
                                $this->dispatch('playWarnSound');

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

                                return;
                            }

                            $invalidMatCodes = [];
                            $materialCodes = [];
                            $missingQuantities = [];
                            $invalidMatQuan = [];
                            $hasQuanTypIds = [];
                            $validRowsFound = false;

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

                                $materialCode = trim($row[0]);
                                $materialQuantity = trim($row[1]);

                                if (empty($materialCode) && empty($materialQuantity)) {
                                    continue;
                                }

                                if (! empty($materialCode)) {
                                    if (Str::length($materialCode) < 6 || ! ctype_alnum($materialCode)) {
                                        $invalidMatCodes[] = $materialCode;
                                    } else {
                                        if (empty($materialQuantity)) {
                                            $missingQuantities[] = $materialCode;
                                        } elseif (! is_numeric($materialQuantity)) {
                                            $invalidMatQuan[] = $materialCode;
                                        } elseif ($materialQuantity == 0) {
                                            $invalidMatQuan[] = $materialCode;
                                        } else {
                                            $materialCodes[] = $materialCode;
                                            $validRowsFound = true;
                                        }
                                    }
                                } else {
                                    continue;
                                }
                            }

                            $uniqueInvalidCodes = array_unique($invalidMatCodes);

                            if (! empty($uniqueInvalidCodes)) {
                                Notification::make()
                                    ->title('Invalid: Item Codes')
                                    ->body('The following item codes should contain minimum 6 digit alpha numeric values:<br>'.implode(', ', $uniqueInvalidCodes))
                                    ->danger()
                                    ->seconds(2)
                                    ->send();

                                $this->dispatch('playWarnSound');

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

                            $uniqueMissingQuanCodes = array_unique($missingQuantities);

                            if (! empty($uniqueMissingQuanCodes)) {
                                Notification::make()
                                    ->title('Missing Material Quantity')
                                    ->body("The following item codes doesn't have valid material quantity:<br>".implode(', ', $uniqueMissingQuanCodes))
                                    ->danger()
                                    ->seconds(2)
                                    ->send();

                                $this->dispatch('playWarnSound');

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

                            $uniqueInvalidMatQuan = array_unique($invalidMatQuan);

                            if (! empty($uniqueInvalidMatQuan)) {
                                Notification::make()
                                    ->title('Invalid Material Quantity')
                                    ->body("The following item codes doesn't have valid material quantity:<br>".implode(', ', $uniqueInvalidMatQuan))
                                    ->danger()
                                    ->seconds(2)
                                    ->send();

                                $this->dispatch('playWarnSound');

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

                            if (! $validRowsFound) {
                                Notification::make()
                                    ->title('Invalid Material Invoice')
                                    ->danger()  // This makes the notification red to indicate an error
                                    ->body('Uploaded Excel sheet is empty or<br>contains no valid data.')
                                    ->seconds(2)
                                    ->send();

                                $this->dispatch('playWarnSound');
                                if ($disk->exists($filePath)) {
                                    $disk->delete($filePath);
                                }

                                return;
                            }

                            $uniqueCodes = array_unique($materialCodes);

                            // itemNotFound
                            $matchedItems = StickerMaster::with('item')
                                ->whereHas('item', function ($query) use ($uniqueCodes) {
                                    $query->whereIn('code', $uniqueCodes);
                                })
                                ->get();

                            $matchedCodes = $matchedItems->pluck('item.code')->toArray();

                            $missingCodes = array_diff($uniqueCodes, $matchedCodes);

                            if (! empty($missingCodes)) {
                                $missingCount = count($missingCodes);

                                $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database." : 'The following item codes are not found in database:<br>'.implode(', ', $missingCodes);

                                Notification::make()
                                    ->title('Unknown: Item Codes')
                                    ->body($message)
                                    ->danger()
                                    ->seconds(2)
                                    ->send();
                                $this->dispatch('playWarnSound');

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

                            // plantNotFound
                            $matchedItems = StickerMaster::with('item')
                                ->whereHas('item', function ($query) use ($uniqueCodes, $plantId) {
                                    $query->whereIn('code', $uniqueCodes)->where('plant_id', $plantId);
                                })
                                ->get();

                            $matchedCodes = $matchedItems->pluck('item.code')->toArray();

                            $missingCodes = array_diff($uniqueCodes, $matchedCodes);

                            if (! empty($missingCodes)) {
                                $missingCount = count($missingCodes);

                                $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database for choosed plant." : 'The following item codes are not found in database for choosed plant:<br>'.implode(', ', $missingCodes);

                                Notification::make()
                                    ->title('Unknown: Item Codes')
                                    ->body($message)
                                    ->danger()
                                    ->seconds(2)
                                    ->send();
                                $this->dispatch('playWarnSound');

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

                            $invalidCodes = $matchedItems
                                ->filter(fn ($sticker) => empty($sticker->material_type))  // filter invalid
                                ->pluck('item.code')
                                ->toArray();

                            if (! empty($invalidCodes)) {
                                $missingCount = count($invalidCodes);

                                $message = $missingCount > 10 ? "'$missingCount' Serial Invoice item codes found." : "'Serial Invoice' item codes found:<br>".implode(', ', $invalidCodes);

                                Notification::make()
                                    ->title('Invalid: Item Codes')
                                    ->body($message)
                                    ->danger()
                                    ->seconds(2)
                                    ->send();
                                $this->dispatch('playWarnSound');

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

                            $nonNumericQtyCodes = [];
                            $zeroQtyCodes = [];
                            $notDivisibleCodes = [];
                            $hasQuanTyp = false;

                            foreach ($matchedItems as $sticker) {
                                $code = $sticker->item->code;
                                $materialType = $sticker->material_type;

                                if ($materialType == 2) {
                                    $bundleQty = $sticker->bundle_quantity ?? 0;
                                    $totalExcelQty = 0;

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

                                        $excelCode = trim($row[0]);
                                        $excelMatQty = trim($row[1]);

                                        if (empty($excelCode) || empty($excelMatQty)) {
                                            continue;
                                        }

                                        if ($excelCode == $code && is_numeric($excelMatQty)) {
                                            $totalExcelQty += $excelMatQty; // Sum up the quantities
                                        }
                                    }

                                    if ($totalExcelQty == 0) {
                                        $zeroQtyCodes[] = $code;
                                    } elseif (! is_numeric($totalExcelQty)) {
                                        $nonNumericQtyCodes[] = $code;  // Here you may want to check divisibility condition too
                                    } elseif ($bundleQty != 0 && $totalExcelQty % $bundleQty != 0) {
                                        $notDivisibleCodes[] = $code;
                                    }
                                } elseif ($materialType == 3) {
                                    $hasQuanTyp = true;
                                    $hasQuanTypIds[] = $sticker->id;
                                }
                            }

                            $showValidationNotification = function (array $codes, string $message) {
                                if (count($codes) == 0) {
                                    return;
                                }

                                $uniqueCodes = array_unique($codes);
                                $codeList = implode(', ', $uniqueCodes);

                                Notification::make()
                                    ->title('Invalid Bundle Quantity')
                                    ->body("$message<br>$codeList")
                                    ->danger()
                                    ->seconds(2)
                                    ->send();
                                $this->dispatch('playWarnSound');
                            };

                            $showValidationNotification($nonNumericQtyCodes, 'The following item codes contains invalid bundle quantity:');
                            $showValidationNotification($zeroQtyCodes, "The following item codes quantity should be greater than '0':");
                            $showValidationNotification($notDivisibleCodes, 'The following item codes quantity is not divisible by bundle quantity.');

                            if ($nonNumericQtyCodes || $zeroQtyCodes || $notDivisibleCodes) {
                                // if ($disk->exists($filePath)) {
                                //     $disk->delete($filePath);
                                // }
                                return;
                            } else {
                                $oldQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
                                $newQuan = -1;

                                $inserted = 0;
                                foreach ($matchedItems as $sticker) {
                                    if ($newQuan == -1 && ! $hasQuanTyp) {
                                        InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where(function ($query) {
                                            $query->whereNull('serial_number')->orWhere('serial_number', '');
                                        })
                                            ->forceDelete(); // ->delete();

                                        $newQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
                                    } elseif ($newQuan == -1 && $hasQuanTyp) {
                                        InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where(function ($query) {
                                            $query->whereNull('serial_number')->orWhere('serial_number', '');
                                        })->whereNotIn('sticker_master_id', $hasQuanTypIds)
                                            ->forceDelete(); // ->delete();

                                        $newQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
                                    }

                                    $code = $sticker->item->code;
                                    $materialType = $sticker->material_type;
                                    // $sticker = StickerMaster::where('plant_id', $plantId)->whereHas('item', function ($query) use ($code) { $query->where('plant_id', $this->plantId)->where('code', $code); })->first();

                                    if ($materialType == 1 || $materialType == 4) {
                                        $totalExcelQty = 0;

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

                                            $excelCode = trim($row[0]);
                                            $excelMatQty = trim($row[1]);

                                            if (empty($excelCode) || empty($excelMatQty)) {
                                                continue;
                                            }

                                            if ($excelCode == $code && is_numeric($excelMatQty)) {
                                                $totalExcelQty += $excelMatQty; // Sum up the quantities
                                            }
                                        }

                                        $existQty = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('sticker_master_id', $sticker->id)->count();

                                        if ($existQty < $totalExcelQty) {
                                            $newQty = $totalExcelQty - $existQty;
                                            for ($i = 0; $i < $newQty; $i++) {
                                                if ($sticker) {
                                                    InvoiceValidation::create([
                                                        'sticker_master_id' => $sticker->id,
                                                        'plant_id' => $plantId,
                                                        'invoice_number' => $invoiceNumber,
                                                        'invoice_quantity' => 1,
                                                        'quantity' => 1,
                                                        'operator_id' => $operatorName,
                                                        'created_by' => $operatorName,
                                                        'updated_by' => $operatorName,
                                                    ]);
                                                    $inserted++;
                                                }
                                            }
                                        }
                                    } elseif ($materialType == 2) {
                                        $bundleQty = $sticker->bundle_quantity;
                                        $totalExcelQty = 0;

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

                                            $excelCode = trim($row[0]);
                                            $excelMatQty = trim($row[1]);

                                            if (empty($excelCode) || empty($excelMatQty)) {
                                                continue;
                                            }

                                            if ($excelCode == $code && is_numeric($excelMatQty)) {
                                                $totalExcelQty += $excelMatQty; // Sum up the quantities
                                            }
                                        }

                                        $existQty = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('sticker_master_id', $sticker->id)->count();

                                        // for ($i = 0; $i < ($totalExcelQty/$bundleQty); $i++)
                                        $newTotQty = $totalExcelQty / $bundleQty;
                                        if ($existQty < $newTotQty) {
                                            $newQty = $newTotQty - $existQty;
                                            for ($i = 0; $i < $newQty; $i++) {
                                                if ($sticker) {
                                                    InvoiceValidation::create([
                                                        'sticker_master_id' => $sticker->id,
                                                        'plant_id' => $plantId,
                                                        'invoice_number' => $invoiceNumber,
                                                        'invoice_quantity' => $bundleQty,
                                                        'quantity' => $bundleQty,
                                                        'operator_id' => $operatorName,
                                                        'created_by' => $operatorName,
                                                        'updated_by' => $operatorName,
                                                    ]);
                                                    $inserted++;
                                                }
                                            }
                                        }
                                    } elseif ($materialType == 3) {
                                        $totalExcelQty = 0;

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

                                            $excelCode = trim($row[0]);
                                            $excelMatQty = trim($row[1]);

                                            if (empty($excelCode) || empty($excelMatQty)) {
                                                continue;
                                            }

                                            if ($excelCode == $code && is_numeric($excelMatQty)) {
                                                $totalExcelQty += $excelMatQty;
                                            }
                                        }

                                        $existEmpRecQty = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where(function ($query) {
                                            $query->whereNull('serial_number')->orWhere('serial_number', '');
                                        })->where('sticker_master_id', $sticker->id)->first();
                                        $existEmpQty = $existEmpRecQty ? $existEmpRecQty->quantity : 0;

                                        $existComQty = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where(function ($query) {
                                            $query->whereNotNull('serial_number')->where('serial_number', '!=', '');
                                        })
                                            ->where('sticker_master_id', $sticker->id)
                                            ->sum(column: 'quantity');
                                        $existComQty = $existComQty ? $existComQty : 0;

                                        // 8 = 3 + 5  // 8 = 5 + 3  // 8 = 0 + 8 // 8 = 8 + 0
                                        // 8 = 3 + 5  // 8 = 5 + 3  // 8 = 0 + 8 // 8 = 8 + 0
                                        // 0 = 0 + 0
                                        // 4 = 1.5 + 2.5
                                        $existQty = $existEmpQty + $existComQty;

                                        // 8 <= 11  // 8 <= 8  // 8 <= 11  // 8 <= 9
                                        // 8 <= 7  // 8 <= 7  // 8 <= 7  // 8 <= 7
                                        // 0 <= 5
                                        // 4 <= 2

                                        if ($existQty <= $totalExcelQty) {
                                            // 6 = 11 - 5  // 5 = 8 - 3  // 3 = 11 - 8 // 9 = 9 - 0
                                            // 5 = 5 - 0
                                            $newInsQty = $totalExcelQty - $existComQty;

                                            // 3 > 0  // 5 > 0  // 0 > 0 // 8 > 0
                                            // 0 > 0
                                            if ($existEmpQty > 0) { // update
                                                // 3 = 6 // 5 = 5 // 0 = 3 // 8 = 9
                                                // 0 = 5
                                                if ($existEmpQty == $newInsQty) {
                                                    continue;
                                                }
                                                // $existEmpRecQty->delete();
                                                $existEmpRecQty->update([
                                                    'quantity' => $newInsQty,
                                                    'operator_id' => $operatorName,
                                                    'updated_by' => $operatorName,
                                                    'updated_at' => now(),
                                                ]);

                                                InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('sticker_master_id', $sticker->id)
                                                    ->update([
                                                        'invoice_quantity' => $totalExcelQty,
                                                    ]);

                                                $newQuan--;
                                                $inserted++;
                                            } elseif ($newInsQty > 0) { // if ($sticker) // create
                                                InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('sticker_master_id', $sticker->id)
                                                    ->update([
                                                        'invoice_quantity' => $totalExcelQty,
                                                    ]);

                                                InvoiceValidation::create([
                                                    'sticker_master_id' => $sticker->id,
                                                    'plant_id' => $plantId,
                                                    'invoice_number' => $invoiceNumber,
                                                    'invoice_quantity' => $totalExcelQty,
                                                    'quantity' => $newInsQty,
                                                    'operator_id' => $operatorName,
                                                    'created_by' => $operatorName,
                                                    'updated_by' => $operatorName,
                                                ]);

                                                $inserted++;
                                            }
                                        }
                                        // 8 > 7  // 8 > 7 // 8 > 7 // 8 > 7
                                        // 4 > 2
                                        else {
                                            // 2 = 7 - 5 // 4 = 7 - 3 // -1 = 7 - 8 // 7 = 7 - 0
                                            // -0.5 = 2 - 2.5 //
                                            $newInsQty = $totalExcelQty - $existComQty;

                                            // 3 > 0 // 5 > 0 // 0 > 0 // 8 > 0
                                            // 1.5 > 0 //
                                            if ($newInsQty > 0 && $existEmpQty > 0) { // update
                                                // 3 = 2 // 5 = 4 // 0 = -1 // 8 = 7
                                                // 1.5 == -0.5 //
                                                if ($existEmpQty == $newInsQty) {
                                                    continue;
                                                }
                                                // $existEmpRecQty->delete();
                                                $existEmpRecQty->update([
                                                    'quantity' => $newInsQty,
                                                    'operator_id' => $operatorName,
                                                    'updated_by' => $operatorName,
                                                    'updated_at' => now(),
                                                ]);

                                                InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('sticker_master_id', $sticker->id)
                                                    ->update([
                                                        'invoice_quantity' => $totalExcelQty,
                                                    ]);

                                                $newQuan--;
                                                $inserted++;
                                            } elseif ($newInsQty > 0) { // create
                                                InvoiceValidation::create([
                                                    'sticker_master_id' => $sticker->id,
                                                    'plant_id' => $plantId,
                                                    'invoice_number' => $invoiceNumber,
                                                    'invoice_quantity' => $totalExcelQty,
                                                    'quantity' => $newInsQty,
                                                    'operator_id' => $operatorName,
                                                    'created_by' => $operatorName,
                                                    'updated_by' => $operatorName,
                                                ]);

                                                InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->where('sticker_master_id', $sticker->id)
                                                    ->update([
                                                        'invoice_quantity' => $totalExcelQty,
                                                    ]);

                                                $inserted++;
                                            }
                                        }
                                    }
                                }

                                if ($inserted > 0 || $oldQuan != $newQuan) {
                                    Notification::make()
                                        ->title('Material invoice successfully updated.')
                                        ->success()
                                        ->seconds(1)
                                        ->send();

                                    Notification::make()
                                        ->title('Start the scanning process!')
                                        ->body("'$inserted' new material invoice records were inserted.")
                                        ->info()
                                        // ->success()
                                        ->seconds(1)
                                        ->send();
                                    $this->dispatch('playNotificationSound');

                                    InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->update(['updated_by' => $operatorName]); // 'updated_at' => now(),

                                    // Update total quantity in the form
                                    $totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
                                    $scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNotNull('serial_number')->where('serial_number', '!=', '')->where('plant_id', $plantId)->count();

                                    $checkMat = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->latest('updated_at')->first(); // ->where('quantity', '!=', '')
                                    if (($checkMat?->stickerMaster->material_type ?? 0) == 3) {
                                        $totMatQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->invoice_quantity ?? 0;
                                        $scanMatQuan = number_format($totMatQuan - (InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->quantity ?? 0), 3, '.', ''); // ('updated_at', 'desc')
                                    } else {
                                        $totMatQuan = $totalQuantity;
                                        $scanMatQuan = $scannedQuantity;
                                    }

                                    $this->form->fill([
                                        'plant_id' => $plantId,
                                        'invoice_number' => $invoiceNumber,
                                        'serial_number' => null,
                                        'total_quantity' => $totMatQuan,
                                        'scanned_quantity' => $scanMatQuan,
                                    ]);

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

                                        $this->dispatch('refreshCompletedInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId, isSerial: false);
                                    } else {
                                        // if ($disk->exists($filePath)) {
                                        //     $disk->delete($filePath);
                                        // }

                                        $this->dispatch('refreshMaterialInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId);
                                    }
                                } else {
                                    Notification::make()
                                        ->title('Update Failed: Material Invoice')
                                        ->body("No new records were inserted for Material Invoice : '$invoiceNumber'.")
                                        ->danger()
                                        ->seconds(2)
                                        ->send();
                                    $this->dispatch('playWarnSound');

                                    $totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
                                    $scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNotNull('serial_number')->where('serial_number', '!=', '')->where('plant_id', $plantId)->count();

                                    $checkMat = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->latest('updated_at')->first(); // ->where('quantity', '!=', '')
                                    if (($checkMat?->stickerMaster->material_type ?? 0) == 3) {
                                        $totMatQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->invoice_quantity ?? 0;
                                        $scanMatQuan = number_format($totMatQuan - (InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->quantity ?? 0), 3, '.', ''); // ('updated_at', 'desc')
                                    } else {
                                        $totMatQuan = $totalQuantity;
                                        $scanMatQuan = $scannedQuantity;
                                    }

                                    $this->form->fill([
                                        'plant_id' => $plantId,
                                        'invoice_number' => $invoiceNumber,
                                        'serial_number' => null,
                                        'total_quantity' => $totMatQuan,
                                        'scanned_quantity' => $scanMatQuan,
                                    ]);

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

                                    $this->dispatch('refreshEmptyInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId);

                                    return;
                                }
                            }
                        } else {
                            Notification::make()
                                ->title('Updated Invoice Not Found')
                                ->body("Import the updated 'Material Invoice' file to proceed..!")
                                ->danger()
                                ->seconds(2)
                                ->send();

                            $this->dispatch('playWarnSound');
                            $this->form->fill([
                                'plant_id' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'serial_number' => null,
                                'total_quantity' => 0,
                                'scanned_quantity' => 0,
                            ]);
                            $this->dispatch('refreshEmptyInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId);

                            return;
                        }
                    }
                }

                return;
            } else {
                $this->form->fill([
                    'plant_id' => $plantId,
                    'invoice_number' => $invoiceNumber,
                    'serial_number' => null,
                    'total_quantity' => $totQuan,
                    'scanned_quantity' => $scanSQuan,
                ]);
                // $hasRecords = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->first()->stickerMasterRelation->material_type ?? null;
                // $this->dispatch('refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId, onCapFocus: false);

                if ($totQuan == $scanSQuan) {
                    Notification::make()
                        ->title('Completed: Serial Invoice')
                        ->body("Serial invoice '$invoiceNumber' completed the scanning process.<br>Scan the next 'Serial Invoice' to proceed..!")
                        ->warning()
                        ->seconds(3)
                        ->send();
                    $this->dispatch('playNotificationSound');

                    $filename = $invoiceNumber.'.xlsx';
                    $directory = "uploads/temp/{$plantCode}";
                    $disk = Storage::disk('local');
                    $filePath = $directory.'/'.$filename;
                    // $fullPath = null;
                    if ($disk->exists($filePath)) {
                        // $fullPath = $disk->path($filePath);
                        $disk->delete($filePath);
                    }

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => null,
                        'serial_number' => null,
                        'total_quantity' => 0,
                        'update_invoice' => false,
                        'scanned_quantity' => 0,
                    ]);

                    $this->dispatch('refreshCompletedInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId, isSerial: true);
                } else {
                    Notification::make()
                        ->title('Start the scanning process!')
                        ->info()
                        ->seconds(1)
                        ->send();
                    $this->dispatch('playNotificationSound');
                    $this->dispatch('refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId, onCapFocus: false);

                    if ($updateStatus == '1') {
                        $filename = $invoiceNumber.'.xlsx';
                        $directory = "uploads/temp/{$plantCode}";
                        $disk = Storage::disk('local');
                        $filePath = $directory.'/'.$filename;
                        $fullPath = $disk->path($filePath);

                        // Check if file exists //if ($disk->exists($filePath))
                        if ($fullPath && file_exists($fullPath)) {
                            // /home/iot-dev/projects/pds/storage/app/private/uploads/temp/{$plantCode}/3RA0018735.xlsx
                            // 'Serial invoice update in progress...'
                            // Now you can read/process the file here
                            $rows = Excel::toArray(null, $fullPath)[0];

                            if ((count($rows) - 1) <= 0) {
                                Notification::make()
                                    ->title('Records Not Found')
                                    ->body("Import the valid updated 'Serial Invoice' file to proceed..!")
                                    ->danger()
                                    ->seconds(3)
                                    ->send();
                                $this->dispatch('playWarnSound');

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

                                return;
                            }

                            $invalidMatCodes = [];
                            $materialCodes = [];
                            $missingSerials = [];
                            $invalidSerCodes = [];
                            $duplicateSerials = [];
                            $serialNumbers = [];
                            $validRowsFound = false;

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

                                $materialCode = trim($row[0]);
                                $serialNumber = trim($row[1]);

                                if (empty($materialCode) && empty($serialNumber)) {
                                    continue;
                                }

                                if (! empty($materialCode)) {
                                    if (Str::length($materialCode) < 6 || ! ctype_alnum($materialCode)) {
                                        $invalidMatCodes[] = $materialCode;

                                        continue;
                                    } else {
                                        if (empty($serialNumber)) {
                                            $missingSerials[] = $materialCode;
                                        } elseif (Str::length($serialNumber) < 9 || ! ctype_alnum($serialNumber)) {
                                            $invalidSerCodes[] = $serialNumber;
                                        } else {
                                            if (in_array($serialNumber, $serialNumbers)) {
                                                $duplicateSerials[] = $serialNumber;
                                            } else {
                                                $serialNumbers[] = $serialNumber;
                                                $materialCodes[] = $materialCode;
                                                $validRowsFound = true;
                                            }
                                        }
                                    }
                                } else {
                                    continue;
                                }
                            }

                            $uniqueInvalidCodes = array_unique($invalidMatCodes);

                            if (! empty($uniqueInvalidCodes)) {
                                Notification::make()
                                    ->title('Invalid: Item Codes')
                                    ->body('The following item codes should contain minimum 6 digit alpha numeric values:<br>'.implode(', ', $uniqueInvalidCodes))
                                    ->danger()
                                    ->seconds(3)
                                    ->send();

                                $this->dispatch('playWarnSound');

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

                            $uniqueMissingSerials = array_unique($missingSerials);

                            if (! empty($uniqueMissingSerials)) {
                                Notification::make()
                                    ->title('Missing Serial Numbers')
                                    ->body("The following item codes doesn't have valid serial number:<br>".implode(', ', $uniqueMissingSerials))
                                    ->danger()
                                    ->seconds(3)
                                    ->send();

                                $this->dispatch('playWarnSound');

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

                            $uniqueInvalidSerCodes = array_unique($invalidSerCodes);

                            if (! empty($uniqueInvalidSerCodes)) {
                                Notification::make()
                                    ->title('Invalid Serial Numbers')
                                    ->body('The following serial numbers should contain minimum 9 digit alpha numeric values:<br>'.implode(', ', $uniqueInvalidSerCodes))
                                    ->danger()
                                    ->seconds(3)
                                    ->send();

                                $this->dispatch('playWarnSound');

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

                            $uniqueDupSerCodes = array_unique($duplicateSerials);

                            if (! empty($uniqueDupSerCodes)) {
                                Notification::make()
                                    ->title('Duplicate Serial Numbers')
                                    ->body('The following serial numbers are already exist in invoice excel:<br>'.implode(', ', $uniqueDupSerCodes))
                                    ->danger()
                                    ->seconds(3)
                                    ->send();

                                $this->dispatch('playWarnSound');

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

                            if (! $validRowsFound) {
                                Notification::make()
                                    ->title('Invalid Serial Invoice')
                                    ->danger()  // This makes the notification red to indicate an error
                                    ->body('Uploaded excel sheet is empty or<br>contains no valid data.')
                                    ->seconds(3)
                                    ->send();

                                $this->dispatch('playWarnSound');
                                if ($disk->exists($filePath)) {
                                    $disk->delete($filePath);
                                }

                                return;
                            }

                            $uniqueCodes = array_unique($materialCodes);

                            // itemNotFound
                            $matchedItems = StickerMaster::with('item')
                                ->whereHas('item', function ($query) use ($uniqueCodes) {
                                    $query->whereIn('code', $uniqueCodes);
                                })
                                ->get();

                            $matchedCodes = $matchedItems->pluck('item.code')->toArray();

                            $missingCodes = array_diff($uniqueCodes, $matchedCodes);

                            if (! empty($missingCodes)) {
                                $missingCount = count($missingCodes);

                                $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database." : 'The following item codes are not found in database:<br>'.implode(', ', $missingCodes); // ->where('plant_id', $plantId)

                                Notification::make()
                                    ->title('Unknown: Item Codes')
                                    ->body($message)
                                    ->danger()
                                    ->seconds(3)
                                    ->send();

                                $this->dispatch('playWarnSound');

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

                            // plantNotFound
                            $matchedItems = StickerMaster::with('item')
                                ->whereHas('item', function ($query) use ($uniqueCodes, $plantId) {
                                    $query->whereIn('code', $uniqueCodes)->where('plant_id', $plantId);
                                })
                                ->get();

                            $matchedCodes = $matchedItems->pluck('item.code')->toArray();

                            $missingCodes = array_diff($uniqueCodes, $matchedCodes);

                            if (! empty($missingCodes)) {
                                $missingCount = count($missingCodes);

                                $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database for choosed plant." : 'The following item codes are not found in database for choosed plant:<br>'.implode(', ', $missingCodes);

                                Notification::make()
                                    ->title('Unknown: Item Codes')
                                    ->body($message)
                                    ->danger()
                                    ->seconds(3)
                                    ->send();
                                $this->dispatch('playWarnSound');

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

                            $invalidCodes = $matchedItems
                                ->filter(fn ($sticker) => ! empty($sticker->material_type))  // filter invalid
                                ->pluck('item.code')
                                ->toArray();

                            if (! empty($invalidCodes)) {
                                $missingCount = count($invalidCodes);

                                $message = $missingCount > 10 ? "'$missingCount' Material Invoice item codes found." : "'Material Invoice' item codes found:<br>".implode(', ', $invalidCodes);

                                Notification::make()
                                    ->title('Invalid: Item Codes')
                                    ->body($message)
                                    ->danger()
                                    ->seconds(3)
                                    ->send();
                                $this->dispatch('playWarnSound');

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

                            $missPackCodes = $matchedItems
                                ->filter(fn ($sticker) => empty($sticker->tube_sticker_motor) && empty($sticker->pack_slip_motor) && empty($sticker->tube_sticker_pump) && empty($sticker->pack_slip_pump) && empty($sticker->tube_sticker_pumpset) && empty($sticker->pack_slip_pumpset) && empty($sticker->panel_box_code))  // filter invalid
                                ->pluck('item.code')
                                ->toArray();

                            if (! empty($missPackCodes)) {
                                $missingCount = count($missPackCodes);

                                $message = $missingCount > 10 ? "'$missingCount' item codes doesn't have valid package type to proceed!" : "The following 'Item Code' doesn't have valid package type:<br>".implode(', ', $missPackCodes);

                                Notification::make()
                                    ->title('Invalid: Item Codes')
                                    ->body($message)
                                    ->danger()
                                    ->seconds(3)
                                    ->send();
                                $this->dispatch('playWarnSound');

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

                            $oldQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
                            $newQuan = 0;

                            $inserted = 0;
                            foreach ($rows as $index => $row) {
                                if ($index == 0) { // Skip header;
                                    InvoiceValidation::where('invoice_number', $invoiceNumber)
                                        ->where(function ($query) {
                                            $query->whereNull('motor_scanned_status')->orWhere('motor_scanned_status', '');
                                        })
                                        ->where(function ($query) {
                                            $query->whereNull('pump_scanned_status')->orWhere('pump_scanned_status', '');
                                        })
                                        ->where(function ($query) {
                                            $query->whereNull('capacitor_scanned_status')->orWhere('capacitor_scanned_status', '');
                                        })
                                        ->where(function ($query) {
                                            $query->whereNull('scanned_status_set')->orWhere('scanned_status_set', '');
                                        })
                                        ->where(function ($query) {
                                            $query->whereNull('scanned_status')->orWhere('scanned_status', '');
                                        })
                                        ->forceDelete(); // ->delete();

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

                                    continue;
                                }

                                $materialCode = trim($row[0]);
                                $serialNumber = trim($row[1]);

                                if (empty($materialCode) || empty($serialNumber)) {
                                    continue;
                                }

                                $sNoExist = InvoiceValidation::where('serial_number', $serialNumber)->where('plant_id', $plantId)->exists(); // ->pluck('serial_number')

                                if ($sNoExist) {
                                    continue;
                                }

                                $sticker = StickerMaster::where('plant_id', $plantId)->whereHas('item', function ($query) use ($materialCode) {
                                    $query->where('plant_id', $this->plantId)->where('code', $materialCode);  // Check if item.code matches Excel's materialCode
                                })->first();

                                if ($sticker) {
                                    InvoiceValidation::create([
                                        'sticker_master_id' => $sticker->id,
                                        'plant_id' => $plantId,
                                        'invoice_number' => $invoiceNumber,
                                        'serial_number' => $serialNumber,
                                        'operator_id' => $operatorName,
                                        'created_by' => $operatorName,
                                        'updated_by' => $operatorName,
                                    ]);
                                    $inserted++;
                                }
                            }

                            if ($inserted > 0 || $oldQuan != $newQuan) {
                                Notification::make()
                                    ->title('Serial invoice successfully updated.')
                                    ->success()
                                    ->seconds(1)
                                    ->send();

                                Notification::make()
                                    ->title('Start the scanning process!')
                                    ->body("'$inserted' new serial invoice records were inserted.")
                                    ->info()
                                    // ->success()
                                    ->seconds(1)
                                    ->send();

                                $this->dispatch('playNotificationSound');

                                InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->update(['updated_by' => $operatorName]); // 'updated_at' => now(),

                                // Update total quantity in the form
                                $totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
                                $scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
                                $this->form->fill([
                                    'plant_id' => $plantId,
                                    'invoice_number' => $invoiceNumber,
                                    'serial_number' => null,
                                    'total_quantity' => $totalQuantity,
                                    'scanned_quantity' => $scannedQuantity,
                                ]);

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

                                    $this->dispatch('refreshCompletedInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId, isSerial: true);
                                } else {
                                    // if ($disk->exists($filePath)) {
                                    //     $disk->delete($filePath);
                                    // }

                                    // $hasRecords = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->first()->stickerMasterRelation->material_type ?? null;
                                    // $this->dispatch( (!empty($hasRecords) && $hasRecords) ? 'refreshMaterialInvoiceData' : 'refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId, onCapFocus: false); //$this->invoiceNumber
                                    $this->dispatch('refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId, onCapFocus: false);
                                }
                            } else {
                                Notification::make()
                                    ->title('Update Failed: Serial Invoice')
                                    ->body("No new records were inserted for Serial Invoice : '$invoiceNumber'.")
                                    ->danger()
                                    ->seconds(3)
                                    ->send();
                                $this->dispatch('playWarnSound');

                                $totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
                                $scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
                                $this->form->fill([
                                    'plant_id' => $plantId,
                                    'invoice_number' => $invoiceNumber,
                                    'serial_number' => null,
                                    'total_quantity' => $totalQuantity,
                                    'scanned_quantity' => $scannedQuantity,
                                ]);

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

                                $this->dispatch('refreshEmptyInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId);

                                return;
                            }
                        } else {
                            Notification::make()
                                ->title('Updated Invoice Not Found')
                                ->body("Import the updated 'Serial Invoice' file to proceed..!")
                                ->danger()
                                ->seconds(3)
                                ->send();

                            $this->dispatch('playWarnSound');

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'serial_number' => null,
                                'total_quantity' => 0,
                                'scanned_quantity' => 0,
                            ]);
                            $this->dispatch('refreshEmptyInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId);

                            return;
                        }
                    }
                }

                return;
            }
        }

        $filename = $invoiceNumber.'.xlsx';
        $directory = "uploads/temp/{$plantCode}";
        $disk = Storage::disk('local');
        $filePath = $directory.'/'.$filename;
        $fullPath = null; // $fullPath = $disk->path($filePath);

        // Check if file exists
        if ($disk->exists($filePath)) {
            $fullPath = $disk->path($filePath);
            // $fullPath = session('uploaded_invoice_path');
            // Notification::make()
            //     ->title('File exists.')
            //     ->success()
            //     ->seconds(3)
            //     ->send();
        } else {
            Notification::make()
                ->title('Invoice Not Found')
                ->body("Import the scanned 'Invoice' file to proceed..!")
                ->danger()
                ->seconds(3)
                ->send();
            $this->dispatch('playWarnSound');
            $this->form->fill([
                'plant_id' => $plantId,
                'invoice_number' => $invoiceNumber,
                'serial_number' => null,
                'total_quantity' => 0,
                'scanned_quantity' => 0,
            ]);
            $this->dispatch('refreshEmptyInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId);

            return;
        }

        if (! file_exists($fullPath)) {
            Notification::make()
                ->title('Invoice file doesn\'t exist.')
                ->danger()
                ->seconds(3)
                ->send();
            $this->dispatch('playWarnSound');

            return;

        }

        // Extract filename without extension (e.g., "3RA0018732")
        $uploadedFilename = pathinfo($fullPath, PATHINFO_FILENAME);

        // Compare with invoice number
        if ($uploadedFilename != $invoiceNumber) {
            Notification::make()
                ->title('Uploaded file name does not match the invoice number.')
                ->danger()
                ->seconds(3)
                ->send();
            $this->dispatch('playWarnSound');

            return;
        }

        if ($fullPath && file_exists($fullPath)) {
            // Now you can read/process the file here
            $rows = Excel::toArray(null, $fullPath)[0];
            // $collection = Excel::toCollection(null, $fullPath);
            // $rows = $collection[0]->toArray();

            // $collection = Excel::toCollection(new ExcelImport, $fullPath);
            // // Convert the collection to an array
            // $rows = $collection->toArray();

            // $excelImport = new ExcelImport();
            // // Import the Excel file
            // Excel::import($excelImport, $fullPath);
            // // Get the rows
            // $rows = $excelImport->getRows();

            if ((count($rows) - 1) <= 0) {
                Notification::make()
                    ->title('Records Not Found')
                    ->body("Import the valid 'Invoice' file to proceed..!")
                    ->danger()
                    ->seconds(3)
                    ->send();

                $this->dispatch('playWarnSound');
                if ($disk->exists($filePath)) {
                    $disk->delete($filePath);
                }

                return;
            }

            $missingCodes = [];
            foreach ($rows as $index => $row) {
                if ($index == 0) {
                    continue;
                }

                $materialCode = trim($row[0]);

                if (! empty($materialCode)) {
                    if (Str::length($materialCode) < 6) {
                        continue;
                    } else {
                        $sticker = StickerMaster::where('plant_id', $plantId)->whereHas('item', function ($query) use ($plantId, $materialCode) {
                            $query->where('plant_id', $plantId)->where('code', $materialCode); // $this->plantId >> Check if item.code matches Excel's materialCode
                        });
                        if ($sticker->exists()) {
                            if ($sticker->first()->material_type && ! empty($sticker->first()->material_type)) {
                                $invoiceType = 'M';
                                break;
                            } else {
                                $invoiceType = 'S';
                                break;
                            }
                        } else {
                            $missingCodes[] = $materialCode;

                            continue;
                        }
                    }
                } else {
                    continue;
                }
            }

            $uniqueCodes = array_unique($missingCodes);

            if (! empty($uniqueCodes)) {
                $missingCount = count($uniqueCodes);

                $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database for choosed plant." : 'The following item codes are not found in database for choosed plant:<br>'.implode(', ', $uniqueCodes);

                Notification::make()
                    ->title('Unknown: Item Codes')
                    ->body($message)
                    ->danger()
                    ->seconds(3)
                    ->send();
                $this->dispatch('playWarnSound');

                // if ($disk->exists($filePath)) {
                //     $disk->delete($filePath);
                // }
                return;
            } elseif ($invoiceType == 'M') {
                $invalidMatCodes = [];
                $materialCodes = [];
                $missingQuantities = [];
                $invalidMatQuan = [];
                $validRowsFound = false;

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

                    $materialCode = trim($row[0]);
                    $materialQuantity = trim($row[1]);

                    if (empty($materialCode) && empty($materialQuantity)) {
                        continue;
                    }

                    if (! empty($materialCode)) {
                        if (Str::length($materialCode) < 6 || ! ctype_alnum($materialCode)) {
                            $invalidMatCodes[] = $materialCode;
                        } else {
                            if (empty($materialQuantity)) {
                                $missingQuantities[] = $materialCode;
                            } elseif (! is_numeric($materialQuantity)) {
                                $invalidMatQuan[] = $materialCode;
                            } elseif ($materialQuantity == 0) {
                                $invalidMatQuan[] = $materialCode;
                            } else {
                                $materialCodes[] = $materialCode;
                                $validRowsFound = true;
                            }
                        }
                    } else {
                        continue;
                    }
                }

                $uniqueInvalidCodes = array_unique($invalidMatCodes);

                if (! empty($uniqueInvalidCodes)) {
                    Notification::make()
                        ->title('Invalid: Item Codes')
                        ->body('The following item codes should contain minimum 6 digit alpha numeric values:<br>'.implode(', ', $uniqueInvalidCodes))
                        ->danger()
                        ->seconds(2)
                        ->send();

                    $this->dispatch('playWarnSound');

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

                $uniqueMissingQuanCodes = array_unique($missingQuantities);

                if (! empty($uniqueMissingQuanCodes)) {
                    Notification::make()
                        ->title('Missing Material Quantity')
                        ->body("The following item codes doesn't have valid material quantity:<br>".implode(', ', $uniqueMissingQuanCodes))
                        ->danger()
                        ->seconds(2)
                        ->send();

                    $this->dispatch('playWarnSound');

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

                $uniqueInvalidMatQuan = array_unique($invalidMatQuan);

                if (! empty($uniqueInvalidMatQuan)) {
                    Notification::make()
                        ->title('Invalid Material Quantity')
                        ->body("The following item codes doesn't have valid material quantity:<br>".implode(', ', $uniqueInvalidMatQuan))
                        ->danger()
                        ->seconds(2)
                        ->send();

                    $this->dispatch('playWarnSound');

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

                if (! $validRowsFound) {
                    Notification::make()
                        ->title('Invalid Material Invoice')
                        ->danger()  // This makes the notification red to indicate an error
                        ->body('Uploaded Excel sheet is empty or<br>contains no valid data.')
                        ->seconds(2)
                        ->send();

                    $this->dispatch('playWarnSound');
                    if ($disk->exists($filePath)) {
                        $disk->delete($filePath);
                    }

                    return;
                }

                $uniqueCodes = array_unique($materialCodes);

                // itemNotFound
                $matchedItems = StickerMaster::with('item')
                    ->whereHas('item', function ($query) use ($uniqueCodes) {
                        $query->whereIn('code', $uniqueCodes);
                    })
                    ->get();

                $matchedCodes = $matchedItems->pluck('item.code')->toArray();

                $missingCodes = array_diff($uniqueCodes, $matchedCodes);

                if (! empty($missingCodes)) {
                    $missingCount = count($missingCodes);

                    $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database." : 'The following item codes are not found in database:<br>'.implode(', ', $missingCodes);

                    Notification::make()
                        ->title('Unknown: Item Codes')
                        ->body($message)
                        ->danger()
                        ->seconds(2)
                        ->send();
                    $this->dispatch('playWarnSound');

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

                // plantNotFound
                $matchedItems = StickerMaster::with('item')
                    ->whereHas('item', function ($query) use ($uniqueCodes, $plantId) {
                        $query->whereIn('code', $uniqueCodes)->where('plant_id', $plantId);
                    })
                    ->get();

                $matchedCodes = $matchedItems->pluck('item.code')->toArray();

                $missingCodes = array_diff($uniqueCodes, $matchedCodes);

                if (! empty($missingCodes)) {
                    $missingCount = count($missingCodes);

                    $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database for choosed plant." : 'The following item codes are not found in database for choosed plant:<br>'.implode(', ', $missingCodes);

                    Notification::make()
                        ->title('Unknown: Item Codes')
                        ->body($message)
                        ->danger()
                        ->seconds(2)
                        ->send();
                    $this->dispatch('playWarnSound');

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

                $invalidCodes = $matchedItems
                    ->filter(fn ($sticker) => empty($sticker->material_type))  // filter invalid
                    ->pluck('item.code')
                    ->toArray();

                if (! empty($invalidCodes)) {
                    $missingCount = count($invalidCodes);

                    $message = $missingCount > 10 ? "'$missingCount' Serial Invoice item codes found." : "'Serial Invoice' item codes found:<br>".implode(', ', $invalidCodes);

                    Notification::make()
                        ->title('Invalid: Item Codes')
                        ->body($message)
                        ->danger()
                        ->seconds(2)
                        ->send();
                    $this->dispatch('playWarnSound');

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

                $nonNumericQtyCodes = [];
                $zeroQtyCodes = [];
                $notDivisibleCodes = [];

                foreach ($matchedItems as $sticker) {
                    $code = $sticker->item->code;
                    $materialType = $sticker->material_type;

                    if ($materialType == 2) {
                        $bundleQty = $sticker->bundle_quantity ?? 0;
                        $totalExcelQty = 0;

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

                            $excelCode = trim($row[0]);
                            $excelMatQty = trim($row[1]);

                            if (empty($excelCode) || empty($excelMatQty)) {
                                continue;
                            }

                            if ($excelCode == $code && is_numeric($excelMatQty)) {
                                $totalExcelQty += $excelMatQty; // Sum up the quantities
                            }
                        }

                        if ($totalExcelQty == 0) {
                            $zeroQtyCodes[] = $code;
                        } elseif (! is_numeric($totalExcelQty)) {
                            $nonNumericQtyCodes[] = $code;  // Here you may want to check divisibility condition too
                        } elseif ($bundleQty != 0 && $totalExcelQty % $bundleQty != 0) {
                            $notDivisibleCodes[] = $code;
                        }
                    }
                }

                $showValidationNotification = function (array $codes, string $message) {
                    if (count($codes) == 0) {
                        return;
                    }

                    $uniqueCodes = array_unique($codes);
                    $codeList = implode(', ', $uniqueCodes);

                    Notification::make()
                        ->title('Invalid Bundle Quantity')
                        ->body("$message<br>$codeList")
                        ->danger()
                        ->seconds(2)
                        ->send();
                    $this->dispatch('playWarnSound');
                };

                $showValidationNotification($nonNumericQtyCodes, 'The following item codes contains invalid bundle quantity:');
                $showValidationNotification($zeroQtyCodes, "The following item codes quantity should be greater than '0':");
                $showValidationNotification($notDivisibleCodes, 'The following item codes quantity is not divisible by bundle quantity.');

                if ($nonNumericQtyCodes || $zeroQtyCodes || $notDivisibleCodes) {
                    // if ($disk->exists($filePath)) {
                    //     $disk->delete($filePath);
                    // }
                    return;
                } else {
                    $inserted = 0;
                    foreach ($matchedItems as $sticker) {
                        $code = $sticker->item->code;
                        $materialType = $sticker->material_type;
                        // $sticker = StickerMaster::where('plant_id', $plantId)->whereHas('item', function ($query) use ($code) { $query->where('plant_id', $this->plantId)->where('code', $code); })->first();

                        if ($materialType == 1 || $materialType == 4) {
                            $totalExcelQty = 0;

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

                                $excelCode = trim($row[0]);
                                $excelMatQty = trim($row[1]);

                                if (empty($excelCode) || empty($excelMatQty)) {
                                    continue;
                                }

                                if ($excelCode == $code && is_numeric($excelMatQty)) {
                                    $totalExcelQty += $excelMatQty; // Sum up the quantities
                                }
                            }

                            for ($i = 0; $i < $totalExcelQty; $i++) {
                                if ($sticker) {
                                    InvoiceValidation::create([
                                        'sticker_master_id' => $sticker->id,
                                        'plant_id' => $plantId,
                                        'invoice_number' => $invoiceNumber,
                                        'invoice_quantity' => 1,
                                        'quantity' => 1,
                                        'operator_id' => $operatorName,
                                        'created_by' => $operatorName,
                                        'updated_by' => $operatorName,
                                    ]);
                                    $inserted++;
                                }
                            }
                        } elseif ($materialType == 2) {
                            $bundleQty = $sticker->bundle_quantity;
                            $totalExcelQty = 0;

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

                                $excelCode = trim($row[0]);
                                $excelMatQty = trim($row[1]);

                                if (empty($excelCode) || empty($excelMatQty)) {
                                    continue;
                                }

                                if ($excelCode == $code && is_numeric($excelMatQty)) {
                                    $totalExcelQty += $excelMatQty; // Sum up the quantities
                                }
                            }

                            for ($i = 0; $i < ($totalExcelQty / $bundleQty); $i++) {
                                if ($sticker) {
                                    InvoiceValidation::create([
                                        'sticker_master_id' => $sticker->id,
                                        'plant_id' => $plantId,
                                        'invoice_number' => $invoiceNumber,
                                        'invoice_quantity' => $bundleQty,
                                        'quantity' => $bundleQty,
                                        'operator_id' => $operatorName,
                                        'created_by' => $operatorName,
                                        'updated_by' => $operatorName,
                                    ]);
                                    $inserted++;
                                }
                            }
                        } elseif ($materialType == 3) {
                            $totalExcelQty = 0;

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

                                $excelCode = trim($row[0]);
                                $excelMatQty = trim($row[1]);

                                if (empty($excelCode) || empty($excelMatQty)) {
                                    continue;
                                }

                                if ($excelCode == $code && is_numeric($excelMatQty)) {
                                    $totalExcelQty += $excelMatQty; // Sum up the quantities
                                }
                            }

                            if ($sticker) {
                                InvoiceValidation::create([
                                    'sticker_master_id' => $sticker->id,
                                    'plant_id' => $plantId,
                                    'invoice_number' => $invoiceNumber,
                                    'invoice_quantity' => $totalExcelQty,
                                    'quantity' => $totalExcelQty,
                                    'operator_id' => $operatorName,
                                    'created_by' => $operatorName,
                                    'updated_by' => $operatorName,
                                ]);
                                $inserted++;
                            }
                        }
                    }

                    if ($inserted > 0) {
                        Notification::make()
                            ->title('Start the scanning process!')
                            ->body("'$inserted' material invoice records were inserted.")
                            ->info()
                            // ->success()
                            ->seconds(1)
                            ->send();

                        // Update total quantity in the form
                        $totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
                        $scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNotNull('serial_number')->where('serial_number', '!=', '')->where('plant_id', $plantId)->count();

                        $checkMat = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->latest('updated_at')->first(); // ->where('quantity', '!=', '')
                        if (($checkMat?->stickerMaster->material_type ?? 0) == 3) {
                            $totMatQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->invoice_quantity ?? 0;
                            $scanMatQuan = number_format($totMatQuan - (InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->quantity ?? 0), 3, '.', ''); // ('updated_at', 'desc')
                        } else {
                            $totMatQuan = $totalQuantity;
                            $scanMatQuan = $scannedQuantity;
                        }

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

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

                            $this->dispatch('refreshCompletedInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId, isSerial: false);
                        } else {
                            // if ($disk->exists($filePath)) {
                            //     $disk->delete($filePath);
                            // }

                            // $hasRecords = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->first()->stickerMasterRelation->material_type ?? null;
                            // $this->dispatch( (!empty($hasRecords) && $hasRecords) ? 'refreshMaterialInvoiceData' : 'refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId, onCapFocus: false); //$this->invoiceNumber
                            $this->dispatch('refreshMaterialInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId);
                        }
                    } else {
                        Notification::make()
                            ->title('Import Failed: Material Invoice')
                            ->body("No new records were inserted for Material Invoice: '$invoiceNumber'.")
                            ->danger()
                            ->seconds(2)
                            ->send();

                        $totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
                        $scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNotNull('serial_number')->where('serial_number', '!=', '')->where('plant_id', $plantId)->count();

                        $checkMat = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->latest('updated_at')->first(); // ->where('quantity', '!=', '')
                        if (($checkMat?->stickerMaster->material_type ?? 0) == 3) {
                            $totMatQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->invoice_quantity ?? 0;
                            $scanMatQuan = number_format($totMatQuan - (InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->quantity ?? 0), 3, '.', ''); // ('updated_at', 'desc')
                        } else {
                            $totMatQuan = $totalQuantity;
                            $scanMatQuan = $scannedQuantity;
                        }

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

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

                        $this->dispatch('refreshEmptyInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId);

                        return;
                    }
                }
            } elseif ($invoiceType == 'S') {
                $invalidMatCodes = [];
                $materialCodes = [];
                $missingSerials = [];
                $invalidSerCodes = [];
                $duplicateSerials = [];
                $serialNumbers = [];
                $validRowsFound = false;

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

                    $materialCode = trim($row[0]);
                    $serialNumber = trim($row[1]);

                    if (empty($materialCode) && empty($serialNumber)) {
                        continue;
                    }

                    if (! empty($materialCode)) {
                        if (Str::length($materialCode) < 6 || ! ctype_alnum($materialCode)) {
                            $invalidMatCodes[] = $materialCode;

                            continue;
                        } else {
                            if (empty($serialNumber)) {
                                $missingSerials[] = $materialCode;
                            } elseif (Str::length($serialNumber) < 9 || ! ctype_alnum($serialNumber)) {
                                $invalidSerCodes[] = $serialNumber;
                            } else {
                                if (in_array($serialNumber, $serialNumbers)) {
                                    $duplicateSerials[] = $serialNumber;
                                } else {
                                    $serialNumbers[] = $serialNumber;
                                    $materialCodes[] = $materialCode;
                                    $validRowsFound = true;
                                }
                            }
                        }
                    } else {
                        continue;
                    }
                }

                $uniqueInvalidCodes = array_unique($invalidMatCodes);

                if (! empty($uniqueInvalidCodes)) {
                    Notification::make()
                        ->title('Invalid: Item Codes')
                        ->body('The following item codes should contain minimum 6 digit alpha numeric values:<br>'.implode(', ', $uniqueInvalidCodes))
                        ->danger()
                        ->seconds(3)
                        ->send();
                    $this->dispatch('playWarnSound');

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

                $uniqueMissingSerials = array_unique($missingSerials);

                if (! empty($uniqueMissingSerials)) {
                    Notification::make()
                        ->title('Missing Serial Numbers')
                        ->body("The following item codes doesn't have valid serial number:<br>".implode(', ', $uniqueMissingSerials))
                        ->danger()
                        ->seconds(3)
                        ->send();
                    $this->dispatch('playWarnSound');

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

                $uniqueInvalidSerCodes = array_unique($invalidSerCodes);

                if (! empty($uniqueInvalidSerCodes)) {
                    Notification::make()
                        ->title('Invalid Serial Numbers')
                        ->body('The following serial numbers should contain minimum 9 digit alpha numeric values:<br>'.implode(', ', $uniqueInvalidSerCodes))
                        ->danger()
                        ->seconds(3)
                        ->send();
                    $this->dispatch('playWarnSound');

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

                $uniqueDupSerCodes = array_unique($duplicateSerials);

                if (! empty($uniqueDupSerCodes)) {
                    Notification::make()
                        ->title('Duplicate Serial Numbers')
                        ->body('The following serial numbers are already exist in invoice excel:<br>'.implode(', ', $uniqueDupSerCodes))
                        ->danger()
                        ->seconds(3)
                        ->send();
                    $this->dispatch('playWarnSound');

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

                if (! $validRowsFound) {
                    Notification::make()
                        ->title('Invalid Serial Invoice')
                        ->danger()  // This makes the notification red to indicate an error
                        ->body('Uploaded excel sheet is empty or<br>contains no valid data.')
                        ->seconds(3)
                        ->send();

                    $this->dispatch('playWarnSound');
                    if ($disk->exists($filePath)) {
                        $disk->delete($filePath);
                    }

                    return;
                }

                $uniqueCodes = array_unique($materialCodes);

                // itemNotFound
                $matchedItems = StickerMaster::with('item')
                    ->whereHas('item', function ($query) use ($uniqueCodes) {
                        $query->whereIn('code', $uniqueCodes);
                    })
                    ->get();

                // // Get all codes that exist in the database for the given plant_id
                // $existingCodes = StickerMaster::where('plant_id', $plantId)
                //     ->whereHas('item', function ($query) use ($uniqueCodes) {
                //         $query->whereIn('code', $uniqueCodes);
                //     })
                //     ->with('item') // Eager load for performance
                //     ->get()
                //     ->pluck('item.code')
                //     ->toArray();

                $matchedCodes = $matchedItems->pluck('item.code')->toArray();

                $missingCodes = array_diff($uniqueCodes, $matchedCodes);

                if (! empty($missingCodes)) {
                    $missingCount = count($missingCodes);

                    $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database." : 'The following item codes are not found in database:<br>'.implode(', ', $missingCodes);

                    Notification::make()
                        ->title('Unknown: Item Codes')
                        ->body($message)
                        ->danger()
                        ->seconds(3)
                        ->send();
                    $this->dispatch('playWarnSound');

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

                // plantNotFound
                $matchedItems = StickerMaster::with('item')
                    ->whereHas('item', function ($query) use ($uniqueCodes, $plantId) {
                        $query->whereIn('code', $uniqueCodes)->where('plant_id', $plantId);
                    })
                    ->get();

                $matchedCodes = $matchedItems->pluck('item.code')->toArray();

                $missingCodes = array_diff($uniqueCodes, $matchedCodes);

                if (! empty($missingCodes)) {
                    $missingCount = count($missingCodes);

                    $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database for choosed plant." : 'The following item codes are not found in database for choosed plant:<br>'.implode(', ', $missingCodes);

                    Notification::make()
                        ->title('Unknown: Item Codes')
                        ->body($message)
                        ->danger()
                        ->seconds(3)
                        ->send();

                    $this->dispatch('playWarnSound');

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

                $invalidCodes = $matchedItems
                    ->filter(fn ($sticker) => ! empty($sticker->material_type))  // filter invalid
                    ->pluck('item.code')
                    ->toArray();

                if (! empty($invalidCodes)) {
                    $missingCount = count($invalidCodes);

                    $message = $missingCount > 10 ? "'$missingCount' Material Invoice item codes found." : "'Material Invoice' item codes found:<br>".implode(', ', $invalidCodes);

                    Notification::make()
                        ->title('Invalid: Item Codes')
                        ->body($message)
                        ->danger()
                        ->seconds(3)
                        ->send();

                    $this->dispatch('playWarnSound');

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

                $missPackCodes = $matchedItems
                    ->filter(fn ($sticker) => empty($sticker->tube_sticker_motor) && empty($sticker->pack_slip_motor) && empty($sticker->tube_sticker_pump) && empty($sticker->pack_slip_pump) && empty($sticker->tube_sticker_pumpset) && empty($sticker->pack_slip_pumpset) && empty($sticker->panel_box_code))
                    ->pluck('item.code')
                    ->toArray();

                if (! empty($missPackCodes)) {
                    $missingCount = count($missPackCodes);

                    $message = $missingCount > 10 ? "'$missingCount' item codes doesn't have valid package type to proceed!" : "The following 'Item Code' doesn't have valid package type:<br>".implode(', ', $missPackCodes);

                    Notification::make()
                        ->title('Invalid: Item Codes')
                        ->body($message)
                        ->danger()
                        ->seconds(3)
                        ->send();

                    $this->dispatch('playWarnSound');

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

                $existingSerialNumbers = InvoiceValidation::whereIn('serial_number', $serialNumbers)->where('plant_id', $plantId)->pluck('serial_number')->toArray();

                // If there are duplicates, notify and stop the process
                if (! empty($existingSerialNumbers)) {
                    Notification::make()
                        ->title('Duplicate Serial Numbers')
                        ->body('The following serial numbers are already exist in database:<br>'.implode(', ', $existingSerialNumbers))
                        ->danger()
                        ->seconds(3)
                        ->send();

                    $this->dispatch('playWarnSound');

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

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

                    $materialCode = trim($row[0]);
                    $serialNumber = trim($row[1]);

                    if (empty($materialCode) || empty($serialNumber)) {
                        continue;
                    }

                    $sticker = StickerMaster::where('plant_id', $plantId)->whereHas('item', function ($query) use ($materialCode) {
                        $query->where('plant_id', $this->plantId)->where('code', $materialCode);  // Check if item.code matches Excel's materialCode
                    })->first();

                    if ($sticker) {
                        InvoiceValidation::create([
                            'sticker_master_id' => $sticker->id,
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => $serialNumber,
                            'operator_id' => $operatorName,
                            'created_by' => $operatorName,
                            'updated_by' => $operatorName,
                        ]);
                        $inserted++;
                    }
                }

                if ($inserted > 0) {
                    Notification::make()
                        ->title('Start the scanning process!')
                        ->body("'$inserted' serial invoice records were inserted.")
                        ->info()
                        // ->success()
                        ->seconds(1)
                        ->send();
                    $this->dispatch('playNotificationSound');

                    // Update total quantity in the form
                    $totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
                    $scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totalQuantity,
                        'scanned_quantity' => $scannedQuantity,
                    ]);

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

                        $this->dispatch('refreshCompletedInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId, isSerial: true);
                    } else {
                        // if ($disk->exists($filePath)) {
                        //     $disk->delete($filePath);
                        // }

                        // $hasRecords = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->first()->stickerMasterRelation->material_type ?? null;
                        // $this->dispatch( (!empty($hasRecords) && $hasRecords) ? 'refreshMaterialInvoiceData' : 'refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId, onCapFocus: false); //$this->invoiceNumber
                        $this->dispatch('refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId, onCapFocus: false);
                    }
                } else {
                    Notification::make()
                        ->title('Import Failed: Serial Invoice')
                        ->body("No new records were inserted for Serial Invoice : '$invoiceNumber'.")
                        ->danger()
                        ->seconds(3)
                        ->send();
                    $this->dispatch('playWarnSound');

                    $totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
                    $scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totalQuantity,
                        'scanned_quantity' => $scannedQuantity,
                    ]);

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

                    $this->dispatch('refreshEmptyInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId);

                    return;
                }
            } else {
                Notification::make()
                    ->title('Invoice Type Not Found')
                    ->body("Import the valid 'Invoice' file to proceed..!")
                    ->danger()
                    ->seconds(3)
                    ->send();
                $this->dispatch('playWarnSound');

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

    protected function refreshInvoiceTable()
    {
        $this->plantId = $this->form->getState()['plant_id'] ?? '';
        $this->invoiceNumber = strtoupper(trim($this->form->getState()['invoice_number'])) ?? '';

        if (! empty($this->invoiceNumber)) {
            $hasInvoice = InvoiceValidation::where('invoice_number', $this->invoiceNumber)->where('plant_id', $this->plantId)->first();

            if (empty($hasInvoice) || ! $hasInvoice) {
                $this->dispatch('refreshEmptyInvoice', invoiceNumber: $this->invoiceNumber, plantId: $this->plantId);
            } else {
                $totalQuantity = InvoiceValidation::where('invoice_number', $this->invoiceNumber)->where('plant_id', $this->plantId)->count();
                $scannedQuantity = InvoiceValidation::where('invoice_number', $this->invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $this->plantId)->count();
                if ($totalQuantity == $scannedQuantity) {
                    $this->dispatch('refreshCompletedInvoice', invoiceNumber: $this->invoiceNumber, plantId: $this->plantId, isSerial: true);
                } else {
                    $hasRecords = $hasInvoice->stickerMasterRelation->material_type ?? null;
                    // $this->dispatch( (!empty($hasRecords) && $hasRecords) ? 'refreshMaterialInvoiceData' : 'refreshInvoiceData', invoiceNumber: $this->invoiceNumber, plantId: $this->plantId);

                    if (! empty($hasRecords) && $hasRecords) {
                        $this->dispatch('refreshMaterialInvoiceData', invoiceNumber: $this->invoiceNumber, plantId: $this->plantId);
                    } else {
                        $this->dispatch('refreshInvoiceData', invoiceNumber: $this->invoiceNumber, plantId: $this->plantId, onCapFocus: false);
                    }
                }
            }
        }
    }

    public function getMail()
    {
        $plantId = $this->form->getState()['plant_id'];
        $this->plantId = $plantId;
        $mInvoiceType = 'Serial';
        $mPlantName = Plant::where('id', $plantId)->value('name');
        $emails = AlertMailRule::where('plant', $plantId)
            // ->where('plant', $plantName)
            ->where('module', 'InvoiceValidation')
            ->where('rule_name', 'InvoiceMail')
            ->where(function ($query) {
                $query->whereNull('schedule_type')
                    ->orWhere('schedule_type', '');
            })
            ->pluck('email')
            ->toArray();

        return [
            'plant_id' => $plantId,
            'plant_name' => $mPlantName,
            'invoice_type' => $mInvoiceType,
            'emails' => $emails,
        ];
    }

    public function processSer($serNo)
    {
        $serNo = trim($serNo);
        $mSerNo = $serNo;
        $user = Filament::auth()->user();
        $operatorName = $user->name;

        $serialNumber = null;
        $plantId = $this->form->getState()['plant_id'];
        $this->plantId = $plantId;
        $invoiceNumber = strtoupper(trim($this->form->getState()['invoice_number']));
        $this->invoiceNumber = $invoiceNumber;

        $plant = Plant::find($plantId);
        $plantCode = $plant?->code ?? null;

        $totQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
        $scanSQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
        $totMQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNotNull('quantity')->where('plant_id', $plantId)->count(); // ->where('quantity', '!=', '')
        $scanMQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNotNull('serial_number')->where('serial_number', '!=', '')->where('plant_id', $plantId)->count();

        if ($totQuan <= 0) {
            Notification::make()
                ->title('Invoice Not Found')
                ->body("Invoice file '$invoiceNumber' doesn't exist.<br>Scan the valid 'Invoice' file to proceed!")
                ->danger()
                ->seconds(3)
                ->send();
            $this->dispatch('playWarnSound');

            $this->form->fill([
                'plant_id' => $plantId,
                'invoice_number' => $invoiceNumber,
                'serial_number' => null,
                'total_quantity' => 0, // $totQuan
                'update_invoice' => false,
                'scanned_quantity' => 0, // ($totMQuan > 0) ? $scanMQuan : $scanSQuan
            ]);
            $this->dispatch('refreshEmptyInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId);

            return;
        } else {
            if ($totMQuan > 0) {
                $checkMat = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->latest('updated_at')->first(); // ->where('quantity', '!=', '')
                if (($checkMat?->stickerMaster->material_type ?? 0) == 3) {
                    $totMatQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->invoice_quantity ?? 0;
                    $scanMatQuan = number_format($totMatQuan - (InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->quantity ?? 0), 3, '.', ''); // ('updated_at', 'desc')
                } else {
                    $totMatQuan = $totQuan;
                    $scanMatQuan = $scanMQuan;
                }

                if ($totQuan == $scanMQuan) {
                    Notification::make()
                        ->title('Completed: Material Invoice')
                        ->body("Material invoice '$invoiceNumber' completed the scanning process.<br>Scan the next 'Material Invoice' to proceed!")
                        ->warning()
                        ->seconds(2)
                        ->send();
                    $this->dispatch('playNotificationSound');

                    $filename = $invoiceNumber.'.xlsx';
                    $directory = "uploads/temp/{$plantCode}";
                    $disk = Storage::disk('local');
                    $filePath = $directory.'/'.$filename;
                    // $fullPath = null;
                    if ($disk->exists($filePath)) {
                        // $fullPath = $disk->path($filePath);
                        $disk->delete($filePath);
                    }

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => null,
                        'serial_number' => null,
                        'total_quantity' => 0,
                        'update_invoice' => false,
                        'scanned_quantity' => 0,
                    ]);

                    $this->dispatch('refreshCompletedInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId, isSerial: false);

                    return;
                } else {
                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totMatQuan,
                        'update_invoice' => false,
                        'scanned_quantity' => $scanMatQuan,
                    ]);
                    // $hasRecords = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->first()->stickerMasterRelation->material_type ?? null;
                    $this->dispatch('refreshMaterialInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId);
                }

                $pattern0 = '/^(?<item_code>[^|]+)\|(?<batch_id>[^|]+)\|(?<batch_count>[^|]+)\|(?<batch_quantity>[0-9]+(?:\.[0-9]+)?)\s?kg$/i';
                $pattern1 = '/^(?<item_code>[^|]+)\|(?<batch_number>[^|]+)\|(?<batch_id>[^|]+)\|(?<batch_count>[^|]+)\/(?<batch_quantity>.+)$/i';
                $pattern2 = '/^(?<item_code>[^|]+)\|(?<batch_number>[^|]+)\|(?<batch_id>[^|]+)\|(?<batch_count>.+)$/i';
                $pattern3 = '/^(?<item_code>[^|]+)\|(?<batch_id>[^|]+)-(?<batch_count>.+)$/i';
                $pattern4 = '/^MP-(?<code>.+)$/i';
                $itemCode = '';
                $batchNumber = '';
                $curScanQty = '';
                $wirePallet = '';
                $curMaterialQty = '';
                $curMaterialSer = '';

                if (preg_match($pattern0, $serNo, $matches)) {
                    $itemCode = $matches['item_code'];
                    $this->currentItemCode = $itemCode;
                    $curScanQty = trim($matches['batch_quantity']);
                    $serialNumber = $matches['batch_id'].'-'.$matches['batch_count'];
                    $serNo = null;

                    if (empty($matches['batch_id']) || ! $matches['batch_id']) {
                        Notification::make()
                            ->danger()
                            ->title('Invalid Material QR Format')
                            ->body('Scan valid Material QR code to proceed!<br>Sample formats are:<br>123456|123456789|001|5kg (or)<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
                            ->seconds(2)
                            ->send();
                        $this->dispatch('playWarnSound');

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

                        return;
                    } elseif (empty($matches['batch_count']) || ! $matches['batch_count']) {
                        Notification::make()
                            ->danger()
                            ->title('Invalid Material QR Format')
                            ->body('Scan valid Material QR code to proceed!<br>Sample formats are:<br>123456|123456789|001|5kg (or)<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
                            ->seconds(2)
                            ->send();
                        $this->dispatch('playWarnSound');

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

                        return;
                    }
                } elseif (preg_match($pattern1, $serNo, $matches)) {
                    $itemCode = $matches['item_code'];
                    $this->currentItemCode = $itemCode;
                    $batchNumber = $matches['batch_number'];
                    $serialNumber = $matches['batch_id'].'-'.$matches['batch_count'];
                    $curScanQty = $matches['batch_quantity'];
                    $serNo = null;

                    if (empty($matches['batch_number']) || ! $matches['batch_number']) {
                        Notification::make()
                            ->danger()
                            ->title('Invalid Material QR Format')
                            ->body('Scan valid Material QR code to proceed!<br>Sample formats are:<br>123456|123456789|001|5kg (or)<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
                            ->seconds(2)
                            ->send();
                        $this->dispatch('playWarnSound');

                        // .Mail

                        // $mailData = $this->getMail();
                        // $mPlantName = $mailData['plant_name'];
                        // $emails = $mailData['emails'];
                        // $mInvoiceType = 'Material';

                        // if (! empty($emails)) {
                        //     Mail::to($emails)->send(
                        //         new InvalidSerialMail($mSerNo, $invoiceNumber, $mPlantName, $mInvoiceType, $itemCode, 'InvalidMaterialFormat')
                        //     );
                        // } else {
                        //     \Log::warning("No recipients found for plant {$plantId}, module Serial, rule invalid_serial.");
                        // }

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

                        return;
                    } elseif (empty($matches['batch_id']) || ! $matches['batch_id']) {
                        Notification::make()
                            ->danger()
                            ->title('Invalid Material QR Format')
                            ->body('Scan valid Material QR code to proceed!<br>Sample formats are:<br>123456|123456789|001|5kg (or)<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
                            ->seconds(2)
                            ->send();
                        $this->dispatch('playWarnSound');

                        // .Mail

                        // $mailData = $this->getMail();
                        // $mPlantName = $mailData['plant_name'];
                        // $emails = $mailData['emails'];
                        // $mInvoiceType = 'Material';

                        // if (! empty($emails)) {
                        //     Mail::to($emails)->send(
                        //         new InvalidSerialMail($mSerNo, $invoiceNumber, $mPlantName, $mInvoiceType, $itemCode, 'InvalidMaterialFormat')
                        //     );
                        // } else {
                        //     \Log::warning("No recipients found for plant {$plantId}, module Serial, rule invalid_serial.");
                        // }

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

                        return;
                    } elseif (empty($matches['batch_count']) || ! $matches['batch_count']) {
                        Notification::make()
                            ->danger()
                            ->title('Invalid Material QR Format')
                            ->body('Scan valid Material QR code to proceed!<br>Sample formats are:<br>123456|123456789|001|5kg (or)<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
                            ->seconds(2)
                            ->send();
                        $this->dispatch('playWarnSound');

                        // .Mail

                        // $mailData = $this->getMail();
                        // $mPlantName = $mailData['plant_name'];
                        // $emails = $mailData['emails'];
                        // $mInvoiceType = 'Material';

                        // if (! empty($emails)) {
                        //     // Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType));
                        //     Mail::to($emails)->send(
                        //         new InvalidSerialMail($mSerNo, $invoiceNumber, $mPlantName, $mInvoiceType, $itemCode, 'InvalidMaterialFormat')
                        //     );
                        // } else {
                        //     \Log::warning("No recipients found for plant {$plantId}, module Serial, rule invalid_serial.");
                        // }

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

                        return;
                    }
                } elseif (preg_match($pattern2, $serNo, $matches)) {
                    $itemCode = $matches['item_code'];
                    $this->currentItemCode = $itemCode;
                    $batchNumber = $matches['batch_number'];
                    $serialNumber = $matches['batch_id'].'-'.$matches['batch_count'];
                    $curMaterialSer = $matches['batch_number'].'-'.$matches['batch_id'];
                    $curMaterialQty = $matches['batch_count'];
                    $serNo = null;

                    if (empty($matches['batch_number']) || ! $matches['batch_number']) {
                        Notification::make()
                            ->danger()
                            ->title('Invalid Material QR Format')
                            ->body('Scan valid Material QR code to proceed!<br>Sample formats are:<br>123456|123456789|001|5kg (or)<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
                            ->seconds(2)
                            ->send();
                        $this->dispatch('playWarnSound');
                        // .Mail

                        // $mailData = $this->getMail();
                        // $mPlantName = $mailData['plant_name'];
                        // $emails = $mailData['emails'];
                        // $mInvoiceType = 'Material';

                        // if (! empty($emails)) {
                        //     Mail::to($emails)->send(
                        //         new InvalidSerialMail($mSerNo, $invoiceNumber, $mPlantName, $mInvoiceType, $itemCode, 'InvalidMaterialFormat')
                        //     );
                        // } else {
                        //     \Log::warning("No recipients found for plant {$plantId}, module Serial, rule invalid_serial.");
                        // }

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

                        return;
                    } elseif (empty($matches['batch_id']) || ! $matches['batch_id']) {
                        Notification::make()
                            ->danger()
                            ->title('Invalid Material QR Format')
                            ->body('Scan valid Material QR code to proceed!<br>Sample formats are:<br>123456|123456789|001|5kg (or)<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
                            ->seconds(2)
                            ->send();
                        $this->dispatch('playWarnSound');
                        // .Mail

                        // $mailData = $this->getMail();
                        // $mPlantName = $mailData['plant_name'];
                        // $emails = $mailData['emails'];
                        // $mInvoiceType = 'Material';

                        // if (! empty($emails)) {
                        //     Mail::to($emails)->send(
                        //         new InvalidSerialMail($mSerNo, $invoiceNumber, $mPlantName, $mInvoiceType, $itemCode, 'InvalidMaterialFormat')
                        //     );
                        // } else {
                        //     \Log::warning("No recipients found for plant {$plantId}, module Serial, rule invalid_serial.");
                        // }

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

                        return;
                    } elseif (empty($matches['batch_count']) || ! $matches['batch_count']) {
                        Notification::make()
                            ->danger()
                            ->title('Invalid Material QR Format')
                            ->body('Scan valid Material QR code to proceed!<br>Sample formats are:<br>123456|123456789|001|5kg (or)<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
                            ->seconds(2)
                            ->send();
                        $this->dispatch('playWarnSound');

                        // $mailData = $this->getMail();
                        // $mPlantName = $mailData['plant_name'];
                        // $emails = $mailData['emails'];
                        // $mInvoiceType = 'Material';

                        // if (! empty($emails)) {
                        //     Mail::to($emails)->send(
                        //         new InvalidSerialMail($mSerNo, $invoiceNumber, $mPlantName, $mInvoiceType, $itemCode, 'InvalidMaterialFormat')
                        //     );
                        // } else {
                        //     \Log::warning("No recipients found for plant {$plantId}, module Serial, rule invalid_serial.");
                        // }

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

                        return;
                    }
                } elseif (preg_match($pattern3, $serNo, $matches)) {
                    $itemCode = $matches['item_code'];
                    $this->currentItemCode = $itemCode;
                    $batchNumber = null; // batch_number not present in this pattern
                    $serialNumber = $matches['batch_id'].'-'.$matches['batch_count'];
                    $serNo = null;

                    if (empty($matches['batch_id']) || ! $matches['batch_id']) {
                        Notification::make()
                            ->danger()
                            ->title('Invalid Material QR Format')
                            ->body('Scan valid Material QR code to proceed!<br>Sample formats are:<br>123456|123456789|001|5kg (or)<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
                            ->seconds(2)
                            ->send();
                        $this->dispatch('playWarnSound');

                        // .Mail

                        // $mailData = $this->getMail();
                        // $mPlantName = $mailData['plant_name'];
                        // $emails = $mailData['emails'];
                        // $mInvoiceType = 'Material';

                        // if (! empty($emails)) {
                        //     Mail::to($emails)->send(
                        //         new InvalidSerialMail($mSerNo, $invoiceNumber, $mPlantName, $mInvoiceType, $itemCode, 'InvalidMaterialFormat')
                        //     );
                        // } else {
                        //     \Log::warning("No recipients found for plant {$plantId}, module Serial, rule invalid_serial.");
                        // }

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

                        return;
                    } elseif (empty($matches['batch_count']) || ! $matches['batch_count']) {
                        Notification::make()
                            ->danger()
                            ->title('Invalid Material QR Format')
                            ->body('Scan valid Material QR code to proceed!<br>Sample formats are:<br>123456|123456789|001|5kg (or)<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
                            ->seconds(2)
                            ->send();
                        $this->dispatch('playWarnSound');
                        // .Mail

                        // $mailData = $this->getMail();
                        // $mPlantName = $mailData['plant_name'];
                        // $emails = $mailData['emails'];
                        // $mInvoiceType = 'Material';

                        // if (! empty($emails)) {
                        //     Mail::to($emails)->send(
                        //         new InvalidSerialMail($mSerNo, $invoiceNumber, $mPlantName, $mInvoiceType, $itemCode, 'InvalidMaterialFormat')
                        //     );
                        // } else {
                        //     \Log::warning("No recipients found for plant {$plantId}, module Serial, rule invalid_serial.");
                        // }

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

                        return;
                    }
                } elseif (preg_match($pattern4, $serNo, $matches)) {
                    $wirePallet = 'MP-'.$matches['code'];
                    $wirePattern = '/^MP-(?<code>\d+)$/i';

                    if (! preg_match($wirePattern, $serNo, $matches)) {
                        Notification::make()
                            ->title('Invalid Master Packing QR Format')
                            ->body("Scan valid Master Packing QR code proceed!<br>Sample format : 'MP-2601001'")
                            ->danger()
                            ->seconds(1)
                            ->send();

                        return;
                    }

                    $wireMaster = WireMasterPacking::where('plant_id', $plantId)->where('wire_packing_number', $wirePallet)->first();

                    if (! $wireMaster) {
                        Notification::make()
                            ->title('Master Pallet Not Found')
                            ->body("No record found for this Master Packing QR $wirePallet")
                            ->danger()
                            ->seconds(2)
                            ->send();

                        return;
                    }

                    $wireItemCodes = WireMasterPacking::join('items', 'items.id', '=', 'wire_master_packings.item_id')
                        ->where('wire_master_packings.plant_id', $plantId)
                        ->where('wire_master_packings.wire_packing_number', $wirePallet)
                        ->pluck('items.code')
                        ->unique()
                        ->toArray();

                    $invoiceItemCodes = InvoiceValidation::join(
                        'sticker_masters',
                        'sticker_masters.id',
                        '=',
                        'invoice_validations.sticker_master_id'
                    )
                        ->join(
                            'items',
                            'items.id',
                            '=',
                            'sticker_masters.item_id'
                        )
                        ->where('invoice_validations.plant_id', $plantId)
                        ->where('invoice_validations.invoice_number', $this->invoiceNumber)
                        ->pluck('items.code')
                        ->unique()
                        ->toArray();

                    $missedCodes = array_diff($wireItemCodes, $invoiceItemCodes);

                    if (! empty($missedCodes)) {

                        Notification::make()
                            ->title('Items Missing in Invoice')
                            ->body('Item codes are missing in invoice: '.implode(', ', $missedCodes))
                            ->danger()
                            ->seconds(3)
                            ->send();

                        return;
                    }

                    $duplicateSerial = [];
                    $weightExceeded = [];
                    $invalidMaterialItems = [];

                    $wireItems1 = WireMasterPacking::join('items', 'items.id', '=', 'wire_master_packings.item_id')
                        ->where('wire_master_packings.plant_id', $plantId)
                        ->where('wire_master_packings.wire_packing_number', $wirePallet)
                        ->select(
                            'items.code as item_code',
                            'wire_master_packings.process_order',
                            DB::raw('SUM(wire_master_packings.weight::numeric) as pallet_weight')
                        )
                        ->groupBy('items.code', 'wire_master_packings.process_order')
                        ->get();

                    foreach ($wireItems1 as $wireItem) {
                        $processOrder = $wireItem->process_order;
                        $palletWeight = $wireItem->pallet_weight;
                        $itemCode = $wireItem->item_code;

                        $duplicate = InvoiceValidation::where('plant_id', $this->plantId)
                            ->where('invoice_number', $this->invoiceNumber)
                            ->where('serial_number', $processOrder)
                            ->exists();

                        if ($duplicate) {
                            $duplicateSerial[] = $processOrder;

                            continue;
                        }

                        $materialType = StickerMaster::where('item_id', function ($q) use ($itemCode) {
                            $q->select('id')->from('items')->where('code', $itemCode);
                        })->value('material_type');

                        if ($materialType != 3) {
                            if (! in_array($itemCode, $invalidMaterialItems)) {
                                $invalidMaterialItems[] = $itemCode;
                            }
                        }

                        $scannedQty = InvoiceValidation::join('sticker_masters', 'sticker_masters.id', '=', 'invoice_validations.sticker_master_id')
                            ->join('items', 'items.id', '=', 'sticker_masters.item_id')
                            ->where('invoice_validations.plant_id', $plantId)
                            ->where('invoice_validations.invoice_number', $this->invoiceNumber)
                            ->where('items.code', $itemCode)
                            ->sum(DB::raw('invoice_validations.quantity::numeric'));

                        if ($palletWeight > $scannedQty) {
                            $weightExceeded[] = $itemCode;
                        }
                    }

                    if (! empty($invalidMaterialItems)) {
                        $uniqueInvalidItems = array_unique($invalidMaterialItems);
                        Notification::make()
                            ->title('Invalid Material Type')
                            ->body(implode(', ', $uniqueInvalidItems)."<br>Invalid material type found for the invoice '$invoiceNumber'.")
                            ->danger()
                            ->seconds(4)
                            ->send();

                        return;
                    } elseif (! empty($weightExceeded)) {
                        Notification::make()
                            ->title('Item Code Limit')
                            ->body(implode(', ', $weightExceeded)."<br>Master pallet weight exceeds the remaining quantity in invoice '$invoiceNumber'.")
                            ->danger()
                            ->seconds(4)
                            ->send();

                        return;
                    } elseif (! empty($duplicateSerial)) {
                        Notification::make()
                            ->title('Duplicate Serial Number')
                            ->body(implode(', ', $duplicateSerial)."<br>Duplicate Serial numbers found for the invoice '$invoiceNumber'.")
                            ->danger()
                            ->seconds(4)
                            ->send();

                        return;
                    }

                    $itemExceeded = [];

                    $invoiceRows = InvoiceValidation::where('plant_id', $plantId)
                        ->where('invoice_number', $invoiceNumber)
                        ->whereNull('serial_number')
                        ->get();

                    $palletItems = WireMasterPacking::where('wire_master_packings.plant_id', $plantId)
                        ->where('wire_master_packings.wire_packing_number', $wirePallet)
                        ->join('items', 'items.id', '=', 'wire_master_packings.item_id')
                        ->select(
                            'items.code as item_code',
                            DB::raw('SUM(wire_master_packings.weight::numeric) as pallet_weight')
                        )
                        ->groupBy('items.code')
                        ->get();

                    foreach ($invoiceRows as $row) {
                        $itemCode = $row->stickerMaster->item->code ?? null;

                        if (! $itemCode) {
                            continue;
                        }

                        $pallet = $palletItems->firstWhere('item_code', $itemCode);
                        $palletWeight = $pallet->pallet_weight ?? 0;

                        $remainingQty = $row->quantity;

                        if ($palletWeight > $remainingQty) {
                            $itemExceeded[] = $itemCode;
                        }
                    }

                    $items = implode(', ', $itemExceeded);

                    if (! empty($itemExceeded)) {
                        Notification::make()
                            ->title('Item Code Limit')
                            ->body("Pallet weight exceeds remaining quantity for invoice number '$invoiceNumber'for below item codes <br>$items")
                            ->danger()
                            ->seconds(5)
                            ->send();

                        return;
                    }

                    $wireItems = WireMasterPacking::join('items', 'items.id', '=', 'wire_master_packings.item_id')
                        ->where('wire_master_packings.wire_packing_number', $wirePallet)
                        ->select(
                            'items.code as item_code',
                            'wire_master_packings.process_order',
                            'wire_master_packings.weight as pallet_weight'
                            // DB::raw('(wire_master_packings.weight::numeric) as pallet_weight')
                        )
                        ->get();

                    foreach ($wireItems as $wireItem) {

                        $itemCode = $wireItem->item_code;
                        $palletWeight = $wireItem->pallet_weight;
                        $processOrder = $wireItem->process_order;

                        if (! $processOrder || $palletWeight <= 0) {
                            continue;
                        }

                        $records = InvoiceValidation::join('sticker_masters', 'sticker_masters.id', '=', 'invoice_validations.sticker_master_id')
                            ->join('items', 'items.id', '=', 'sticker_masters.item_id')
                            ->where('invoice_validations.invoice_number', $invoiceNumber)
                            ->where('invoice_validations.plant_id', $plantId)
                            ->where('items.code', $itemCode)
                            ->whereNull('invoice_validations.serial_number')
                            ->where('invoice_validations.quantity', '>', 0)
                            ->orderBy('invoice_validations.created_at')
                            ->select('invoice_validations.*')
                            ->get();

                        if ($records->isEmpty()) {
                            continue;
                        }

                        foreach ($records as $record) {

                            if ($palletWeight <= 0) {
                                break;
                            }

                            $usedQty = min($record->quantity, $palletWeight);

                            $record->quantity -= $usedQty;

                            if ($usedQty == $record->quantity + $usedQty) {
                                $record->serial_number = $processOrder;
                                $record->quantity = $palletWeight;
                                $record->save();
                            } else {
                                $record->save();

                                InvoiceValidation::create([
                                    'sticker_master_id' => $record->sticker_master_id,
                                    'plant_id' => $plantId,
                                    'invoice_number' => $invoiceNumber,
                                    'serial_number' => $processOrder,
                                    'quantity' => $usedQty,
                                    'operator_id' => $operatorName,
                                    'created_by' => $operatorName,
                                    'updated_by' => $operatorName,
                                ]);
                            }

                            $palletWeight -= $usedQty;

                            // if ($record->quantity <= 0) {
                            //     $records->forget($key);
                            // }
                        }
                    }

                    $this->dispatch('refreshMaterialInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId);

                    $totQuan = InvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->count();
                    $scanMQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNotNull('serial_number')->where('serial_number', '!=', '')->where('plant_id', $plantId)->count();

                    $checkMat = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->latest('updated_at')->first(); // ->where('quantity', '!=', '')
                    if (($checkMat?->stickerMaster->material_type ?? 0) == 3) {
                        $totMatQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->invoice_quantity ?? 0;
                        $scanMatQuan = number_format($totMatQuan - (InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->quantity ?? 0), 3, '.', ''); // ('updated_at', 'desc')
                    } else {
                        $totMatQuan = $totQuan;
                        $scanMatQuan = $scanMQuan;
                    }

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totMatQuan,
                        'update_invoice' => false,
                        'scanned_quantity' => $scanMatQuan,
                    ]);

                    return;
                } else {
                    $itemCode = null;
                    $this->currentItemCode = '';
                    $batchNumber = null;
                    $serNo = null;
                    $serialNumber = null;

                    Notification::make()
                        ->danger()
                        ->title('Invalid Material QR Format')
                        ->body('Scan valid Material QR code to proceed!<br>Sample formats are:<br>123456|123456789|001|5kg (or)<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
                        ->seconds(1)
                        ->send();

                    $this->dispatch('playWarnSound');

                    // .Mail

                    // $mailData = $this->getMail();
                    // $mPlantName = $mailData['plant_name'];
                    // $emails = $mailData['emails'];
                    // $mInvoiceType = 'Material';

                    // if (! empty($emails)) {
                    //     Mail::to($emails)->send(
                    //         new InvalidSerialMail($mSerNo, $invoiceNumber, $mPlantName, $mInvoiceType, $itemCode, 'InvalidMaterialFormat')
                    //     );
                    // } else {
                    //     \Log::warning("No recipients found for plant {$plantId}, module Serial, rule invalid_serial.");
                    // }

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totMatQuan,
                        'update_invoice' => false,
                        'scanned_quantity' => $scanMatQuan,
                    ]);

                    return;
                }

                // $record = StickerMaster::where('plant_id', $plantId)->with('item')->where('item.code', $itemCode);
                $record = StickerMaster::whereHas('item', function ($query) {
                    $query->where('code', $this->currentItemCode);
                });
                if ($record->count() <= 0) {
                    Notification::make()
                        ->title('Unknown: Item Code')
                        ->body("Item code '$itemCode' not found in database.")
                        ->danger()
                        ->seconds(2)
                        ->send();
                    $this->dispatch('playWarnSound');

                    // $mailData = $this->getMail();
                    // $mPlantName = $mailData['plant_name'];
                    // $emails = $mailData['emails'];
                    // $mInvoiceType = 'Material';

                    // if (! empty($emails)) {
                    //     Mail::to($emails)->send(
                    //         new InvalidSerialMail($mSerNo, $invoiceNumber, $mPlantName, $mInvoiceType, $itemCode, 'ItemNotFound')
                    //     );
                    // } else {
                    //     \Log::warning("No recipients found for plant {$plantId}, module Serial, rule invalid_serial.");
                    // }

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totMatQuan,
                        'update_invoice' => false,
                        'scanned_quantity' => $scanMatQuan,
                    ]);

                    return;
                }

                $record = StickerMaster::where('plant_id', $plantId)->whereHas('item', function ($query) {
                    $query->where('code', $this->currentItemCode);
                });
                if ($record->count() <= 0) {
                    Notification::make()
                        ->title('Unknown: Item Code')
                        ->body("Item code '$itemCode' not found in database for choosed plant.")
                        ->danger()
                        ->seconds(2)
                        ->send();
                    $this->dispatch('playWarnSound');

                    // $mailData = $this->getMail();
                    // $mPlantName = $mailData['plant_name'];
                    // $emails = $mailData['emails'];
                    // $mInvoiceType = 'Material';

                    // if (! empty($emails)) {
                    //     Mail::to($emails)->send(
                    //         new InvalidSerialMail($mSerNo, $invoiceNumber, $mPlantName, $mInvoiceType, $itemCode, 'ItemNotFoundDB')
                    //     );
                    // } else {
                    //     \Log::warning("No recipients found for plant {$plantId}, module Serial, rule invalid_serial.");
                    // }

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totMatQuan,
                        'update_invoice' => false,
                        'scanned_quantity' => $scanMatQuan,
                    ]);

                    return;
                }

                $record = StickerMaster::where('plant_id', $plantId)->where('item_id', Item::where('plant_id', $plantId)->where('code', $itemCode)->first()->id)->first();

                if (empty($record->material_type) || ! $record->material_type) {
                    Notification::make()
                        ->title('Invalid: Item Code')
                        ->body("Item code '$itemCode' doesn't have a valid material type.")
                        ->danger()
                        ->seconds(2)
                        ->send();
                    $this->dispatch('playWarnSound');

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totMatQuan,
                        'update_invoice' => false,
                        'scanned_quantity' => $scanMatQuan,
                    ]);

                    return;
                }

                $hasQuanTyp = ($record->material_type == 3) ? true : false;

                if ($hasQuanTyp && $curMaterialSer && $curMaterialQty) {
                    $batchNumber = null;
                    $serialNumber = $curMaterialSer;
                    $curScanQty = $curMaterialQty;
                }

                $record = InvoiceValidation::where('invoice_number', $invoiceNumber)
                    ->where('plant_id', $plantId)
                    ->whereHas('stickerMasterRelation.item', function ($query) use ($itemCode) {
                        $query->where('plant_id', $this->plantId)->where('code', $itemCode);
                    })
                    ->first();
                if (! $record) {
                    Notification::make()
                        ->title('Unknown: Item Code')
                        ->body("Item code '$itemCode' doesn't exist in invoice.")
                        ->danger()
                        ->seconds(2)
                        ->send();
                    $this->dispatch('playWarnSound');

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totMatQuan,
                        'update_invoice' => false,
                        'scanned_quantity' => $scanMatQuan,
                    ]);

                    return;
                }

                // ->whereNotNull('serial_number')->where('serial_number', '!=', '')
                $record = InvoiceValidation::where('invoice_number', $invoiceNumber)->where(function ($query) {
                    $query->whereNull('serial_number')->orWhere('serial_number', '');
                })->where('plant_id', $plantId)->whereHas('stickerMasterRelation.item', function ($query) use ($itemCode) {
                    $query->where('plant_id', $this->plantId)->where('code', $itemCode);
                })
                    ->first();
                if (! $record) {
                    Notification::make()
                        ->title('Item Code Limit Exceeds')
                        ->body("Scanned item code '$itemCode' already reached its scanning quantity for the invoice '$invoiceNumber'.")
                        ->danger()
                        ->seconds(2)
                        ->send();
                    $this->dispatch('playWarnSound');

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totMatQuan,
                        'update_invoice' => false,
                        'scanned_quantity' => $scanMatQuan,
                    ]);

                    return;
                }

                $dupRecord = InvoiceValidation::where('serial_number', $serialNumber)->where('plant_id', $plantId)->first();
                if ($dupRecord) {
                    Notification::make()
                        ->title('Duplicate: Material QR')
                        ->body("Scanned Material QR : '{$serialNumber}' already completed the scanning process..!")
                        ->danger()
                        ->seconds(2)
                        ->send();
                    $this->dispatch('playWarnSound');

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totMatQuan,
                        'update_invoice' => false,
                        'scanned_quantity' => $scanMatQuan,
                    ]);

                    return;
                }

                if ($hasQuanTyp) {
                    if (! is_numeric($curScanQty)) {
                        Notification::make()
                            ->danger()
                            ->title('Invalid Quantity Material QR Format')
                            ->body('Scan valid Quantity Material QR code to proceed!<br>Sample formats are:<br>123456|123456789|001|5kg (or)<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1')
                            ->seconds(2)
                            ->send();
                        $this->dispatch('playWarnSound');

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

                        return;
                    }

                    $createdDt = $record->created_at;
                    $stickMasterId = $record->sticker_master_id;
                    $curExistQty = $record->quantity;
                    $curItemInvQty = $record->invoice_quantity;
                    // $curScanQty = 2;

                    if ($curExistQty > $curScanQty) { // 5 > 2
                        $record->quantity = $curExistQty - $curScanQty; // 5 - 2
                        $record->operator_id = $operatorName;
                        // $record->updated_by = $operatorName;
                        // $record->updated_at = now();
                        $record->save();

                        InvoiceValidation::create([
                            'sticker_master_id' => $stickMasterId,
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => $serialNumber,
                            'batch_number' => $batchNumber,
                            'invoice_quantity' => $curItemInvQty,
                            'quantity' => $curScanQty,
                            'created_at' => $createdDt,
                            'operator_id' => $operatorName,
                            'created_by' => $operatorName,
                            'updated_by' => $operatorName,
                        ]);
                    } elseif ($curExistQty == $curScanQty) { // 2 = 2
                        // $record->delete();
                        $record->serial_number = $serialNumber;
                        $record->batch_number = $batchNumber;
                        $record->operator_id = $operatorName;
                        $record->updated_by = $operatorName;
                        $record->updated_at = now();
                        $record->save();

                        // InvoiceValidation::create([
                        //     'sticker_master_id' => $stickMasterId,
                        //     'plant_id' => $plantId,
                        //     'invoice_number' => $invoiceNumber,
                        //     'quantity' => $curScanQty,
                        //     'created_at' => $createdDt,
                        //     'operator_id'=> $operatorName,
                        //     'created_by' => $operatorName,
                        //     'updated_by' => $operatorName,
                        // ]);
                    } else {
                        Notification::make()
                            ->title('Item Code Limit Exceeds')
                            ->body("Scanned item code '$itemCode' has '$curScanQty' quantity.<br>But, '$curExistQty' quantity only available for the invoice '$invoiceNumber'.")
                            ->danger()
                            ->seconds(2)
                            ->send();
                        $this->dispatch('playWarnSound');

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

                        return;
                    }
                } else {
                    if (str_contains($serialNumber, '|')) {
                        Notification::make()
                            ->title('Duplicate: Material QR')
                            ->body("Scanned Material QR : '{$serialNumber}' already completed the scanning process..!")
                            ->danger()
                            ->seconds(2)
                            ->send();

                        $itemCode = null;
                        $this->currentItemCode = '';
                        $batchNumber = null;
                        $serNo = null;
                        $serialNumber = null;

                        $this->dispatch('playWarnSound');

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totMatQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanMatQuan,
                        ]);

                        return;
                    }

                    $record->serial_number = $serialNumber;
                    // if ($batchNumber && !empty($batchNumber)) {}
                    $record->batch_number = $batchNumber;
                    // $record->updated_at = now();
                    $record->operator_id = $operatorName;
                    // $record->updated_by = $operatorName;
                    $record->save();
                }

                // Notification::make()
                //     ->title('Success: Material QR')
                //     ->body("'Material QR' scanned status updated, Scan next QR.")
                //     ->success() // commented
                //     ->seconds(2)
                //     ->send();

                $totQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
                $scannedMQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNotNull('serial_number')->where('serial_number', '!=', '')->where('plant_id', $plantId)->count();

                $checkMat = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->latest('updated_at')->first(); // ->where('quantity', '!=', '')
                if (($checkMat?->stickerMaster->material_type ?? 0) == 3) {
                    $totMatQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->invoice_quantity ?? 0;
                    $scanMatQuan = number_format($totMatQuan - (InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNull('serial_number')->where('plant_id', $plantId)->latest('updated_at')->first()?->quantity ?? 0), 3, '.', ''); // ('updated_at', 'desc')
                } else {
                    $totMatQuan = $totQuan;
                    $scanMatQuan = $scannedMQuantity;
                }

                if ($totQuan == $scannedMQuantity) {
                    Notification::make()
                        ->title('Completed: Material Invoice')
                        ->body("Material invoice '$invoiceNumber' completed the scanning process.<br>Scan the next 'Material Invoice' to proceed!")
                        ->success()
                        ->seconds(2)
                        ->send();

                    $this->dispatch('playNotificationSound');

                    $filename = $invoiceNumber.'.xlsx';
                    $directory = "uploads/temp/{$plantCode}";
                    $disk = Storage::disk('local');
                    $filePath = $directory.'/'.$filename;
                    // $fullPath = null;
                    if ($disk->exists($filePath)) {
                        // $fullPath = $disk->path($filePath);
                        $disk->delete($filePath);
                    }

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => null,
                        'serial_number' => null,
                        'total_quantity' => 0,
                        'update_invoice' => false,
                        'scanned_quantity' => 0,
                    ]);

                    $this->dispatch('refreshCompletedInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId, isSerial: false);
                } else {
                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totMatQuan,
                        'update_invoice' => false,
                        'scanned_quantity' => $scanMatQuan,
                    ]);
                    $this->dispatch('refreshMaterialInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId);
                }

                return;
            } else {
                if ($totQuan == $scanSQuan) {
                    Notification::make()
                        ->title('Completed: Serial Invoice')
                        ->body("Serial invoice '$invoiceNumber' completed the scanning process.<br>Scan the next 'Serial Invoice' to proceed!")
                        ->warning()
                        ->seconds(3)
                        ->send();

                    $this->dispatch('playNotificationSound');

                    $filename = $invoiceNumber.'.xlsx';
                    $directory = "uploads/temp/{$plantCode}";
                    $disk = Storage::disk('local');
                    $filePath = $directory.'/'.$filename;
                    // $fullPath = null;
                    if ($disk->exists($filePath)) {
                        // $fullPath = $disk->path($filePath);
                        $disk->delete($filePath);
                    }

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => null,
                        'serial_number' => null,
                        'total_quantity' => 0,
                        'update_invoice' => false,
                        'scanned_quantity' => 0,
                    ]);

                    $this->dispatch('refreshCompletedInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId, isSerial: true);

                    return;
                } else {
                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totQuan,
                        'update_invoice' => false,
                        'scanned_quantity' => $scanSQuan,
                    ]);
                    // $hasRecords = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->first()->stickerMasterRelation->material_type ?? null;
                    $this->dispatch('refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId, onCapFocus: false);
                }

                // TN01/BOX22/SERIAL999 >> PANEL BOX QR
                // /^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/
                if (! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $serNo, $matches)) {
                    Notification::make()
                        ->danger()
                        ->title('Invalid Serial QR Format')
                        ->body('Scan valid Serial QR code proceed!<br>Sample formats are:<br>123456|1234567890123/M (or)<br>123456|1234567890123/P (or)<br>123456|1234567890123/C (or)<br>123456|1234567890123')
                        ->seconds(3)
                        ->send();

                    $this->dispatch('playWarnSound');

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'invoice_number' => $invoiceNumber,
                        'serial_number' => null,
                        'total_quantity' => $totQuan,
                        'update_invoice' => false,
                        'scanned_quantity' => $scanSQuan,
                    ]);

                    return;
                }

                // '/^([a-zA-Z0-9]+)\|([a-zA-Z0-9]+(?:\/[MmPpCc]?)?)$/'
                if (preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $serNo, $matches)) {
                    $itemCode = $matches[1];
                    $serialNumber = $matches[2];

                    // // Check if it ends with /M, /P, /C etc.
                    // $isMarkM = preg_match('/\/[Mm]$/', $serialNumber);
                    // $isMarkP = preg_match('/\/[Pp]$/', $serialNumber);
                    // $isMarkC = preg_match('/\/[Cc]$/', $serialNumber);
                    $isMarkM = preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})\/[Mm]?\|?$/', $serNo) ? true : false;
                    $isMarkP = preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})\/[Pp]?\|?$/', $serNo) ? true : false;
                    $isMarkC = preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})\/[Cc]?\|?$/', $serNo) ? true : false;
                    $isMarkPs = (! $isMarkM && ! $isMarkP && ! $isMarkC) ? true : false;
                    // dd($serialNumber, $isMarkM, $isMarkP, $isMarkC, $isMarkPs);

                    $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber);

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

                    if (! $record) {
                        Notification::make()
                            ->title('<b><span style="color:red;">Serial Number Not Found<br>Serial \''.$serialNumber.'\' not found in database for choosed plant.</span></b>')
                            // ->body("Serial '$serialNumber' not found in database for choosed plant.")..........
                            ->danger()
                            ->seconds(3)
                            ->send();

                        $this->dispatch('play-warn-sound');

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanSQuan,
                        ]);

                        return;
                    }

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

                    if (! $record) {
                        Notification::make()
                            ->title('<b><span style="color:red;">Unknown: Serial Number<br>Serial \''.$serialNumber.'\' not found in invoice.</span></b>')
                            // ->body("Serial '$serialNumber' not found in invoice.")
                            ->danger()
                            ->seconds(3)
                            ->send();

                        $this->dispatch('playWarnSound');

                        // .Mail
                        $mInvoiceType = 'Serial';
                        $mailData = $this->getMail();
                        $mPlantName = $mailData['plant_name'];
                        $emails = $mailData['emails'];

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

                        if (! empty($emails)) {
                            Mail::to($emails)->send(
                                new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType, $itemCode, $mUserName, 'NotFoundInvoice')
                            );
                        } else {
                            \Log::warning("No recipients found for plant {$plantId}, module Serial, rule invalid_serial.");
                        }

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanSQuan,
                        ]);

                        return;
                    }

                    $record = InvoiceValidation::where('serial_number', $serialNumber)
                        ->where('plant_id', $plantId)
                        ->whereHas('stickerMasterRelation.item', function ($query) use ($itemCode) {
                            $query->where('plant_id', $this->plantId)->where('code', $itemCode);
                        })
                        ->first();

                    if (! $record) {
                        Notification::make()
                            ->title('Unknown: Item Code')
                            ->body("Item code '$itemCode' with serial number '$serialNumber' not found.")
                            ->danger()
                            ->seconds(3)
                            ->send();

                        $this->dispatch('playWarnSound');

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanSQuan,
                        ]);

                        return;
                    }

                    $invalidPackage = false;

                    $hasMotorQr = $record->stickerMasterRelation->tube_sticker_motor ?? null;
                    $hasPumpQr = $record->stickerMasterRelation->tube_sticker_pump ?? null;
                    $hasPumpSetQr = $record->stickerMasterRelation->tube_sticker_pumpset ?? null;
                    $hasCapacitorQr = $record->stickerMasterRelation->panel_box_code ?? null;

                    if (! $hasMotorQr && ! $hasPumpQr && ! $hasPumpSetQr) {// && ! $hasCapacitorQr
                        $hasMotorQr = $record->stickerMasterRelation->pack_slip_motor ?? null;
                        $hasPumpQr = $record->stickerMasterRelation->pack_slip_pump ?? null;
                        $hasPumpSetQr = $record->stickerMasterRelation->pack_slip_pumpset ?? null;
                    } else {
                        if (! $hasPumpSetQr && ! $hasPumpQr) {
                            $hasPumpQr = $record->stickerMasterRelation->pack_slip_pump ?? null;
                        }

                        $hasTubeMotorQr = $record->stickerMasterRelation->tube_sticker_motor ?? null;
                        $hasPackMotorQr = $record->stickerMasterRelation->pack_slip_motor ?? null;
                        $hasTubePumpSetQr = $record->stickerMasterRelation->tube_sticker_pumpset ?? null;
                        $hasPackPumpSetQr = $record->stickerMasterRelation->pack_slip_pumpset ?? null;
                        if ($hasTubeMotorQr != $hasPackMotorQr || $hasTubePumpSetQr != $hasPackPumpSetQr) {
                            $invalidPackage = true;
                        }
                    }

                    $hadMotorQr = $record->motor_scanned_status ?? null;
                    $hadPumpQr = $record->pump_scanned_status ?? null;
                    $hadPumpSetQr = $record->scanned_status_set ?? null;
                    $hadCapacitorQr = $record->capacitor_scanned_status ?? null;

                    if ((! $hasMotorQr && ! $hasPumpQr && ! $hasPumpSetQr && ! $hasCapacitorQr) || $invalidPackage) {
                        Notification::make()
                            ->title('Invalid: Item Code')
                            ->body("Scanned 'Item Code' doesn't have valid package type to proceed!")
                            ->danger()
                            ->seconds(3)
                            ->send();

                        $this->dispatch('playWarnSound');

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scanSQuan,
                        ]);

                        return;
                    }

                    if ($hasMotorQr && ! $hasPumpQr && ! $hasPumpSetQr && ! $hasCapacitorQr) {
                        $isMarkM = true;
                        $isMarkP = false;
                        $isMarkC = false;
                        $isMarkPs = false;
                    } elseif (! $hasMotorQr && $hasPumpQr && ! $hasPumpSetQr && ! $hasCapacitorQr) {
                        $isMarkM = false;
                        $isMarkP = true;
                        $isMarkC = false;
                        $isMarkPs = false;
                    } elseif (! $hasMotorQr && ! $hasPumpQr && ! $hasPumpSetQr && $hasCapacitorQr) {
                        $isMarkM = false;
                        $isMarkP = false;
                        $isMarkC = true;
                        $isMarkPs = false;
                    }

                    if ($isMarkM) {
                        if (! $hasMotorQr) {
                            Notification::make()
                                ->title('Unknown: Motor QR')
                                ->body("Scanned 'Item Code' doesn't have 'Motor' QR to proceed!")
                                ->danger()
                                ->seconds(3)
                                ->send();
                            $this->dispatch('playWarnSound');

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'serial_number' => null,
                                'total_quantity' => $totQuan,
                                'update_invoice' => false,
                                'scanned_quantity' => $scanSQuan,
                            ]);

                            return;
                        } elseif ($hadMotorQr == $hasMotorQr) {
                            Notification::make()
                                ->title('Duplicate: Motor QR')
                                ->body("Scanned Motor Serial Number : '{$serialNumber}' already completed the scanning process.")
                                ->danger()
                                ->seconds(3)
                                ->send();

                            $this->dispatch('playWarnSound');

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'serial_number' => null,
                                'total_quantity' => $totQuan,
                                'update_invoice' => false,
                                'scanned_quantity' => $scanSQuan,
                            ]);

                            return;
                        }

                        $packCnt = 1;
                        $scanCnt = 1;
                        $record->motor_scanned_status = 1;
                        // if ($hadPumpQr == $hasPumpQr && $hadPumpSetQr == $hasPumpSetQr)
                        if ($hasPumpQr || $hasPumpSetQr || $hasCapacitorQr) {
                            $packCnt = $hasPumpQr ? $packCnt + 1 : $packCnt;
                            $packCnt = $hasPumpSetQr ? $packCnt + 1 : $packCnt;
                            $packCnt = $hasCapacitorQr ? $packCnt + 1 : $packCnt;

                            $scanCnt = $hadPumpQr ? $scanCnt + 1 : $scanCnt;
                            $scanCnt = $hadPumpSetQr ? $scanCnt + 1 : $scanCnt;
                            $scanCnt = $hadCapacitorQr ? $scanCnt + 1 : $scanCnt;

                            if ($packCnt == $scanCnt) {
                                $record->scanned_status = 'Scanned';
                            }
                        } else {
                            $record->scanned_status = 'Scanned';
                        }
                        $record->operator_id = $operatorName;
                        // $record->updated_by = $operatorName;
                        $record->save();

                        // Notification::make()
                        //     ->title('Success: Motor QR')
                        //     ->body("'Motor' QR scanned status updated, Scan next QR.")
                        //     ->success() // commented
                        //     ->seconds(3)
                        //     ->send();

                        $scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scannedQuantity,
                        ]);

                        if ($totQuan == $scannedQuantity) {
                            Notification::make()
                                ->title('Completed: Serial Invoice')
                                ->body("Serial invoice '$invoiceNumber' completed the scanning process.<br>Scan the next 'Serial Invoice' to proceed!")
                                ->success()
                                ->seconds(3)
                                ->send();
                            $this->dispatch('playNotificationSound');

                            $filename = $invoiceNumber.'.xlsx';
                            $directory = "uploads/temp/{$plantCode}";
                            $disk = Storage::disk('local');
                            $filePath = $directory.'/'.$filename;
                            // $fullPath = null;
                            if ($disk->exists($filePath)) {
                                // $fullPath = $disk->path($filePath);
                                $disk->delete($filePath);
                            }

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'invoice_number' => null,
                                'serial_number' => null,
                                'total_quantity' => 0,
                                'update_invoice' => false,
                                'scanned_quantity' => 0,
                            ]);

                            $this->dispatch('refreshCompletedInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId, isSerial: true);
                        } else {
                            $this->dispatch('refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId, onCapFocus: false);
                            // $this->refreshInvoiceTable();
                        }

                        return;
                    } elseif ($isMarkP) {
                        if (! $hasPumpQr) {
                            Notification::make()
                                ->title('Unknown: Pump QR')
                                ->body("Scanned 'Item Code' doesn't have 'Pump' QR to proceed!")
                                ->danger()
                                ->seconds(3)
                                ->send();

                            $this->dispatch('playWarnSound');

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'serial_number' => null,
                                'total_quantity' => $totQuan,
                                'update_invoice' => false,
                                'scanned_quantity' => $scanSQuan,
                            ]);

                            return;
                        } elseif ($hadPumpQr == $hasPumpQr) {
                            Notification::make()
                                ->title('Duplicate: Pump QR')
                                ->body("Scanned Pump Serial Number : '{$serialNumber}' already completed the scanning process.")
                                ->danger()
                                ->seconds(3)
                                ->send();
                            $this->dispatch('playWarnSound');

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'serial_number' => null,
                                'total_quantity' => $totQuan,
                                'update_invoice' => false,
                                'scanned_quantity' => $scanSQuan,
                            ]);

                            return;
                        }

                        $packCnt = 1;
                        $scanCnt = 1;
                        $record->pump_scanned_status = 1;
                        // if ($hadMotorQr == $hasMotorQr && $hadPumpSetQr == $hasPumpSetQr && ($hadCapacitorQr == '1' && $hasCapacitorQr))
                        if ($hasMotorQr || $hasPumpSetQr || $hasCapacitorQr) {
                            $packCnt = $hasMotorQr ? $packCnt + 1 : $packCnt;
                            $packCnt = $hasPumpSetQr ? $packCnt + 1 : $packCnt;
                            $packCnt = $hasCapacitorQr ? $packCnt + 1 : $packCnt;

                            $scanCnt = $hadMotorQr ? $scanCnt + 1 : $scanCnt;
                            $scanCnt = $hadPumpSetQr ? $scanCnt + 1 : $scanCnt;
                            $scanCnt = $hadCapacitorQr ? $scanCnt + 1 : $scanCnt;

                            if ($packCnt == $scanCnt) {
                                $record->scanned_status = 'Scanned';
                            }
                        } else {
                            $record->scanned_status = 'Scanned';
                        }
                        $record->operator_id = $operatorName;
                        // $record->updated_by = $operatorName;
                        $record->save();

                        // Notification::make()
                        //     ->title('Success: Pump QR')
                        //     ->body("'Pump' QR scanned status updated, Scan next QR.")
                        //     ->success() // commented
                        //     ->seconds(3)
                        //     ->send();

                        $scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scannedQuantity,
                        ]);

                        if ($totQuan == $scannedQuantity) {
                            Notification::make()
                                ->title('Completed: Serial Invoice')
                                ->body("Serial invoice '$invoiceNumber' completed the scanning process.<br>Scan the next 'Serial Invoice' to proceed!")
                                ->success()
                                ->seconds(3)
                                ->send();

                            $this->dispatch('playNotificationSound');

                            $filename = $invoiceNumber.'.xlsx';
                            $directory = "uploads/temp/{$plantCode}";
                            $disk = Storage::disk('local');
                            $filePath = $directory.'/'.$filename;
                            // $fullPath = null;
                            if ($disk->exists($filePath)) {
                                // $fullPath = $disk->path($filePath);
                                $disk->delete($filePath);
                            }

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'invoice_number' => null,
                                'serial_number' => null,
                                'total_quantity' => 0,
                                'update_invoice' => false,
                                'scanned_quantity' => 0,
                            ]);

                            $this->dispatch('refreshCompletedInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId, isSerial: true);
                        } else {
                            $this->dispatch('refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId, onCapFocus: false);
                            // $this->refreshInvoiceTable();
                        }

                        return;
                    } elseif ($isMarkC) {
                        if (! $hasCapacitorQr) {
                            Notification::make()
                                // ->title('Unknown: Capacitor QR')
                                ->title('Missing: Panel Box Code')
                                // ->body("Panel Box Code is not available for Item Code : '$itemCode'.")
                                ->body("Scanned 'Item Code' doesn't have 'Panel Box Code' to proceed!")
                                ->danger()
                                ->seconds(3)
                                ->send();

                            $this->dispatch('playWarnSound');

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'serial_number' => null,
                                'total_quantity' => $totQuan,
                                'update_invoice' => false,
                                'scanned_quantity' => $scanSQuan,
                            ]);

                            return;
                        } elseif ($hadCapacitorQr == '1' && $hasCapacitorQr) {
                            Notification::make()
                                ->title('Duplicate: Capacitor QR')
                                ->body("Scanned Capacitor Serial Number : '{$serialNumber}' already completed the scanning process.")
                                ->danger()
                                ->seconds(3)
                                ->send();

                            $this->dispatch('playWarnSound');

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'serial_number' => null,
                                'total_quantity' => $totQuan,
                                'update_invoice' => false,
                                'scanned_quantity' => $scanSQuan,
                            ]);

                            return;
                        }

                        // hereToUpdate
                        // $this->dispatch('openCapacitorModal');
                        $this->dispatch('openCapacitorModal', itemCode: $itemCode, serialNumber: $serialNumber, plantId: $plantId);

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

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scannedQuantity,
                        ]);

                        $this->dispatch('refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId, onCapFocus: true);

                        // $this->refreshInvoiceTable();
                        return;
                    } elseif ($isMarkPs) {
                        if (! $hasPumpSetQr) {
                            Notification::make()
                                ->title('Unknown: Pump Set QR')
                                ->body("Scanned 'Item Code' doesn't have 'Pump Set' QR to proceed!")
                                ->danger()
                                ->seconds(3)
                                ->send();

                            $this->dispatch('playWarnSound');

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'serial_number' => null,
                                'total_quantity' => $totQuan,
                                'update_invoice' => false,
                                'scanned_quantity' => $scanSQuan,
                            ]);

                            return;
                        } elseif ($hadPumpSetQr == $hasPumpSetQr) {
                            Notification::make()
                                ->title('Duplicate: Pump Set QR')
                                ->body("Scanned Pump Set Serial Number : '{$serialNumber}' already completed the scanning process.")
                                ->danger()
                                ->seconds(3)
                                ->send();

                            $this->dispatch('playWarnSound');

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'invoice_number' => $invoiceNumber,
                                'serial_number' => null,
                                'total_quantity' => $totQuan,
                                'update_invoice' => false,
                                'scanned_quantity' => $scanSQuan,
                            ]);

                            return;
                        }

                        $packCnt = 1;
                        $scanCnt = 1;
                        $record->scanned_status_set = 1;
                        // if ($hadMotorQr == $hasMotorQr && $hadPumpQr == $hasPumpQr && ($hadCapacitorQr == '1' && $hasCapacitorQr))
                        if ($hasMotorQr || $hasPumpQr || $hasCapacitorQr) {
                            $packCnt = $hasMotorQr ? $packCnt + 1 : $packCnt;
                            $packCnt = $hasPumpQr ? $packCnt + 1 : $packCnt;
                            $packCnt = $hasCapacitorQr ? $packCnt + 1 : $packCnt;

                            $scanCnt = $hadMotorQr ? $scanCnt + 1 : $scanCnt;
                            $scanCnt = $hadPumpQr ? $scanCnt + 1 : $scanCnt;
                            $scanCnt = $hadCapacitorQr ? $scanCnt + 1 : $scanCnt;

                            if ($packCnt == $scanCnt) {
                                $record->scanned_status = 'Scanned';
                            }
                        } else {
                            $record->scanned_status = 'Scanned';
                        }
                        $record->operator_id = $operatorName;
                        // $record->updated_by = $operatorName;
                        $record->save();

                        // Notification::make()
                        //     ->title('Success: Pump Set QR')
                        //     ->body("'Pump Set' QR scanned status updated, Scan next QR.")
                        //     ->success() // commented
                        //     ->seconds(3)
                        //     ->send();

                        $scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
                        $this->form->fill([
                            'plant_id' => $plantId,
                            'invoice_number' => $invoiceNumber,
                            'serial_number' => null,
                            'total_quantity' => $totQuan,
                            'update_invoice' => false,
                            'scanned_quantity' => $scannedQuantity,
                        ]);

                        if ($totQuan == $scannedQuantity) {
                            Notification::make()
                                ->title('Completed: Serial Invoice')
                                ->body("Serial invoice '$invoiceNumber' completed the scanning process.<br>Scan the next 'Serial Invoice' to proceed!")
                                ->success()
                                ->seconds(3)
                                ->send();

                            $this->dispatch('playNotificationSound');

                            // $mInvoiceType = 'Serial';
                            // $mailData = $this->getMail();
                            // $mPlantName = $mailData['plant_name'];
                            // $emails = $mailData['emails'];

                            // if (! empty($emails)) {
                            //     // Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType));
                            //     Mail::to($emails)->send(
                            //         new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType, $itemCode, 'ComSerInv')
                            //     );
                            // } else {
                            //     \Log::warning("No recipients found for plant {$plantId}, module Serial, rule invalid_serial.");
                            // }

                            $filename = $invoiceNumber.'.xlsx';
                            $directory = "uploads/temp/{$plantCode}";
                            $disk = Storage::disk('local');
                            $filePath = $directory.'/'.$filename;
                            // $fullPath = null;
                            if ($disk->exists($filePath)) {
                                // $fullPath = $disk->path($filePath);
                                $disk->delete($filePath);
                            }

                            $this->form->fill([
                                'plant_id' => $plantId,
                                'invoice_number' => null,
                                'serial_number' => null,
                                'total_quantity' => 0,
                                'update_invoice' => false,
                                'scanned_quantity' => 0,
                            ]);

                            $this->dispatch('refreshCompletedInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId, isSerial: true);
                        } else {
                            $this->dispatch('refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId, onCapFocus: false);
                            // $this->refreshInvoiceTable();
                        }

                        return;
                    }
                }
            }
        }
    }

    #[On('process-scan')]
    public function processSerial($serial)
    {
        $this->processSer($serial);
    }

    public function getHeading(): string
    {
        return 'Scan Invoice Validation';
    }
}
