<?php

namespace App\Filament\Resources;

use App\Filament\Exports\QualityValidationExporter;
use App\Filament\Imports\QualityValidationImporter;
use App\Filament\Resources\QualityValidationResource\Pages;
use App\Filament\Resources\QualityValidationResource\RelationManagers;
use App\Mail\InvalidQualityMail;
use App\Models\AlertMailRule;
use App\Models\Item;
use App\Models\Line;
use App\Models\Plant;
use App\Models\QualityValidation;
use App\Models\StickerMaster;
use Carbon\Carbon;
use Closure;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\Relationship;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Filters\Filter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\ValidationException;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Mail;
use Storage;

class QualityValidationResource extends Resource
{
    protected static ?string $model = QualityValidation::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    protected static ?string $navigationGroup = 'Display';
    public $isSubmitted = false;
    public $data = [];

    public static function form(Form $form): Form
    {
        return $form
            ->statePath('data')
            ->schema(components: [
                Forms\Components\Select::make('plant_id')
                    ->relationship('plant', 'name')
                    ->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();
                    })
                    ->afterStateUpdated(function (callable $set, callable $get, $state) {
                        $set('item_id', null);
                        $set('line_id', null);
                        $set('production_order', null);

                        $set('part_validation_type_options', []);
                        $set('part_validation_type', null);
                        $set('show_validation_image', false);
                        $set('validation1_image_url', null);

                        $set('plant', $state);

                        $pId = $get('plant_id');
                        if (!$pId) {
                            $set('pqPlantError', 'Please select a plant first.');
                        }
                        else {
                            $set('pqPlantError', null);
                        }

                        $pId = $get('line_id');
                        if (!$pId) {
                            $set('pqLineError', null);
                        }
                    })
                    ->required()
                    //->default(fn () => request()->query('plant_id'))
                    ->default(fn ($get) => $get('plant') ?? session('last_selected_plant_id'))
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('pqPlantError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('pqPlantError') ? $get('pqPlantError') : null)
                    ->hintColor('danger'),
                Forms\Components\Hidden::make('plant')
                    ->default(fn () => session('last_selected_plant_id')),

                Forms\Components\Select::make('line_id')
                    ->relationship('line', titleAttribute: 'name')
                    ->reactive()
                    ->required()
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if (!$plantId)
                        {
                            return [];
                        }

                        return Line::where('plant_id', $plantId)
                        ->where('type', 'FG Line') // Filter by type
                        ->pluck('name', 'id')
                        ->toArray();
                    })
                    ->afterStateUpdated(function (callable $set, callable $get, $state) {
                        $set('item_id', null);
                        $set('production_order', null);

                        $set('line', $state);

                        $pId = $get('line_id');
                        if (!$pId) {
                            $set('pqLineError', 'Please select a line.');
                        } else {
                            $set('pqLineError', null);
                        }
                    })
                    ->default(fn ($get) => $get('line') ?? session('last_selected_line'))
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('pqLineError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('pqLineError') ? $get('pqLineError') : null)
                    ->hintColor('danger'),
                Forms\Components\Hidden::make('line')
                    ->default(fn () => session('last_selected_line')),
                Forms\Components\Hidden::make('sticker_master_id')
                   // ->relationship('stickerMaster', 'id')
                    ->required(),
                Forms\Components\Hidden::make('uom')
                    ->required(),
                Forms\Components\Hidden::make('sap_msg_status'),
                Forms\Components\Hidden::make('sap_msg_description'),
                Forms\Components\TextInput::make('production_order')
                    ->placeholder('Scan the valid Production Order')
                    ->minLength(7)
                    ->maxLength(14)
                    ->reactive()
                    ->readOnly(fn (callable $get) => $get('item_id'))
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        if(!is_numeric($get('production_order')) || !preg_match('/^[1-9][0-9]{6,13}$/', $get('production_order')))
                        {
                            $set('prodOrdError', "Must be a numeric value with 7 to 14 digits.");
                            $set('production_order', null);
                            $set('item_id', null);
                            $set('sticker_master_id', null);
                            $set('uom', null);
                            $set('serial_number', null);
                        }
                        else
                        {
                            $set('prodOrdError', null);
                            $set('production_order', $state);
                            $set('production', $state);
                        }
                    })
                    ->default(fn ($get) => $get('production') ?? session('last_selected_production'))
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('prodOrdError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('prodOrdError') ? $get('prodOrdError') : null)
                    ->hintColor('danger')
                    ->required(),

                Forms\Components\Hidden::make('production')
                    ->default(fn () => session('last_selected_production')),

                Forms\Components\Hidden::make('operator_id')
                    ->required()
                    ->default(Filament::auth()->user()->name),

                Forms\Components\Hidden::make('sap_msg_status')
                    ->default(null),

                Forms\Components\Hidden::make('sap_msg_description')
                    ->default(null),

                // Forms\Components\TextInput::make('name')
                //     ->required()
                //     ->autofocus()
                //     ->live(debounce: 600)
                //     ->afterStateUpdated(function ($state, callable $set, callable $get) {
                //         $set('email', $state . '@cripumps.com');
                //     })
                //     ->maxLength(255),
                // Forms\Components\TextInput::make('email')
                //     // ->email()
                //     ->unique(ignoreRecord: true)
                //     ->required()
                //     ->readOnly()
                //     // ->rule(function (callable $get) {
                //     //     return Rule::unique('users', 'email')
                //     //         ->ignore($get('id')); // Ignore current record during updates
                //     // })
                //     // ->dehydrated()
                //     //->prefix(fn ($get) => $get('name') ?? null)
                //     // ->suffix('@cripumps.com')
                //     ->maxLength(255),

                Forms\Components\TextInput::make('item_id')
                    ->label('Item Code')
                    ->placeholder('Scan the valid QR code')
                    ->reactive()
                    ->required()
                    ->autofocus()
                    ->live()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $pId = $get('line_id');
                        $set('part_validation_type', null);
                        $set('show_validation_image', false);
                        $set('validation1_image_url', null);

                        if (!$pId) {
                            $set('pqLineError', 'Please select a line.');
                        } else {
                            $set('pqLineError', null);
                        }

                        $pOrder = $get('production_order');
                        if (!$pOrder)
                        {
                            $set('prodOrdError', "Production Order can't be empty.");
                            $set('production_order', null);
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('validation1_image_url', null);
                        }
                        else
                        {
                            $set('prodOrdError', null);
                        }

                        $serialFields = [
                            'serial_number_motor_qr', 'serial_number_pump_qr', 'serial_number_pumpset_qr', 'pack_slip_motor_qr', 'pack_slip_pump_qr', 'pack_slip_pumpset_qr', 'name_plate_motor_qr', 'name_plate_pump_qr', 'name_plate_pumpset_qr', 'tube_sticker_motor_qr', 'tube_sticker_pump_qr', 'tube_sticker_pumpset_qr', 'warranty_card_qr'
                        ];

                        $set('serial_number', null);

                        $serialnumber = ['serial_number_motor_qr', 'serial_number_pump_qr', 'serial_number_pumpset_qr'];

                        $partValidationColumns = [
                            'part_validation1', 'part_validation2', 'part_validation3', 'part_validation4', 'part_validation5'
                        ];

                        foreach ($serialFields as $field) {
                            $set($field . '_visible', false);
                            $set($field, null);
                        }

                        foreach ($partValidationColumns as $column) {
                            $set($column . '_visible', false);
                            $set($column, null);
                        }

                        // Proceed with validation logic for new scanned QR code
                        if (!$state || trim($state) == '') {
                            $set('validationError', null);
                            return;
                        }

                        // // Check if QR format contains '|'
                        if (strpos($state, '|') == false) {
                            $set('validationError', 'Scan valid QR code. (Ex: Item_Code|Serial_Number)');
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);
                            return;
                        }

                        if (!preg_match('/^[a-zA-Z0-9]{6,}+\|[1-9][a-zA-Z0-9]{8,}+(\|)?$/', $state)) {
                            // if (strpos($state, '|') == false) {
                            //     $set('validationError', 'Scan valid QR code. (Ex: Item_Code|Serial_Number)');
                            //     $set('item_id', null);
                            //     $set('item_description', null);
                            //     $set('serial_number', null);
                            //     return;
                            // }
                            // else
                            // {
                                $splits = explode('|', $state);
                                $iCode = trim($splits[0]);
                                $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                                if (!ctype_alnum($iCode)) {
                                    $set('validationError', 'Item code must contain alpha-numeric values.');
                                    $set('part_validation_type', null);
                                    $set('show_validation_image', false);
                                    $set('part_validation_type_options', []);
                                    $set('validation1_image_url', null);
                                    return;
                                }
                                else if (strlen($iCode) < 6) {
                                    $set('validationError', 'Item code must be at least 6 digits.');
                                    $set('part_validation_type', null);
                                    $set('show_validation_image', false);
                                    $set('part_validation_type_options', []);
                                    $set('validation1_image_url', null);
                                    return;
                                }
                                else if (!ctype_alnum($sNumber)) {
                                    $set('validationError', 'Serial Number must contain alpha-numeric values.');
                                    $set('part_validation_type', null);
                                    $set('show_validation_image', false);
                                    $set('part_validation_type_options', []);
                                    $set('validation1_image_url', null);
                                    return;
                                }
                                else if (strlen($sNumber) < 9) {
                                    $set('validationError', 'Serial Number must be at least 9 digits.');
                                    $set('part_validation_type', null);
                                    $set('show_validation_image', false);
                                    $set('part_validation_type_options', []);
                                    $set('validation1_image_url', null);
                                    return;
                                }
                            // }

                        }
                        else
                        {
                            $set('validationError', null);
                        }

                        $parts = explode('|', $state);

                        $itemCode = trim($parts[0]); // Extract item code // 123456|123456789

                        $serialNumber = trim($parts[1]);

                        // Store serial number before resetting fields
                        $previousSerialNumber = $serialNumber;

                        $previousItemCode = $itemCode;

                        if (strlen($itemCode) < 6) {
                            $set('validationError', 'Item code must be at least 6 digits.');
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);
                            return;
                        }
                        else if (!ctype_alnum($itemCode)) {
                            $set('validationError', 'Item Code should contain alpha-numeric values.');
                            $set('item_id', null);
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);
                            return;
                        }
                        else if ($serialNumber == '') {
                            $set('validationError', 'Waiting for full QR scan...');
                            return;
                        }
                        else if (strlen($serialNumber) < 9) {
                            $set('validationError', 'Serial Number must be at least 9 digits.');
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);
                            return;
                        }
                        else if (!ctype_alnum($serialNumber)) {
                            $set('validationError', 'Serial Number should contain alpha-numeric values.');
                            $set('item_id', null);
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);
                            return;
                        }
                        else
                        {
                            $set('validationError', null);
                        }

                        $plantId = $get('plant_id'); // Get selected plant

                        if (!$plantId) {
                            $set('validationError', 'Please select a plant first.');
                            $set('item_id', null);
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);
                            return;
                        }
                        // Check if the item exists for the selected plant
                        $stickerMaster = StickerMaster::where('plant_id', $plantId)->whereHas('item', function ($query) use ($itemCode) {
                                $query->where('code', $itemCode);
                            })->first();


                        if (!$stickerMaster) {
                            $set('validationError', 'Item code does not exist in master data.');
                            $set('sticker_master_id', null);
                            $set('uom', null);
                            $set('serial_number', null);
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);
                            return;
                        }
                        else
                        {
                            if (!$stickerMaster->item->uom) {
                                $set('validationError', "Item code does not have 'UOM' in master data.");
                                $set('sticker_master_id', null);
                                $set('uom', null);
                                $set('serial_number', null);
                                $set('part_validation_type', null);
                                $set('show_validation_image', false);
                                $set('validation1_image_url', null);
                                return;
                            }
                            else if(!is_numeric($get('production_order')) || !preg_match('/^[1-9][0-9]{6,13}$/', $get('production_order')))
                            {
                                $set('prodOrdError', "Must be a numeric value.");
                                $set('item_id', null);
                                $set('sticker_master_id', null);
                                $set('uom', null);
                                $set('serial_number', null);
                                $set('part_validation_type', null);
                                $set('show_validation_image', false);
                                $set('part_validation_type_options', []);
                                $set('validation1_image_url', null);
                                return;
                            }

                            $set('sticker_master_id', $stickerMaster->id);
                            $set('uom', $stickerMaster->item->uom);
                            $set('item_id', $itemCode);
                            // $set('serial_number', null);
                            // $set('serial_number', $serialNumber);
                        }
                        // Check if user input matches the database values
                        foreach ($partValidationColumns as $field) {
                            if ($get("{$field}_visible")) {
                                $userInput = $get($field);
                                $expectedValue = $stickerMaster->$field;

                                if ($userInput != null && $userInput != $expectedValue) {
                                    $set('validationError', "Invalid input for $field. Expected: $expectedValue");
                                    return; // Stop execution if any validation fails
                                }
                            }
                        }

                        $serialExists = QualityValidation::where('serial_number', $serialNumber)->where('plant_id', $plantId)->exists();

                        // $serialExists = QualityValidation::where(function ($query) use ($serialNumber, $serialFields) {
                        //     foreach ($serialFields as $column) {
                        //         $colFld  = $column;
                        //         if (str_ends_with($colFld, '_qr')) {
                        //             $colFld = substr($colFld, 0, -3);
                        //         }
                        //         $query->where($colFld, $serialNumber);
                        //     }
                        // })->exists();


                        if ($serialExists && !$get('id')) {
                            $set('validationError', 'Serial number already exists in quality validation.');
                            //$set('item_id', "$itemCode|$previousSerialNumber");
                           // $set('item_id', null);
                            $set('sticker_master_id', null);
                            $set('uom', null);
                            $set('serial_number', null);
                            return;
                        }

                        // Clear validation error if all inputs match
                         $set('validationError', null);

                        // $visibleColumns = [];
                        // foreach ($serialFields as $column) {
                        //     if ($stickerMaster->$column == 1) {
                        //         $visibleColumns[] = $column;
                        //     }
                        // }

                        // $visiblePartValidations = [];
                        // foreach ($partValidationColumns as $column) {
                        //     if ($stickerMaster->$column != null) {
                        //         $visiblePartValidations[] = $column;
                        //     }
                        // }

                        foreach ($serialFields as $column) {

                            $colFld  = $column;
                            if (str_ends_with($colFld, '_qr')) {
                                $colFld = substr($colFld, 0, -3);
                            }

                            if ($stickerMaster->$colFld != null) {
                                $set($column . '_visible', true);
                            } else {
                                $set($column . '_visible', false);
                            }
                        }

                        foreach ($partValidationColumns as $column) {
                            if ($stickerMaster->$column != null) {
                                $set($column . '_visible', true);
                            } else {
                                $set($column . '_visible', false);
                            }
                        }

                        foreach ($serialnumber as $field) {
                            if ($get("{$field}_visible")) {
                                $set($field, $serialNumber);
                                $colFld  = $field;
                                if (str_ends_with($colFld, '_qr')) {
                                    $colFld = substr($colFld, 0, -3);
                                }
                                $set($colFld, '1');
                                break;
                            }
                        }
                        $set('serial_number', $serialNumber);

                        // Find item based on scanned code
                        $item = Item::where('code', $itemCode)
                        ->where('plant_id', $plantId)->first();

                        if (!$item) {
                            $set('part_validation_type_options', []);
                            return;
                        }

                        // Find sticker master
                        $sticker = StickerMaster::where('plant_id', $plantId)
                                    ->where('item_id', $item->id)
                                    ->first();

                        if (!$sticker) {
                            $set('part_validation_type_options', []);
                            return;
                        }

                        // Build dynamic options
                        $options = [];

                        if (!empty($sticker->part_validation1)) {
                            $options['part_validation1'] = 'Part Validation 1';
                        }
                        if (!empty($sticker->part_validation2)) {
                            $options['part_validation2'] = 'Part Validation 2';
                        }
                        if (!empty($sticker->part_validation3)) {
                            $options['part_validation3'] = 'Part Validation 3';
                        }
                        if (!empty($sticker->part_validation4)) {
                            $options['part_validation4'] = 'Part Validation 4';
                        }

                        // Save options in hidden field
                        $set('part_validation_type_options', $options);

                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('validationError') ? 'border-red-500' : '',
                    ])
                    ->extraAttributes([
                        'onkeydown' => "if (event.key === 'Enter') { event.preventDefault(); return false; }",
                    ])
                    ->hint(fn ($get) => $get('validationError') ? $get('validationError') : null)
                    ->hintColor('danger'),

                // Forms\Components\Select::make('part_validation_type')
                //     ->reactive()
                //     ->label('Select Validation')
                //     ->options(function (callable $get) {

                //         $plantId = $get('plant_id');
                //         $itemId  = $get('item_id');

                //         if (!$plantId || !$itemId) {
                //             return [];
                //         }

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

                //         if (!$sticker) {
                //             return [];
                //         }

                //         $options = [];

                //         if (!empty($sticker->part_validation1)) {
                //             $options['part_validation1'] = 'Part Validation 1';
                //         }

                //         if (!empty($sticker->part_validation2)) {
                //             $options['part_validation2'] = 'Part Validation 2';
                //         }

                //         if (!empty($sticker->part_validation3)) {
                //             $options['part_validation3'] = 'Part Validation 3';
                //         }

                //         if (!empty($sticker->part_validation4)) {
                //             $options['part_validation4'] = 'Part Validation 4';
                //         }

                //         // if (!empty($sticker->part_validation5)) {
                //         //     $options['part_validation5'] = 'Part Validation 5';
                //         // }

                //         return $options;
                //     })
                //     ->reactive()
                //     ->required(),

                Forms\Components\Hidden::make('part_validation_type_options')
                    ->default([])
                    ->reactive()
                    ->dehydrated(false),

                Forms\Components\Hidden::make('show_validation_image')
                    ->reactive()
                    ->default(false),

                // Forms\Components\Select::make('part_validation_type')
                //     ->label('Select Validation')
                //     ->reactive()
                //     ->options(fn (callable $get) => $get('part_validation_type_options') ?? [])
                //     ->required()
                //     ->visible(fn ($get) => !empty($get('part_validation_type_options')))
                //     ->afterStateUpdated(function ($state, callable $set) {
                //         // when user selects something new, hide the image
                //         $set('show_validation_image', false);
                //         $set('validation1_image_url', null);
                //     }),

                Forms\Components\Select::make('part_validation_type')
                    ->label('Select Validation')
                    ->reactive()
                    ->options(fn (callable $get) => $get('part_validation_type_options') ?? [])
                    ->required()
                    ->afterStateUpdated(function ($state, callable $set) {
                        // when user selects something new, hide the image
                        $set('show_validation_image', false);
                        $set('validation1_image_url', null);
                    })
                    ->visible(fn ($get) => !empty($get('part_validation_type_options')))
                    ->suffixAction(
                Forms\Components\Actions\Action::make('toggleValidationImage')
                    ->icon(fn (callable $get) => $get('show_validation_image') ? 'heroicon-o-eye-slash' : 'heroicon-o-eye')
                    ->tooltip('View Validation Image')
                    ->action(function (callable $get, $set) {

                        $currentState = $get('show_validation_image');
                        $set('show_validation_image', !$currentState);

                        if ($currentState == true) {
                            $set('validation1_image_url', null);
                            return;
                        }

                        $partvalidationType = $get('part_validation_type');
                        $plantId1 = $get('plant_id');

                        $plantCode1 = Plant::where('id', $plantId1)->value('code');

                        $itemState = $get('item_id');
                        $parts = explode('|', $itemState);
                        $itemCode = trim($parts[0]);

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

                        $itemId2 = $itemId1?->id;

                        $sticker = StickerMaster::where('plant_id', $plantId1)
                            ->where('item_id', $itemId2)
                             ->first();

                        if (!$sticker) {
                            Notification::make()
                                ->title('Sticker Master Missing')
                                ->body('No Sticker Master found for selected Plant & Item.')
                                ->danger()
                                ->send();
                            return;
                        }

                        $value = $sticker->{$partvalidationType};
                        $fileName = "{$value}.png";

                        $imageUrl = route('part.validation.image', [
                            'plant' => $plantCode1,
                            'filename' => $fileName
                        ]);

                        $set('validation1_image_url', $imageUrl);
                    })
                ),

                // Forms\Components\Actions::make([
                //     Forms\Components\Actions\Action::make('openValidation')
                //         ->label('Open/Close')
                //         ->button()
                //         ->color('primary')
                //         ->action(function (callable $get, $set) {

                //             $currentState = $get('show_validation_image');
                //             $set('show_validation_image', !$currentState);

                //             if ($currentState == true) {
                //                 $set('validation1_image_url', null);
                //                 return;
                //             }

                //             $partvalidationType = $get('part_validation_type');
                //             $plantId1 = $get('plant_id');

                //             $plantCode1 = Plant::where('id', $plantId1)->value('code');


                //             $itemState = $get('item_id');

                //             $parts = explode('|', $itemState);

                //             $itemCode = trim($parts[0]);

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

                //             $itemId2 = $itemId1?->id;

                //             $sticker = StickerMaster::where('plant_id', $plantId1)
                //             ->where('item_id', $itemId2)
                //             ->first();

                //             if (!$sticker) {
                //                 Notification::make()
                //                     ->title('Sticker Master Missing')
                //                     ->body('No Sticker Master found for selected Plant & Item.')
                //                     ->danger()
                //                     ->send();
                //                 return;
                //             }

                //             $value = $sticker->{$partvalidationType};

                //             $fileName = "{$value}.png";

                //             // Check existence
                //             $fullPath = storage_path("app/private/uploads/PartValidation/{$plantCode1}/{$fileName}");

                //             // Generate URL through custom route
                //             $imageUrl = route('part.validation.image', [
                //                 'plant' => $plantCode1,
                //                 'filename' => $fileName
                //             ]);

                //             // Pass to state (for modal/view)
                //             $set('validation1_image_url', $imageUrl);

                //         }),
                //     ])
                // ->visible(fn ($get) => !empty($get('part_validation_type_options'))),

                Forms\Components\Hidden::make('validation1_image_url')
                ->reactive(),

                Forms\Components\View::make('components.part-validation-error-icon')
                ->statePath('validation1_image_url')   // bind state directly
                ->visible(fn ($get) => $get('show_validation_image') == true)
                ->reactive(),

                Forms\Components\Hidden::make('serial_number')
                    ->required(),

                Forms\Components\Hidden::make('serial_number_motor'),

                Forms\Components\TextInput::make('serial_number_motor_qr')
                    ->label('Serial Number Motor')
                    ->reactive()
                    ->readOnly(fn (callable $get) => !$get('id'))
                    ->hidden(fn (callable $get) => !$get('serial_number_motor_qr_visible'))  // Controls visibility
                    ->default(''),

                Forms\Components\Hidden::make('serial_number_pump'),

                Forms\Components\TextInput::make('serial_number_pump_qr')
                    ->label('Serial Number Pump')
                    ->reactive()
                    ->required()
                    ->hidden(fn (callable $get) => !$get('serial_number_pump_qr_visible'))
                    ->default('')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $set('serial_number_pump_error', null);

                        if (empty($state)) {
                            $set('serial_number_pump_error', null);
                            return;
                        }

                        if (strpos($state, '|') == false)
                        {
                            if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state))
                            {
                                $visibleSerialNumber = $get('serial_number');
                                $serialNumber = $state;

                                if ($visibleSerialNumber != $serialNumber)
                                {
                                    $set('serial_number_pump_error', 'Serial number does not match.');
                                    $set('serial_number_pump_qr', null);
                                    return;
                                }
                                else {
                                    $set('serial_number_pump_error', null);
                                    $set('serial_number_pump_qr', $serialNumber);
                                    $set('serial_number_pump', '1');
                                    return;
                                }
                            }

                            if (strlen($state) < 9) {
                                $set('serial_number_pump_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($state)) {
                                $set('serial_number_pump_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }
                        }
                        else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state))
                        {
                            $splits = explode('|', $state);
                            $iCode = trim($splits[0]);
                            $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                            if (!ctype_alnum($iCode)) {
                                $set('serial_number_pump_error', 'Item code must contain alpha-numeric values.');
                                return;
                            }
                            else if (strlen($iCode) < 6) {
                                $set('serial_number_pump_error', 'Item code must be at least 6 digits.');
                                return;
                            }
                            else if (strlen($sNumber) < 9) {
                                $set('serial_number_pump_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($sNumber)) {
                                $set('serial_number_pump_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }

                            $set('serial_number_pump_error', 'Scan valid QR code.');
                            return;
                        }
                        else
                        {
                            $set('serial_number_pump_error', null);
                        }

                        // Split state by pipeline "|"
                        $parts = explode('|', $state);
                        $itemCode = trim($parts[0]);

                        $serialNumber = trim($parts[1]);
                        $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                        // Retrieve visible serial numbers
                        // $visibleSerialNumbers = array_filter([
                        //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                        //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                        //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                        // ]);

                        $visibleSerialNumber = $get('serial_number');

                        $expectedItemCode = trim((string) $get('item_id'));

                        if ($itemCode != $expectedItemCode)
                        {
                            $set('serial_number_pump_error', 'Item code does not match.');
                            return;
                        }

                         $set('serial_number_pump_qr', $serialNumber);
                         $set('serial_number_pump', '1');

                        //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                        $isMatch = ($visibleSerialNumber == $serialNumber);

                        if (!$serialNumber || trim($serialNumber) == '') {
                            $set('serial_number_pump_error', null);
                            return;
                        }

                        if (!$isMatch)
                        {
                            $set('serial_number_pump_error', 'Serial number does not match.');
                            $set('serial_number_pump_qr', null);
                            return;
                        }
                        else {
                            $set('serial_number_pump_error', null);
                            $set('serial_number_pump_qr', $serialNumber);
                            $set('serial_number_pump', '1');
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('serial_number_pump_error') ? 'border-red-500' : '',
                    ])
                   ->hint(fn ($get) => $get('serial_number_pump_error') ? $get('serial_number_pump_error') : null)
                   ->hintColor('danger'),

                Forms\Components\Hidden::make('serial_number_pumpset'),

                Forms\Components\TextInput::make('serial_number_pumpset_qr')
                    ->label('Serial Number PumpSet')
                    ->reactive()
                    ->readOnly(fn (callable $get) => !$get('id'))
                    ->hidden(fn (callable $get) => !$get('serial_number_pumpset_qr_visible'))
                    ->default(''),

                Forms\Components\Hidden::make('pack_slip_motor'),

                Forms\Components\TextInput::make('pack_slip_motor_qr')
                    ->label('Pack Slip Motor')
                    ->hidden(fn (callable $get) => !$get('pack_slip_motor_qr_visible'))
                    ->default('')
                    ->reactive()
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $set('pack_slip_motor_error', null);

                        if (empty($state)) {
                            $set('pack_slip_motor_error', null);
                            return;
                        }

                        if (strpos($state, '|') == false)
                        {
                            if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state))
                            {
                                $visibleSerialNumber = $get('serial_number');
                                $serialNumber = $state;

                                if ($visibleSerialNumber != $serialNumber)
                                {
                                    $set('pack_slip_motor_error', 'Serial number does not match.');
                                    $set('pack_slip_motor_qr', null);
                                    return;
                                }
                                else {
                                    $set('pack_slip_motor_error', null);
                                    $set('pack_slip_motor_qr', $serialNumber);
                                    $set('pack_slip_motor', '1');
                                    return;
                                }
                            }

                            if (strlen($state) < 9) {
                                $set('pack_slip_motor_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($state)) {
                                $set('pack_slip_motor_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }
                        }
                        else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state))
                        {
                            $splits = explode('|', $state);
                            $iCode = trim($splits[0]);
                            $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                            if (!ctype_alnum($iCode)) {
                                $set('pack_slip_motor_error', 'Item code must contain alpha-numeric values.');
                                return;
                            }
                            else if (strlen($iCode) < 6) {
                                $set('pack_slip_motor_error', 'Item code must be at least 6 digits.');
                                return;
                            }
                            else if (strlen($sNumber) < 9) {
                                $set('pack_slip_motor_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($sNumber)) {
                                $set('pack_slip_motor_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }

                            $set('pack_slip_motor_error', 'Scan valid QR code');
                            return;
                        }
                        else
                        {
                            $set('pack_slip_motor_error', null);
                        }

                        // Split state by pipeline "|"
                        $parts = explode('|', $state);
                        $itemCode = trim($parts[0]);

                        $serialNumber = trim($parts[1]);
                        $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                        // // Retrieve visible serial numbers
                        // $visibleSerialNumbers = array_filter([
                        //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor_qr')) : null,
                        //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                        //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                        // ]);

                         $visibleSerialNumber = $get('serial_number');

                         $expectedItemCode = trim((string) $get('item_id'));

                         if ($itemCode != $expectedItemCode) {
                             $set('pack_slip_motor_error', 'Item code does not match.');
                             return;
                         }

                         $set('pack_slip_motor_qr', $serialNumber);

                         $set('pack_slip_motor', '1');


                        //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                        $isMatch = ($visibleSerialNumber == $serialNumber);

                        if (!$serialNumber || trim($serialNumber) == '') {
                            $set('pack_slip_motor_error', null);
                            return;
                        }

                        if (!$isMatch)
                        {
                            $set('pack_slip_motor_error', 'Serial number does not match.');
                            $set('pack_slip_motor_qr', null);
                            return;
                        }
                        else {
                            $set('pack_slip_motor_error', null);
                            $set('pack_slip_motor_qr', $serialNumber);
                            $set('pack_slip_motor', '1');
                        }
                   })

                ->extraAttributes(fn ($get) => [
                    'class' => $get('pack_slip_motor_error') ? 'border-red-500' : '',
                ])
                ->hint(fn ($get) => $get('pack_slip_motor_error') ? $get('pack_slip_motor_error') : null)
                ->hintColor('danger'),

                Forms\Components\Hidden::make('pack_slip_pump'),

                Forms\Components\TextInput::make('pack_slip_pump_qr')
                    ->label('Pack Slip Pump')
                    ->hidden(fn (callable $get) => !$get('pack_slip_pump_qr_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $set('pack_slip_pump_error', null);

                        if (empty($state)) {
                            $set('pack_slip_pump_error', null);
                            return;
                        }

                        if (strpos($state, '|') == false)
                        {
                            if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state))
                            {
                                $visibleSerialNumber = $get('serial_number');
                                $serialNumber = $state;

                                if ($visibleSerialNumber != $serialNumber)
                                {
                                    $set('pack_slip_pump_error', 'Serial number does not match.');
                                    $set('pack_slip_pump_qr', null);
                                    return;
                                }
                                else {
                                    $set('pack_slip_pump_error', null);
                                    $set('pack_slip_pump_qr', $serialNumber);
                                    $set('pack_slip_pump', '1');
                                    return;
                                }
                            }

                            if (strlen($state) < 9) {
                                $set('pack_slip_pump_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($state)) {
                                $set('pack_slip_pump_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }
                        }
                        else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state))
                        {
                            $splits = explode('|', $state);
                            $iCode = trim($splits[0]);
                            $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                            if (!ctype_alnum($iCode)) {
                                $set('pack_slip_pump_error', 'Item code must contain alpha-numeric values.');
                                return;
                            }
                            else if (strlen($iCode) < 6) {
                                $set('pack_slip_pump_error', 'Item code must be at least 6 digits.');
                                return;
                            }
                            else if (strlen($sNumber) < 9) {
                                $set('pack_slip_pump_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($sNumber)) {
                                $set('pack_slip_pump_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }

                            $set('pack_slip_pump_error', 'Scan valid QR code.');
                            return;
                        }
                        else
                        {
                            $set('pack_slip_pump_error', null);
                        }

                        // Split state by pipeline "|"
                        $parts = explode('|', $state);
                        $itemCode = trim($parts[0]);

                        $serialNumber = trim($parts[1]);
                        $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                        // Retrieve visible serial numbers
                        // $visibleSerialNumbers = array_filter([
                        //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                        //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                        //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                        // ]);
                        $visibleSerialNumber = $get('serial_number');

                         $expectedItemCode = trim((string) $get('item_id'));

                         if ($itemCode != $expectedItemCode) {
                             $set('pack_slip_pump_error', 'Item code does not match.');
                             return;
                         }

                         $set('pack_slip_pump_qr', $serialNumber);
                         $set('pack_slip_pump', '1');

                        //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                        $isMatch = ($visibleSerialNumber == $serialNumber);

                        if (!$serialNumber || trim($serialNumber) == '') {
                            $set('pack_slip_pump_error', null);
                            return;
                        }

                        if (!$isMatch)
                        {
                            $set('pack_slip_pump_error', 'Serial number does not match.');
                            $set('pack_slip_pump_qr', null);
                            return;
                        }
                        else {
                            $set('pack_slip_pump_error', null);
                            $set('pack_slip_pump_qr', $serialNumber);
                            $set('pack_slip_pump', '1');
                        }
                   })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('pack_slip_pump_error') ? 'border-red-500' : '',
                    ])
                   ->hint(fn ($get) => $get('pack_slip_pump_error') ? $get('pack_slip_pump_error') : null)
                   ->hintColor('danger'),

                Forms\Components\Hidden::make('pack_slip_pumpset'),

                Forms\Components\TextInput::make('pack_slip_pumpset_qr')
                    ->label('Pack Slip PumpSet')
                    ->hidden(fn (callable $get) => !$get('pack_slip_pumpset_qr_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $set('pack_slip_pumpset_error', null);

                        if (empty($state)) {
                            $set('pack_slip_pumpset_error', null);
                            return;
                        }

                        if (strpos($state, '|') == false)
                        {
                            if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state))
                            {
                                $visibleSerialNumber = $get('serial_number');
                                $serialNumber = $state;

                                if ($visibleSerialNumber != $serialNumber)
                                {
                                    $set('pack_slip_pumpset_error', 'Serial number does not match.');
                                    $set('pack_slip_pumpset_qr', null);
                                    return;
                                }
                                else {
                                    $set('pack_slip_pumpset_error', null);
                                    $set('pack_slip_pumpset_qr', $serialNumber);
                                    $set('pack_slip_pumpset', '1');
                                    return;
                                }
                            }

                            if (strlen($state) < 9) {
                                $set('pack_slip_pumpset_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($state)) {
                                $set('pack_slip_pumpset_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }
                        }
                        else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state))
                        {
                            $splits = explode('|', $state);
                            $iCode = trim($splits[0]);
                            $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                            if (!ctype_alnum($iCode)) {
                                $set('pack_slip_pumpset_error', 'Item code must contain alpha-numeric values.');
                                return;
                            }
                            else if (strlen($iCode) < 6) {
                                $set('pack_slip_pumpset_error', 'Item code must be at least 6 digits.');
                                return;
                            }
                            else if (strlen($sNumber) < 9) {
                                $set('pack_slip_pumpset_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($sNumber)) {
                                $set('pack_slip_pumpset_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }

                            $set('pack_slip_pumpset_error', 'Scan valid QR code.');
                            return;
                        }
                        else
                        {
                            $set('pack_slip_pumpset_error', null);
                        }

                        // Split state by pipeline "|"
                        $parts = explode('|', $state);
                        $itemCode = trim($parts[0]);

                        $serialNumber = trim($parts[1]);
                        $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                        // Retrieve visible serial numbers
                        // $visibleSerialNumbers = array_filter([
                        //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                        //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                        //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                        // ]);

                        $visibleSerialNumber = $get('serial_number');

                         $expectedItemCode = trim((string) $get('item_id'));

                         if ($itemCode != $expectedItemCode) {
                             $set('pack_slip_pumpset_error', 'Item code does not match.');
                             return;
                         }

                         $set('pack_slip_pumpset_qr', $serialNumber);
                         $set('pack_slip_pumpset', '1');

                        //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                        $isMatch = ($visibleSerialNumber == $serialNumber);

                        if (!$serialNumber || trim($serialNumber) == '') {
                            $set('pack_slip_pumpset_error', null);
                            return;
                        }

                        if (!$isMatch)
                        {
                            $set('pack_slip_pumpset_error', 'Serial number does not match.');
                            $set('pack_slip_pumpset_qr', null);
                            return;
                        }
                        else {
                            $set('pack_slip_pumpset_error', null);
                            $set('pack_slip_pumpset_qr', $serialNumber);
                            $set('pack_slip_pumpset', '1');
                        }

                   })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('pack_slip_pumpset_error') ? 'border-red-500' : '',
                    ])
                   ->hint(fn ($get) => $get('pack_slip_pumpset_error') ? $get('pack_slip_pumpset_error') : null)
                   ->hintColor('danger'),

                Forms\Components\Hidden::make('name_plate_motor'),

                Forms\Components\TextInput::make('name_plate_motor_qr')
                    ->label('Name Plate Motor')
                    ->hidden(fn (callable $get) => !$get('name_plate_motor_qr_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $set('name_plate_motor_error', null);

                        if (empty($state)) {
                            $set('name_plate_motor_error', null);
                            return;
                        }

                        if (strpos($state, '|') == false)
                        {
                            if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state))
                            {
                                $visibleSerialNumber = $get('serial_number');
                                $serialNumber = $state;

                                if ($visibleSerialNumber != $serialNumber)
                                {
                                    $set('name_plate_motor_error', 'Serial number does not match.');
                                    $set('name_plate_motor_qr', null);
                                    return;
                                }
                                else {
                                    $set('name_plate_motor_error', null);
                                    $set('name_plate_motor_qr', $serialNumber);
                                    $set('name_plate_motor', '1');
                                    return;
                                }
                            }

                            if (strlen($state) < 9) {
                                $set('name_plate_motor_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($state)) {
                                $set('name_plate_motor_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }
                        }
                        else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state))
                        {
                            $splits = explode('|', $state);
                            $iCode = trim($splits[0]);
                            $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                            if (!ctype_alnum($iCode)) {
                                $set('name_plate_motor_error', 'Item code must contain alpha-numeric values.');
                                return;
                            }
                            else if (strlen($iCode) < 6) {
                                $set('name_plate_motor_error', 'Item code must be at least 6 digits.');
                                return;
                            }
                            else if (strlen($sNumber) < 9) {
                                $set('name_plate_motor_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($sNumber)) {
                                $set('name_plate_motor_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }

                            $set('name_plate_motor_error', 'Scan valid QR code.');
                            return;
                        }
                        else
                        {
                            $set('name_plate_motor_error', null);
                        }

                        // Split state by pipeline "|"
                        $parts = explode('|', $state);
                        $itemCode = trim($parts[0]);

                        $serialNumber = trim($parts[1]);
                        $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                        // Retrieve visible serial numbers
                        // $visibleSerialNumbers = array_filter([
                        //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                        //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                        //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                        // ]);
                        $visibleSerialNumber = $get('serial_number');

                         $expectedItemCode = trim((string) $get('item_id'));

                         if ($itemCode != $expectedItemCode) {
                             $set('name_plate_motor_error', 'Item code does not match.');
                             return;
                         }

                         $set('name_plate_motor_error', $serialNumber);

                        //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                        $isMatch = ($visibleSerialNumber == $serialNumber);

                        if (!$serialNumber || trim($serialNumber) == '') {
                            $set('name_plate_motor_error', null);
                            return;
                        }

                        if (!$isMatch)
                        {
                            $set('name_plate_motor_error', 'Serial number does not match.');
                            $set('name_plate_motor_qr', null);
                            return;
                        }
                        else {
                            $set('name_plate_motor_error', null);
                            $set('name_plate_motor_qr', $serialNumber);
                            $set('name_plate_motor', '1');
                        }

                   })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('name_plate_motor_error') ? 'border-red-500' : '',
                    ])
                   ->hint(fn ($get) => $get('name_plate_motor_error') ? $get('name_plate_motor_error') : null)
                   ->hintColor('danger'),

                Forms\Components\Hidden::make('name_plate_pump'),

                Forms\Components\TextInput::make('name_plate_pump_qr')
                    ->label('Name Plate Pump')
                    ->hidden(fn (callable $get) => !$get('name_plate_pump_qr_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $set('name_plate_pump_error', null);

                        if (empty($state)) {
                            $set('name_plate_pump_error', null);
                            return;
                        }

                        if (strpos($state, '|') == false)
                        {
                            if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state))
                            {
                                $visibleSerialNumber = $get('serial_number');
                                $serialNumber = $state;

                                if ($visibleSerialNumber != $serialNumber)
                                {
                                    $set('name_plate_pump_error', 'Serial number does not match.');
                                    $set('name_plate_pump_qr', null);
                                    return;
                                }
                                else {
                                    $set('name_plate_pump_error', null);
                                    $set('name_plate_pump_qr', $serialNumber);
                                    $set('name_plate_pump', '1');
                                    return;
                                }
                            }

                            if (strlen($state) < 9) {
                                $set('name_plate_pump_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($state)) {
                                $set('name_plate_pump_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }
                        }
                        else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state))
                        {
                            $splits = explode('|', $state);
                            $iCode = trim($splits[0]);
                            $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                            if (!ctype_alnum($iCode)) {
                                $set('name_plate_pump_error', 'Item code must contain alpha-numeric values.');
                                return;
                            }
                            else if (strlen($iCode) < 6) {
                                $set('name_plate_pump_error', 'Item code must be at least 6 digits.');
                                return;
                            }
                            else if (strlen($sNumber) < 9) {
                                $set('name_plate_pump_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($sNumber)) {
                                $set('name_plate_pump_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }

                            $set('name_plate_pump_error', 'Scan valid QR code.');
                            return;
                        }
                        else
                        {
                            $set('name_plate_pump_error', null);
                        }

                        // Split state by pipeline "|"
                        $parts = explode('|', $state);
                        $itemCode = trim($parts[0]);

                        $serialNumber = trim($parts[1]);
                        $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                        // Retrieve visible serial numbers
                        // $visibleSerialNumbers = array_filter([
                        //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                        //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                        //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                        // ]);
                        $visibleSerialNumber = $get('serial_number');

                         $expectedItemCode = trim((string) $get('item_id'));

                         if ($itemCode != $expectedItemCode) {
                             $set('name_plate_pump_error', 'Item code does not match.');
                             return;
                         }

                         $set('name_plate_pump_error', $serialNumber);

                        //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                        $isMatch = ($visibleSerialNumber == $serialNumber);

                        if (!$serialNumber || trim($serialNumber) == '') {
                            $set('name_plate_pump_error', null);
                            return;
                        }

                        if (!$isMatch)
                        {
                            $set('name_plate_pump_error', 'Serial number does not match.');
                            $set('name_plate_pump_qr', null);
                            return;
                        }
                        else {
                            $set('name_plate_pump_error', null);
                            $set('name_plate_pump_qr', $serialNumber);
                            $set('name_plate_pump', '1');
                        }

                   })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('name_plate_pump_error') ? 'border-red-500' : '',
                    ])
                   ->hint(fn ($get) => $get('name_plate_pump_error') ? $get('name_plate_pump_error') : null)
                   ->hintColor('danger'),

                Forms\Components\Hidden::make('name_plate_pumpset'),

                Forms\Components\TextInput::make('name_plate_pumpset_qr')
                    ->label('Name Plate PumpSet')
                    ->hidden(fn (callable $get) => !$get('name_plate_pumpset_qr_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $set('name_plate_pumpset_error', null);

                        if (empty($state)) {
                            $set('name_plate_pumpset_error', null);
                            return;
                        }

                        if (strpos($state, '|') == false)
                        {
                            if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state))
                            {
                                $visibleSerialNumber = $get('serial_number');
                                $serialNumber = $state;

                                if ($visibleSerialNumber != $serialNumber)
                                {
                                    $set('name_plate_pumpset_error', 'Serial number does not match.');
                                    $set('name_plate_pumpset_qr', null);
                                    return;
                                }
                                else {
                                    $set('name_plate_pumpset_error', null);
                                    $set('name_plate_pumpset_qr', $serialNumber);
                                    $set('name_plate_pumpset', '1');
                                    return;
                                }
                            }

                            if (strlen($state) < 9) {
                                $set('name_plate_pumpset_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($state)) {
                                $set('name_plate_pumpset_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }
                        }
                        else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state))
                        {
                            $splits = explode('|', $state);
                            $iCode = trim($splits[0]);
                            $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                            if (!ctype_alnum($iCode)) {
                                $set('name_plate_pumpset_error', 'Item code must contain alpha-numeric values.');
                                return;
                            }
                            else if (strlen($iCode) < 6) {
                                $set('name_plate_pumpset_error', 'Item code must be at least 6 digits.');
                                return;
                            }
                            else if (strlen($sNumber) < 9) {
                                $set('name_plate_pumpset_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($sNumber)) {
                                $set('name_plate_pumpset_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }

                            $set('name_plate_pumpset_error', 'Scan valid QR code.');
                            return;
                        }
                        else
                        {
                            $set('name_plate_pumpset_error', null);
                        }

                        // Split state by pipeline "|"
                        $parts = explode('|', $state);
                        $itemCode = trim($parts[0]);

                        $serialNumber = trim($parts[1]);
                        $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                        // Retrieve visible serial numbers
                        // $visibleSerialNumbers = array_filter([
                        //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                        //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                        //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                        // ]);
                        $visibleSerialNumber = $get('serial_number');

                         $expectedItemCode = trim((string) $get('item_id'));

                         if ($itemCode != $expectedItemCode) {
                             $set('name_plate_pumpset_error', 'Item code does not match.');
                             return;
                         }

                         $set('name_plate_pumpset_error', $serialNumber);

                        //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                        $isMatch = ($visibleSerialNumber == $serialNumber);

                        if (!$serialNumber || trim($serialNumber) == '') {
                            $set('name_plate_pumpset_error', null);
                            return;
                        }

                        if (!$isMatch)
                        {
                            $set('name_plate_pumpset_error', 'Serial number does not match.');
                            $set('name_plate_pumpset_qr', null);
                            return;
                        }
                        else {
                            $set('name_plate_pumpset_error', null);
                            $set('name_plate_pumpset_qr', $serialNumber);
                            $set('name_plate_pumpset', '1');
                        }

                   })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('name_plate_pumpset_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('name_plate_pumpset_error') ? $get('name_plate_pumpset_error') : null)
                    ->hintColor('danger'),

                Forms\Components\Hidden::make('tube_sticker_motor'),

                Forms\Components\TextInput::make('tube_sticker_motor_qr')
                    ->label('Tube Sticker Motor')
                    ->hidden(fn (callable $get) => !$get('tube_sticker_motor_qr_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $set('tube_sticker_motor_error', null);

                        if (empty($state)) {
                            $set('tube_sticker_motor_error', null);
                            return;
                        }

                        if (strpos($state, '|') == false)
                        {
                            if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state))
                            {
                                $visibleSerialNumber = $get('serial_number');
                                $serialNumber = $state;

                                if ($visibleSerialNumber != $serialNumber)
                                {
                                    $set('tube_sticker_motor_error', 'Serial number does not match.');
                                    $set('tube_sticker_motor_qr', null);
                                    return;
                                }
                                else {
                                    $set('tube_sticker_motor_error', null);
                                    $set('tube_sticker_motor_qr', $serialNumber);
                                    $set('tube_sticker_motor', '1');
                                    return;
                                }
                            }

                            if (strlen($state) < 9) {
                                $set('tube_sticker_motor_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($state)) {
                                $set('tube_sticker_motor_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }
                        }
                        else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state))
                        {
                            $splits = explode('|', $state);
                            $iCode = trim($splits[0]);
                            $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                            if (!ctype_alnum($iCode)) {
                                $set('tube_sticker_motor_error', 'Item code must contain alpha-numeric values.');
                                return;
                            }
                            else if (strlen($iCode) < 6) {
                                $set('tube_sticker_motor_error', 'Item code must be at least 6 digits.');
                                return;
                            }
                            else if (strlen($sNumber) < 9) {
                                $set('tube_sticker_motor_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($sNumber)) {
                                $set('tube_sticker_motor_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }

                            $set('tube_sticker_motor_error', 'Scan valid QR code.');
                            return;
                        }
                        else
                        {
                            $set('tube_sticker_motor_error', null);
                        }

                        // Split state by pipeline "|"
                        $parts = explode('|', $state);
                        $itemCode = trim($parts[0]);

                        $serialNumber = trim($parts[1]);
                        $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                        // Retrieve visible serial numbers
                        // $visibleSerialNumbers = array_filter([
                        //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                        //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                        //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                        // ]);
                        $visibleSerialNumber = $get('serial_number');

                         $expectedItemCode = trim((string) $get('item_id'));

                         if ($itemCode != $expectedItemCode) {
                             $set('tube_sticker_motor_error', 'Item code does not match.');
                             return;
                         }

                         $set('tube_sticker_motor_error', $serialNumber);

                        //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                        $isMatch = ($visibleSerialNumber == $serialNumber);

                        if (!$serialNumber || trim($serialNumber) == '') {
                            $set('tube_sticker_motor_error', null);
                            return;
                        }

                        if (!$isMatch)
                        {
                            $set('tube_sticker_motor_error', 'Serial number does not match.');
                            $set('tube_sticker_motor_qr', null);
                            return;
                        }
                        else {
                            $set('tube_sticker_motor_error', null);
                            $set('tube_sticker_motor_qr', $serialNumber);
                            $set('tube_sticker_motor', '1');
                        }

                   })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('tube_sticker_motor_error') ? 'border-red-500' : '',
                    ])
                   ->hint(fn ($get) => $get('tube_sticker_motor_error') ? $get('tube_sticker_motor_error') : null)
                   ->hintColor('danger'),

                 Forms\Components\Hidden::make('tube_sticker_pump'),

                 Forms\Components\TextInput::make('tube_sticker_pump_qr')
                    ->label('Tube Sticker Pump')
                    ->hidden(fn (callable $get) => !$get('tube_sticker_pump_qr_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $set('tube_sticker_pump_error', null);

                        if (empty($state)) {
                            $set('tube_sticker_pump_error', null);
                            return;
                        }

                        if (strpos($state, '|') == false)
                        {
                            if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state))
                            {
                                $visibleSerialNumber = $get('serial_number');
                                $serialNumber = $state;

                                if ($visibleSerialNumber != $serialNumber)
                                {
                                    $set('tube_sticker_pump_error', 'Serial number does not match.');
                                    $set('tube_sticker_pump_qr', null);
                                    return;
                                }
                                else {
                                    $set('tube_sticker_pump_error', null);
                                    $set('tube_sticker_pump_qr', $serialNumber);
                                    $set('tube_sticker_pump', '1');
                                    return;
                                }
                            }

                            if (strlen($state) < 9) {
                                $set('tube_sticker_pump_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($state)) {
                                $set('tube_sticker_pump_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }
                        }
                        else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state))
                        {
                            $splits = explode('|', $state);
                            $iCode = trim($splits[0]);
                            $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                            if (!ctype_alnum($iCode)) {
                                $set('tube_sticker_pump_error', 'Item code must contain alpha-numeric values.');
                                return;
                            }
                            else if (strlen($iCode) < 6) {
                                $set('tube_sticker_pump_error', 'Item code must be at least 6 digits.');
                                return;
                            }
                            else if (strlen($sNumber) < 9) {
                                $set('tube_sticker_pump_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($sNumber)) {
                                $set('tube_sticker_pump_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }

                            $set('tube_sticker_pump_error', 'Scan valid QR code.');
                            return;
                        }
                        else
                        {
                            $set('tube_sticker_pump_error', null);
                        }

                        // Split state by pipeline "|"
                        $parts = explode('|', $state);
                        $itemCode = trim($parts[0]);

                        $serialNumber = trim($parts[1]);
                        $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                        // Retrieve visible serial numbers
                        // $visibleSerialNumbers = array_filter([
                        //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                        //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                        //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                        // ]);
                        $visibleSerialNumber = $get('serial_number');

                         $expectedItemCode = trim((string) $get('item_id'));

                         if ($itemCode != $expectedItemCode) {
                             $set('tube_sticker_pump_error', 'Item code does not match.');
                             return;
                         }

                         $set('tube_sticker_pump_error', $serialNumber);

                        //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                        $isMatch = ($visibleSerialNumber == $serialNumber);

                        if (!$serialNumber || trim($serialNumber) == '') {
                            $set('tube_sticker_pump_error', null);
                            return;
                        }

                        if (!$isMatch)
                        {
                            $set('tube_sticker_pump_error', 'Serial number does not match.');
                            $set('tube_sticker_pump_qr', null);
                            return;
                        }
                        else {
                            $set('tube_sticker_pump_error', null);
                            $set('tube_sticker_pump_qr', $serialNumber);
                            $set('tube_sticker_pump', '1');
                        }

                   })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('tube_sticker_pump_error') ? 'border-red-500' : '',
                    ])
                   ->hint(fn ($get) => $get('tube_sticker_pump_error') ? $get('tube_sticker_pump_error') : null)
                   ->hintColor('danger'),

                Forms\Components\Hidden::make('tube_sticker_pumpset'),

                Forms\Components\TextInput::make('tube_sticker_pumpset_qr')
                    ->label('Tube Sticker PumpSet')
                    ->hidden(fn (callable $get) => !$get('tube_sticker_pumpset_qr_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $set('tube_sticker_pumpset_error', null);

                        if (empty($state)) {
                            $set('tube_sticker_pumpset_error', null);
                            return;
                        }

                        if (strpos($state, '|') == false)
                        {
                            if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state))
                            {
                                $visibleSerialNumber = $get('serial_number');
                                $serialNumber = $state;

                                if ($visibleSerialNumber != $serialNumber)
                                {
                                    $set('tube_sticker_pumpset_error', 'Serial number does not match.');
                                    $set('tube_sticker_pumpset_qr', null);
                                    return;
                                }
                                else {
                                    $set('tube_sticker_pumpset_error', null);
                                    $set('tube_sticker_pumpset_qr', $serialNumber);
                                    $set('tube_sticker_pumpset', '1');
                                    return;
                                }
                            }

                            if (strlen($state) < 9) {
                                $set('tube_sticker_pumpset_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($state)) {
                                $set('tube_sticker_pumpset_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }
                        }
                        else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state))
                        {
                            $splits = explode('|', $state);
                            $iCode = trim($splits[0]);
                            $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                            if (!ctype_alnum($iCode)) {
                                $set('tube_sticker_pumpset_error', 'Item code must contain alpha-numeric values.');
                                return;
                            }
                            else if (strlen($iCode) < 6) {
                                $set('tube_sticker_pumpset_error', 'Item code must be at least 6 digits.');
                                return;
                            }
                            else if (strlen($sNumber) < 9) {
                                $set('tube_sticker_pumpset_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($sNumber)) {
                                $set('tube_sticker_pumpset_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }

                            $set('tube_sticker_pumpset_error', 'Scan valid QR code.');
                            return;
                        }
                        else
                        {
                            $set('tube_sticker_pumpset_error', null);
                        }

                        // Split state by pipeline "|"
                        $parts = explode('|', $state);
                        $itemCode = trim($parts[0]);

                        $serialNumber = trim($parts[1]);
                       // $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove
                       $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove
                        // Retrieve visible serial numbers
                        // $visibleSerialNumbers = array_filter([
                        //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                        //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                        //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                        // ]);
                        $visibleSerialNumber = $get('serial_number');

                        //dd($parts);

                         $expectedItemCode = trim((string) $get('item_id'));

                         if ($itemCode != $expectedItemCode) {
                             $set('tube_sticker_pumpset_error', 'Item code does not match.');
                             return;
                         }

                         $set('tube_sticker_pumpset_error', $serialNumber);

                        //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                        $isMatch = ($visibleSerialNumber == $serialNumber);

                        if (!$serialNumber || trim($serialNumber) == '') {
                            $set('tube_sticker_pumpset_error', null);
                            return;
                        }

                        if (!$isMatch)
                        {
                            $set('tube_sticker_pumpset_error', 'Serial number does not match.');
                            $set('tube_sticker_pumpset_qr', null);
                            return;
                        }
                        else {
                            $set('tube_sticker_pumpset_error', null);
                            $set('tube_sticker_pumpset_qr', $serialNumber);
                            $set('tube_sticker_pumpset', '1');
                        }

                   })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('tube_sticker_pumpset_error') ? 'border-red-500' : '',
                    ])
                   ->hint(fn ($get) => $get('tube_sticker_pumpset_error') ? $get('tube_sticker_pumpset_error') : null)
                   ->hintColor('danger'),

                Forms\Components\Hidden::make('warranty_card'),

                Forms\Components\TextInput::make('warranty_card_qr')
                    ->label('Warranty Card')
                    ->hidden(fn (callable $get) => !$get('warranty_card_qr_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $set('warranty_card_error', null);

                        if (empty($state)) {
                            $set('warranty_card_error', null);
                            return;
                        }

                        if (strpos($state, '|') == false)
                        {
                            if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state))
                            {
                                $visibleSerialNumber = $get('serial_number');
                                $serialNumber = $state;

                                if ($visibleSerialNumber != $serialNumber)
                                {
                                    $set('warranty_card_error', 'Serial number does not match.');
                                    $set('warranty_card_qr', null);
                                    return;
                                }
                                else {
                                    $set('warranty_card_error', null);
                                    $set('warranty_card_qr', $serialNumber);
                                    $set('warranty_card', '1');
                                    return;
                                }
                            }

                            if (strlen($state) < 9) {
                                $set('warranty_card_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($state)) {
                                $set('warranty_card_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }
                        }
                        else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state))
                        {
                            $splits = explode('|', $state);
                            $iCode = trim($splits[0]);
                            $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                            if (!ctype_alnum($iCode)) {
                                $set('warranty_card_error', 'Item code must contain alpha-numeric values.');
                                return;
                            }
                            else if (strlen($iCode) < 6) {
                                $set('warranty_card_error', 'Item code must be at least 6 digits.');
                                return;
                            }
                            else if (strlen($sNumber) < 9) {
                                $set('warranty_card_error', 'Serial Number must be at least 9 digits.');
                                return;
                            }
                            else if (!ctype_alnum($sNumber)) {
                                $set('warranty_card_error', 'Serial Number must contain alpha-numeric values.');
                                return;
                            }

                            $set('warranty_card_error', 'Scan valid QR code.');
                            return;
                        }
                        else
                        {
                            $set('warranty_card_error', null);
                        }

                        // Split state by pipeline "|"
                        $parts = explode('|', $state);
                        $itemCode = trim($parts[0]);

                        $serialNumber = trim($parts[1]);
                        $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                        // Retrieve visible serial numbers
                        // $visibleSerialNumbers = array_filter([
                        //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                        //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                        //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                        // ]);

                        $visibleSerialNumber = $get('serial_number');

                         $expectedItemCode = trim((string) $get('item_id'));

                         if ($itemCode != $expectedItemCode) {
                             $set('warranty_card_error', 'Item code does not match.');
                             return;
                         }

                         $set('warranty_card_error', $serialNumber);

                        //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);

                        $isMatch = ($visibleSerialNumber == $serialNumber);

                        if (!$serialNumber || trim($serialNumber) == '') {
                            $set('warranty_card_error', null);
                            return;
                        }

                        if (!$isMatch)
                        {
                            $set('warranty_card_error', 'Serial number does not match.');
                            $set('warranty_card_qr', null);
                            return;
                        }
                        else {
                            $set('warranty_card_error', null);
                            $set('warranty_card_qr', $serialNumber);
                            $set('warranty_card', '1');
                        }
                   })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('warranty_card_error') ? 'border-red-500' : '',
                    ])
                   ->hint(fn ($get) => $get('warranty_card_error') ? $get('warranty_card_error') : null)
                   ->hintColor('danger'),

                Forms\Components\TextInput::make('part_validation1')
                    ->hidden(fn (callable $get) => !$get('part_validation1_visible'))
                    ->default('')
                    ->reactive()
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $mPorder = $get('production_order');

                        $mPlantId = $get('plant_id');

                        $plant = Plant::find($mPlantId);
                        $plantCodePart1 = $plant?->code;

                        $stickerMasterId = $get('sticker_master_id');
                        if (!$stickerMasterId) {
                            return;
                        }

                        $stickerMaster = StickerMaster::find($stickerMasterId);
                        if (!$stickerMaster) {
                            return;
                        }

                        $expectedValue = $stickerMaster->part_validation1;

                        if ($state == null || trim($state) == '') {
                            $set('part_validation1_error', null);
                            return;
                        }

                        if ($state == $expectedValue)
                        {
                            $set('part_validation1_error', null);
                        }
                        else
                        {
                            $set('part_validation1_error', "Invalid input for part validation 1.");

                            //.Mail

                            $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                            $mPlantName = $mailData['plant_name'];
                            $emails = $mailData['emails'];

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

                            $fileName = $expectedValue . ".png"; // or .jpg based on your file
                            $fullPath = storage_path("app/private/uploads/PartValidation/{$plantCodePart1}/{$fileName}");

                            // dd($fullPath);

                            // // Generate URL through custom route
                            // $imageUrl = route('part.validation.image', [
                            //     'plant' => $plantCodePart1,
                            //     'filename' => $fileName
                            // ]);
                            if (file_exists($fullPath)) {
                                $imageUrl = route('part.validation.image', [
                                    'plant' => $plantCodePart1,
                                    'filename' => $fileName
                                ]);
                            } else {
                                $imageUrl = asset("images/not_found.png");
                            }

                            $set('part_validation1_error_image', $imageUrl);
                            return;
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('part_validation1_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('part_validation1_error'))
                    ->hintColor('danger'),

                Forms\Components\Hidden::make('part_validation1_error_image'),


                Forms\Components\View::make('components.part-validation1-error-icon')
                    ->visible(fn ($get) => $get('part_validation1_error') != null)
                    ->statePath('part_validation1_error_image')
                    ->reactive(),

                Forms\Components\TextInput::make('part_validation2')
                    ->hidden(fn (callable $get) => !$get('part_validation2_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $mPorder = $get('production_order');

                        $mPlantId = $get('plant_id');
                        $plant = Plant::find($mPlantId);
                        $plantCodePart2 = $plant?->code;

                        $stickerMasterId = $get('sticker_master_id');
                        if (!$stickerMasterId) {
                            return;
                        }

                        $stickerMaster = StickerMaster::find($stickerMasterId);
                        if (!$stickerMaster) {
                            return;
                        }

                        $expectedValue = $stickerMaster->part_validation2;

                        if ($state == null || trim($state) == '') {
                            $set('part_validation2_error', null);
                            return;
                        }

                        if ($state == $expectedValue)
                        {
                            $set('part_validation2_error', null);
                        }
                        else
                        {
                            $set('part_validation2_error', "Invalid input for part validation 2.");
                            $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                            $mPlantName = $mailData['plant_name'];
                            $emails = $mailData['emails'];

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

                            $fileName = $expectedValue . ".png"; // or .jpg based on your file
                            $fullPath = storage_path("app/private/uploads/PartValidation/{$plantCodePart2}/{$fileName}");

                            // if (!file_exists($fullPath)) {
                            //     Notification::make()
                            //         ->title('Image Not Found')
                            //         ->body($fileName)
                            //         ->danger()
                            //         ->send();
                            //     return;
                            // }

                            // Generate URL through custom route
                            $imageUrl = route('part.validation.image', [
                                'plant' => $plantCodePart2,
                                'filename' => $fileName
                            ]);

                            $set('part_validation2_error_image', $imageUrl);
                            return;
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('part_validation2_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('part_validation2_error'))
                    ->hintColor('danger'),

                Forms\Components\Hidden::make('part_validation2_error_image')
                    ->default(null)
                    ->dehydrated(false),

                Forms\Components\View::make('components.part-validation1-error-icon')
                    ->visible(fn ($get) => $get('part_validation2_error') != null)
                    ->statePath('part_validation2_error_image')
                    ->reactive(),

                Forms\Components\TextInput::make('part_validation3')
                    ->hidden(fn (callable $get) => !$get('part_validation3_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $stickerMasterId = $get('sticker_master_id');

                        $mPorder  = $get('production_order');

                        $mPlantId = $get('plant_id');
                        $plant = Plant::find($mPlantId);
                        $plantCodePart3 = $plant?->code;

                        if (!$stickerMasterId) {
                            return;
                        }

                        $stickerMaster = StickerMaster::find($stickerMasterId);
                        if (!$stickerMaster)
                        {
                            return;
                        }

                        if ($state == null || trim($state) == '') {
                            $set('part_validation3_error', null);
                            return;
                        }

                        $expectedValue = $stickerMaster->part_validation3;

                        if ($state == $expectedValue)
                        {
                            $set('part_validation3_error', null);
                        }
                        else
                        {
                            $set('part_validation3_error', "Invalid input for part validation 3.");
                            $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                            $mPlantName = $mailData['plant_name'];
                            $emails = $mailData['emails'];

                            if (!empty($emails))
                            {
                                //Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType));
                                Mail::to($emails)->send(
                                    new InvalidQualityMail($state, $mPorder, $mPlantName, 'InvalidPartNumber3')
                                );
                            }
                            else
                            {
                                \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial.");
                            }
                            $set('part_validation3', null);
                            $fileName = $expectedValue . ".png"; // or .jpg based on your file
                            //$fullPath = storage_path("app/private/uploads/PartValidation/{$plantCodePart3}/{$fileName}");

                            // if (!file_exists($fullPath)) {
                            //     Notification::make()
                            //         ->title('Image Not Found')
                            //         ->body($fileName)
                            //         ->danger()
                            //         ->send();
                            //     return;
                            // }

                            // Generate URL through custom route
                            $imageUrl = route('part.validation.image', [
                                'plant' => $plantCodePart3,
                                'filename' => $fileName
                            ]);

                            $set('part_validation2_error_image', $imageUrl);
                            return;
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('part_validation3_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('part_validation3_error'))
                    ->hintColor('danger'),

                Forms\Components\Hidden::make('part_validation3_error_image')
                    ->default(null)
                    ->dehydrated(false),

                Forms\Components\View::make('components.part-validation1-error-icon')
                    ->visible(fn ($get) => $get('part_validation3_error') != null)
                    ->statePath('part_validation3_error_image')
                    ->reactive(),

                Forms\Components\TextInput::make('part_validation4')
                    ->hidden(fn (callable $get) => !$get('part_validation4_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $stickerMasterId = $get('sticker_master_id');
                        $mPorder = $get('production_order');

                        $mPlantId = $get('plant_id');
                        $plant = Plant::find($mPlantId);
                        $plantCodePart4 = $plant?->code;

                        if (!$stickerMasterId) {
                            return;
                        }

                        $stickerMaster = StickerMaster::find($stickerMasterId);
                        if (!$stickerMaster) {
                            return;
                        }

                        $expectedValue = $stickerMaster->part_validation4;

                         // If input is empty, reset the error
                        if ($state == null || trim($state) == '') {
                            $set('part_validation4_error', null);
                            return;
                        }

                        if ($state == $expectedValue)
                        {
                            $set('part_validation4_error', null);
                        }
                        else
                        {
                            $set('part_validation4_error', "Invalid input for part validation 4.");
                            $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                            $mPlantName = $mailData['plant_name'];
                            $emails = $mailData['emails'];

                            if (!empty($emails))
                            {
                                //Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType));
                                Mail::to($emails)->send(
                                    new InvalidQualityMail($state, $mPorder, $mPlantName, 'InvalidPartNumber4')
                                );
                            }
                            else
                            {
                                \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial.");
                            }
                            $set('part_validation4', null);
                            $fileName = $expectedValue . ".png"; // or .jpg based on your file
                            $fullPath = storage_path("app/private/uploads/PartValidation/{$plantCodePart4}/{$fileName}");

                            // Generate URL through custom route
                            $imageUrl = route('part.validation.image', [
                                'plant' => $plantCodePart4,
                                'filename' => $fileName
                            ]);

                            $set('part_validation2_error_image', $imageUrl);

                            return;
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('part_validation4_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('part_validation4_error'))
                    ->hintColor('danger'),

                Forms\Components\Hidden::make('part_validation4_error_image')
                    ->default(null)
                    ->dehydrated(false),

                Forms\Components\View::make('components.part-validation1-error-icon')
                    ->visible(fn ($get) => $get('part_validation4_error') != null)
                    ->statePath('part_validation4_error_image')
                    ->reactive(),

                Forms\Components\TextInput::make('part_validation5')
                    ->hidden(fn (callable $get) => !$get('part_validation5_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $stickerMasterId = $get('sticker_master_id');

                        $mPorder = $get('production_order');
                        $mPlantId = $get('plant_id');

                        if (!$stickerMasterId) {
                            return;
                        }

                        $stickerMaster = StickerMaster::find($stickerMasterId);
                        if (!$stickerMaster) {
                            return;
                        }

                        $expectedValue = $stickerMaster->part_validation5;

                         // If input is empty, reset the error
                        if ($state == null || trim($state) == '') {
                            $set('part_validation5_error', null);
                            return;
                        }

                        // if ($state == $expectedValue)
                        // {
                        //     $set('part_validation5_error', null);
                        // }
                        // else if (strpos($state, '/') != false) {
                        //     $parts = explode('/', $state);
                        //     if (count($parts) >= 2) {
                        //         $segmentToValidate = $parts[1];
                        //     }
                        //     else
                        //     {
                        //         $segmentToValidate = null;
                        //     }
                        // }
                        // else
                        // {
                        //     $set('part_validation5_error', "Invalid input for part validation 5.");
                        //     $set('part_validation5', null);
                        //     return;
                        // }
                        if ($state == $expectedValue)
                        {
                            $set('part_validation5_error', null);
                        }
                        else if (strpos($state, '/') != false)
                        {
                            $parts = explode('/', $state);
                            if (count($parts) >= 2)
                            {
                                $segmentToValidate = $parts[1];
                                if ($segmentToValidate == $expectedValue) {
                                    $set('part_validation5_error', null);
                                    $set('part_validation5', $segmentToValidate);
                                } else {
                                    $set('part_validation5_error', "Invalid input for part validation 5.");
                                    $set('part_validation5', null);
                                    return;
                                }
                            }
                            else
                            {
                                $set('part_validation5_error', "Invalid input format for part validation 5.");
                                $set('part_validation5', null);
                                return;
                            }
                        }
                        else
                        {
                            $set('part_validation5_error', "Invalid input for part validation 5.");
                            $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                            $mPlantName = $mailData['plant_name'];
                            $emails = $mailData['emails'];

                            if (!empty($emails))
                            {
                                //Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType));
                                Mail::to($emails)->send(
                                    new InvalidQualityMail($state, $mPorder, $mPlantName, 'InvalidPartNumber5')
                                );
                            }
                            else
                            {
                                \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial.");
                            }
                            $set('part_validation5', null);
                            return;
                        }

                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('part_validation5_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('part_validation5_error'))
                    ->hintColor('danger'),

                Forms\Components\TextInput::make('id')
                    ->hidden()
                    ->readOnly(),
            ]);
    }

    public static function getMailData($plantId)
    {

        $mPlantName = Plant::where('id', $plantId)->value('name');

        $emails = AlertMailRule::where('plant', $plantId)
            ->where('module', 'QualityValidation')
            ->where('rule_name', 'QualityMail')
            ->where(fn ($q) => $q->whereNull('schedule_type')->orWhere('schedule_type', ''))
            ->pluck('email')
            ->toArray();

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


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

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


    public static function table(Table $table): Table
    {
        return $table
            ->query(QualityValidation::query())
            ->columns([
                // Tables\Columns\TextColumn::make('id')
                //     ->label('ID')
                //     ->numeric()
                //     ->sortable(),
                Tables\Columns\TextColumn::make('No.')
                    ->label('No.')
                    ->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
                        $paginator = $livewire->getTableRecords();
                        $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
                        $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
                        return ($currentPage - 1) * $perPage + $rowLoop->iteration;
                    }),
                Tables\Columns\TextColumn::make('plant.name')
                    ->label('Plant')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('line.name')
                    ->label('Line')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('production_order')
                    ->label('Production Order')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('serial_number')
                    ->label('Serial Number')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('stickerMaster.item.code')
                    ->label('Item Code')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('uom')
                    ->label('Unit of Measure')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('serial_number_motor')
                    ->label('Serial Number Motor')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('serial_number_pump')
                    ->label('Serial Number Pump')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('serial_number_pumpset')
                    ->label('Serial Number Pumpset')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('pack_slip_motor')
                    ->label('Pack Slip Motor')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('pack_slip_pump')
                    ->label('Pack Slip Pump')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('pack_slip_pumpset')
                    ->label('Pack Slip Pumpset')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('name_plate_motor')
                    ->label('Name Plate Motor')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('name_plate_pump')
                    ->label('Name Plate Pump')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('name_plate_pumpset')
                    ->label('Name Plate Pumpset')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('tube_sticker_motor')
                    ->label('Tube Sticker Motor')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('tube_sticker_pump')
                    ->label('Tube Sticker Pump')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('tube_sticker_pumpset')
                    ->label('Tube Sticker Pumpset')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('warranty_card')
                    ->label('Warranty Card')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('part_validation1')
                    ->label('Part Validation 1')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('part_validation2')
                    ->label('Part Validation 2')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('part_validation3')
                    ->label('Part Validation 3')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('part_validation4')
                    ->label('Part Validation 4')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('part_validation5')
                    ->label('Part Validation 5')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('sap_msg_status')
                    ->label('SAP Message Status')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('sap_msg_description')
                    ->label('SAP Message Description')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('operator_id')
                    ->label('Created By')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])

            ->filters([

            Tables\Filters\TrashedFilter::make(),
            Filter::make('advanced_filters')
                ->label('Advanced Filters')
                ->form([
                    Select::make('Plant')
                        ->label('Select Plant')
                        ->nullable()
                        // ->options(function () {
                        //     return Plant::pluck('name', 'id');
                        // })
                        ->options(function (callable $get) {
                            $userHas = Filament::auth()->user()->plant_id;
                            return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                        })
                        ->reactive()
                        ->afterStateUpdated(function ($state, callable $set, callable $get) {
                            $set('sticker_master_id', null);
                            $set('sap_msg_status', null);
                            $set('Line', null);
                            $set('operator_id', null);
                        }),
                    Select::make('Line')
                        ->label('Select Line')
                        ->nullable()
                        ->options(function (callable $get) {
                            $plantId = $get('Plant');
                            if (!$plantId)
                            {
                                return [];
                            }

                            return Line::where('plant_id', $plantId)
                            ->where('type', 'FG Line') // Filter by type
                            ->pluck('name', 'id')
                            ->toArray();
                        })
                        ->reactive()
                        ->afterStateUpdated(function ($state, callable $set, callable $get) {
                            $set('sticker_master_id', null);
                            $set('sap_msg_status', null);
                            $set('operator_id', null);
                        }),
                    TextInput::make('production_order')
                        ->label('Production Order')
                        ->placeholder('Enter Production Order'),
                    TextInput::make('serial_number')
                        ->label('Serial Number')
                        ->placeholder(placeholder: 'Enter Serial Number'),
                    Select::make('sticker_master_id')
                        ->label('Search by Item Code')
                        ->nullable()
                        ->options(function (callable $get) {
                            $pId = $get('Plant');
                            return Item::whereHas('stickerMasters', function ($query) use ($pId) {
                                if ($pId) {
                                    $query->where('plant_id', $pId);
                                }
                                $query->whereHas('qualityValidations');
                            })->pluck('code', 'id');
                        })
                        ->searchable()
                        ->reactive(),
                    Select::make('sap_msg_status')
                        ->label('Select SAP Message Status')
                        ->nullable()
                        ->options(function (callable $get) {
                            $plantId = $get('Plant');

                            if (!$plantId ) {
                                return QualityValidation::whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status');
                            }
                            else {
                                return QualityValidation::where('plant_id', $plantId)->whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status');
                            }
                        })
                        // ->options(QualityValidation::whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status'))
                        ->reactive(),
                    Select::make('operator_id')
                        ->label('Created By')
                        ->nullable()
                        ->options(function (callable $get) {
                            $plantId = $get('Plant');
                            $lineId = $get('Line');
                            if (!$plantId && !$lineId)
                            {
                                return QualityValidation::whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
                            }
                            else if ($plantId && !$lineId)
                            {
                                return QualityValidation::where('plant_id', $plantId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
                            }
                            else// if ($plantId && $lineId)
                            {
                                return QualityValidation::where('plant_id', $plantId)->where('line_id', $lineId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
                            }
                        })
                        ->searchable()
                        ->reactive(),
                    DateTimePicker::make(name: 'created_from')
                        ->label('Created From')
                        ->placeholder(placeholder: 'Select From DateTime')
                        ->reactive()
                        ->native(false),
                    DateTimePicker::make('created_to')
                        ->label('Created To')
                        ->placeholder(placeholder: 'Select To DateTime')
                        ->reactive()
                        ->native(false),
                ])
                ->query(function ($query, array $data) {
                    // Hide all records initially if no filters are applied
                    if (empty($data['Plant']) && empty($data['production_order']) && empty($data['serial_number']) && empty($data['sap_msg_status']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['operator_id']) && empty($data['sticker_master_id'])) {
                        return $query->whereRaw('1 = 0');
                    }

                    if (!empty($data['Plant'])) {
                        $query->where('plant_id', $data['Plant']);
                    }

                    if (!empty($data['Line'])) {
                        $query->where('line_id', $data['Line']);
                    }

                    if (!empty($data['production_order'])) {
                        $query->where('production_order', $data['production_order']);
                    }

                    if (!empty($data['serial_number'])) {
                        $query->where('serial_number', $data['serial_number']);
                    }

                    if (!empty($data['sap_msg_status'])) {
                        $query->where('sap_msg_status', $data['sap_msg_status']);
                    }

                    if (!empty($data['created_from'])) {
                        $query->where('created_at', '>=', $data['created_from']);
                    }

                    if (!empty($data['created_to'])) {
                        $query->where('created_at', '<=', $data['created_to']);
                    }

                    if (!empty($data['operator_id'])) {
                        $query->where('operator_id', $data['operator_id']);
                    }

                    if (!empty($data['sticker_master_id'])) {
                        $stickerMasterIds = StickerMaster::where('item_id', $data['sticker_master_id'])
                            ->pluck('id')
                            ->toArray();

                        if (!empty($stickerMasterIds)) {
                            $query->whereIn('sticker_master_id', $stickerMasterIds);
                        }
                    }

                    //$query->orderBy('created_at', 'asc');
                })
                ->indicateUsing(function (array $data) {
                    $indicators = [];

                    if (!empty($data['Plant'])) {
                        $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name');
                    }

                    if (!empty($data['Line'])) {
                        $indicators[] = 'Line: ' . Line::where('id', $data['Line'])->value('name');
                    }

                    if (!empty($data['production_order'])) {
                        $indicators[] = 'Production Order: ' . $data['production_order'];
                    }

                    if (!empty($data['serial_number'])) {
                        $indicators[] = 'Serial Number: ' . $data['serial_number'];
                    }

                    if (!empty($data['sticker_master_id'])) {
                        $itemCode = Item::find($data['sticker_master_id'])->code ?? 'Unknown';
                        $indicators[] = 'Item Codes: ' . $itemCode;
                    }

                    if (!empty($data['sap_msg_status'])) {
                        $indicators[] = 'SAP Message Status: ' . $data['sap_msg_status'];
                    }

                    if (!empty($data['operator_id'])) {
                        $indicators[] = 'Created By: ' . $data['operator_id'];
                    }

                    if (!empty($data['created_from'])) {
                        $indicators[] = 'From: ' . $data['created_from'];
                    }

                    if (!empty($data['created_to'])) {
                        $indicators[] = 'To: ' . $data['created_to'];
                    }

                    return $indicators;
                })
            ])
            ->filtersFormMaxHeight('280px')
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])

            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                Tables\Actions\DeleteBulkAction::make(),
                Tables\Actions\ForceDeleteBulkAction::make(),
                Tables\Actions\RestoreBulkAction::make(),
                ]),
            ])
            ->headerActions([
                ImportAction::make()
                    ->label('Import Quality Validations')
                    ->color('warning')
                    ->importer(QualityValidationImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import quality validation');
                    }),
                ExportAction::make()
                    ->label('Export Quality Validations')
                    ->color('warning')
                    ->exporter(QualityValidationExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export quality validation');
                    }),
            ]);
    }


    // public static function mutateFormDataBeforeCreate(array $data): array
    // {
    //    $user =Filament::auth()->user();
    //    dd($user);
    //    if($user){
    //     $data['operator_id'] = $user->name;
    //    }
    //    // $data['operator_id'] = Filament::auth()->user()->name;
    //     return $data;
    // }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListQualityValidations::route('/'),
            'create' => Pages\CreateQualityValidation::route('/create'),
            'view' => Pages\ViewQualityValidation::route('/{record}'),
            'edit' => Pages\EditQualityValidation::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }
}
