<?php

namespace App\Filament\Resources;

use App\Filament\Exports\RequestCharacteristicExporter;
use App\Filament\Imports\RequestCharacteristicImporter;
use App\Filament\Resources\RequestCharacteristicResource\Pages;
use App\Models\CharacteristicApproverMaster;
use App\Models\Item;
use App\Models\Machine;
use App\Models\Plant;
use App\Models\RequestCharacteristic;
use App\Models\StickerMaster;
use Closure;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Forms\Set;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
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\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\Rule;

class RequestCharacteristicResource extends Resource
{
    protected static ?string $model = RequestCharacteristic::class;

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

    protected static ?string $navigationGroup = 'Laser Marking';

    public static function form(Form $form): Form
    {

        // $disableField = function ($get) {
        //     $currentUser = Filament::auth()->user();
        //     $approverId = $get('characteristic_approver_master_id');

        //     if (!$approverId) return true; // disable if no approver selected

        //     $approver = CharacteristicApproverMaster::find($approverId);
        //     if (!$approver) return true;

        //     // Enable if Super Admin
        //     if ($currentUser && $currentUser->hasRole('Super Admin')) {
        //         return false; // not disabled
        //     }

        //     // Enable only if current user is one of the approvers
        //     $userName = $currentUser?->name;

        //     return !in_array($userName, [
        //         $approver->name1,
        //         $approver->name2,
        //         $approver->name3,
        //     ]);
        // };

        return $form
            ->schema([
                Section::make('')
                    ->schema([
                        Forms\Components\Select::make('plant_id')
                            ->label('Plant Name')
                            ->relationship('plant', 'name')
                            ->reactive()
                            ->searchable()
                            ->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();
                            })
                            ->required()
                            ->default(function () {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? null : optional(RequestCharacteristic::latest()->first())->plant_id ?? null;
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $plantId = $get('plant_id');
                                $updRec = $get('id');
                                $set('machine_id', null);
                                $set('item_id', null);
                                $set('aufnr', null);
                                $set('machine_name', null);
                                $set('characteristic_approver_master_id', null);
                                $set('approver_type', null);
                                if (! $updRec) {
                                    $set('work_flow_id', $plantId ? self::isNewWorkFlow($get) : null);
                                }
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->disabled(fn ($get) => self::isFieldDisabled($get)),
                        Forms\Components\Select::make('machine_id')
                            ->label('Work Center')
                            // ->relationship('machine', 'name')
                            ->reactive()
                            ->searchable()
                            ->options(function (callable $get) {
                                $plantId = $get('plant_id');
                                if (! $plantId) {
                                    return [];
                                }

                                return Machine::where('plant_id', $plantId)->pluck('work_center', 'id');
                            })
                            ->required()
                            ->default(function () {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? null : optional(RequestCharacteristic::latest()->first())->machine_id ?? null;
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('item_id', null);
                                $set('aufnr', null);
                                $set('machine_name', null);
                                $set('characteristic_approver_master_id', null);
                                $set('approver_type', null);
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->disabled(fn ($get) => self::isFieldDisabled($get)),
                        Forms\Components\Hidden::make('show_validation_image')
                                ->reactive()
                                ->default(false),
                        Forms\Components\Hidden::make('validation1_image_url')
                            ->reactive(),

                        Forms\Components\View::make('components.part-validation-error-icon')
                            ->statePath('validation1_image_url')
                            ->visible(fn ($get) => $get('show_validation_image') == true)
                            ->reactive(),
                        Forms\Components\TextInput::make('work_flow_id')
                            ->label('Work Flow ID')
                            ->readOnly()
                            ->reactive()
                            ->required()
                            ->default(function ($state, callable $set, callable $get) {
                                $updRec = $get('id');
                                if (! $updRec) {
                                    return self::isNewWorkFlow($get);
                                }
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->suffixAction(
                                Forms\Components\Actions\Action::make('toggleValidationImage')
                                    ->icon(fn (callable $get) => $get('show_validation_image') ? 'heroicon-o-eye-slash' : 'heroicon-o-eye')
                                    ->tooltip('View Validation Image')
                                    ->action(function (callable $get, $set) {

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

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

                                        $workFlowId = $get('work_flow_id');

                                        if (!$workFlowId) {
                                            Notification::make()
                                                ->title('Missing Workflow ID')
                                                ->body('Please select a Workflow ID.')
                                                ->danger()
                                                ->send();
                                            return;
                                        }

                                        // Build filename
                                        $fileName = "{$workFlowId}.png";

                                        $imageUrl = route('workflow.image', [
                                            'filename' => $fileName,
                                        ]);

                                        $set('validation1_image_url', $imageUrl);
                                    })
                            ),
                        // ->rule(function (callable $get) {
                        //     return Rule::unique('request_characteristics', 'work_flow_id')
                        //         ->where('plant_id', $get('plant_id'))
                        //         ->ignore($get('id'));
                        // }),
                        Forms\Components\Select::make('item_id')
                            ->label('Item Code')
                            // ->relationship('item', 'id')
                            ->reactive()
                            ->required()
                            ->searchable()
                            ->options(function (callable $get) {
                                $plantId = $get('plant_id');
                                if (! $plantId) {
                                    return [];
                                }

                                return Item::where('plant_id', $plantId)->pluck('code', 'id');
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                if (! $state) {
                                    $set('aufnr', null);
                                }
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->default(function () {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? null : optional(RequestCharacteristic::latest()->first())->item_id ?? null;
                            })
                            ->disabled(fn ($get) => self::isFieldDisabled($get)),
                        Forms\Components\TextInput::make('aufnr')
                            ->label('Job Number')
                            ->reactive()
                            ->numeric()
                            ->minlength(7)
                            ->maxlength(10)
                            ->required(function (callable $get) {
                                $item = $get('item_id');
                                if ($item) {
                                    return true;
                                }

                                return false;
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->default(function () {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? null : optional(RequestCharacteristic::latest()->first())->aufnr ?? null;
                            })
                            ->readOnly(fn ($get) => ($get('item_id') == null))
                            ->disabled(fn ($get) => self::isFieldDisabled($get)),
                        Forms\Components\Select::make('machine_name')
                            ->label('Machine Name')
                            ->reactive()
                            ->nullable()
                            ->searchable()
                            ->options(function (callable $set, callable $get) {
                                $plantId = $get('plant_id');
                                $machineId = $get('machine_id');

                                if (! $plantId || ! $machineId) {
                                    $set('characteristic_name', null);
                                    $set('current_value', null);
                                    $set('update_value', null);

                                    return [];
                                }

                                return CharacteristicApproverMaster::where('plant_id', $plantId)->where('machine_id', $machineId)->pluck('machine_name', 'machine_name')->unique();
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('approver_type', null); // dd($get('characteristic_approver_master_id'));
                                $set('characteristic_approver_master_id', null);
                                $set('characteristic_name', null);
                                $set('current_value', null);
                                $set('update_value', null);
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->default(function () {
                                $machineName = '';
                                $reqId = RequestCharacteristic::latest()->first()?->characteristic_approver_master_id;
                                if ($reqId) {
                                    $reqMac = CharacteristicApproverMaster::where('id', $reqId)->first()?->machine_name;
                                    $machineName = $reqMac ?? null;
                                } else {
                                    $machineName = null;
                                }

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

                                return ($userHas && strlen($userHas) > 0) ? null : $machineName ?? null;
                            })
                            ->afterStateHydrated(function ($component, $state, Get $get, Set $set) {
                                if ($get('id')) {
                                    $reqId = RequestCharacteristic::where('id', $get('id'))->first()?->characteristic_approver_master_id;
                                    if ($reqId) {
                                        $reqMac = CharacteristicApproverMaster::where('id', $reqId)->first()?->machine_name;
                                        $set('machine_name', $reqMac ?? null);
                                    } else {
                                        $set('machine_name', null);
                                    }
                                }
                            })
                            ->required(),
                        Forms\Components\Select::make('approver_type')
                            ->label('Request Type')
                            // ->columnSpan(1)
                            ->reactive()
                            ->nullable()
                            ->searchable()
                            ->required()
                            ->options(function (callable $set, callable $get) {
                                $plantId = $get('plant_id');
                                $machineId = $get('machine_id');
                                $machineName = $get('machine_name');

                                if (! $plantId || ! $machineId || ! $machineName) {
                                    $set('characteristic_name', null);
                                    $set('current_value', null);
                                    $set('update_value', null);

                                    return [];
                                }

                                return [
                                    'Characteristic' => 'Characteristic',
                                    'Quality' => 'Quality',
                                ];
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('characteristic_approver_master_id', null);
                                if ($get('approver_type') != 'Characteristic') {
                                    $set('characteristic_name', null);
                                    $set('current_value', null);
                                    $set('update_value', null);
                                }
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->default(function () {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? null : 'Characteristic';
                                // $approverType = null;
                                // $reqId = RequestCharacteristic::latest()->first()?->characteristic_approver_master_id;
                                // if ($reqId) {
                                //     $reqTyp = CharacteristicApproverMaster::where('id', $reqId)->first()?->approver_type;
                                //     $approverType = $reqTyp ?? null;
                                // } else {
                                //     $approverType = null;
                                // }

                                // // return optional(CharacteristicApproverMaster::latest()->first())->approver_type ?? null;
                                // return $approverType ?? null;
                            })
                            ->afterStateHydrated(function ($component, $state, Get $get, Set $set) {
                                if ($get('id')) {
                                    $reqId = RequestCharacteristic::where('id', $get('id'))->first()?->characteristic_approver_master_id;
                                    if ($reqId) {
                                        $reqTyp = CharacteristicApproverMaster::where('id', $reqId)->first()?->approver_type;
                                        $set('approver_type', $reqTyp ?? null);
                                    } else {
                                        $set('approver_type', null);
                                    }
                                }
                            }),
                        Forms\Components\Select::make('characteristic_approver_master_id')
                            ->label('Master Characteristic Field')
                            // ->relationship('characteristicApproverMaster', 'characteristic_field')
                            // ->columnSpan(2)
                            ->reactive()
                            ->nullable()
                            ->searchable()
                            ->options(function (callable $set, callable $get) {
                                $plantId = $get('plant_id');
                                $machineId = $get('machine_id');
                                $machineName = $get('machine_name');
                                $reqTyp = $get('approver_type');

                                if (! $plantId || ! $machineId || ! $machineName || ! $reqTyp) {
                                    return [];
                                }

                                return CharacteristicApproverMaster::where('plant_id', $plantId)->where('machine_id', $machineId)->where('machine_name', $machineName)->where('approver_type', $reqTyp)->pluck('characteristic_field', 'id');
                            })
                            ->default(function () {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? null : optional(RequestCharacteristic::latest()->first())->characteristic_approver_master_id ?? null;
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('characteristic_name', null);
                                $set('current_value', null);
                                $set('update_value', null);
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->required(),
                        Forms\Components\TextInput::make('model_type')
                            ->label('Model Type')
                            ->reactive()
                            ->nullable()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('characteristic_name', null);
                                $set('current_value', null);
                                $set('update_value', null);
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->required(),
                        // ->disabled(fn ($get) => self::isFieldDisabled($get))
                        Section::make('Request Characteristic Details')
                            // ->columnSpan(['default' => 2, 'sm' => 4])
                            ->reactive()
                            ->schema([
                                Forms\Components\TextInput::make('characteristic_name')
                                    ->label('Characteristic Name')
                                    ->reactive()
                                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                        $set('characteristic_name', strtoupper($state));
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    })
                                    ->required(function (callable $get) {
                                        $reqTyp = $get('approver_type');
                                        if ($reqTyp == 'Characteristic') {
                                            return true;
                                        }

                                        return false;
                                    })
                                    ->rules([
                                        // function (callable $get) {
                                        //     return Rule::unique('request_characteristics', 'characteristic_name')
                                        //         ->where('plant_id', $get('plant_id'))
                                        //         ->where('machine_id', $get('machine_id'))
                                        //         ->where('machine_name', $get('machine_name'))
                                        //         ->ignore($get('id'));
                                        // },
                                        function (callable $get): Closure {
                                            return function (string $attribute, $value, Closure $fail) use ($get) {
                                                $charVal = strtolower($value);
                                                $columns = Schema::getColumnListing('class_characteristics');

                                                if (! in_array($charVal, $columns, true)) {
                                                    $fail('Unknown characteristic field found.'); // .implode(', ', $columns).
                                                } else {

                                                    $plantId = $get('plant_id');
                                                    $jobNo = $get('aufnr');
                                                    $updId = $get('id');
                                                    $pendingExists = RequestCharacteristic::where('plant_id', $plantId)->where('aufnr', $jobNo)->where('characteristic_name', $value)->latest()->first();

                                                    if ($pendingExists) {
                                                        if ($updId && $pendingExists->id == $updId) {
                                                            return;
                                                        }
                                                        $app1 = $pendingExists->approver_status1 ?? null;
                                                        $app2 = $pendingExists->approver_status2 ?? null;
                                                        $app3 = $pendingExists->approver_status3 ?? null;

                                                        if ($app1 != 'Rejected' && $app2 != 'Rejected' && $app3 != 'Rejected' && $app1 != 'Approved' && $app2 != 'Approved' && $app3 != 'Approved') {
                                                            $fail('Approval is already pending.');
                                                        }
                                                    }
                                                }
                                            };
                                        },
                                    ])
                                    ->readOnly(fn ($get) => ($get('approver_type') != 'Characteristic') ?? self::isFieldDisabled($get)),
                                Forms\Components\TextInput::make('current_value')
                                    ->label('Current Value')
                                    ->reactive()
                                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    })
                                    ->required(function (callable $get) {
                                        $reqTyp = $get('approver_type');
                                        $updateVal = $get('update_value');
                                        if ($reqTyp == 'Characteristic' && ($updateVal == null || $updateVal == '')) {
                                            return true;
                                        }

                                        return false;
                                    })
                                    ->readOnly(fn ($get) => ($get('approver_type') != 'Characteristic') ?? self::isFieldDisabled($get)),
                                Forms\Components\TextInput::make('update_value')
                                    ->label('Update Value')
                                    ->reactive()
                                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    })
                                    ->rules([
                                        function (callable $get): Closure {
                                            return function (string $attribute, $value, Closure $fail) use ($get) {
                                                $currVal = $get('current_value');

                                                if ($value == $currVal) {
                                                    $fail('Update value must be different from current value.');
                                                }
                                            };
                                        },
                                    ])
                                    ->readOnly(fn ($get) => ($get('approver_type') != 'Characteristic') ?? self::isFieldDisabled($get)),
                            ])
                            // ->collapsed(function ($get): bool {
                            //     $reqTyp = $get('approver_type');
                            //     if ($reqTyp == 'Characteristic') {
                            //         return true;
                            //     }

                            //     return false;
                            // })
                            ->collapsed()
                            ->columns(['default' => 1, 'sm' => 3]),
                        Section::make(function ($get): string {
                            $approverId = $get('characteristic_approver_master_id');
                            $approverName = $approverId ? CharacteristicApproverMaster::find($approverId)?->name1 : null;

                            return 'Approver - 1'.($approverName ? " ( {$approverName} )" : '');
                        })
                            ->reactive()
                            // ->description(fn (Get $get) => CharacteristicApproverMaster::find($get('characteristic_approver_master_id'))?->name1 ?? 'Select approver above'
                            // )
                            ->schema([
                                Forms\Components\Select::make('approver_status1')
                                    ->label('Approver Status')
                                    ->reactive()
                                    // ->live()
                                    ->options([
                                        'Approved' => 'Approved',
                                        'Hold' => 'Hold',
                                        'Rejected' => 'Rejected',
                                    ])
                                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                        if ($state) {// && empty($get('approved1_at'))
                                            $set('approved1_at', now()->toDateTimeString()); // now()->format('d-m-Y H:i:s')
                                        } else {
                                            $set('approved1_at', null);
                                        }
                                        $set('approver_remark1', null);
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    })
                                    ->disabled(function ($get) {
                                        $currentUser = Filament::auth()->user();
                                        $approverId = $get('characteristic_approver_master_id');

                                        if (! $approverId) {
                                            return true;
                                        }

                                        if (str_contains($approverId, '_')) {
                                            [$approverId, $level] = explode('_', $approverId);
                                        }

                                        $approver = CharacteristicApproverMaster::find($approverId);
                                        if (! $approver) {
                                            return true;
                                        }

                                        // Super Admin can edit any
                                        if ($currentUser && $currentUser->hasRole('Super Admin')) {
                                            return false; // field enabled
                                        }

                                        // Otherwise, enable only if the user's name matches
                                        return $approver->name1 != $currentUser?->name;
                                    }),
                                Forms\Components\TextInput::make('approver_remark1')
                                    ->label('Approver Remark')
                                    ->live()
                                    ->maxLength(60)
                                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                        $appStat = $get('approver_status1');
                                        if ($appStat && $state) {
                                            $set('approved1_at', now()->toDateTimeString()); // now()->format('d-m-Y H:i:s')
                                        } else {
                                            $set('approved1_at', null);
                                        }
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    })
                                    ->readOnly(fn ($get) => ($get('approver_status1') == null))
                                    ->disabled(function ($get) {
                                        $currentUser = Filament::auth()->user();
                                        $updId = $get('id');

                                        if (! $updId) {
                                            return true;
                                        } elseif ($currentUser && $currentUser->hasRole('Super Admin')) {
                                            return false;
                                        } else {
                                            return true;
                                        }
                                    }),
                                Forms\Components\DateTimePicker::make('approved1_at')
                                    // ->label('Approved At')
                                    ->label(fn (callable $get): string => match ($get('approver_status1')) {
                                        'Approved' => 'Approved At',
                                        'Hold' => 'Hold At',
                                        'Rejected' => 'Rejected At',
                                        default => 'Updated At',
                                    })
                                    ->reactive()
                                    // ->live()
                                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    })
                                    // ->format('d-m-Y H:i:s')
                                    ->readOnly(fn ($get) => ($get('approver_status1') == null))
                                    ->disabled(function ($get) {
                                        $currentUser = Filament::auth()->user(); // logged-in user
                                        $approverId = $get('characteristic_approver_master_id');

                                        if (! $approverId) {
                                            return true;
                                        }

                                        if (str_contains($approverId, '_')) {
                                            [$approverId, $level] = explode('_', $approverId);
                                        }

                                        $approver = CharacteristicApproverMaster::find($approverId);
                                        if (! $approver) {
                                            return true;
                                        }
                                        if ($currentUser && $currentUser->hasRole('Super Admin')) {
                                            return false;
                                        }

                                        return $approver->name1 != $currentUser?->name;
                                    }),
                            ])
                            ->collapsed()// collapsible()
                            ->columns(['default' => 1, 'sm' => 3]),
                        Section::make(function ($get): string {
                            $approverId = $get('characteristic_approver_master_id');
                            $approverName = $approverId ? CharacteristicApproverMaster::find($approverId)?->name2 : null;

                            return 'Approver - 2'.($approverName ? " ( {$approverName} )" : '');
                        })
                            ->reactive()
                            ->schema([
                                Forms\Components\Select::make('approver_status2')
                                    ->label('Approver Status')
                                    ->reactive()
                                    ->options([
                                        'Approved' => 'Approved',
                                        'Hold' => 'Hold',
                                        'Rejected' => 'Rejected',
                                    ])
                                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                        if ($state) {
                                            $set('approved2_at', now()->toDateTimeString());
                                        } else {
                                            $set('approved2_at', null);
                                        }
                                        $set('approver_remark2', null);
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    })
                                    ->disabled(function ($get) {
                                        $currentUser = Filament::auth()->user(); // get the User object
                                        $approverId = $get('characteristic_approver_master_id');

                                        if (! $approverId) {
                                            return true;
                                        }

                                        if (str_contains($approverId, '_')) {
                                            [$approverId, $level] = explode('_', $approverId);
                                        }

                                        $approver = CharacteristicApproverMaster::find($approverId);
                                        if (! $approver) {
                                            return true;
                                        }

                                        // Super Admin can always edit
                                        if ($currentUser && $currentUser->hasRole('Super Admin')) {
                                            return false; // ENABLE field
                                        }

                                        // Otherwise, enable only if the user's name matches
                                        return $approver->name2 != $currentUser?->name;
                                    }),
                                Forms\Components\TextInput::make('approver_remark2')
                                    ->label('Approver Remark')
                                    ->live()
                                    ->maxLength(60)
                                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                        $appStat = $get('approver_status2');
                                        if ($appStat && $state) {
                                            $set('approved2_at', now()->toDateTimeString());
                                        } else {
                                            $set('approved2_at', null);
                                        }
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    })
                                    ->readOnly(fn ($get) => ($get('approver_status2') == null))
                                    ->disabled(function ($get) {
                                        $currentUser = Filament::auth()->user();
                                        $updId = $get('id');

                                        if (! $updId) {
                                            return true;
                                        } elseif ($currentUser && $currentUser->hasRole('Super Admin')) {
                                            return false;
                                        } else {
                                            return true;
                                        }
                                    }),
                                Forms\Components\DateTimePicker::make('approved2_at')
                                    ->label(fn (callable $get): string => match ($get('approver_status2')) {
                                        'Approved' => 'Approved At',
                                        'Hold' => 'Hold At',
                                        'Rejected' => 'Rejected At',
                                        default => 'Updated At',
                                    })
                                    ->reactive()
                                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    })
                                    ->readOnly(fn ($get) => ($get('approver_status2') == null))
                                    ->disabled(function ($get) {
                                        $currentUser = Filament::auth()->user(); // logged-in user
                                        $approverId = $get('characteristic_approver_master_id');

                                        if (! $approverId) {
                                            return true;
                                        }

                                        if (str_contains($approverId, '_')) {
                                            [$approverId, $level] = explode('_', $approverId);
                                        }

                                        $approver = CharacteristicApproverMaster::find($approverId);
                                        if (! $approver) {
                                            return true;
                                        }
                                        if ($currentUser && $currentUser->hasRole('Super Admin')) {
                                            return false;
                                        }

                                        return $approver->name2 != $currentUser?->name;
                                    }),
                                // ->dehydrated(true),
                            ])
                            ->collapsed()// collapsible()
                            ->columns(['default' => 1, 'sm' => 3]),
                        Section::make(function ($get): string {
                            $approverId = $get('characteristic_approver_master_id');
                            $approverName = $approverId ? CharacteristicApproverMaster::find($approverId)?->name3 : null;

                            return 'Approver - 3'.($approverName ? " ( {$approverName} )" : '');
                        })
                            ->reactive()
                            ->schema([
                                Forms\Components\Select::make('approver_status3')
                                    ->label('Approver Status')
                                    ->reactive()
                                    ->options([
                                        'Approved' => 'Approved',
                                        'Hold' => 'Hold',
                                        'Rejected' => 'Rejected',
                                    ])
                                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                        if ($state) {
                                            $set('approved3_at', now()->toDateTimeString());
                                        } else {
                                            $set('approved3_at', null);
                                        }
                                        $set('approver_remark3', null);
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    })
                                    ->disabled(function ($get) {
                                        $currentUser = Filament::auth()->user();
                                        $approverId = $get('characteristic_approver_master_id');

                                        if (! $approverId) {
                                            return true;
                                        }

                                        if (str_contains($approverId, '_')) {
                                            [$approverId, $level] = explode('_', $approverId);
                                        }

                                        $approver = CharacteristicApproverMaster::find($approverId);
                                        if (! $approver) {
                                            return true;
                                        }

                                        if ($currentUser->hasRole('Super Admin')) {
                                            return false;
                                        } else {
                                            return $approver->name3 != $currentUser?->name;
                                        }

                                    }),
                                Forms\Components\TextInput::make('approver_remark3')
                                    ->label('Approver Remark')
                                    ->live()
                                    ->maxLength(60)
                                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                        $appStat = $get('approver_status3');
                                        if ($appStat && $state) {
                                            $set('approved3_at', now()->toDateTimeString());
                                        } else {
                                            $set('approved3_at', null);
                                        }
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    })
                                    ->readOnly(fn ($get) => ($get('approver_status3') == null))
                                    ->disabled(function ($get) {
                                        $currentUser = Filament::auth()->user();
                                        $updId = $get('id');

                                        if (! $updId) {
                                            return true;
                                        } elseif ($currentUser && $currentUser->hasRole('Super Admin')) {
                                            return false;
                                        } else {
                                            return true;
                                        }
                                    }),
                                Forms\Components\DateTimePicker::make('approved3_at')
                                    ->label(fn (callable $get): string => match ($get('approver_status3')) {
                                        'Approved' => 'Approved At',
                                        'Hold' => 'Hold At',
                                        'Rejected' => 'Rejected At',
                                        default => 'Updated At',
                                    })
                                    ->reactive()
                                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    })
                                    ->readOnly(fn ($get) => ($get('approver_status3') == null))
                                    ->disabled(function ($get) {
                                        $currentUser = Filament::auth()->user(); // logged-in user
                                        $approverId = $get('characteristic_approver_master_id');

                                        if (! $approverId) {
                                            return true;
                                        }

                                        if (str_contains($approverId, '_')) {
                                            [$approverId, $level] = explode('_', $approverId);
                                        }

                                        $approver = CharacteristicApproverMaster::find($approverId);
                                        if (! $approver) {
                                            return true;
                                        }
                                        if ($currentUser && $currentUser->hasRole('Super Admin')) {
                                            return false;
                                        }

                                        return $approver->name3 != $currentUser?->name;
                                    }),
                            ])
                            ->collapsed()// collapsible()
                            ->columns(['default' => 1, 'sm' => 3]),
                        Forms\Components\Hidden::make('created_by')
                            ->label('Created By')
                            ->default(Filament::auth()->user()?->name),
                        Forms\Components\Hidden::make('updated_by')
                            ->label('Updated By')
                            ->default(Filament::auth()->user()?->name),
                        Forms\Components\TextInput::make('id')
                            ->hidden()
                            ->readOnly(),
                    ])
                    ->columns(['default' => 1, 'sm' => 3]),
            ]);
    }

    protected static function isFieldDisabled($get): bool
    {
        $currentUser = Filament::auth()->user();
        $approverId = $get('characteristic_approver_master_id');

        if (! $approverId) {
            return false;
        }

        if (str_contains($approverId, '_')) {
            [$approverId, $level] = explode('_', $approverId);
        }

        $approver = CharacteristicApproverMaster::find($approverId);
        if (! $approver) {
            return false;
        }

        if ($currentUser && $currentUser->hasRole('Super Admin')) {
            return false;
        }

        $userName = $currentUser?->name;

        return in_array($userName, [
            $approver->name1,
            $approver->name2,
            $approver->name3,
        ]);
    }

    protected static function isNewWorkFlow($get): string
    {
        $year = now()->format('y');
        $month = now()->format('m');
        $date = now()->format('d');
        $prefix = "WF-{$year}{$month}{$date}-";

        $lastWorkflow = RequestCharacteristic::where('work_flow_id', 'like', "{$prefix}%")
            // ->where('plant_id', $plantId)
            // ->where('machine_id', $MachineId)
            ->orderByDesc('work_flow_id')
            ->first();

        if ($lastWorkflow) {
            $lastSerial = substr($lastWorkflow->work_flow_id, strlen($prefix));
            $nextSerial = str_pad(
                intval($lastSerial) + 1,
                4,
                '0',
                STR_PAD_LEFT
            );
        } else {
            $nextSerial = '0001';
        }

        $workFlowId = "{$prefix}{$nextSerial}";

        return $workFlowId;
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                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('work_flow_id')
                    ->label('Work Flow ID')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(), // isIndividual: true
                Tables\Columns\TextColumn::make('plant.name')
                    ->label('Plant Name')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('machine.work_center')
                    ->label('Work Center')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.code')
                    ->label('Item Code')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('aufnr')
                    ->label('Job Number')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('characteristicApproverMaster.machine_name')
                    ->label('Machine Name')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('characteristicApproverMaster.approver_type')
                    ->label('Request Type')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('characteristicApproverMaster.characteristic_field')
                    ->label('Master Characteristic Field')
                    ->alignCenter()
                    ->searchable()
                    ->formatStateUsing(fn (string $state): string => strtoupper(__($state)))
                    ->extraAttributes(['class' => 'uppercase'])
                    ->sortable(),
                Tables\Columns\TextColumn::make('model_type')
                    ->label('Model Type')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('characteristic_name')
                    ->label('Characteristic Name')
                    ->default('-')
                    ->alignCenter()
                    ->searchable()
                    ->formatStateUsing(fn (string $state): string => strtoupper(__($state)))
                    ->extraAttributes(['class' => 'uppercase'])
                    ->sortable(),
                Tables\Columns\TextColumn::make('current_value')
                    ->label('Current Value')
                    ->default('-')
                    ->alignCenter()
                    ->searchable()
                    ->formatStateUsing(function ($record) {
                        return empty($record->characteristic_name) ? '-' : $record->current_value;
                    })
                    ->sortable(),
                Tables\Columns\TextColumn::make('update_value')
                    ->label('Update Value')
                    ->default('-')
                    ->alignCenter()
                    ->searchable()
                    ->formatStateUsing(function ($record) {
                        return empty($record->characteristic_name) ? '-' : $record->update_value;
                    })
                    ->sortable(),
                Tables\Columns\TextColumn::make('characteristicApproverMaster.name1')
                    ->label('Approver Name 1')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('approver_status1')
                    ->label('Approver Status 1')
                    ->color(fn (string $state): string => match ($state) {
                        'Approved' => 'success',
                        'Hold' => 'warning',
                        'Rejected' => 'danger',
                        default => 'gray',
                    })
                    ->alignCenter()
                    ->default('-')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('approver_remark1')
                    ->label('Approver Remark 1')
                    // ->color('success')
                    ->alignCenter()
                    ->default('-')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('approved1_at')
                    ->label('Approver At 1')
                    ->alignCenter()
                    ->dateTime()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('characteristicApproverMaster.name2')
                    ->label('Approver Name 2')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('approver_status2')
                    ->label('Approver Status 2')
                    ->color(fn (string $state): string => match ($state) {
                        'Approved' => 'success',
                        'Hold' => 'warning',
                        'Rejected' => 'danger',
                        default => 'gray',
                    })
                    ->alignCenter()
                    ->default('-')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('approver_remark2')
                    ->label('Approver Remark 2')
                    // ->color('success')
                    ->alignCenter()
                    ->default('-')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('approved2_at')
                    ->label('Approver At 2')
                    ->alignCenter()
                    ->dateTime()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('characteristicApproverMaster.name3')
                    ->label('Approver Name 3')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('approver_status3')
                    ->label('Approver Status 3')
                    ->color(fn (string $state): string => match ($state) {
                        'Approved' => 'success',
                        'Hold' => 'warning',
                        'Rejected' => 'danger',
                        default => 'gray',
                    })
                    ->alignCenter()
                    ->default('-')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('approver_remark3')
                    ->label('Approver Remark 3')
                    // ->color('success')
                    ->alignCenter()
                    ->default('-')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('approved3_at')
                    ->label('Approver At 3')
                    ->alignCenter()
                    ->dateTime()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('mail_status')
                    ->label('Mail Status')
                    ->default('-')
                    ->alignCenter()
                    ->searchable()
                    ->formatStateUsing(function ($state) {
                        if (! $state || $state == '' || $state == null) {
                            return '-';
                        }

                        return match ($state) {
                            'Sent' => 'Sent-M1',
                            'Sent-Mail2' => 'Sent-M2',
                            'Sent-Mail3' => 'Sent-M3',
                            default => '-',
                        };
                    })
                    ->sortable(),
                Tables\Columns\TextColumn::make('trigger_at')
                    ->label('Trigger At')
                    ->dateTime()
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->dateTime()
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->dateTime()
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_by')
                    ->label('Updated By')
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->dateTime()
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->searchPlaceholder('Search Work Flow ID')
            ->filters([
                Tables\Filters\TrashedFilter::make(),
                Filter::make('advanced_filters')
                    ->label('Advanced Filters')
                    ->form([
                        Select::make('Plant')
                            ->label('Search by Plant Name')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $userHas = Filament::auth()->user()->plant_id;

                                if ($userHas && strlen($userHas) > 0) {
                                    return Plant::where('id', $userHas)->pluck('name', 'id')->toArray();
                                } else {
                                    return Plant::whereHas('requestCharacteristics', 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();
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get): void {
                                $set('machine', null);
                                $set('item_id', null);
                                // $set('aufnr', null);
                            }),
                        Select::make('machine')
                            ->label('Search by Work Center')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');

                                if (empty($plantId)) {
                                    return [];
                                }

                                return Machine::whereHas('requestCharacteristics', function ($query) use ($plantId) {
                                    if ($plantId) {
                                        $query->where('plant_id', $plantId);
                                    }
                                })->pluck('work_center', 'id');
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get): void {
                                // $set('item_id', null);
                                // $set('aufnr', null);
                            }),
                        Select::make('item_id')
                            ->label('Search by Item Code')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');

                                if (empty($plantId)) {
                                    return [];
                                }

                                return Item::whereHas('requestCharacteristics', function ($query) use ($plantId) {
                                    if ($plantId) {
                                        $query->where('plant_id', $plantId);
                                    }
                                })->pluck('code', 'id');
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get): void {
                                // $set('aufnr', null);
                            }),
                        TextInput::make('aufnr')
                            ->label('Job Number')
                            ->placeholder('Enter Job Number')
                            ->numeric()
                            ->minlength(7)
                            ->maxlength(10),
                        TextInput::make('work_flow_id')
                            ->label('Work Flow ID')
                            ->placeholder('Enter Work Flow ID'),
                        TextInput::make('machine_name')
                            ->label('Machine Name')
                            ->placeholder('Enter Machine Name'),
                        Select::make('request_type')
                            ->label('Request Type')
                            ->options([
                                'Characteristic' => 'Characteristic',
                                'Quality' => 'Quality',
                            ])
                            ->placeholder('Select Request Type'),
                        TextInput::make('master_characteristic_field')
                            ->label('Master Characteristic Field')
                            ->placeholder('Enter Master Characteristic Field'),
                        TextInput::make('model_type')
                            ->label('Model Type')
                            ->placeholder('Enter Model Type'),
                        Select::make('approver_status')
                            ->label('Approver Status')
                            ->options([
                                'Approved' => 'Approved',
                                'Hold' => 'Hold',
                                'Rejected' => 'Rejected',
                            ])
                            ->placeholder('Select Status')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('approver_status1', null);
                                $set('approver_status2', null);
                                $set('approver_status3', null);
                            }),
                        Select::make('approver_status1')
                            ->label('Approver Status 1')
                            ->options([
                                'Approved' => 'Approved',
                                'Hold' => 'Hold',
                                'Rejected' => 'Rejected',
                            ])
                            ->placeholder('Select Status')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('approver_status2', null);
                                $set('approver_status3', null);
                            }),
                        Select::make('approver_status2')
                            ->label('Approver Status 2')
                            ->options([
                                'Approved' => 'Approved',
                                'Hold' => 'Hold',
                                'Rejected' => 'Rejected',
                            ])
                            ->placeholder('Select Status'),
                        Select::make('approver_status3')
                            ->label('Approver Status 3')
                            ->options([
                                'Approved' => 'Approved',
                                'Hold' => 'Hold',
                                'Rejected' => 'Rejected',
                            ])
                            ->placeholder('Select Status'),

                        DateTimePicker::make(name: 'created_from')
                            ->label('Created From')
                            ->placeholder('Select From DateTime')
                            ->reactive()
                            ->native(false),
                        DateTimePicker::make('created_to')
                            ->label('Created To')
                            ->placeholder('Select To DateTime')
                            ->reactive()
                            ->native(false),
                    ])
                    ->query(function ($query, array $data) {
                        // Hide all records initially if no filters are applied
                        if (empty($data['Plant']) && empty($data['machine']) && empty($data['item_id']) && empty($data['aufnr']) && empty($data['model_type']) && empty($data['work_flow_id']) && empty($data['machine_name']) && empty($data['request_type']) && empty($data['master_characteristic_field'])&& empty($data['approver_status1']) && empty($data['approver_status2']) && empty($data['approver_status3']) && empty($data['approver_status']) && empty($data['created_from']) && empty($data['created_to'])) {
                            return $query->whereRaw('1 = 0');
                        }

                        if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null
                            $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['machine'])) {
                            $query->where('machine_id', $data['machine']);
                        }

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

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

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

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

                        if (!empty($data['machine_name'])) {
                            $query->whereHas('characteristicApproverMaster', function ($q) use ($data) {
                                $q->where('characteristic_approver_masters.machine_name', '=', (string) $data['machine_name']);
                            });
                        }

                        if (!empty($data['request_type'])) {
                            $query->whereHas('characteristicApproverMaster', function ($q) use ($data) {
                                $q->where('characteristic_approver_masters.approver_type', '=', (string) $data['request_type']);
                            });
                        }

                        if (!empty($data['master_characteristic_field'])) {
                            $query->whereHas('characteristicApproverMaster', function ($q) use ($data) {
                                $q->where('characteristic_approver_masters.characteristic_field', '=', (string) $data['master_characteristic_field']);
                            });
                        }

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

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

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

                        if (!empty($data['approver_status'])) {

                            $status = $data['approver_status'];

                            $query->whereRaw("
                                CASE

                                    -- If status3 exists, it must be considered first
                                    WHEN approver_status3 IS NOT NULL AND approver_status3 != ''
                                        THEN approver_status3

                                    -- then status2 overrides only if status3 is empty
                                    WHEN approver_status2 IS NOT NULL AND approver_status2 != ''
                                        THEN approver_status2

                                    -- finally status1 only if both 2 and 3 are empty
                                    WHEN approver_status1 IS NOT NULL AND approver_status1 != ''
                                        THEN approver_status1

                                    ELSE NULL

                                END = ?
                            ", [$status]);

                        }

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

                        if (! empty($data['created_to'])) {
                            $query->where('created_at', '<=', $data['created_to']);
                        }
                    })
                    ->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['machine'])) {
                            $indicators[] = 'Work Center: '.Machine::where('id', $data['machine'])->value('work_center');
                        }

                        if (! empty($data['item_id'])) {
                            $indicators[] = 'Item Code: '.Item::where('id', $data['item_id'])->value('code');
                        }

                        if (! empty($data['aufnr'])) {
                            $indicators[] = 'Job No: '.$data['aufnr'];
                        }

                        if (! empty($data['model_type'])) {
                            $indicators[] = 'Model Type: '.$data['model_type'];
                        }

                        if (! empty($data['work_flow_id'])) {
                            $indicators[] = 'Work Flow ID: '.$data['work_flow_id'];
                        }

                        if (! empty($data['machine_name'])) {
                            $indicators[] = 'Machine Name: '.$data['machine_name'];
                        }

                        if (! empty($data['request_type'])) {
                            $indicators[] = 'Request Type: '.$data['request_type'];
                        }

                        if (! empty($data['master_characteristic_field'])) {
                            $indicators[] = 'Master Characteristic Field: '.$data['master_characteristic_field'];
                        }

                        if (! empty($data['approver_status'])) {
                            $indicators[] = 'Approver Status: '.$data['approver_status'];
                        }

                        if (! empty($data['approver_status1'])) {
                            $indicators[] = 'Approver Status 1: '.$data['approver_status1'];
                        }

                        if (! empty($data['approver_status2'])) {
                            $indicators[] = 'Approver Status 2: '.$data['approver_status2'];
                        }

                        if (! empty($data['approver_status3'])) {
                            $indicators[] = 'Approver Status 3: '.$data['approver_status3'];
                        }

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

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

                        return $indicators;
                    }),
            ])
            ->filtersFormMaxHeight('280px')
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                ]),
            ])
            ->headerActions([
                ImportAction::make()
                    ->label('Import Request Characteristics')
                    ->color('warning')
                    ->importer(RequestCharacteristicImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import request characteristic');
                    }),
                ExportAction::make()
                    ->label('Export Request Characteristics')
                    ->color('warning')
                    ->exporter(RequestCharacteristicExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export request characteristic');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListRequestCharacteristics::route('/'),
            'create' => Pages\CreateRequestCharacteristic::route('/create'),
            'view' => Pages\ViewRequestCharacteristic::route('/{record}'),
            'edit' => Pages\EditRequestCharacteristic::route('/{record}/edit'),
        ];
    }

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