<?php

namespace App\Filament\Pages;

use App\Models\InvoiceValidation;
use App\Models\Item;
use App\Models\NotInStock;
use App\Models\Plant;
use App\Models\StickerMaster;
use App\Models\StockDataMaster;
use Filament\Actions\Action;
use Filament\Actions\Concerns\InteractsWithActions;
use Filament\Facades\Filament;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Illuminate\Support\Facades\Auth;

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

    protected static string $view = 'filament.pages.cycle-count';

    protected static ?string $navigationGroup = 'Cycle Count Software';

    use InteractsWithActions;
    use InteractsWithForms;

    public $serialNumber;

    public $location;

    public $bin;

    public $snoCount = 0;

    public $state = [];

    public $plantId;

    public $itemCode;

    public $batch;

    public $docNo;

    public $quantity;

    public $sNo;

    public array $filters = [];

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

    public function form(Form $form): Form
    {
        return $form
            ->statePath('filters')
            ->schema([
                Section::make('')
                    ->schema([
                        Select::make('plant_id')
                            ->label('Plant')
                            ->reactive()
                            ->options(function (callable $get) {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                            })
                            ->required(),
                        TextInput::make('location')
                            ->label('Location')
                            ->reactive()
                            ->required()
                            ->readOnly(fn (callable $get) => ! $get('plant_id')),
                        // ->extraAttributes([
                        //     'wire:keydown.enter' => 'processLocation($event.target.value)',
                        // ]),
                        TextInput::make('bin')
                            ->label('Bin')
                            ->readOnly(fn (callable $get) => ! $get('plant_id') || ! $get('location'))
                            ->reactive()
                            ->required()
                            ->rules(['min:6']),
                        TextInput::make('qr_code')
                            ->label('QR Code')
                            ->reactive()
                            ->readOnly(fn (callable $get) => ! $get('plant_id') || ! $get('location') || ! $get('bin'))
                            ->extraAttributes([
                                'wire:keydown.enter' => 'processScan($event.target.value)',
                            ]),
                        // TextInput::make('scanned_quantity')
                        //     ->label('Scanned Quantity')
                        //     ->reactive()
                        //     ->readOnly(),
                    ])
                    ->columns(4),
            ]);
    }

    public function processScan($value)
    {

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

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

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

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

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

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

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

        $pattern1 = '/^[^#]*#[^#]*#[^#]*#[^#]*#$/';
        // $pattern2 = '/^[^|]*\|[^|]*\|[^|]*$/';
        $pattern2 = '/^[^|]+\|[^|]+(?:\|[^|]*)?$/';
        $pattern3 = '/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPp])?\|?$/';

        // $pattern2 = '/^[^|]+\|[^|]+\|[^|]+\|?$/';  Optional Pipeline at end

        if (! preg_match($pattern1, $value) && ! preg_match($pattern2, $value) && ! preg_match($pattern3, $value)) {
            Notification::make()
                ->danger()
                ->title('Invalid QR Format')
                ->body('Scan the valid QR code to proceed either FG or Non-FG!')
                ->seconds(3)
                ->send();

            $this->form->fill([
                'plant_id' => $plantId,
                'location' => $location,
                'bin' => $bin,
                'qr_code' => null,
            ]);

            return;
        }

        if (preg_match($pattern1, $value)) {
            $value = rtrim($value, '#');
            $parts = explode('#', $value);

            $this->itemCode = $parts[0] ?? null;
            $this->batch = $parts[1] ?? null;
            $this->docNo = $parts[2] ?? null;
            $this->quantity = $parts[3] ?? null;

            if (strlen($this->itemCode) < 6) {
                Notification::make()
                    ->title('Unknown Item Code')
                    ->body("Item Code should contain minimum 6 digits '$this->itemCode'")
                    ->danger()
                    ->send();
                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            } elseif (! ctype_alnum($this->itemCode)) {
                Notification::make()
                    ->title('Unknown Item Code')
                    ->body("Item Code should contain alpha-numeric values '$this->itemCode'")
                    ->danger()
                    ->duration(5000)
                    ->send();
                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            } elseif ($this->batch != '' || $this->batch != null) {

                if (strlen($this->batch) < 5) {
                    Notification::make()
                        ->title('Unknown Batch')
                        ->body("Batch should contain minimum 5 digits '$this->batch'")
                        ->danger()
                        ->duration(5000)
                        ->send();
                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

            } elseif (strlen($this->docNo) < 5) {
                Notification::make()
                    ->title('Unknown Doc No')
                    ->body("Doc No should contain minimum 5 digits '$this->docNo'")
                    ->danger()
                    ->duration(5000)
                    ->send();
                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            } elseif (! ctype_digit($this->quantity)) {
                Notification::make()
                    ->title('Unknown Quantity')
                    ->body("Quantity must be an integer value '$this->quantity'")
                    ->danger()
                    ->duration(5000)
                    ->send();
                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $item = Item::where('code', $this->itemCode)->first();

            if (! $item) {
                Notification::make()
                    ->title('Item Code Not Found')
                    ->body("Item code not found '$this->itemCode'")
                    ->danger()
                    ->duration(5000)
                    ->send();
                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $itemCodeAgaPlant = Item::where('plant_id', $plantId)->where('code', $this->itemCode)->first();

            $plantCo = Plant::where('id', $plantId)->first();

            $plantCode = $plantCo->code;

            if (! $itemCodeAgaPlant) {
                Notification::make()
                    ->title('Item Code Not Found')
                    ->body("Item code '$this->itemCode' not found against plant code '$plantCode'")
                    ->danger()
                    ->duration(5000)
                    ->send();
                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $stickerExists = StickerMaster::where('item_id', $item->id)->first();

            if (! $stickerExists) {

                Notification::make()
                    ->title('Unknown Sticker Master')
                    ->body("Item code not found in sticker master '{$this->itemCode}'")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $stickerExists = StickerMaster::where('plant_id', $plantId)
                ->where('item_id', $item->id)
                ->first();

            if (! $stickerExists) {

                Notification::make()
                    ->title('Unknown Sticker Master')
                    ->body("Item code not found in sticker master '{$this->itemCode}' in plant '{$plantCode}'")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $stickerMasterId = $stickerExists->id;

            $locationExist = StockDataMaster::where('type', '1')
                ->where('location', $location)
                ->first();

            if (! $locationExist) {

                $existingInOtherLocation = NotInStock::where('plant_id', $plantId)
                    ->where('serial_number', $this->sNo)
                    ->first();

                if ($existingInOtherLocation) {
                    Notification::make()
                        ->title('Serial Number : Not In Stock')
                        ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                Notification::make()
                    ->title('Unknown Location')
                    ->body("Location '$location' not found for the type Non-FG.")
                    ->danger()
                    ->persistent()
                    ->actions([
                        \Filament\Notifications\Actions\Action::make('confirm_update')
                            ->label('Yes, Update')
                            ->button()
                            ->dispatch('confirmStockUpdate', [
                                'plantId' => $plantId,
                                'location' => $location,
                                'bin' => $bin,
                                'stickerMasterId' => $stickerMasterId,
                                'batch' => $this->batch,
                                'docNo' => $this->docNo,
                                'quantity' => $this->quantity,
                            ]),
                    ])
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $locationAgaPlant = StockDataMaster::where('plant_id', $plantId)
                ->where('type', '1')
                ->where('location', $location)
                ->first();

            if (! $locationAgaPlant) {

                $existingInOtherLocation = NotInStock::where('plant_id', $plantId)
                    ->where('serial_number', $this->sNo)
                    ->first();

                if ($existingInOtherLocation) {
                    Notification::make()
                        ->title('Serial Number : Not In Stock')
                        ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                Notification::make()
                    ->title('Unknown Location')
                    ->body("Location '$location' not found for the type Non-FG against plant code '$plantCode'.")
                    ->danger()
                    ->actions([
                        \Filament\Notifications\Actions\Action::make('confirm_update')
                            ->label('Yes, Update')
                            ->button()
                            ->dispatch('confirmStockUpdate', [
                                'plantId' => $plantId,
                                'location' => $location,
                                'bin' => $bin,
                                'stickerMasterId' => $stickerMasterId,
                                'batch' => $this->batch,
                                'docNo' => $this->docNo,
                                'quantity' => $this->quantity,
                            ]),
                    ])
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $locationItemAgaPlant = StockDataMaster::where('plant_id', $plantId)
                ->where('type', '1')
                ->where('location', $location)
                ->where('sticker_master_id', $stickerMasterId)
                ->first();

            if (! $locationItemAgaPlant) {

                $existingInOtherLocation = NotInStock::where('plant_id', $plantId)
                    ->where('serial_number', $this->sNo)
                    ->first();

                if ($existingInOtherLocation) {
                    Notification::make()
                        ->title('Serial Number : Not In Stock')
                        ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                Notification::make()
                    ->title('Item Not Found in Location')
                    ->body("Item Code '$this->itemCode' is not available in location '$location' (Type: Non-FG) for Plant Code '$plantCode'.")
                    ->danger()
                    ->actions([
                        \Filament\Notifications\Actions\Action::make('confirm_update')
                            ->label('Yes, Update')
                            ->button()
                            ->dispatch('confirmStockUpdate', [
                                'plantId' => $plantId,
                                'location' => $location,
                                'bin' => $bin,
                                'stickerMasterId' => $stickerMasterId,
                                'batch' => $this->batch,
                                'docNo' => $this->docNo,
                                'quantity' => $this->quantity,
                            ]),
                    ])
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            if ($locationItemAgaPlant->batch != $this->batch) {

                $existingInOtherLocation = NotInStock::where('plant_id', $plantId)
                    ->where('serial_number', $this->sNo)
                    ->first();

                if ($existingInOtherLocation) {
                    Notification::make()
                        ->title('Serial Number : Not In Stock')
                        ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                Notification::make()
                    ->title('Batch Mismatch')
                    ->body("Location '$location' exists for item code '$this->itemCode', but it belongs to batch '{$locationItemAgaPlant->batch}'.")
                    ->danger()
                    ->actions([
                        \Filament\Notifications\Actions\Action::make('confirm_update')
                            ->label('Yes, Update')
                            ->button()
                            ->dispatch('confirmStockUpdate', [
                                'plantId' => $plantId,
                                'location' => $location,
                                'bin' => $bin,
                                'stickerMasterId' => $stickerMasterId,
                                'batch' => $this->batch,
                                'docNo' => $this->docNo,
                                'quantity' => $this->quantity,
                            ]),
                    ])
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            if ($locationItemAgaPlant->doc_no != $this->docNo) {

                $existingInOtherLocation = NotInStock::where('plant_id', $plantId)
                    ->where('serial_number', $this->sNo)
                    ->first();

                if ($existingInOtherLocation) {
                    Notification::make()
                        ->title('Serial Number : Not In Stock')
                        ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                Notification::make()
                    ->title('Document Mismatch')
                    ->body("Location '$location' exists for item code '$this->itemCode', but it belongs to document number '{$locationItemAgaPlant->doc_no}'.")
                    ->danger()
                    ->actions([
                        \Filament\Notifications\Actions\Action::make('confirm_update')
                            ->label('Yes, Update')
                            ->button()
                            ->dispatch('confirmStockUpdate', [
                                'plantId' => $plantId,
                                'location' => $location,
                                'bin' => $bin,
                                'stickerMasterId' => $stickerMasterId,
                                'batch' => $this->batch,
                                'docNo' => $this->docNo,
                                'quantity' => $this->quantity,
                            ]),
                    ])
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $stock = StockDataMaster::where('plant_id', $plantId)
                ->where('sticker_master_id', $stickerMasterId)
                ->where('location', $location)
                ->where('doc_no', $this->docNo)
                ->first();

            if ($stock) {

                $currentScanned = $stock->scanned_quantity ?? 0;
                $newScannedQty = $currentScanned + $this->quantity;

                // $remainingStock = $stock->quantity - $currentScanned;

                if ($stock->scanned_status == 'Scanned') {

                    Notification::make()
                        ->title('Duplicate Serial Number')
                        ->body("Serial number '$this->sNo' has already been scanned in stock data master for the type Non-FG against plant code '$plantCode'.<br>Do you want to update in duplicate stock table?")
                        ->danger()
                        ->actions([
                            \Filament\Notifications\Actions\Action::make('confirm')
                                ->label('Yes, Update')
                                ->button()
                                ->dispatch('confirmDuplicateUpdate', [
                                    'plantId' => $plantId,
                                    'location' => $location,
                                    'bin' => $bin,
                                    'serial_number' => $this->sNo,
                                    'stickerMasterId' => $stickerMasterId,
                                    'batch' => $this->batch,
                                    'docNo' => $this->docNo,
                                    'quantity' => $this->quantity,
                                ]),
                        ])
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                if ($newScannedQty > $stock->quantity) {

                    Notification::make()
                        ->title('Exceeded Quantity')
                        ->body("Total Scanned quantity '$newScannedQty' exceeds available stock quantity '$stock->quantity'.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                $status = $newScannedQty == $stock->quantity ? 'Scanned' : null;

                $stock->update([
                    'bin' => $bin,
                    'batch' => $this->batch,
                    'doc_no' =>$this->docNo,
                    'scanned_quantity' => $newScannedQty,
                    'scanned_status' => $status,
                ]);
                $this->dispatch('refreshSfgData', location: $location, plantId: $plantId, itemCode: $this->itemCode, docNo: $this->docNo);
            } else {
                Notification::make()
                    ->title('Unknown : Data Found')
                    ->body("No matching record found for the given Location, Item Code, Batch, and Document Number under Plant Code '$plantCode' in stock data master.")
                    ->danger()
                    ->actions([
                        \Filament\Notifications\Actions\Action::make('confirm_update')
                            ->label('Yes, Update')
                            ->button()
                            ->dispatch('confirmStockUpdate', [
                                'plantId' => $plantId,
                                'location' => $location,
                                'bin' => $bin,
                                'stickerMasterId' => $stickerMasterId,
                                'batch' => $this->batch,
                                'docNo' => $this->docNo,
                                'quantity' => $this->quantity,
                            ]),
                    ])
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                $this->dispatch('playWarnSound');

                return;

            }
        } elseif (preg_match($pattern2, $value)) {
            $value = rtrim($value, '|');
            $parts = explode('|', $value);

            $this->itemCode = $parts[0] ?? null;

             if (count($parts) == 2) {
                // Format: itemcode|serialnumber
                $this->sNo = $parts[1];
                $this->batch = null;
            } else {
                // Format: itemcode|value1|value2
                if (strlen($parts[1]) > strlen($parts[2])) {
                    $this->sNo = $parts[1];
                    $this->batch = $parts[2];
                } else {
                    $this->batch = $parts[1];
                    $this->sNo = $parts[2];
                }
            }
            // if (strlen($parts[1]) > strlen($parts[2])) {
            //     $this->sNo = $parts[1];
            //     $this->batch = $parts[2];
            // } else {
            //     $this->batch = $parts[1];
            //     $this->sNo = $parts[2];
            // }

            if (strlen($this->itemCode) < 6) {
                Notification::make()
                    ->title('Unknown Item Code')
                    ->body("Item Code should contain minimum 6 digits '$this->itemCode'")
                    ->danger()
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            } elseif (! ctype_alnum($this->itemCode)) {
                Notification::make()
                    ->title('Unknown Item Code')
                    ->body("Item Code should contain alpha-numeric values '$this->itemCode'")
                    ->danger()
                    ->duration(5000)
                    ->send();
                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            } elseif (count($parts) !== 2 &&  strlen($this->batch) < 5) {
                Notification::make()
                    ->title('Unknown Batch')
                    ->body("Batch should contain minimum 5 digits '$this->batch'")
                    ->danger()
                    ->duration(5000)
                    ->send();

                return;
            } elseif (strlen($this->sNo) < 9) {
                Notification::make()
                    ->title('Unknown Serial Number')
                    ->body("Serial Number should contain minimum 9 digits '$this->sNo'")
                    ->danger()
                    ->duration(5000)
                    ->send();
                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            } elseif (! ctype_alnum($this->sNo)) {
                Notification::make()
                    ->title('Unknown Serial Number')
                    ->body("Serial Number should contain alpha-numeric values '$this->sNo'")
                    ->danger()
                    ->duration(5000)
                    ->send();
                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $item = Item::where('code', $this->itemCode)->first();

            if (! $item) {
                Notification::make()
                    ->title('Item Code Not Found')
                    ->body("Item code not found '$this->itemCode'")
                    ->danger()
                    ->duration(5000)
                    ->send();
                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $itemCodeAgaPlant = Item::where('plant_id', $plantId)->where('code', $this->itemCode)->first();

            $plantCo = Plant::where('id', $plantId)->first();

            $plantCode = $plantCo->code;

            if (! $itemCodeAgaPlant) {
                Notification::make()
                    ->title('Item Code Not Found')
                    ->body("Item code '$this->itemCode' not found against plant code '$plantCode'")
                    ->danger()
                    ->duration(5000)
                    ->send();
                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $stickerExists = StickerMaster::where('item_id', $item->id)->first();

            if (! $stickerExists) {

                Notification::make()
                    ->title('Unknown Sticker Master')
                    ->body("Item code not found in sticker master '{$this->itemCode}'")
                    ->danger()
                    ->duration(5000)
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $stickerExists = StickerMaster::where('plant_id', $plantId)
                ->where('item_id', $item->id)
                ->first();

            if (! $stickerExists) {
                Notification::make()
                    ->title('Unknown Sticker Master')
                    ->body("Item code not found in sticker master '{$this->itemCode}' in plant '{$plantCode}'")
                    ->danger()
                    ->duration(5000)
                    ->send();
                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $stickerMasterId = $stickerExists->id;

            $locationExist = StockDataMaster::where('location', $location)
                ->where('type', '1')
                ->first();

            if (! $locationExist) {

                $existingInOtherLocation = NotInStock::where('plant_id', $plantId)
                    ->where('serial_number', $this->sNo)
                    ->first();

                if ($existingInOtherLocation) {
                    Notification::make()
                        ->title('Serial Number : Not In Stock')
                        ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                Notification::make()
                    ->title('Unknown Location')
                    ->body("location '$location' not found in stock data master for the type Non-FG.<br>Do you want to update in not in stock table?")
                    ->danger()
                    ->actions([
                        \Filament\Notifications\Actions\Action::make('confirm')
                            ->label('Yes, Update')
                            ->button()
                            ->dispatch('confirmSerialUpdate', [
                                'plantId' => $plantId,
                                'location' => $location,
                                'bin' => $bin,
                                'serial_number' => $this->sNo,
                                'stickerMasterId' => $stickerMasterId,
                                'batch' => $this->batch ?? null,
                                'docNo' => $this->docNo,
                                'quantity' => $this->quantity,
                            ]),
                    ])
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $locationAgaPlant = StockDataMaster::where('plant_id', $plantId)
                ->where('location', $location)
                ->where('type', '1')
                ->first();

            if (! $locationAgaPlant) {

                $existingInOtherLocation = NotInStock::where('plant_id', $plantId)
                    ->where('serial_number', $this->sNo)
                    ->first();

                if ($existingInOtherLocation) {
                    Notification::make()
                        ->title('Serial Number : Not In Stock')
                        ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                Notification::make()
                    ->title('Unknown Location')
                    ->body("location '$location' not found in stock data master for the type Non-FG against plant code '$plantCode'.<br>Do you want to update in not in stock table?")
                    ->danger()
                    ->actions([
                        \Filament\Notifications\Actions\Action::make('confirm')
                            ->label('Yes, Update')
                            ->button()
                            ->dispatch('confirmSerialUpdate', [
                                'plantId' => $plantId,
                                'location' => $location,
                                'bin' => $bin,
                                'serial_number' => $this->sNo,
                                'stickerMasterId' => $stickerMasterId,
                                'batch' => $this->batch,
                                'docNo' => $this->docNo,
                                'quantity' => $this->quantity,
                            ]),
                    ])
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            if ($bin == '' || $bin == null) {
                Notification::make()
                    ->title('Unknown Bin')
                    ->body("Bin can't be empty!")
                    ->danger()
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $serialExist = StockDataMaster::where('serial_number', $this->sNo)->where('type', '1')->first();

            if (! $serialExist) {

                $existingInOtherLocation = NotInStock::where('plant_id', $plantId)
                    ->where('serial_number', $this->sNo)
                    ->first();

                if ($existingInOtherLocation) {
                    Notification::make()
                        ->title('Serial Number : Not In Stock')
                        ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                Notification::make()
                    ->title('Unknown Serial Number')
                    ->body('Scanned serial number not found in stock data master for the type Non-FG.<br>Do you want to update in not in stock table?')
                    ->danger()
                    ->actions([
                        \Filament\Notifications\Actions\Action::make('confirm')
                            ->label('Yes, Update')
                            ->button()
                            ->dispatch('confirmSerialUpdate', [
                                'plantId' => $plantId,
                                'location' => $location,
                                'bin' => $bin,
                                'serial_number' => $this->sNo,
                                'stickerMasterId' => $stickerMasterId,
                                'batch' => $this->batch,
                                'docNo' => $this->docNo,
                                'quantity' => $this->quantity,
                            ]),
                    ])
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            $serialAgaPlant = StockDataMaster::where('plant_id', $plantId)->where('serial_number', $this->sNo)->where('type', '1')->first();

            if (! $serialAgaPlant) {

                $sNoExist = NotInStock::where('plant_id', $plantId)
                    ->where('serial_number', $this->sNo)
                    ->first();

                if ($sNoExist) {
                    Notification::make()
                        ->title('Serial Number : Not In Stock')
                        ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                Notification::make()
                    ->title('Unknown Serial Number')
                    ->body("Scanned serial number not found in stock data master for the type Non-FG against plant code '$plantCode'.<br>Do you want to update in not in stock table?")
                    ->danger()
                    ->actions([
                        \Filament\Notifications\Actions\Action::make('confirm_update')
                            ->label('Yes, Update')
                            ->button()
                            ->dispatch('confirmSerialUpdate', [
                                'plantId' => $plantId,
                                'location' => $location,
                                'bin' => $bin,
                                'serial_number' => $this->sNo,
                                'stickerMasterId' => $stickerMasterId,
                                'batch' => $this->batch,
                                'docNo' => $this->docNo,
                                'quantity' => $this->quantity,
                            ]),
                    ])
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            if ($serialAgaPlant->location != $location) {

                $sNoExistLocation = NotInStock::where('plant_id', $plantId)
                    ->where('serial_number', $this->sNo)
                    ->first();

                if ($sNoExistLocation) {
                    Notification::make()
                        ->title('Serial Number : Not In Stock')
                        ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                Notification::make()
                    ->title('Invalid Location')
                    ->body("Serial number '$this->sNo' does not belong to location '$location' for the type Non-FG against plant code '$plantCode'.<br>Do you want to update in not in stock table?")
                    ->danger()
                    ->actions([
                        \Filament\Notifications\Actions\Action::make('confirm_update')
                            ->label('Yes, Update')
                            ->button()
                            ->dispatch('confirmSerialUpdate', [
                                'plantId' => $plantId,
                                'location' => $location,
                                'bin' => $bin,
                                'serial_number' => $this->sNo,
                                'stickerMasterId' => $stickerMasterId,
                                'batch' => $this->batch,
                                'docNo' => $this->docNo,
                                'quantity' => $this->quantity,
                            ]),
                    ])
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            if ($serialAgaPlant->sticker_master_id != $stickerMasterId) {

                $sNoExistLocation = NotInStock::where('plant_id', $plantId)
                    ->where('serial_number', $this->sNo)
                    ->first();

                if ($sNoExistLocation) {
                    Notification::make()
                        ->title('Serial Number : Not In Stock')
                        ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                Notification::make()
                    ->title('Invalid Item Code')
                    ->body("Serial number '$this->sNo' does not belong to item code '$this->itemCode' for the type Non-FG against plant code '$plantCode'.<br>Do you want to update in not in stock table?")
                    ->danger()
                    ->actions([
                        \Filament\Notifications\Actions\Action::make('confirm_update')
                            ->label('Yes, Update')
                            ->button()
                            ->dispatch('confirmSerialUpdate', [
                                'plantId' => $plantId,
                                'location' => $location,
                                'bin' => $bin,
                                'serial_number' => $this->sNo,
                                'stickerMasterId' => $stickerMasterId,
                                'batch' => $this->batch,
                                'docNo' => $this->docNo,
                                'quantity' => $this->quantity,
                            ]),
                    ])
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            if (count($parts) !== 2 && ($serialAgaPlant->batch != '' || $serialAgaPlant->batch != null)){

                if ($serialAgaPlant->batch != $this->batch) {

                    $sNoExistLocation = NotInStock::where('plant_id', $plantId)
                        ->where('serial_number', $this->sNo)
                        ->first();

                    if ($sNoExistLocation) {
                        Notification::make()
                            ->title('Serial Number : Not In Stock')
                            ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                            ->danger()
                            ->send();

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'location' => $location,
                            'bin' => $bin,
                            'qr_code' => null,
                        ]);

                        return;
                    }

                    Notification::make()
                        ->title('Invalid Batch')
                        ->body("Serial number '$this->sNo' does not belong to batch '$this->batch' for the type Non-FG against plant code '$plantCode'.<br>Do you want to update in not in stock table?")
                        ->danger()
                        ->actions([
                            \Filament\Notifications\Actions\Action::make('confirm_update')
                                ->label('Yes, Update')
                                ->button()
                                ->dispatch('confirmSerialUpdate', [
                                    'plantId' => $plantId,
                                    'location' => $location,
                                    'bin' => $bin,
                                    'serial_number' => $this->sNo,
                                    'stickerMasterId' => $stickerMasterId,
                                    'batch' => $this->batch,
                                    'docNo' => $this->docNo,
                                    'quantity' => $this->quantity,
                                ]),
                        ])
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }
            }

            // if ($serialAgaPlant->bin != '' || $serialAgaPlant->bin != null) {

            //     if($serialAgaPlant->bin != $bin){
            //         Notification::make()
            //             ->danger()
            //             ->title('Invalid Bin')
            //             ->body("Serial number '$this->sNo' does not belong to bin '$bin' for the type Non-FG against plant code '$plantCode'.")
            //             ->seconds(3)
            //             ->send();

            //         Notification::make()
            //             ->title('Invalid Bin')
            //             ->body("Serial number '$this->sNo' does not belong to bin '$bin' for the type Non-FG against plant code '$plantCode'.")
            //             ->danger()
            //             ->actions([
            //                 \Filament\Notifications\Actions\Action::make('confirm_update')
            //                     ->label('Yes, Update')
            //                     ->button()
            //                     ->dispatch('confirmSerialUpdate', [
            //                         'plantId' => $plantId,
            //                         'location' => $location,
            //                         'bin' => $bin,
            //                         'serial_number' => $this->sNo,
            //                         'stickerMasterId' => $stickerMasterId,
            //                         'batch' => $this->batch,
            //                         'docNo' => $this->docNo,
            //                         'quantity' => $this->quantity
            //                     ]),
            //             ])
            //             ->send();

            //         $this->form->fill([
            //             'plant_id' => $plantId,
            //             'location' => $location,
            //             'bin' => $bin,
            //             'qr_code' => null,
            //         ]);
            //         return;
            //     }
            // }

            $serial = StockDataMaster::where('plant_id', $plantId)
                ->where('serial_number', $this->sNo)
                ->where('location', $location)
                ->where('type', '1')
                ->first();

            if ($serial->quantity == '' || $serial->quantity == null) {
                Notification::make()
                    ->warning()
                    ->title('Unknown Quantity')
                    ->body("Quantity is missing for serial number '$this->sNo' (Type: Non-FG) in Plant Code '$plantCode'. Please update it in Stock Data Master.")
                    ->seconds(3)
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            } elseif ((int) $serial->quantity > 1) {
                Notification::make()
                    ->warning()
                    ->title('Invalid Quantity')
                    ->body("Quantity should be '1' against '$this->sNo' for the type Non-FG against plant code '$plantCode'!Please update quantity in stock data master.")
                    ->seconds(3)
                    ->send();

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

            if ($serial) {

                if ($serial->scanned_status == 'Scanned') {

                    Notification::make()
                        ->title('Duplicate Serial Number')
                        ->body("Serial number '$this->sNo' has already been scanned in stock data master for the type Non-FG against plant code '$plantCode'.<br>Do you want to update in duplicate stock table?")
                        ->danger()
                        ->actions([
                            \Filament\Notifications\Actions\Action::make('confirm')
                                ->label('Yes, Update')
                                ->button()
                                ->dispatch('confirmDuplicateUpdate', [
                                    'plantId' => $plantId,
                                    'location' => $location,
                                    'bin' => $bin,
                                    'serial_number' => $this->sNo,
                                    'stickerMasterId' => $stickerMasterId,
                                    'batch' => $this->batch ?? null,
                                    'docNo' => $this->docNo,
                                    'quantity' => $this->quantity,
                                ]),
                        ])
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                $serial->update([
                    'bin' => $bin ?? null,
                    'batch' => count($parts) !== 2 ? $this->batch : $serial->batch,
                    // 'doc_no' => $this->docNo ?? null,
                    'scanned_status' => 'Scanned',
                    'scanned_quantity' => '1',
                    'updated_at' => now(),
                    'updated_by' => $operatorName,
                ]);

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                $this->dispatch('refreshSfgNonData', location: $location, plantId: $plantId, serialNumber: $this->sNo, itemCode: $this->itemCode);
            }
        } else {
            $serNo = $value;

            if (! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPp])?\|?$/', $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')
                    ->seconds(3)
                    ->send();

                $this->dispatch('playWarnSound');

                $this->form->fill([
                    'plant_id' => $plantId,
                    'location' => $location,
                    'bin' => $bin,
                    'qr_code' => null,
                ]);

                return;
            }

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

                $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;
                $isMarkPs = (! $isMarkM && ! $isMarkP) ? true : false;

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

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

                if (! $record) {
                    Notification::make()
                        ->title("Serial number '$serialNumber' not found in stock data table<br>Update 'Stock Data' table or Scan the valid 'Serial Number QR' data to proceed...")
                        ->danger()
                        ->seconds(3)
                        ->send();

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

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                $plant = Plant::find($plantId);

                if ($plant) {
                    $plantCode = $plant->code;
                } else {
                    $plantCode = null;
                }

                $item = Item::where('plant_id', $plantId)
                    ->where('code', $itemCode)
                    ->first();

                if (! $item) {
                    Notification::make()
                        ->title('Invalid Item Code')
                        ->body("Item code '$this->itemCode' not found for the type FG against plant code '$plantCode'.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                $itemId = $item->id;

                $stickerMaster = StickerMaster::where('plant_id', $plantId)
                    ->where('item_id', $itemId)
                    ->first();

                if (! $stickerMaster) {
                    Notification::make()
                        ->title('Invalid Item Code')
                        ->body("Item code '$this->itemCode' not found in sticker master for the type FG against plant code '$plantCode'.")
                        ->danger()
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                $stickerMasterId = $stickerMaster->id;

                $locationExist = StockDataMaster::where('location', $location)
                    ->where('type', '0')
                    ->first();

                if (! $locationExist) {

                    $existingInOtherLocation = NotInStock::where('plant_id', $plantId)
                        ->where('serial_number', $this->sNo)
                        ->first();

                    if ($existingInOtherLocation) {
                        Notification::make()
                            ->title('Serial Number : Not In Stock')
                            ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                            ->danger()
                            ->send();

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'location' => $location,
                            'bin' => $bin,
                            'qr_code' => null,
                        ]);

                        return;
                    }

                    Notification::make()
                        ->title('Unknown Location')
                        ->body("location '$location' not found in stock data master for the type FG.<br>Do you want to update in not in stock table?")
                        ->danger()
                        ->actions([
                            \Filament\Notifications\Actions\Action::make('confirm')
                                ->label('Yes, Update')
                                ->button()
                                ->dispatch('confirmSerialFGUpdate', [
                                    'plantId' => $plantId,
                                    'location' => $location,
                                    'bin' => $bin,
                                    'serial_number' => $this->sNo,
                                    'stickerMasterId' => $stickerMasterId,
                                    'batch' => $this->batch,
                                    'docNo' => $this->docNo,
                                    'quantity' => $this->quantity,
                                ]),
                        ])
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                $locationAgaPlant = StockDataMaster::where('plant_id', $plantId)
                    ->where('location', $location)
                    ->where('type', '0')
                    ->first();

                if (! $locationAgaPlant) {

                    $existingInOtherLocation = NotInStock::where('plant_id', $plantId)
                        ->where('serial_number', $this->sNo)
                        ->first();

                    if ($existingInOtherLocation) {
                        Notification::make()
                            ->title('Serial Number : Not In Stock')
                            ->body("Serial number '{$this->sNo}' already exists against plant code '$plantCode' in not in stock table.")
                            ->danger()
                            ->send();

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'location' => $location,
                            'bin' => $bin,
                            'qr_code' => null,
                        ]);

                        return;
                    }

                    Notification::make()
                        ->title('Unknown Location')
                        ->body("location '$location' not found in stock data master for the type FG against plant code '$plantCode'.<br>Do you want to update in not in stock table?")
                        ->danger()
                        ->actions([
                            \Filament\Notifications\Actions\Action::make('confirm')
                                ->label('Yes, Update')
                                ->button()
                                ->dispatch('confirmSerialFGUpdate', [
                                    'plantId' => $plantId,
                                    'location' => $location,
                                    'bin' => $bin,
                                    'serial_number' => $this->sNo,
                                    'stickerMasterId' => $stickerMasterId,
                                    'batch' => $this->batch,
                                    'docNo' => $this->docNo,
                                    'quantity' => $this->quantity,
                                ]),
                        ])
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

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

                if (! $record) {

                    $sNoExistLocation = NotInStock::where('plant_id', $plantId)
                        ->where('serial_number', $this->sNo)
                        ->where('type', '0')
                        ->first();

                    if ($sNoExistLocation) {
                        Notification::make()
                            ->title('Serial Number : Not In Stock')
                            ->body("Serial number '{$this->sNo}' already exists for the type FG against plant code '$plantCode' in not in stock table.")
                            ->danger()
                            ->send();

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'location' => $location,
                            'bin' => $bin,
                            'qr_code' => null,
                        ]);

                        return;
                    }

                    $message = "serial number not found '$serialNumber' for the type FG against item code '$itemCode' and plant code '$plantCode'<br>Do you want to update in not in stock table";
                    Notification::make()
                        ->title('Invalid Item Code')
                        ->body($message)
                        ->danger()
                        ->actions([
                            \Filament\Notifications\Actions\Action::make('confirm_update')
                                ->label('Yes, Update')
                                ->button()
                                ->dispatch('confirmSerialFGUpdate', [
                                    'plantId' => $plantId,
                                    'location' => $location,
                                    'bin' => $bin,
                                    'serial_number' => $this->sNo,
                                    'stickerMasterId' => $stickerMasterId,
                                ]),
                        ])
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                $serialRecord = StockDataMaster::where('serial_number', $serialNumber)
                    ->where('plant_id', $plantId)
                    ->where('type', '0')
                    ->with('stickerMasterRelation.item')
                    ->first();

                if ($serialRecord && $serialRecord->stickerMasterRelation->item->code != $itemCode) {

                    $sNoExistLocation = NotInStock::where('plant_id', $plantId)
                        ->where('serial_number', $this->sNo)
                        ->where('type', '0')
                        ->first();

                    if ($sNoExistLocation) {
                        Notification::make()
                            ->title('Serial Number : Not In Stock')
                            ->body("Serial number '{$this->sNo}' already exists for the type FG against plant code '$plantCode' in not in stock table.")
                            ->danger()
                            ->send();

                        $this->form->fill([
                            'plant_id' => $plantId,
                            'location' => $location,
                            'bin' => $bin,
                            'qr_code' => null,
                        ]);

                        return;
                    }

                    Notification::make()
                        ->title('Unknown Item Code')
                        ->body("Item code not found '$this->itemCode' in stock data master for the type FG against plant code '$plantCode'.<br>Do you want to update in duplicate stock table?")
                        ->danger()
                        ->actions([
                            \Filament\Notifications\Actions\Action::make('confirm')
                                ->label('Yes, Update')
                                ->button()
                                ->dispatch('confirmSerialFGUpdate', [
                                    'plantId' => $plantId,
                                    'location' => $location,
                                    'bin' => $bin,
                                    'serial_number' => $this->sNo,
                                    'stickerMasterId' => $stickerMasterId,
                                ]),
                        ])
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                if ($record->scanned_status == 'Scanned') {

                    Notification::make()
                        ->title('Duplicate Serial Number')
                        ->body("Serial number '$this->sNo' has already been scanned in stock data master for the type FG against plant code '$plantCode'.<br>Do you want to update in duplicate stock table?")
                        ->danger()
                        ->actions([
                            \Filament\Notifications\Actions\Action::make('confirm')
                                ->label('Yes, Update')
                                ->button()
                                ->dispatch('confirmDuplicateUpdate', [
                                    'plantId' => $plantId,
                                    'location' => $location,
                                    'bin' => $bin,
                                    'serial_number' => $this->sNo,
                                    'stickerMasterId' => $stickerMasterId,
                                    'batch' => $this->batch,
                                    'docNo' => $this->docNo,
                                    'quantity' => $this->quantity,
                                ]),
                        ])
                        ->send();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;

                }

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

                $notFg = $typeStock->type;

                if (! $typeStock || $notFg != '0') {
                    Notification::make()
                        ->title('Unknown: FG Type')
                        ->body("Item code '$itemCode' is not a valid FG type!")
                        ->danger()
                        ->seconds(3)
                        ->send();

                    $this->dispatch('playWarnSound');

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                $invalidPackage = false;

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

                if (! $hasMotorQr && ! $hasPumpQr && ! $hasPumpSetQr) {
                    $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;

                if ((! $hasMotorQr && ! $hasPumpQr && ! $hasPumpSetQr) || $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,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }

                if ($hasMotorQr && ! $hasPumpQr && ! $hasPumpSetQr) {
                    $isMarkM = true;
                    $isMarkP = false;
                    $isMarkPs = false;
                } elseif (! $hasMotorQr && $hasPumpQr && ! $hasPumpSetQr) {
                    $isMarkM = false;
                    $isMarkP = true;
                    $isMarkPs = false;
                } elseif (! $hasMotorQr && ! $hasPumpQr && ! $hasPumpSetQr) {
                    $isMarkM = false;
                    $isMarkP = false;
                    $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,
                            'location' => $location,
                            'bin' => $bin,
                            'qr_code' => null,
                        ]);

                        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,
                            'location' => $location,
                            'bin' => $bin,
                            'qr_code' => null,
                        ]);

                        return;
                    }

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

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

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

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

                    // $scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    $this->dispatch('refreshInvoiceData', location: $location, plantId: $plantId, itemCode: $itemCode, serialNumber: $serialNumber);

                    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,
                            'location' => $location,
                            'bin' => $bin,
                            'qr_code' => null,
                        ]);

                        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,
                            'location' => $location,
                            'bin' => $bin,
                            'qr_code' => null,
                        ]);

                        return;
                    }

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

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

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

                    $this->dispatch('refreshInvoiceData', location: $location, plantId: $plantId, itemCode: $itemCode, serialNumber: $serialNumber);

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

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    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,
                            'location' => $location,
                            'bin' => $bin,
                            'qr_code' => null,
                        ]);

                        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,
                            'location' => $location,
                            'bin' => $bin,
                            'qr_code' => null,
                        ]);

                        return;
                    }

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

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

                        if ($packCnt == $scanCnt) {
                            $record->scanned_status = 'Scanned';
                        }
                    } else {
                        $record->scanned_status = 'Scanned';
                    }
                    $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();

                    $this->form->fill([
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                        'qr_code' => null,
                    ]);

                    return;
                }
            }
        }

    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('confirmAddToNotInStock')
                ->requiresConfirmation()
                ->modalHeading('Item Not Found')
                ->modalDescription('Do you want to add this item to Not In Stocks?')
                // ->visible(false)
                ->extraAttributes(['style' => 'display:none;'])
                ->action(function () {

                    $itemCode = $this->itemCode;

                    $plantId = $this->plantId;

                    $location = $this->location;

                    $bin = $this->bin;

                    $stickerMaster = StickerMaster::whereHas('item', function ($query) use ($itemCode, $plantId) {
                        $query->where('code', $itemCode)
                            ->where('plant_id', $plantId);
                    })
                        ->first();

                    if (! $stickerMaster) {

                        Notification::make()
                            ->title('Sticker Master Not Found')
                            ->danger()
                            ->send();

                        return;
                    }
                    $existingRecord = NotInStock::where('serial_number', $this->serialNumber)
                        ->where('plant_id', $plantId)
                        ->whereHas('stickerMasterRelation.item', function ($query) use ($plantId) {
                            $query->where('plant_id', $plantId);
                        })
                        ->first();

                    if ($existingRecord) {

                        $existingItemCode = $existingRecord->stickerMasterRelation->item->code;

                        if ($existingItemCode != $itemCode) {
                            Notification::make()
                                ->title('Serial Number Conflict')
                                ->body("Serial number '{$this->serialNumber}' already exists with Item Code '{$existingItemCode}'.")
                                ->danger()
                                ->send();

                            return;
                        }
                    }

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

                    if ($record) {
                        Notification::make()
                            ->title('Duplicate : Item Code')
                            ->body("Item Code '$itemCode' with Serial number '$this->serialNumber' already exist in not in stock table!")
                            ->danger()
                            ->send();

                        return;
                    }

                    NotInStock::create([
                        'serial_number' => $this->serialNumber,
                        'sticker_master_id' => $stickerMaster->id,
                        'plant_id' => $plantId,
                        'location' => $location,
                        'bin' => $bin,
                    ]);

                    Notification::make()
                        ->title('Saved Successfully')
                        ->success()
                        ->send();
                }),
        ];
    }

    public static function canAccess(): bool
    {
        return Auth::check() && Auth::user()->can('view cycle count page');
    }
}
