<?php

namespace App\Livewire;

use App\Models\InvoiceValidation;
use App\Models\Item;
use App\Models\PanelBoxValidation;
use App\Models\StickerMaster;
use Filament\Facades\Filament;
use Filament\Notifications\Notification;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithPagination;
use Str;

class InvoiceDataTable extends Component
{
    use WithPagination;

    protected $paginationTheme = 'tailwind';

    public $invoiceData = [];

    // public $invoiceRecords;

    public $plantId = 0;

    public $package = [];

    public $packageCount = 0;

    public string $invoiceNumber = '';

    public bool $completedInvoice = false;

    public bool $isSerial = false;

    public bool $onCapFocus = false;

    public bool $emptyInvoice = false;

    public bool $hasSearched = false;

    public bool $materialInvoice = false;

    public bool $showCapacitorInput = false;

    // protected $listeners = ['refreshInvoiceData' => 'loadData',];

    protected $listeners = [
        'refreshCompletedInvoice' => 'loadCompletedData',
        'refreshEmptyInvoice' => 'loadEmptyData',
        'refreshInvoiceData' => 'loadData',
        'refreshMaterialInvoiceData' => 'loadMaterialData',
        'refreshMaterialInvoiceData1' => 'loadMaterialData1',
        'openCapacitorModal' => 'showCapacitorInputBox',
    ];

    public $capacitorInput = '';

    public $panel_box_supplier;

    public $panel_box_code;

    public $panel_box_serial_number;

    public string $currentItemCode = '';

    public string $currentSerialNumber = '';

    public function loadCompletedData($invoiceNumber, $plantId, $isSerial)
    {
        $this->plantId = $plantId;
        $this->invoiceNumber = $invoiceNumber;
        $this->completedInvoice = true;
        $this->isSerial = $isSerial;
        $this->onCapFocus = false;
        $this->emptyInvoice = false;
        $this->hasSearched = false;
        $this->materialInvoice = false;
        $this->packageCount = 0;
        // $this->showCapacitorInput = false;
        $this->dispatch('focus-invoice-number');
    }

    public function loadEmptyData($invoiceNumber, $plantId)
    {
        $this->plantId = $plantId;
        $this->invoiceNumber = $invoiceNumber;
        $this->completedInvoice = false;
        $this->onCapFocus = false;
        $this->emptyInvoice = true;
        $this->hasSearched = false;
        $this->materialInvoice = false;
        $this->packageCount = 0;
        // $this->showCapacitorInput = false;
    }

    // public function loadData($invoiceNumber, $plantId, $onCapFocus)
    // {
    //     $this->plantId = $plantId;
    //     $this->invoiceNumber = $invoiceNumber;
    //     $this->completedInvoice = false;
    //     $this->isSerial = true;
    //     $this->onCapFocus = $onCapFocus;
    //     $this->emptyInvoice = false;
    //     $this->hasSearched = true;
    //     $this->materialInvoice = false;
    //     // $this->showCapacitorInput = false;

    //     // ->where('serial_number', '!=', '')
    //     $this->invoiceData = InvoiceValidation::where('invoice_number', $this->invoiceNumber)
    //         ->where('plant_id', $plantId)->where('scanned_status', null)
    //         ->get()
    //         ->map(function ($record) {
    //             return [
    //                 'sticker_master_id' => $record->sticker_master_id,
    //                 'serial_number' => $record->serial_number,
    //                 'motor_scanned_status' => $record->motor_scanned_status ?? '',
    //                 'pump_scanned_status' => $record->pump_scanned_status ?? '',
    //                 'capacitor_scanned_status' => $record->capacitor_scanned_status ?? '',
    //                 'scanned_status_set' => $record->scanned_status_set ?? '',
    //                 'scanned_status' => $record->scanned_status ?? '',
    //                 'panel_box_supplier' => $record->panel_box_supplier ?? '',
    //                 'panel_box_serial_number' => $record->panel_box_serial_number ?? '',
    //                 'created_at' => $record->created_at,
    //                 'operator_id' => $record->operator_id,
    //             ];
    //         })
    //         ->toArray();

    //     $this->packageCount = 0;

    //     // Loop through and replace 'code' using related StickerMaster > Item > code
    //     foreach ($this->invoiceData as &$row) {
    //         $stickCount = 0;
    //         $scannedCount = 0;

    //         // $stickerMaster = \App\Models\StickerMaster::with('item')->find($row['sticker_master_id'] ?? null);
    //         $row['code'] = StickerMaster::with('item')->find($row['sticker_master_id'] ?? null)?->item?->code ?? 'N/A';
    //         $curStick = StickerMaster::where('id', $row['sticker_master_id'])->first();
    //         if ($curStick) {
    //             if (Str::length($curStick->panel_box_code) > 0) {
    //                 $stickCount++;
    //             }
    //             if ($curStick->tube_sticker_motor == 1 || $curStick->tube_sticker_pump == 1 || $curStick->tube_sticker_pumpset == 1) {
    //                 if ($curStick->tube_sticker_motor == 1) {
    //                     $stickCount++;
    //                 }
    //                 if ($curStick->tube_sticker_pump == 1 || ($curStick->tube_sticker_pumpset != 1 && $curStick->tube_sticker_pump != 1 && $curStick->pack_slip_pump == 1)) {
    //                     $stickCount++;
    //                 }
    //                 if ($curStick->tube_sticker_pumpset == 1) {
    //                     $stickCount++;
    //                 }
    //             } elseif ($curStick->pack_slip_motor == 1 || $curStick->pack_slip_pump == 1 || $curStick->pack_slip_pumpset == 1) {
    //                 if ($curStick->pack_slip_motor == 1) {
    //                     $stickCount++;
    //                 }
    //                 if ($curStick->pack_slip_pump == 1) {
    //                     $stickCount++;
    //                 }
    //                 if ($curStick->pack_slip_pumpset == 1) {
    //                     $stickCount++;
    //                 }
    //             }
    //         }

    //         if ($row['motor_scanned_status'] == 1) {
    //             $scannedCount++;
    //         }
    //         if ($row['pump_scanned_status'] == 1) {
    //             $scannedCount++;
    //         }
    //         if ($row['capacitor_scanned_status'] == 1) {
    //             $scannedCount++;
    //         }
    //         if ($row['scanned_status_set'] == 1) {
    //             $scannedCount++;
    //         }

    //         $this->packageCount += $stickCount - $scannedCount;
    //     }

    //     if ($onCapFocus) {
    //         $this->dispatch('focus-capacitor-input');
    //     } else {
    //         $this->dispatch('focus-serial-number');
    //     }
    // }

    //     public function loadData($invoiceNumber, $plantId, $onCapFocus = false)
    // {
    //     $this->invoiceNumber = $invoiceNumber;
    //     $this->plantId = $plantId;

    //     $this->completedInvoice = false;
    //     $this->isSerial = true;
    //     $this->onCapFocus = $onCapFocus;
    //     $this->emptyInvoice = false;
    //     $this->hasSearched = true;
    //     $this->materialInvoice = false;

    //     $this->resetPage();

    //     $this->packageCount = 0;

    //     // IMPORTANT: keep scanned rows, otherwise count will not update
    //     $this->invoiceRecords = InvoiceValidation::with('stickerMasterRelation')
    //         ->where('invoice_number', $this->invoiceNumber)
    //         ->where('plant_id', $this->plantId)
    //         ->get();

    //     foreach ($this->invoiceRecords as &$row) {

    //         $stickCount   = 0;
    //         $scannedCount = 0;

    //         // Get item code
    //         $row['code'] = StickerMaster::with('item')
    //             ->find($row['sticker_master_id'] ?? null)?->item?->code ?? 'N/A';

    //         $curStick = StickerMaster::find($row['sticker_master_id']);

    //         if ($curStick) {

    //             /** ---------------- REQUIRED STICKERS ---------------- */

    //             // PANEL BOX (capacitor)
    //             if (!empty($curStick->panel_box_code)) {
    //                 $stickCount++;

    //                 // Panel box scan = capacitor_scanned_status
    //                 if ($row['capacitor_scanned_status'] == 1) {
    //                     $scannedCount++;
    //                 }
    //             }

    //             // Tube stickers
    //             if (
    //                 $curStick->tube_sticker_motor == 1 ||
    //                 $curStick->tube_sticker_pump == 1 ||
    //                 $curStick->tube_sticker_pumpset == 1
    //             ) {
    //                 if ($curStick->tube_sticker_motor == 1) {
    //                     $stickCount++;
    //                     if ($row['motor_scanned_status'] == 1) {
    //                         $scannedCount++;
    //                     }
    //                 }

    //                 if (
    //                     $curStick->tube_sticker_pump == 1 ||
    //                     ($curStick->tube_sticker_pumpset != 1 &&
    //                         $curStick->tube_sticker_pump != 1 &&
    //                         $curStick->pack_slip_pump == 1)
    //                 ) {
    //                     $stickCount++;
    //                     if ($row['pump_scanned_status'] == 1) {
    //                         $scannedCount++;
    //                     }
    //                 }

    //                 if ($curStick->tube_sticker_pumpset == 1) {
    //                     $stickCount++;
    //                     if ($row['scanned_status_set'] == 1) {
    //                         $scannedCount++;
    //                     }
    //                 }
    //             }

    //             // Pack slips (only if no tube stickers)
    //             elseif (
    //                 $curStick->pack_slip_motor == 1 ||
    //                 $curStick->pack_slip_pump == 1 ||
    //                 $curStick->pack_slip_pumpset == 1
    //             ) {
    //                 if ($curStick->pack_slip_motor == 1) {
    //                     $stickCount++;
    //                     if ($row['motor_scanned_status'] == 1) {
    //                         $scannedCount++;
    //                     }
    //                 }

    //                 if ($curStick->pack_slip_pump == 1) {
    //                     $stickCount++;
    //                     if ($row['pump_scanned_status'] == 1) {
    //                         $scannedCount++;
    //                     }
    //                 }

    //                 if ($curStick->pack_slip_pumpset == 1) {
    //                     $stickCount++;
    //                     if ($row['scanned_status_set'] == 1) {
    //                         $scannedCount++;
    //                     }
    //                 }
    //             }
    //         }

    //         // SAFETY: never go negative
    //         $this->packageCount += max($stickCount - $scannedCount, 0);
    //     }

    //     $this->dispatch($onCapFocus ? 'focus-capacitor-input' : 'focus-serial-number');
    // }

    // #[On('refreshInvoiceData')]

    // public function loadData($invoiceNumber, $plantId, $onCapFocus = false)
    // {
    //     $this->invoiceNumber = $invoiceNumber;
    //     $this->plantId = $plantId;

    //     $this->completedInvoice = false;
    //     $this->isSerial = true;
    //     $this->onCapFocus = $onCapFocus;
    //     $this->emptyInvoice = false;
    //     $this->hasSearched = true;
    //     $this->materialInvoice = false;

    //     $this->resetPage();

    //     $this->packageCount = 0;

    //     $records = InvoiceValidation::with('stickerMasterRelation')
    //     ->where('invoice_number', $this->invoiceNumber)
    //     ->where('plant_id', $this->plantId)
    //     ->get();

    //      $this->packageCount = $records->sum(function ($record) {
    //             $sm = $record->stickerMasterRelation;

    //             $stickCount = 0;
    //             $scannedCount = 0;

    //             if ($sm) {

    //                 if (strlen($sm->panel_box_code) > 0) $stickCount++;

    //                 // if (!empty($sm->panel_box_code)) {
    //                 //     $stickCount++;
    //                 //     if (!empty($record->panel_box_serial_number)) {
    //                 //         $scannedCount++;
    //                 //     }
    //                 // }

    //                 // Tube stickers
    //                 if ($sm->tube_sticker_motor || $sm->tube_sticker_pump || $sm->tube_sticker_pumpset) {
    //                     $stickCount += $sm->tube_sticker_motor ? 1 : 0;
    //                     $stickCount += ($sm->tube_sticker_pump || ($sm->tube_sticker_pumpset != 1 && !$sm->tube_sticker_pump && $sm->pack_slip_pump)) ? 1 : 0;
    //                     $stickCount += $sm->tube_sticker_pumpset ? 1 : 0;
    //                 }
    //                 // Pack slips (only if tube stickers not applied)
    //                 elseif ($sm->pack_slip_motor || $sm->pack_slip_pump || $sm->pack_slip_pumpset) {
    //                     $stickCount += $sm->pack_slip_motor ? 1 : 0;
    //                     $stickCount += $sm->pack_slip_pump ? 1 : 0;
    //                     $stickCount += $sm->pack_slip_pumpset ? 1 : 0;
    //                 }
    //             }

    //             // Already scanned
    //             $scannedCount += $record->motor_scanned_status == 1 ? 1 : 0;
    //             $scannedCount += $record->pump_scanned_status == 1 ? 1 : 0;
    //             $scannedCount += $record->capacitor_scanned_status == 1 ? 1 : 0;
    //             $scannedCount += $record->scanned_status_set == 1 ? 1 : 0;

    //             return max($stickCount - $scannedCount, 0);
    //         });

    //     $this->dispatch($onCapFocus ? 'focus-capacitor-input' : 'focus-serial-number');
    // }

    public function loadData($invoiceNumber, $plantId, $onCapFocus = false)
    {
        $this->invoiceNumber = $invoiceNumber;
        $this->plantId = $plantId;

        $this->completedInvoice = false;
        $this->isSerial = true;
        $this->onCapFocus = $onCapFocus;
        $this->emptyInvoice = false;
        $this->hasSearched = true;
        $this->materialInvoice = false;

        $this->resetPage();
        $this->packageCount = 0;

        $records = InvoiceValidation::with('stickerMasterRelation')
            ->where('invoice_number', $this->invoiceNumber)
            ->where('plant_id', $this->plantId)
            ->get();

        $this->packageCount = $records->sum(function ($record) {

            $sm = $record->stickerMasterRelation;

            if (! $sm) {
                return 0;
            }

            $stickCount = 0;
            $scannedCount = 0;

            if (! empty($sm->panel_box_code)) {
                $stickCount++;

                if ($record->capacitor_scanned_status == 1) {
                    $scannedCount++;
                }
            }

            // $sm->tube_sticker_motor == 1 || $sm->tube_sticker_pump == 1 || $sm->tube_sticker_pumpset == 1
            if (! empty($sm->tube_sticker_motor) || ! empty($sm->tube_sticker_pump) || ! empty($sm->tube_sticker_pumpset)) {

                if (! empty($sm->tube_sticker_motor)) {
                    $stickCount++;
                    if ($record->motor_scanned_status == 1) {
                        $scannedCount++;
                    }
                }

                // ($sm->tube_sticker_pumpset != 1 && $sm->tube_sticker_pump != 1 && $sm->pack_slip_pump == 1)
                if (! empty($sm->tube_sticker_pump) || (empty($sm->tube_sticker_pumpset) && empty($sm->tube_sticker_pump) && ! empty($sm->pack_slip_pump))) {
                    $stickCount++;
                    if ($record->pump_scanned_status == 1) {
                        $scannedCount++;
                    }
                }

                if (! empty($sm->tube_sticker_pumpset)) {
                    $stickCount++;
                    if ($record->scanned_status_set == 1) {
                        $scannedCount++;
                    }
                }
            } elseif (! empty($sm->pack_slip_motor) || ! empty($sm->pack_slip_pump) || ! empty($sm->pack_slip_pumpset)) {
                if (! empty($sm->pack_slip_motor)) {
                    $stickCount++;
                    if ($record->motor_scanned_status == 1) {
                        $scannedCount++;
                    }
                }

                if (! empty($sm->pack_slip_pump)) {
                    $stickCount++;
                    if ($record->pump_scanned_status == 1) {
                        $scannedCount++;
                    }
                }

                if (! empty($sm->pack_slip_pumpset)) {
                    $stickCount++;
                    if ($record->scanned_status_set == 1) {
                        $scannedCount++;
                    }
                }
            }

            return max($stickCount - $scannedCount, 0);
        });

        $this->dispatch(
            $onCapFocus ? 'focus-capacitor-input' : 'focus-serial-number'
        );
    }

    public function getInvoiceRecordsProperty()
    {
        return InvoiceValidation::with('stickerMasterRelation.item')
            ->where('invoice_number', $this->invoiceNumber)
            ->where('plant_id', $this->plantId)
            ->where(function ($query) {
                $query->whereNull('scanned_status')
                    ->orWhere('scanned_status', '');
            })
            // ->when($this->hasSearched, function ($query) {
            //     $query->where('invoice_number', $this->invoiceNumber)
            //         ->where('plant_id', $this->plantId)
            //         ->where('scanned_status', '=', '');
            // })
            ->paginate(6);
    }

    // public function loadData($invoiceNumber, $plantId, $onCapFocus = false)
    // {
    //     $this->plantId = $plantId;
    //     $this->invoiceNumber = $invoiceNumber;
    //     $this->completedInvoice = false;
    //     $this->isSerial = true;
    //     $this->onCapFocus = $onCapFocus;
    //     $this->emptyInvoice = false;
    //     $this->hasSearched = true;
    //     $this->materialInvoice = false;

    //     // Eager load stickerMasterRelation and item
    //     $invoiceRecords = InvoiceValidation::with('stickerMasterRelation.item')
    //         ->where('invoice_number', $invoiceNumber)
    //         ->where('plant_id', $plantId)
    //         ->whereNull('scanned_status')
    //         ->get();

    //     $this->invoiceData = [];
    //     $this->packageCount = 0;

    //     foreach ($invoiceRecords as $record) {
    //         $sm = $record->stickerMasterRelation;

    //         // Compute code
    //         $rowCode = $sm?->item?->code ?? 'N/A';

    //         $stickCount = 0;
    //         $scannedCount = 0;

    //         if ($sm) {
    //             // Panel box code
    //             if (Str::length($sm->panel_box_code) > 0) {
    //                 $stickCount++;
    //             }
    //             // Tube stickers logic
    //             if ($sm->tube_sticker_motor == 1 || $sm->tube_sticker_pump == 1 || $sm->tube_sticker_pumpset == 1) {
    //                 if ($sm->tube_sticker_motor == 1) $stickCount++;
    //                 if ($sm->tube_sticker_pump == 1 || ($sm->tube_sticker_pumpset != 1 && $sm->tube_sticker_pump != 1 && $sm->pack_slip_pump == 1)) $stickCount++;
    //                 if ($sm->tube_sticker_pumpset == 1) $stickCount++;
    //             }
    //             // Pack slip logic (only if tube sticker block didn't apply)
    //             elseif ($sm->pack_slip_motor == 1 || $sm->pack_slip_pump == 1 || $sm->pack_slip_pumpset == 1) {
    //                 if ($sm->pack_slip_motor == 1) $stickCount++;
    //                 if ($sm->pack_slip_pump == 1) $stickCount++;
    //                 if ($sm->pack_slip_pumpset == 1) $stickCount++;
    //             }
    //         }

    //         // Count already scanned
    //         $scannedCount += ($record->motor_scanned_status == 1) ? 1 : 0;
    //         $scannedCount += ($record->pump_scanned_status == 1) ? 1 : 0;
    //         $scannedCount += ($record->capacitor_scanned_status == 1) ? 1 : 0;
    //         $scannedCount += ($record->scanned_status_set == 1) ? 1 : 0;

    //         // Increment packageCount
    //         $this->packageCount += max($stickCount - $scannedCount, 0);

    //         $this->invoiceData[] = [
    //             'sticker_master_id' => $record->sticker_master_id,
    //             'serial_number' => $record->serial_number,
    //             'motor_scanned_status' => $record->motor_scanned_status ?? '',
    //             'pump_scanned_status' => $record->pump_scanned_status ?? '',
    //             'capacitor_scanned_status' => $record->capacitor_scanned_status ?? '',
    //             'scanned_status_set' => $record->scanned_status_set ?? '',
    //             'scanned_status' => $record->scanned_status ?? '',
    //             'panel_box_supplier' => $record->panel_box_supplier ?? '',
    //             'panel_box_serial_number' => $record->panel_box_serial_number ?? '',
    //             'created_at' => $record->created_at,
    //             'operator_id' => $record->operator_id,
    //             'code' => $rowCode,
    //             'stickCount' => $stickCount,
    //         ];
    //     }

    //     if ($onCapFocus) {
    //         $this->dispatch('focus-capacitor-input');
    //     } else {
    //         $this->dispatch('focus-serial-number');
    //     }
    // }

    public function loadMaterialData($invoiceNumber, $plantId)
    {
        $this->plantId = $plantId;
        $this->invoiceNumber = $invoiceNumber;
        $this->completedInvoice = false;
        $this->isSerial = false;
        $this->onCapFocus = false;
        $this->emptyInvoice = false;
        $this->hasSearched = false;
        $this->materialInvoice = true;
        // $this->showCapacitorInput = false;

        // ->where('serial_number', '!=', '')
        $this->invoiceData = InvoiceValidation::where('invoice_number', $this->invoiceNumber)->where('plant_id', $plantId)->where('serial_number', null)
            ->get()
            ->map(function ($record) {
                return [
                    'sticker_master_id' => $record->sticker_master_id,
                    // 'material_type' => StickerMaster::where('id', $record->sticker_master_id)->first()->material_type ?? '',
                    'invoice_quantity' => $record->invoice_quantity ?? 0,
                    'scanned_quantity' => ($record->invoice_quantity == null) ? 0 : ($record->invoice_quantity - $record->quantity) ?? 0,
                    // 'scanned_quantity' => number_format(($record->invoice_quantity == null ? 0 : ($record->invoice_quantity - $record->quantity)), 3, '.', ''),
                    'quantity' => $record->quantity ?? '',
                    'serial_number' => $record->serial_number ?? '',
                    'batch_number' => $record->batch_number ?? '',
                    'created_at' => $record->created_at,
                    'operator_id' => $record->operator_id,
                ];
            })
            ->toArray();

        // Loop through and replace 'code' using related StickerMaster > Item > code
        foreach ($this->invoiceData as &$row) {
            // $stickerMaster = \App\Models\StickerMaster::with('item')->find($row['sticker_master_id'] ?? null);
            $row['code'] = StickerMaster::with('item')->find($row['sticker_master_id'] ?? null)?->item?->code ?? 'N/A';
            $matType = StickerMaster::where('id', $row['sticker_master_id'] ?? null)->first()->material_type ?? '';
            if ($matType == 1) {
                $row['material_type'] = 'Individual';
                $row['invoice_quantity'] = $row['quantity'];
            } elseif ($matType == 2) {
                $row['material_type'] = 'Bundle';
                $row['invoice_quantity'] = $row['quantity'];
            } elseif ($matType == 3) {
                $row['material_type'] = 'Quantity';
                $row['invoice_quantity'] = number_format($row['invoice_quantity'], 3, '.', '');
                $row['scanned_quantity'] = number_format($row['scanned_quantity'], 3, '.', '');
            } elseif ($matType == 4) {
                $row['material_type'] = 'Bundle Individual';
                $row['invoice_quantity'] = $row['quantity'];
            } else {
                $row['material_type'] = 'N/A';
            }
        }
        $this->dispatch('focus-serial-number');
    }

    public function showCapacitorInputBox($itemCode, $serialNumber, $plantId)
    {
        $this->plantId = $plantId;
        $this->currentItemCode = $itemCode;
        $this->currentSerialNumber = $serialNumber;
        $this->showCapacitorInput = true;
        // $this->capacitorInput = '';
        $this->completedInvoice = false;
        $this->isSerial = true;
        $this->onCapFocus = false;
        $this->emptyInvoice = false;
        $this->hasSearched = false;
        $this->materialInvoice = false;
        $this->dispatch('focus-capacitor-input');
    }

    public function cancelCapacitorInput()
    {
        $this->capacitorInput = null;
        $this->showCapacitorInput = false;
        $this->dispatch('focus-serial-number');
    }

    // public function processCapacitorInput()
    // {
    //     $user = Filament::auth()->user();
    //     $operatorName = $user->name;

    //     if (! $this->capacitorInput) {
    //         return;
    //     }

    //     if (! preg_match('/^[^\/]+\/[^\/]+\/.+$/', $this->capacitorInput)) {
    //         Notification::make()
    //             ->title('Invalid Panel Box QR Format:')
    //             ->body("Scan the valid panel box QR '$this->capacitorInput' to proceed!")
    //             ->danger()
    //             // ->duration(3000)
    //             ->seconds(2)
    //             ->send();

    //         $this->capacitorInput = '';
    //         return;
    //     }

    //     $parts = explode('/', $this->capacitorInput);
    //     $supplier = $parts[0];
    //     $itemCode = $parts[1];
    //     $serialNumber = implode('/', array_slice($parts, 2)); // Keep rest of the string

    //     $existsInStickerMaster = StickerMaster::where('panel_box_code', $itemCode)->where('plant_id', $this->plantId)->whereHas('item', function ($query) {
    //         $query->where('code', $this->currentItemCode);
    //     })
    //         ->exists();

    //     if (! $existsInStickerMaster) {
    //         Notification::make()
    //             ->title('Unknown: Panel Box Code')
    //             ->body("Unknown panel box code: $itemCode found for item code: $this->currentItemCode")
    //             ->danger()
    //             // ->duration(4000)
    //             ->seconds(2)
    //             ->send();
    //         $this->capacitorInput = '';

    //         return;
    //     }

    //     foreach ($this->invoiceData as &$row) {

    //         if (($row['code'] ?? '') == $this->currentItemCode && ($row['serial_number'] ?? '') == $this->currentSerialNumber) {
    //             $row['panel_box_supplier'] = $supplier;
    //             $row['panel_box_code'] = $itemCode;
    //             $row['panel_box_serial_number'] = $serialNumber;
    //             $row['capacitor_scanned_status'] = 1;
    //             // $row['scanned_status_set'] = true;

    //             $matchingValidation = InvoiceValidation::with('stickerMaster.item')
    //                 ->where('serial_number', $this->currentSerialNumber)
    //                 ->where('plant_id', $this->plantId)
    //                 ->get()
    //                 ->first(function ($validation) {
    //                     return $validation->stickerMaster?->item?->code == $this->currentItemCode;
    //                 });

    //                 // dd($matchingValidation);

    //             if ($matchingValidation) {
    //                 $hasMotorQr = $matchingValidation->stickerMasterRelation->tube_sticker_motor ?? null;
    //                 $hasPumpQr = $matchingValidation->stickerMasterRelation->tube_sticker_pump ?? null;
    //                 $hasPumpSetQr = $matchingValidation->stickerMasterRelation->tube_sticker_pumpset ?? null;
    //                 // $hasCapacitorQr = $matchingValidation->stickerMasterRelation->panel_box_code ?? null;

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

    //                 $packCnt = 1;
    //                 $scanCnt = 1;
    //                 // if ($hadMotorQr == $hasMotorQr && $hadPumpQr == $hasPumpQr && $hadPumpSetQr == $hasPumpSetQr)
    //                 if ($hasMotorQr || $hasPumpQr || $hasPumpSetQr) {
    //                     $packCnt = $hasMotorQr ? $packCnt + 1 : $packCnt;
    //                     $packCnt = $hasPumpQr ? $packCnt + 1 : $packCnt;
    //                     $packCnt = $hasPumpSetQr ? $packCnt + 1 : $packCnt;

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

    //                     if ($packCnt == $scanCnt) {
    //                         $matchingValidation->update([
    //                             'panel_box_supplier' => $supplier,
    //                             'panel_box_code' => $itemCode,
    //                             'panel_box_serial_number' => $serialNumber,
    //                             'capacitor_scanned_status' => 1,
    //                             'scanned_status' => 'Scanned',
    //                             'operator_id' => $operatorName,
    //                         ]);
    //                     } else {
    //                         $matchingValidation->update([
    //                             'panel_box_supplier' => $supplier,
    //                             'panel_box_code' => $itemCode,
    //                             'panel_box_serial_number' => $serialNumber,
    //                             'capacitor_scanned_status' => 1,
    //                             'operator_id' => $operatorName,
    //                         ]);
    //                     }
    //                 } else {
    //                     $matchingValidation->update([
    //                         'panel_box_supplier' => $supplier,
    //                         'panel_box_code' => $itemCode,
    //                         'panel_box_serial_number' => $serialNumber,
    //                         'capacitor_scanned_status' => 1,
    //                         'scanned_status' => 'Scanned',
    //                         'operator_id' => $operatorName,
    //                     ]);
    //                 }

    //                 // Notification::make()
    //                 //     ->title('Success: Capacitor QR')
    //                 //     // ->title("Panel box code scanned: $itemCode")
    //                 //     ->body("'Capacitor' QR scanned status updated, Scan next QR.")
    //                 //     ->success() // commented
    //                 //     ->seconds(2)
    //                 //     ->send();

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

    //                 if ($totalQuantity == $scannedQuantity) {
    //                     Notification::make()
    //                         ->title('Completed: Serial Invoice')
    //                         ->body("Serial invoice '$matchingValidation->invoice_number' completed the scanning process.<br>Scan the next 'Serial Invoice' to proceed!")
    //                         ->success()
    //                         ->seconds(2)
    //                         ->send();
    //                     $this->loadCompletedData($matchingValidation->invoice_number, $matchingValidation->plant_id, true);
    //                 } else {
    //                     $this->loadData($matchingValidation->invoice_number, $matchingValidation->plant_id, false);
    //                 }
    //             }
    //             break;
    //         }
    //     }

    //     $this->showCapacitorInput = false;
    //     $this->capacitorInput = '';
    //     $this->dispatch('updateScannedQuantity');
    //     // $this->loadData($this->invoiceNumber, $this->plantId);
    //     $this->dispatch('focus-serial-number');
    // }

    public function processCapacitorInput()
    {
        $user = Filament::auth()->user();
        $operatorName = $user->name;

        if (! $this->capacitorInput) {
            return;
        }

        if (! preg_match('/^[^\/]+\/[^\/]+\/.+$/', $this->capacitorInput)) {
            Notification::make()
                ->title('Invalid Panel Box QR Format:')
                ->body("Scan the valid panel box QR '$this->capacitorInput' to proceed!")
                ->danger()
                // ->duration(3000)
                ->seconds(2)
                ->send();

            $this->capacitorInput = '';

            return;
        }

        $parts = explode('/', $this->capacitorInput);
        $supplier = $parts[0];
        $itemCode = $parts[1];
        $serialNumber = implode('/', array_slice($parts, 2)); // Keep rest of the string

        $existsInStickerMaster = StickerMaster::where('panel_box_code', $itemCode)->where('plant_id', $this->plantId)->whereHas('item', function ($query) {
            $query->where('code', $this->currentItemCode);
        })
            ->exists();

        if (! $existsInStickerMaster) {
            Notification::make()
                ->title('Unknown: Panel Box Code')
                ->body("Unknown panel box code: $itemCode found for item code: $this->currentItemCode")
                ->danger()
                // ->duration(4000)
                ->seconds(2)
                ->send();
            $this->capacitorInput = '';

            return;
        }

        // $categoryExist = Item::where('code', $itemCode)->first();

        // if($categoryExist?->category == 'Panel Box'){

        //     $panelExist = PanelBoxValidation::where('panel_box_serial_number', $serialNumber)->where('panel_box_code', $itemCode)->where('panel_box_supplier', $supplier)->first();

        //     if(!$panelExist){
        //         Notification::make()
        //             ->title('Panel Not Verified')
        //             ->body("Panel Quality Inspection failed.<br>Panel Box Code: $itemCode, Item Code: {$this->currentItemCode}, Serial Number: $serialNumber.</br>")
        //             ->danger()
        //             ->seconds(2)
        //             ->send();
        //         $this->capacitorInput = '';

        //         return;
        //     }
        // }

        $this->package = InvoiceValidation::with('stickerMasterRelation')
            ->where('invoice_number', $this->invoiceNumber)
            ->where('plant_id', $this->plantId)
            ->get();

        foreach ($this->package as &$row) {

            $stickerCode = $row->stickerMasterRelation?->item?->code ?? null;
            $serialNo = $row->serial_number ?? null;

            if ($stickerCode == $this->currentItemCode && $serialNo == $this->currentSerialNumber) {
                $row['panel_box_supplier'] = $supplier;
                $row['panel_box_code'] = $itemCode;
                $row['panel_box_serial_number'] = $serialNumber;
                $row['capacitor_scanned_status'] = 1;
                // $row['scanned_status_set'] = true;

                $matchingValidation = InvoiceValidation::with('stickerMaster.item')
                    ->where('serial_number', $this->currentSerialNumber)
                    ->where('plant_id', $this->plantId)
                    ->get()
                    ->first(function ($validation) {
                        return $validation->stickerMaster?->item?->code == $this->currentItemCode;
                    });

                // dd($matchingValidation);

                if ($matchingValidation) {
                    $hasMotorQr = $matchingValidation->stickerMasterRelation->tube_sticker_motor ?? null;
                    $hasPumpQr = $matchingValidation->stickerMasterRelation->tube_sticker_pump ?? null;
                    $hasPumpSetQr = $matchingValidation->stickerMasterRelation->tube_sticker_pumpset ?? null;
                    // $hasCapacitorQr = $matchingValidation->stickerMasterRelation->panel_box_code ?? null;

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

                    $packCnt = 1;
                    $scanCnt = 1;
                    // if ($hadMotorQr == $hasMotorQr && $hadPumpQr == $hasPumpQr && $hadPumpSetQr == $hasPumpSetQr)
                    if ($hasMotorQr || $hasPumpQr || $hasPumpSetQr) {
                        $packCnt = $hasMotorQr ? $packCnt + 1 : $packCnt;
                        $packCnt = $hasPumpQr ? $packCnt + 1 : $packCnt;
                        $packCnt = $hasPumpSetQr ? $packCnt + 1 : $packCnt;

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

                        if ($packCnt === $scanCnt) {
                            $matchingValidation->update([
                                'panel_box_supplier' => $supplier,
                                'panel_box_code' => $itemCode,
                                'panel_box_serial_number' => $serialNumber,
                                'capacitor_scanned_status' => 1,
                                'scanned_status' => 'Scanned',
                                'operator_id' => $operatorName,
                            ]);
                        } else {
                            $matchingValidation->update([
                                'panel_box_supplier' => $supplier,
                                'panel_box_code' => $itemCode,
                                'panel_box_serial_number' => $serialNumber,
                                'capacitor_scanned_status' => 1,
                                'operator_id' => $operatorName,
                            ]);
                        }
                    } else {
                        $matchingValidation->update([
                            'panel_box_supplier' => $supplier,
                            'panel_box_code' => $itemCode,
                            'panel_box_serial_number' => $serialNumber,
                            'capacitor_scanned_status' => 1,
                            'scanned_status' => 'Scanned',
                            'operator_id' => $operatorName,
                        ]);
                    }

                    // Notification::make()
                    //     ->title('Success: Capacitor QR')
                    //     // ->title("Panel box code scanned: $itemCode")
                    //     ->body("'Capacitor' QR scanned status updated, Scan next QR.")
                    //     ->success() // commented
                    //     ->seconds(2)
                    //     ->send();

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

                    if ($totalQuantity == $scannedQuantity) {
                        Notification::make()
                            ->title('Completed: Serial Invoice')
                            ->body("Serial invoice '$matchingValidation->invoice_number' completed the scanning process.<br>Scan the next 'Serial Invoice' to proceed!")
                            ->success()
                            ->seconds(2)
                            ->send();
                        $this->loadCompletedData($matchingValidation->invoice_number, $matchingValidation->plant_id, true);
                    } else {
                        $this->loadData($matchingValidation->invoice_number, $matchingValidation->plant_id, false);
                    }
                }
                break;
            }
        }

        $this->showCapacitorInput = false;
        $this->capacitorInput = '';
        $this->dispatch('updateScannedQuantity');
        // $this->loadData($this->invoiceNumber, $this->plantId);
        $this->dispatch('focus-serial-number');
    }

    // public function render()
    // {
    //     return view('livewire.invoice-data-table');
    // }

    public function render()
    {
        return view('livewire.invoice-data-table', [
            'records' => $this->invoiceRecords,
        ]);
    }
}
