<?php

namespace App\Filament\Resources;

use App\Exports\MotorFreeRunExport;
use App\Filament\Exports\TestingPanelReadingExporter;
use App\Filament\Imports\TestingPanelReadingImporter;
use App\Filament\Resources\TestingPanelReadingResource\Pages;
use App\Models\Configuration;
use App\Models\Item;
use App\Models\Line;
use App\Models\Machine;
use App\Models\MotorTestingMaster;
use App\Models\Plant;
use App\Models\TestingPanelReading;
use Barryvdh\DomPDF\Facade\Pdf;
use Closure;
// use Barryvdh\Reflection\DocBlock\Type\Collection;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\Action;
use Filament\Tables\Actions\BulkAction;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Response;
// use Barryvdh\Snappy\Facades\SnappyPdf as PDF;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;
// use App\Exports\TestingPanelReadingExport;
use PhpOffice\PhpSpreadsheet\IOFactory; // For loading Excel file
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class TestingPanelReadingResource extends Resource
{
    protected static ?string $model = TestingPanelReading::class;

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

    protected static ?string $navigationGroup = 'Testing Panel';

    protected static ?int $navigationSort = 4;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant Name')
                    ->relationship('plant', 'name')
                    ->searchable()
                    ->required()
                    ->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::orderBy('code')->pluck('name', 'id')->toArray();
                    })
                    ->default(function () {
                        return optional(TestingPanelReading::latest()->first())->plant_id;
                    })
                    ->disabled(fn (Get $get) => ! empty($get('id')))
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $plantId = $get('plant_id');
                        if (! $plantId) {
                            $set('line_id', null);
                            $set('motor_testing_master_id', null);
                            $set('machine_id', null);
                            $set('tPrError', 'Please select a plant first.');

                            return;
                        } else {
                            $set('line_id', null);
                            $set('motor_testing_master_id', null);
                            $set('machine_id', null);
                            $set('tPrError', null);
                        }

                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('tPrError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('tPrError') ? $get('tPrError') : null)
                    ->hintColor('danger'),
                Forms\Components\Select::make('line_id')
                    ->label('Line Name')
                    // ->relationship('line', 'name')
                    ->searchable()
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if (! $plantId) {
                            return [];
                        }

                        return Line::where('plant_id', $plantId)
                            ->pluck('name', 'id')
                            ->toArray();
                    })
                    ->default(function () {
                        return optional(TestingPanelReading::latest()->first())->line_id;
                    })
                    ->disabled(fn (Get $get) => ! empty($get('id')))
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('motor_testing_master_id', null);
                        $set('machine_id', null);
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\Select::make('machine_id')
                    ->label('Work Center')
                    // ->relationship('machine', 'work_center')
                    ->searchable()
                    ->options(function (callable $get) {
                        $lineId = $get('line_id');
                        if (! $lineId) {
                            return [];
                        }

                        // Only show machines for the selected line
                        return Machine::where('line_id', $lineId)
                            ->pluck('work_center', 'id')
                            ->toArray();
                    })
                    ->default(function () {
                        return optional(TestingPanelReading::latest()->first())->machine_id;
                    })
                    ->disabled(fn (Get $get) => ! empty($get('id')))
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\Select::make('motor_testing_master_id')
                    ->label('Item Code')
                    // ->relationship('motorTestingMaster', 'item.code')
                    // ->options(function (callable $get) {
                    //     $plantId = $get('plant_id');
                    //     if (!$plantId) {
                    //         return [];
                    //     }
                    //     return MotorTestingMaster::with('item')
                    //         ->where('plant_id', $plantId)
                    //         ->get()
                    //         //->filter(fn ($mtm) => $mtm->item)
                    //         ->pluck('item.code', 'id')
                    //         ->toArray();
                    // })
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if (! $plantId) {
                            return [];
                        }

                        return MotorTestingMaster::query()
                            ->join('items', 'motor_testing_masters.item_id', '=', 'items.id')
                            ->where('motor_testing_masters.plant_id', $plantId)
                            ->select('motor_testing_masters.id', 'items.code')
                            ->pluck('items.code', 'motor_testing_masters.id')
                            ->toArray();
                    })
                    // ->getOptionLabelUsing(fn ($value) =>
                    //     MotorTestingMaster::with('item')->find($value)?->item?->code
                    // )
                    ->required()
                    ->searchable()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('output')
                    ->label('Output')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->rule(function (callable $get) {
                        return function (string $attribute, $value, Closure $fail) use ($get) {

                            $plantId = $get('plant_id');
                            $lineId = $get('line_id');
                            $machineId = $get('machine_id');
                            $itemId = $get('motor_testing_master_id');
                            $output = trim($value);
                            // $currentId = $get('id'); // current editing record id

                            if (! $plantId || ! $lineId || ! $machineId || ! $itemId) {
                                return;
                            }

                            if ($output == null || $output == '' || ! $output) {
                                $fail("Output can't be empty!"); // Output1 - Output99
                            } elseif (Str::length($output) < 7) {
                                $fail('Output must be at least 7 characters long!');
                            } elseif (Str::length($output) > 8) {
                                $fail('Output must be at most 8 characters long!');
                            } elseif (! ctype_alnum($output)) {
                                $fail('Output should contain only alpha-numeric values!');
                            } elseif (! preg_match('/^Output([1-9]|[1-9][0-9])$/', $output)) {
                                $fail("Output should be between 'Output1' and 'Output99'!");
                            }
                        };
                    }),
                Forms\Components\TextInput::make('serial_number')
                    ->label('Serial Number')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->rule(function (callable $get) {
                        return function (string $attribute, $value, Closure $fail) use ($get) {

                            $plantId = $get('plant_id');
                            $lineId = $get('line_id');
                            $machineId = $get('machine_id');
                            $itemId = $get('motor_testing_master_id');
                            $serialNumber = trim($value);
                            // $currentId = $get('id'); // current editing record id

                            if (! $plantId || ! $lineId || ! $machineId || ! $itemId) {
                                return;
                            }

                            if ($serialNumber == null || $serialNumber == '' || ! $serialNumber) {
                                $fail("Serial number can't be empty!");
                            } elseif (Str::length($serialNumber) < 9) {
                                $fail('Serial number should contain minimum 9 digits!');
                            } elseif (! ctype_alnum($serialNumber)) {
                                $fail('Serial number should contain only alpha-numeric values!');
                            } elseif (! preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $serialNumber)) {
                                $fail("Serial number should not begin with '0' or letter!");
                            }
                        };
                    }),
                Forms\Components\TextInput::make('winded_serial_number')
                    ->label('Winded Serial Number')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->rule(function (callable $get) {
                        return function (string $attribute, $value, Closure $fail) use ($get) {

                            $plantId = $get('plant_id');
                            $lineId = $get('line_id');
                            $machineId = $get('machine_id');
                            $itemId = $get('motor_testing_master_id');
                            $serialNumber = trim($value);
                            // $currentId = $get('id'); // current editing record id

                            if (! $plantId || ! $lineId || ! $machineId || ! $itemId || ! $serialNumber) {
                                return;
                            }

                            if (Str::length($serialNumber) > 0 && Str::length($serialNumber) < 9) {
                                $fail('Winded serial number should contain minimum 9 digits!');
                            } elseif (! ctype_alnum($serialNumber)) {
                                $fail('Winded serial number should contain only alpha-numeric values!');
                            } elseif (! preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $serialNumber)) {
                                $fail("Winded serial number should not begin with '0' or letter!");
                            }
                        };
                    }),
                Forms\Components\TextInput::make('before_fr_volt')
                    ->label('Before FR Volt')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('before_fr_cur')
                    ->label('Before FR Current')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('before_fr_pow')
                    ->label('Before FR Power')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('before_fr_res_ry')
                    ->label('Before FR Resistance RY')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('before_fr_res_yb')
                    ->label('Before FR Resistance YB')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('before_fr_res_br')
                    ->label('Before FR Resistance BR')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('before_fr_ir')
                    ->label('Before FR IR')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('before_fr_ir_r')
                    ->label('Before FR IR R')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('before_fr_ir_y')
                    ->label('Before FR IR Y')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('before_fr_ir_b')
                    ->label('Before FR IR B')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('before_fr_freq')
                    ->label('Before FR Frequency')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('before_fr_speed')
                    ->label('Before FR Speed')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_vol')
                    ->label('After FR Volt')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_cur')
                    ->label('After FR Current')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_pow')
                    ->label('After FR Power')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_ir_hot')
                    ->label('After FR IR Hot')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_ir_hot_r')
                    ->label('After FR IR Hot R')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_ir_hot_y')
                    ->label('After FR IR Hot Y')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_ir_hot_b')
                    ->label('After FR IR Hot B')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_ir_cool')
                    ->label('After FR IR Cool')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_ir_cool_r')
                    ->label('After FR IR Cool R')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_ir_cool_y')
                    ->label('After FR IR Cool Y')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_ir_cool_b')
                    ->label('After FR IR Cool B')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_freq')
                    ->label('After FR Frequency')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_speed')
                    ->label('After FR Speed')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('after_fr_leak_cur')
                    ->label('After FR Leak Current')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('locked_rt_volt')
                    ->label('Locked RT Volt')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('locked_rt_cur')
                    ->label('Locked RT Current')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('locked_rt_pow')
                    ->label('Locked RT Power')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('no_load_pickup_volt')
                    ->label('No Load Pickup Volt')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('room_temperature')
                    ->label('Room Temperature')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\Select::make('hv_test')
                    ->label('High Voltage Test')
                    ->options([
                        'With Stood' => 'With Stood',
                        'Not With Stood' => 'Not With Stood',
                    ])
                    ->selectablePlaceholder(false)
                    ->default('Not With Stood')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('batch_number')
                    ->label('Batch Number')
                    ->readOnly(fn (callable $get) => ! $get('id'))
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('batch_count')
                    ->label('Batch Count')
                    ->default('0')
                    ->readOnly(fn (callable $get) => ! $get('id'))
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\Select::make('result')
                    ->label('Result')
                    ->options([
                        'PASS' => 'PASS', // Not With Stood
                        'FAIL' => 'FAIL',
                    ])
                    ->selectablePlaceholder(false)
                    ->default('FAIL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('remark')
                    ->label('Remark')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('rework_count')
                    ->label('Rework Count')
                    ->default('0')
                    ->readOnly(fn (callable $get) => ! $get('id'))
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('update_count')
                    ->label('Update Count')
                    ->default('0')
                    ->readOnly(fn (callable $get) => ! $get('id'))
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('output_flag')
                    ->label('Output Flag')
                    ->default('0')
                    ->readOnly(fn (callable $get) => ! $get('id'))
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\Hidden::make('tested_by')
                    ->default(fn () => Filament::auth()->user()?->name)
                    ->required(),
                Forms\Components\Hidden::make('updated_by')
                    ->default(fn () => Filament::auth()->user()?->name)
                    ->required(),
                Forms\Components\TextInput::make('id')
                    ->hidden()
                    ->readOnly(),
            ]);
    }

    public static function table(Table $table): Table
    {

        return $table
            ->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 Name')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('line.name')
                    ->label('Line Name')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('machine.work_center')
                    ->label('Work Center')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('motorTestingMaster.item.code')
                    ->label('Item Code')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('motorTestingMaster.subassembly_code')
                    ->label('Subassembly Code')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('motorTestingMaster.item.description')
                    ->label('Model')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('output')
                    ->label('Output')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('serial_number')
                    ->label('Serial Number')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('winded_serial_number')
                    ->label('Winded Serial Number')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('motorTestingMaster.kw')
                    ->label('KW')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('motorTestingMaster.hp')
                    ->label('HP')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('motorTestingMaster.phase')
                    ->label('Phase')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('motorTestingMaster.connection')
                    ->label('Connection')
                    ->alignCenter(),
                Tables\Columns\IconColumn::make('motorTestingMaster.isi_model')
                    ->label('ISI Model')
                    ->alignCenter()
                    ->boolean(),
                Tables\Columns\TextColumn::make('before_fr_volt')
                    ->label('Before FR Volt')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('before_fr_cur')
                    ->label('Before FR Current')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('before_fr_pow')
                    ->label('Before FR Power')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('before_fr_res_ry')
                    ->label('Before FR Resistance RY')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('before_fr_res_yb')
                    ->label('Before FR Resistance YB')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('before_fr_res_br')
                    ->label('Before FR Resistance BR')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('before_fr_ir')
                    ->label('Before FR IR')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('before_fr_ir_r')
                    ->label('Before FR IR R')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('before_fr_ir_y')
                    ->label('Before FR IR Y')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('before_fr_ir_b')
                    ->label('Before FR IR B')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('before_fr_freq')
                    ->label('Before FR Frequency')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('before_fr_speed')
                    ->label('Before FR Speed')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_vol')
                    ->label('After FR Volt')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_cur')
                    ->label('After FR Current')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_pow')
                    ->label('After FR Power')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_ir_hot')
                    ->label('After FR IR Hot')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_ir_hot_r')
                    ->label('After FR IR Hot R')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_ir_hot_y')
                    ->label('After FR IR Hot Y')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_ir_hot_b')
                    ->label('After FR IR Hot B')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_ir_cool')
                    ->label('After FR IR Cool')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_ir_cool_r')
                    ->label('After FR IR Cool R')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_ir_cool_y')
                    ->label('After FR IR Cool Y')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_ir_cool_b')
                    ->label('After FR IR Cool B')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_freq')
                    ->label('After FR Frequency')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_speed')
                    ->label('After FR Speed')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('after_fr_leak_cur')
                    ->label('After FR Leak Current')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('locked_rt_volt')
                    ->label('Locked RT Volt')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('locked_rt_cur')
                    ->label('Locked RT Current')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('locked_rt_pow')
                    ->label('Locked RT Power')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('no_load_pickup_volt')
                    ->label('No Load Pickup Volt')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('room_temperature')
                    ->label('Room Temperature')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('hv_test')
                    ->label('High Voltage Test')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('batch_number')
                    ->label('Batch Number')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('batch_count')
                    ->label('Batch Count')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('result')
                    ->label('Result')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('remark')
                    ->label('Remark')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('rework_count')
                    ->label('Rework Count')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('update_count')
                    ->label('Updated Count')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('output_flag')
                    ->label('Output Flag')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('scanned_at')
                    ->label('Scanned At')
                    ->alignCenter()
                    ->sortable()
                    ->dateTime(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable(),
                Tables\Columns\TextColumn::make('tested_by')
                    ->label('Tested By')
                    ->alignCenter()
                    ->numeric(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->alignCenter()
                    ->sortable()
                    ->dateTime(),
                Tables\Columns\TextColumn::make('updated_by')
                    ->label('Updated By')
                    ->alignCenter()
                    ->numeric(),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->alignCenter()
                    ->sortable()
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
                Filter::make('advanced_filters')
                    ->label('Advanced Filters')
                    ->form([
                        Select::make('Plant')
                            ->label('Search by Plant Name')
                            ->searchable()
                            ->nullable()
                            ->options(function () {
                                // return Plant::pluck('name', 'id');
                                $userHas = Filament::auth()->user()->plant_id;

                                if ($userHas && strlen($userHas) > 0) {
                                    return Plant::where('id', $userHas)->pluck('name', 'id')->toArray();
                                } else {
                                    return Plant::whereHas('testingPanelReadings', function ($query) {
                                        $query->whereNotNull('id');
                                    })->orderBy('code')->pluck('name', 'id');
                                }

                                // return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::orderBy('code')->pluck('name', 'id')->toArray();
                            })
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('Line', null);
                                $set('item_code', null);

                            }),
                        Select::make('Line')
                            ->label('Search by Line Name')
                            ->searchable()
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return [];
                                }

                                return Line::where('plant_id', $plantId)
                                    ->pluck('name', 'id')
                                    ->toArray();
                            })
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('item_code', null);
                            }),
                        Select::make('machine_name')
                            ->label('Search by Work Center')
                            ->searchable()
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                $lineId = $get('Line');

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

                                return Machine::where('plant_id', $plantId)
                                    ->where('line_id', $lineId)
                                    ->pluck('work_center', 'id')
                                    ->toArray();
                            })
                            ->reactive(),
                        Select::make('item_code')
                            ->label('Search by Item Code')
                            ->searchable()
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if ($plantId) {
                                    return Item::where('plant_id', $plantId)
                                        ->whereHas('motorTestingMasters')
                                        ->pluck('code', 'id')
                                        ->toArray();
                                } else {
                                    return [];
                                    // return Item::whereHas('motorTestingMasters')
                                    //     ->pluck('code', 'id')
                                    //     ->toArray();
                                }
                            })
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('item_description', null);
                            }),
                        TextInput::make('serial_number')
                            ->label('Serial Number')
                            ->reactive()
                            ->placeholder('Enter Serial Number'),
                        Select::make('subassembly_code')
                            ->label('Search by Subassembly Code')
                            ->searchable()
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if ($plantId) {
                                    return MotorTestingMaster::whereHas('testingPanelReadings', function ($query) {
                                        $query->whereNotNull('id');
                                    })->whereNotNull('subassembly_code')->orderBy('subassembly_code')->pluck('subassembly_code', 'id');
                                } else {
                                    return [];
                                    // return Item::whereHas('motorTestingMasters')
                                    //     ->pluck('code', 'id')
                                    //     ->toArray();
                                }
                            })
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('item_description', null);
                            }),
                        TextInput::make('winded_serial_number')
                            ->label('Winded Serial Number')
                            ->reactive()
                            ->placeholder('Enter Winded Serial Number'),
                        Select::make('item_description')
                            ->label('Search by Model')
                            ->searchable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');

                                // $query = Item::query();
                                // if ($plantId) {
                                //     $query->where('plant_id', $plantId);
                                // }

                                $plantId = $get('Plant');
                                if ($plantId) {
                                    return Item::where('plant_id', $plantId)
                                        ->whereHas('motorTestingMasters')
                                        ->pluck('description', 'id')
                                        ->toArray();
                                } else {
                                    return [];
                                    // return Item::whereHas('motorTestingMasters')
                                    //     ->pluck('description', 'id')
                                    //     ->toArray();
                                }
                                // return $query->pluck('description', 'description')->toArray();
                            })
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('item_code', null);
                            }),
                        Select::make('output')
                            ->label('Search by Output')
                            ->searchable()
                            ->options(function () {
                                return TestingPanelReading::whereNotNull('output')
                                    ->select('output')
                                    ->distinct()
                                    ->orderBy('output')
                                    ->pluck('output', 'output') // key and label are both the output value
                                    ->toArray();
                            })
                            ->reactive(),
                        // TextInput::make('phase')
                        //     ->label('Phase'),
                        // Select::make('phase')
                        //     ->label('Phase')
                        //     ->searchable()
                        //     ->options(function (callable $get) {
                        //         $plantId = $get('Plant');
                        //         $lineId = $get('Line');

                        //         // if (!$plantId || !$lineId)
                        //         // {
                        //         //     return [];
                        //         // }
                        //         if ($plantId && $lineId)
                        //         {
                        //             return Configuration::where('plant_id', $plantId)
                        //             ->where('line_id', $lineId)
                        //             ->where('c_name', 'MOTOR_PHASE')
                        //             ->pluck('c_value', 'id')
                        //             ->toArray();
                        //         }
                        //         else
                        //         {
                        //             return Configuration::where('c_name', 'MOTOR_PHASE')
                        //                 ->pluck('c_value', 'c_value')
                        //                 ->toArray();
                        //         }
                        //     })
                        //     ->reactive(),
                        // ...

                        Select::make('connection')
                            ->label('Connection')
                            ->required()
                            ->default('Star')
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if ($plantId) {
                                    return Configuration::where('plant_id', $plantId)
                                        ->where('c_name', 'MOTOR_CONNECTION')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                } else {
                                    return Configuration::where('c_name', 'MOTOR_CONNECTION')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                }
                            })
                            ->selectablePlaceholder(false)
                            ->reactive(),
                        // ..
                        TextInput::make('remark')
                            ->label('Remark')
                            ->reactive()
                            ->placeholder(placeholder: 'Enter Remark'),
                        TextInput::make('batch_number')
                            ->label('Batch Number')
                            ->reactive()
                            ->placeholder(placeholder: 'Enter Batch Number'),
                        Select::make('result')
                            ->label('Search by Result')
                            ->searchable()
                            ->options(function () {
                                return TestingPanelReading::query()
                                    ->whereNotNull('result')
                                    ->pluck('result') // just get the column
                                    ->unique()
                                    ->filter() // filters out nulls and empty automatically
                                    ->mapWithKeys(fn ($value) => [$value => $value])
                                    ->toArray();
                            })
                            ->reactive(),
                        Select::make('tested_by')
                            ->label('Tested By')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return TestingPanelReading::whereNotNull('tested_by')->select('tested_by')->distinct()->pluck('tested_by', 'tested_by');
                                } else {
                                    return TestingPanelReading::where('plant_id', $plantId)->whereNotNull('tested_by')->select('tested_by')->distinct()->pluck('tested_by', 'tested_by');
                                }
                            })
                            ->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),
                        Select::make('updated_by')
                            ->label('Updated By')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return TestingPanelReading::whereNotNull('updated_by')->select('updated_by')->distinct()->pluck('updated_by', 'updated_by');
                                } else {
                                    return TestingPanelReading::where('plant_id', $plantId)->whereNotNull('updated_by')->select('updated_by')->distinct()->pluck('updated_by', 'updated_by');
                                }
                            })
                            ->searchable()
                            ->reactive(),
                        DateTimePicker::make(name: 'updated_from')
                            ->label('Updated From')
                            ->placeholder(placeholder: 'Select From DateTime')
                            ->reactive()
                            ->native(false),
                        DateTimePicker::make('updated_to')
                            ->label('Updated To')
                            ->placeholder(placeholder: 'Select To DateTime')
                            ->reactive()
                            ->native(false),
                    ])
                    ->query(function ($query, array $data) {

                        // dd($data);
                        // Hide all records initially if no filters are applied
                        if (empty($data['Plant']) && empty($data['Line']) && empty($data['item_code']) && empty($data['subassembly_code']) && empty($data['machine_name']) && empty($data['item_description']) && empty($data['serial_number']) && empty($data['winded_serial_number']) && empty($data['output']) && empty($data['phase']) && empty($data['connection']) && empty($data['remark']) && empty($data['batch_no']) && empty($data['result']) && empty($data['tested_by']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['updated_by']) && empty($data['updated_from']) && empty($data['updated_to'])) {
                            return $query->whereRaw('1 = 0');
                        }

                        // if (empty($data['Plant']) && empty($data['Line']) && empty($data['item_code']) && empty($data['machine_name']) && empty($data['item_description']) && empty($data['serial_number']) && empty($data['output']) && empty($data['phase']) && !empty($data['connection']) && empty($data['remark']) && empty($data['batch_no'])&& empty($data['result'])  && empty($data['created_from']) && empty($data['created_to'])) {
                        //     return $query->whereRaw('1 = 0');
                        // }

                        if (! empty($data['Plant'])) {
                            $query->where('plant_id', $data['Plant']);
                        } else {
                            $userHas = Filament::auth()->user()->plant_id;

                            if ($userHas && strlen($userHas) > 0) {
                                return $query->whereRaw('1 = 0');
                            }
                        }

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

                        if (! empty($data['item_code'])) {
                            // $query->where('item_id', $data['item_code']);
                            $query->whereHas('motorTestingMaster', function ($subQuery) use ($data) {
                                $subQuery->where('item_id', $data['item_code']);
                            });
                        }

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

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

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

                        if (! empty($data['winded_serial_number'])) {
                            $query->where('winded_serial_number', 'like', '%'.$data['winded_serial_number'].'%');
                        }

                        if (! empty($data['item_description'])) {
                            $itemId = $data['item_description']; // Item::where('description', $data['item_description'])->first()?->id ?? null;

                            if ($itemId) { // $item
                                $mastId = MotorTestingMaster::where('item_id', $itemId)->first()?->id ?? null;
                                if ($mastId) { // $item
                                    $motId = TestingPanelReading::where('motor_testing_master_id', $mastId)->first()?->id ?? null;
                                    if ($motId) { // $item
                                        $query->where('motor_testing_master_id', $mastId);
                                        // $query->whereHas('motorTestingMaster', function ($subQuery) use ($itemId) {
                                        //     $subQuery->where('item_id', $itemId); //$item->id
                                        // });
                                    } else {
                                        $query->whereRaw('1 = 0');
                                    }
                                } else {
                                    $query->whereRaw('1 = 0');
                                }
                            } else {
                                $query->whereRaw('1 = 0');
                            }
                        }

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

                        // if (!empty($data['phase']))
                        // {
                        //     //$query->where('phase',$data['phase']);
                        //     $query->whereHas('motorTestingMaster', function ($subQuery) use ($data) {
                        //         $subQuery->where('phase', $data['phase']);
                        //     });
                        // }

                        if (! empty($data['connection'])) {
                            // $query->where('connection',$data['connection']);
                            $query->whereHas('motorTestingMaster', function ($subQuery) use ($data) {
                                $subQuery->where('connection', $data['connection']);
                            });
                        }

                        if (! empty($data['remark'])) {
                            $query->where('remark', 'like', '%'.$data['remark'].'%');
                        }

                        if (! empty($data['batch_number'])) {
                            $query->where('batch_number', 'like', '%'.$data['batch_number'].'%');
                        }

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

                        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['tested_by'])) {
                            $query->where('tested_by', $data['tested_by']);
                        }

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

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

                        if (! empty($data['updated_by'])) {
                            $query->where('updated_by', $data['updated_by']);
                        }
                    })
                    ->indicateUsing(function (array $data) {
                        $indicators = [];

                        if (! empty($data['Plant'])) {
                            $indicators[] = 'Plant Name: '.Plant::where('id', $data['Plant'])->value('name');
                        } else {
                            $userHas = Filament::auth()->user()->plant_id;

                            if ($userHas && strlen($userHas) > 0) {
                                return 'Plant: Choose plant to filter records.';
                            }
                        }
                        if (! empty($data['Line'])) {
                            $indicators[] = 'Line Name: '.Line::where('id', $data['Line'])->value('name');
                        }
                        if (! empty($data['machine_name'])) {
                            $indicators[] = 'Work Center: '.Machine::where('id', $data['machine_name'])->value('work_center');
                        }
                        if (! empty($data['item_code'])) {
                            $indicators[] = 'Item Code: '.Item::where('id', $data['item_code'])->value('code');
                        }
                        if (! empty($data['subassembly_code'])) {
                            $indicators[] = 'Subassembly Code: '.MotorTestingMaster::where('id', $data['subassembly_code'])->value('subassembly_code');
                        }
                        if (! empty($data['output'])) {
                            $indicators[] = 'Output: '.$data['output'];
                        }
                        if (! empty($data['item_description'])) {
                            $item = Item::where('id', $data['item_description'])->first()?->description ?? null;
                            $indicators[] = 'Model: '.$item;
                        }
                        // if (!empty($data['phase'])) {
                        //     $indicators[] = 'Phase: ' . $data['phase'];
                        // }
                        if (! empty($data['connection'])) {
                            $indicators[] = 'Connection: '.$data['connection'];
                        }
                        if (! empty($data['remark'])) {
                            $indicators[] = 'Remark: '.$data['remark'];
                        }
                        if (! empty($data['batch_number'])) {
                            $indicators[] = 'Batch Number: '.$data['batch_number'];
                        }
                        if (! empty($data['result'])) {
                            $indicators[] = 'Result: '.$data['result'];
                        }

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

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

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

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

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

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

                        if (! empty($data['updated_to'])) {
                            $indicators[] = 'Updated To: '.$data['updated_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(),

                    //     BulkAction::make('exportExcel')
                    // ->label('Export Selected to Excel')
                    // ->icon('heroicon-o-document-arrow-down')
                    // ->action(function (Collection $records) {
                    //     return Excel::download(
                    //         new MotorFreeRunExport($records),
                    //         'Motor_Free_Run_Register.xlsx'
                    //     );
                    // }),

                    BulkAction::make('export_pdf')
                        ->label('Export Selected to Excel')
                        ->action(function ($records) {
                            // $ids = $records->pluck('id')->toArray();
                            // $query = TestingPanelReading::whereIn('id', $ids);
                            $templatePath = storage_path('app/private/uploads/temp/MotorTestingPanelReportTemplate.xlsx');

                            return Excel::download(new MotorFreeRunExport($records, $templatePath), 'MotorFreeRunData.xlsx');
                        })
                        ->icon('heroicon-o-document-arrow-down'),

                    // BulkAction::make('export_pdf')
                    //     ->label('Export Readings PDF'),
                    //     ->action(function ($records)
                    //     {
                    //         //$records->load('item');
                    //         $records->load('motorTestingMaster.item');
                    //         $plantId = $records->first()?->plant_id;

                    //         $plant = $plantId ? Plant::find($plantId) : null;

                    //         // Check if all records are Star-Delta type
                    //         $isAllStarDelta = $records->every(function ($record) {
                    //             return $record->motorTestingMaster?->connection === 'Star-Delta';
                    //         });
                    //         // $hasStarDelta = $records->contains(function ($record) {
                    //         //     return $record->motorTestingMaster?->connection === 'Star-Delta';
                    //         // });

                    //         //dd($isAllStarDelta);
                    //         if(!$isAllStarDelta)
                    //         {
                    //             $mappedData = collect($records)->map(function ($record) {
                    //                 return [
                    //                     // 'Date' => $record['created_at'] ?? '',
                    //                     'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
                    //                     'Output' => $record['output'] ?? '',
                    //                     'Motor SNo' => $record['serial_number'] ?? '',
                    //                     'Item Code' => $record->motorTestingMaster->item->code ?? '',
                    //                     'Motor Type' => $record->motorTestingMaster->item->description ?? '',

                    //                     'kw' => $record->motorTestingMaster->kw ?? '',
                    //                     'hp' => $record->motorTestingMaster->hp ?? '',
                    //                     'phase' => $record->motorTestingMaster->phase ?? '',
                    //                     'isi_model' => $record->motorTestingMaster->isi_model ?? '',

                    //                     // BEFORE FREE RUN
                    //                     'Voltage_Before' => $record['before_fr_volt'] ?? '',
                    //                     'Current_Before' => $record['before_fr_cur'] ?? '',
                    //                     'Power_Before' => $record['before_fr_pow'] ?? '',
                    //                     'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
                    //                     'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
                    //                     'Resistance_BR' => $record['before_fr_res_br'] ?? '',
                    //                     'Insulation_Resistance' => $record['before_fr_ir'] ?? '',
                    //                     'Frequency_Before' => $record['before_fr_freq'] ?? '',
                    //                     'Speed_Before' => $record['before_fr_speed'] ?? '',

                    //                     // AFTER FREE RUN
                    //                     'Voltage_After' => $record['after_fr_vol'] ?? '',
                    //                     'Current_After' => $record['after_fr_cur'] ?? '',
                    //                     'Power_After' => $record['after_fr_pow'] ?? '',
                    //                     'IR_Hot' => $record['after_fr_ir_hot'] ?? '',
                    //                     'IR_Cool' => $record['after_fr_ir_cool'] ?? '',
                    //                     'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
                    //                     'Frequency_After' => $record['after_fr_freq'] ?? '',
                    //                     'Speed_After' => $record['after_fr_speed'] ?? '',

                    //                     // LOCKED ROTOR TEST
                    //                     'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
                    //                     'Current_Locked' => $record['locked_rt_cur'] ?? '',
                    //                     'Power_Locked' => $record['locked_rt_pow'] ?? '',

                    //                     // Last 8 columns
                    //                     'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
                    //                     'Room_Temp' => $record['room_temperature'] ?? '',
                    //                     'High_Voltage_Test' => $record['hv_test'] ?? '',
                    //                     'Batch_Number' => $record['batch_number'] ?? '',
                    //                     'Batch_Count' => $record['batch_count'] ?? '',
                    //                     'Result' => $record['result'] ?? '',
                    //                     'Remark' => $record['remark'] ?? '',
                    //                     'Tested_By' => $record['tested_by'] ?? '',
                    //                 ];
                    //         });
                    //         }
                    //         else
                    //         {

                    //             $mappedData = collect($records)->map(function ($record) {
                    //                 return [
                    //                     //'Date' => $record['created_at'] ?? '',
                    //                     'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
                    //                     'Output' => $record['output'] ?? '',
                    //                     'Motor SNo' => $record['serial_number'] ?? '',
                    //                     'Item Code' => $record->motorTestingMaster->item->code ?? '',
                    //                     'Motor Type' => $record->motorTestingMaster->item->description ?? '',

                    //                     'kw' => $record->motorTestingMaster->kw ?? '',
                    //                     'hp' => $record->motorTestingMaster->hp ?? '',
                    //                     'phase' => $record->motorTestingMaster->phase ?? '',
                    //                     'isi_model' => $record->motorTestingMaster->isi_model ?? '',

                    //                     // BEFORE FREE RUN
                    //                     'Voltage_Before' => $record['before_fr_volt'] ?? '',
                    //                     'Current_Before' => $record['before_fr_cur'] ?? '',
                    //                     'Power_Before' => $record['before_fr_pow'] ?? '',
                    //                     'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
                    //                     'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
                    //                     'Resistance_BR' => $record['before_fr_res_br'] ?? '',
                    //                     'Insulation_Resistance_R' => $record['before_fr_ir_r'] ?? '',
                    //                     'Insulation_Resistance_Y' => $record['before_fr_ir_y'] ?? '',
                    //                     'Insulation_Resistance_B' => $record['before_fr_ir_b'] ?? '',
                    //                     'Frequency_Before' => $record['before_fr_freq'] ?? '',
                    //                     'Speed_Before' => $record['before_fr_speed'] ?? '',

                    //                     // AFTER FREE RUN
                    //                     'Voltage_After' => $record['after_fr_vol'] ?? '',
                    //                     'Current_After' => $record['after_fr_cur'] ?? '',
                    //                     'Power_After' => $record['after_fr_pow'] ?? '',
                    //                     'IR_Hot_R' => $record['after_fr_ir_hot_r'] ?? '',
                    //                     'IR_Hot_Y' => $record['after_fr_ir_hot_y'] ?? '',
                    //                     'IR_Hot_B' => $record['after_fr_ir_hot_b'] ?? '',
                    //                     'IR_Cool_R' => $record['after_fr_ir_cool_r'] ?? '',
                    //                     'IR_Cool_Y' => $record['after_fr_ir_cool_y'] ?? '',
                    //                     'IR_Cool_B' => $record['after_fr_ir_cool_b'] ?? '',
                    //                     'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
                    //                     'Frequency_After' => $record['after_fr_freq'] ?? '',
                    //                     'Speed_After' => $record['after_fr_speed'] ?? '',

                    //                     // LOCKED ROTOR TEST
                    //                     'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
                    //                     'Current_Locked' => $record['locked_rt_cur'] ?? '',
                    //                     'Power_Locked' => $record['locked_rt_pow'] ?? '',

                    //                     // Last 8 columns
                    //                     'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
                    //                     'Room_Temp' => $record['room_temperature'] ?? '',
                    //                     'High_Voltage_Test' => $record['hv_test'] ?? '',
                    //                     'Batch_Number' => $record['batch_number'] ?? '',
                    //                     'Batch_Count' => $record['batch_count'] ?? '',
                    //                     'Result' => $record['result'] ?? '',
                    //                     'Remark' => $record['remark'] ?? '',
                    //                     'Tested_By' => $record['tested_by'] ?? '',
                    //                 ];
                    //             });
                    //         }

                    //     $view = $isAllStarDelta ? 'exports.export-three-phase-pdf' : 'exports.testingpanel-pdf';

                    //     $pdf = Pdf::loadView($view, [
                    //         'records' => $mappedData,
                    //         'plant' => $plant,
                    //     ]);

                    //     // $pdf = Pdf::loadView('exports.testingpanel-pdf',[
                    //     //    // ['records' => $mappedData]
                    //     //    'records' => $mappedData,
                    //     //    'plant' => $plant,

                    //     // ]);

                    //     return response()->streamDownload(
                    //         fn () => print($pdf->stream()),
                    //         'TestingPanelReading.pdf'
                    //     );
                    //    // return $pdf->download('TestingPanelReading.pdf');
                    //     })

                    //                 ->action(function ($records) {

                    //         // Load related item data
                    //         $records->load('motorTestingMaster.item');

                    //         $plantId = $records->first()?->plant_id;
                    //         $plant = $plantId ? Plant::find($plantId) : null;

                    //         // Check if all records are Star-Delta type
                    //         $isAllStarDelta = $records->every(fn($record) => $record->motorTestingMaster?->connection === 'Star-Delta');

                    //         // Map records for export
                    //         $mappedData = $records->map(function ($record) use ($isAllStarDelta) {

                    //             if (!$isAllStarDelta) {
                    //                 return [
                    //                     'Date' => date('Y-m-d', strtotime($record['created_at'] ?? '')),
                    //                     'Output' => $record['output'] ?? '',
                    //                     'Motor SNo' => $record['serial_number'] ?? '',
                    //                     'Item Code' => $record->motorTestingMaster->item->code ?? '',
                    //                     'Motor Type' => $record->motorTestingMaster->item->description ?? '',
                    //                     'kw' => $record->motorTestingMaster->kw ?? '',
                    //                     'hp' => $record->motorTestingMaster->hp ?? '',
                    //                     'phase' => $record->motorTestingMaster->phase ?? '',
                    //                     'isi_model' => $record->motorTestingMaster->isi_model ?? '',
                    //                     'Voltage_Before' => $record['before_fr_volt'] ?? '',
                    //                     'Current_Before' => $record['before_fr_cur'] ?? '',
                    //                     'Power_Before' => $record['before_fr_pow'] ?? '',
                    //                     'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
                    //                     'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
                    //                     'Resistance_BR' => $record['before_fr_res_br'] ?? '',
                    //                     'Insulation_Resistance' => $record['before_fr_ir'] ?? '',
                    //                     'Frequency_Before' => $record['before_fr_freq'] ?? '',
                    //                     'Speed_Before' => $record['before_fr_speed'] ?? '',
                    //                     'Voltage_After' => $record['after_fr_vol'] ?? '',
                    //                     'Current_After' => $record['after_fr_cur'] ?? '',
                    //                     'Power_After' => $record['after_fr_pow'] ?? '',
                    //                     'IR_Hot' => $record['after_fr_ir_hot'] ?? '',
                    //                     'IR_Cool' => $record['after_fr_ir_cool'] ?? '',
                    //                     'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
                    //                     'Frequency_After' => $record['after_fr_freq'] ?? '',
                    //                     'Speed_After' => $record['after_fr_speed'] ?? '',
                    //                     'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
                    //                     'Current_Locked' => $record['locked_rt_cur'] ?? '',
                    //                     'Power_Locked' => $record['locked_rt_pow'] ?? '',
                    //                     'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
                    //                     'Room_Temp' => $record['room_temperature'] ?? '',
                    //                     'High_Voltage_Test' => $record['hv_test'] ?? '',
                    //                     'Batch_Number' => $record['batch_number'] ?? '',
                    //                     'Batch_Count' => $record['batch_count'] ?? '',
                    //                     'Result' => $record['result'] ?? '',
                    //                     'Remark' => $record['remark'] ?? '',
                    //                     'Tested_By' => $record['tested_by'] ?? '',
                    //                 ];
                    //             } else {
                    //                 // Star-Delta records
                    //                 return [
                    //                     'Date' => date('Y-m-d', strtotime($record['created_at'] ?? '')),
                    //                     'Output' => $record['output'] ?? '',
                    //                     'Motor SNo' => $record['serial_number'] ?? '',
                    //                     'Item Code' => $record->motorTestingMaster->item->code ?? '',
                    //                     'Motor Type' => $record->motorTestingMaster->item->description ?? '',
                    //                     'kw' => $record->motorTestingMaster->kw ?? '',
                    //                     'hp' => $record->motorTestingMaster->hp ?? '',
                    //                     'phase' => $record->motorTestingMaster->phase ?? '',
                    //                     'isi_model' => $record->motorTestingMaster->isi_model ?? '',
                    //                     'Voltage_Before' => $record['before_fr_volt'] ?? '',
                    //                     'Current_Before' => $record['before_fr_cur'] ?? '',
                    //                     'Power_Before' => $record['before_fr_pow'] ?? '',
                    //                     'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
                    //                     'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
                    //                     'Resistance_BR' => $record['before_fr_res_br'] ?? '',
                    //                     'Insulation_Resistance_R' => $record['before_fr_ir_r'] ?? '',
                    //                     'Insulation_Resistance_Y' => $record['before_fr_ir_y'] ?? '',
                    //                     'Insulation_Resistance_B' => $record['before_fr_ir_b'] ?? '',
                    //                     'Frequency_Before' => $record['before_fr_freq'] ?? '',
                    //                     'Speed_Before' => $record['before_fr_speed'] ?? '',
                    //                     'Voltage_After' => $record['after_fr_vol'] ?? '',
                    //                     'Current_After' => $record['after_fr_cur'] ?? '',
                    //                     'Power_After' => $record['after_fr_pow'] ?? '',
                    //                     'IR_Hot_R' => $record['after_fr_ir_hot_r'] ?? '',
                    //                     'IR_Hot_Y' => $record['after_fr_ir_hot_y'] ?? '',
                    //                     'IR_Hot_B' => $record['after_fr_ir_hot_b'] ?? '',
                    //                     'IR_Cool_R' => $record['after_fr_ir_cool_r'] ?? '',
                    //                     'IR_Cool_Y' => $record['after_fr_ir_cool_y'] ?? '',
                    //                     'IR_Cool_B' => $record['after_fr_ir_cool_b'] ?? '',
                    //                     'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
                    //                     'Frequency_After' => $record['after_fr_freq'] ?? '',
                    //                     'Speed_After' => $record['after_fr_speed'] ?? '',
                    //                     'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
                    //                     'Current_Locked' => $record['locked_rt_cur'] ?? '',
                    //                     'Power_Locked' => $record['locked_rt_pow'] ?? '',
                    //                     'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
                    //                     'Room_Temp' => $record['room_temperature'] ?? '',
                    //                     'High_Voltage_Test' => $record['hv_test'] ?? '',
                    //                     'Batch_Number' => $record['batch_number'] ?? '',
                    //                     'Batch_Count' => $record['batch_count'] ?? '',
                    //                     'Result' => $record['result'] ?? '',
                    //                     'Remark' => $record['remark'] ?? '',
                    //                     'Tested_By' => $record['tested_by'] ?? '',
                    //                 ];
                    //             }
                    //         });

                    //         // Excel template path
                    //         $templatePath = storage_path('app/private/uploads/temp/MotorTestingPanelReportTemplate.xlsx');

                    //         // Check if template exists
                    // if (!file_exists($templatePath)) {
                    //     Notification::make()
                    //         ->title('Template Not Found')
                    //         ->danger()
                    //         ->body('The Excel template file does not exist. Please upload it first.')
                    //         ->send();

                    //     return; // Stop further execution
                    // }
                    //          // Export Excel
                    //     // return Excel::download(
                    //     //     new MotorFreeRunExport(collect($mappedData)),
                    //     //     'TestingPanelReading.xlsx',
                    //     //     \Maatwebsite\Excel\Excel::XLSX,
                    //     //     [
                    //     //         'template' => $templatePath,
                    //     //     ]
                    //     // );
                    //     // Load the template
                    // $spreadsheet = IOFactory::load($templatePath);
                    // $sheet = $spreadsheet->getActiveSheet();

                    // // Insert mapped data starting from row 3
                    // $row = 7;
                    // foreach ($mappedData as $dataRow) {
                    //     $col = 'A';
                    //     foreach ($dataRow as $cell) {
                    //         $sheet->setCellValue($col . $row, $cell);
                    //         $col++;
                    //     }
                    //     $row++;
                    // }

                    // // Download the modified template as Excel
                    // $writer = new Xlsx($spreadsheet);
                    // return response()->streamDownload(function() use ($writer) {
                    //     $writer->save('php://output');
                    // }, 'TestingPanelReading.xlsx');
                    //     })
                    // ->action(function ($records) {

                    //     // If no template, notify
                    //     $templatePath = storage_path('app/private/uploads/temp/MotorTestingPanelReportTemplate.xlsx');
                    //     if (!file_exists($templatePath)) {
                    //         Notification::make()
                    //             ->title('Template Not Found')
                    //             ->danger()
                    //             ->body('The Excel template file does not exist. Please upload it first.')
                    //             ->send();
                    //         return;
                    //     }

                    //     // Just export the raw data (fast, chunked)
                    //     return Excel::download(new MotorFreeRunExport($records->pluck('id')), 'MotorFreeRunData.xlsx');
                    // })
                    // ->icon('heroicon-o-document-arrow-down'),  c

                    BulkAction::make('export_isi_pdf')
                        ->label('Export ISI Readings PDF')
                        ->action(function ($records) {
                            // Increase memory and execution time
                            // ini_set('memory_limit', '1024M');
                            // set_time_limit(300);
                            $records->load('motorTestingMaster.item');
                            $plantId = $records->first()?->plant_id;

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

                            $isAllStarDelta = $records->every(function ($record) {
                                return $record->motorTestingMaster?->connection === 'Star-Delta';
                            });
                            // $hasStarDelta = $records->contains(function ($record) {
                            //     return $record->motorTestingMaster?->connection === 'Star-Delta';
                            // });

                            // dd($isAllStarDelta);
                            if (! $isAllStarDelta) {
                                $mappedData = collect($records)->map(function ($record) {
                                    return [
                                        // 'Date' => $record['created_at'] ?? '',
                                        'Date' => date('Y-m-d', strtotime($record['created_at'] ?? '')),
                                        'Output' => $record['output'] ?? '',
                                        'Motor SNo' => $record['serial_number'] ?? '',
                                        'Item Code' => $record->motorTestingMaster->item->code ?? '',
                                        'Motor Type' => $record->motorTestingMaster->item->description ?? '',

                                        'kw' => $record->motorTestingMaster->kw ?? '',
                                        'hp' => $record->motorTestingMaster->hp ?? '',
                                        'phase' => $record->motorTestingMaster->phase ?? '',
                                        'isi_model' => $record->motorTestingMaster->isi_model ?? '',

                                        // AFTER FREE RUN
                                        'Voltage_After' => $record['after_fr_vol'] ?? '',
                                        'Current_After' => $record['after_fr_cur'] ?? '',
                                        'Power_After' => $record['after_fr_pow'] ?? '',
                                        'IR_Hot' => $record['after_fr_ir_hot'] ?? '',
                                        'IR_Cool' => $record['after_fr_ir_cool'] ?? '',
                                        'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
                                        'Frequency_After' => $record['after_fr_freq'] ?? '',
                                        'Speed_After' => $record['after_fr_speed'] ?? '',

                                        // LOCKED ROTOR TEST
                                        'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
                                        'Current_Locked' => $record['locked_rt_cur'] ?? '',
                                        'Power_Locked' => $record['locked_rt_pow'] ?? '',

                                        // Last 8 columns
                                        'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
                                        'Room_Temp' => $record['room_temperature'] ?? '',
                                        'High_Voltage_Test' => $record['hv_test'] ?? '',
                                        'Result' => $record['result'] ?? '',
                                        'Remark' => $record['remark'] ?? '',
                                    ];
                                });
                            } else {
                                $mappedData = collect($records)->map(function ($record) {
                                    return [
                                        // 'Date' => $record['created_at'] ?? '',
                                        'Date' => date('Y-m-d', strtotime($record['created_at'] ?? '')),
                                        'Output' => $record['output'] ?? '',
                                        'Motor SNo' => $record['serial_number'] ?? '',
                                        'Item Code' => $record->motorTestingMaster->item->code ?? '',
                                        'Motor Type' => $record->motorTestingMaster->item->description ?? '',

                                        'kw' => $record->motorTestingMaster->kw ?? '',
                                        'hp' => $record->motorTestingMaster->hp ?? '',
                                        'phase' => $record->motorTestingMaster->phase ?? '',
                                        'isi_model' => $record->motorTestingMaster->isi_model ?? '',

                                        // AFTER FREE RUN
                                        'Voltage_After' => $record['after_fr_vol'] ?? '',
                                        'Current_After' => $record['after_fr_cur'] ?? '',
                                        'Power_After' => $record['after_fr_pow'] ?? '',
                                        'IR_Hot_R' => $record['after_fr_ir_hot_r'] ?? '',
                                        'IR_Hot_Y' => $record['after_fr_ir_hot_y'] ?? '',
                                        'IR_Hot_B' => $record['after_fr_ir_hot_b'] ?? '',
                                        'IR_Cool_R' => $record['after_fr_ir_cool_r'] ?? '',
                                        'IR_Cool_Y' => $record['after_fr_ir_cool_y'] ?? '',
                                        'IR_Cool_B' => $record['after_fr_ir_cool_b'] ?? '',
                                        'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
                                        'Frequency_After' => $record['after_fr_freq'] ?? '',
                                        'Speed_After' => $record['after_fr_speed'] ?? '',

                                        // LOCKED ROTOR TEST
                                        'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
                                        'Current_Locked' => $record['locked_rt_cur'] ?? '',
                                        'Power_Locked' => $record['locked_rt_pow'] ?? '',

                                        // Last 8 columns
                                        'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
                                        'Room_Temp' => $record['room_temperature'] ?? '',
                                        'High_Voltage_Test' => $record['hv_test'] ?? '',
                                        'Result' => $record['result'] ?? '',
                                        'Remark' => $record['remark'] ?? '',
                                    ];
                                });
                            }

                            $view = $isAllStarDelta ? 'exports.export-isi-three-phase-pdf' : 'exports.export-isi-pdf';

                            $pdf = Pdf::loadView($view, [
                                'records' => $mappedData,
                                'plant' => $plant,
                            ]);

                            //  $pdf = Pdf::loadView('exports.export-isi-pdf',[
                            //    // ['records' => $mappedData]
                            //    'records' => $mappedData,
                            //    'plant' => $plant,

                            // ]);

                            return response()->streamDownload(
                                fn () => print ($pdf->stream()),
                                'TestingPanelReading.pdf'
                            );

                        })
                        ->icon('heroicon-o-document-arrow-down'),
                ]),
            ])
            ->headerActions([
                ImportAction::make()
                    ->label('Import Testing Panel Readings')
                    ->color('warning')
                    ->importer(TestingPanelReadingImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import testing panel reading');
                    }),
                ExportAction::make()
                    ->label('Export Testing Panel Readings')
                    ->color('warning')
                    ->exporter(TestingPanelReadingExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export testing panel reading');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListTestingPanelReadings::route('/'),
            'create' => Pages\CreateTestingPanelReading::route('/create'),
            'view' => Pages\ViewTestingPanelReading::route('/{record}'),
            'edit' => Pages\EditTestingPanelReading::route('/{record}/edit'),
        ];
    }

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