<?php

namespace App\Filament\Resources;

use App\Filament\Exports\VisitorEntryExporter;
use App\Filament\Imports\VisitorEntryImporter;
use App\Filament\Resources\VisitorEntryResource\Pages;
use App\Filament\Resources\VisitorEntryResource\RelationManagers;
use App\Models\VisitorEntry;
use App\Models\EmployeeMaster;
use App\Models\DealerVisitPlan;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Infolists\Infolist;
use Filament\Infolists\Components\ImageEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\Section;
use Carbon\Carbon;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Radio;

class VisitorEntryResource extends Resource
{
    protected static ?string $model = VisitorEntry::class;

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

    protected static ?string $navigationGroup = 'Gate Entry';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('register_id')
                    ->label('Register ID')
                    ->default(function () {

                        $datePart = Carbon::now()->format('ymd'); // 260527

                        $prefix = 'CRI' . $datePart . 'V';

                        // Get latest record for today
                        $lastRecord = VisitorEntry::where('register_id', 'like', $prefix . '%')
                            ->latest('id')
                            ->first();

                        if ($lastRecord) {
                            $lastNumber = (int) substr($lastRecord->register_id, -3);
                            $nextNumber = str_pad($lastNumber + 1, 3, '0', STR_PAD_LEFT);
                        } else {
                            $nextNumber = '001';
                        }

                        return $prefix . $nextNumber;
                    })
                    ->readOnly(),
                Forms\Components\Select::make('inter_unit')
                    ->label('Inter Unit Staff Code')
                    ->options(
                        EmployeeMaster::distinct()
                            ->orderBy('code')
                            ->get(['code', 'name'])
                            ->mapWithKeys(function ($employee) {
                                return [
                                    $employee->code => "{$employee->code} ({$employee->name})"
                                ];
                            })
                            // ->pluck('code', 'code')
                    )
                    ->searchable()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, $state) {

                        $code = $get('inter_unit');

                        if($code){
                            $employeeExist = EmployeeMaster::where('code', $code)->first();

                            $plantId = $employeeExist->plant_id;

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

                            if ($employeeExist) {
                                $set('name', $employeeExist->name);
                                $set('mobile_number', $employeeExist->mobile_number);
                                $set('company', $plant->name);
                                $set('type', 'InterUnitStaff');
                                $set('dealer', null);
                            } else {
                                $set('name', null);
                                $set('mobile_number', null);
                                $set('company', null);
                                $set('type', null);
                                $set('dealer', null);
                            }
                        }
                        else
                        {
                            $set('name', null);
                            $set('mobile_number', null);
                            $set('company', null);
                            $set('type', null);

                        }
                    }),
                Forms\Components\Select::make('dealer')
                    ->label('Dealer Visit')
                    ->options(
                        DealerVisitPlan::where('status', 'Planned')
                            ->whereDate('visit_plan_date', today())
                            ->select('organizer', 'company', 'name')
                            ->distinct()
                            ->orderBy('organizer')
                            ->get()
                            ->mapWithKeys(function ($dealer) {
                                $key = "{$dealer->organizer}|{$dealer->company}|{$dealer->name}";

                                return [
                                    $key => "{$dealer->organizer} ({$dealer->company}) ({$dealer->name})"
                                ];
                            })
                    )
                    ->searchable()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, $state) {

                        if(!$state){
                            $set('name', null);
                            $set('inter_unit', null);
                            $set('company', null);
                            $set('type', null);
                            $set('number_of_person', null);
                            $set('purpose_of_visit', null);
                            $set('department', null);
                            $set('employee_master_id', null);
                            return;
                        }

                        [$organizer, $company, $name] = explode('|', $state);


                        $dealer = DealerVisitPlan::where('organizer', $organizer)
                            ->where('company', $company)
                            ->where('name', $name)
                            ->where('status', 'Planned')
                            ->whereDate('visit_plan_date', today())
                            ->first();

                        if($dealer){

                            $organizerExist = DealerVisitPlan::where('organizer', $organizer)->where('name', $name)->where('company', $company)->latest()->first();

                            $empDepart = EmployeeMaster::where('id', $dealer->employee_master_id)->first();

                            if ($organizerExist) {
                                $set('name', $organizerExist->name);
                                $set('company', $organizerExist->company);
                                $set('number_of_person', $organizerExist->number_of_person);
                                $set('purpose_of_visit', $organizerExist->purpose_of_visit);
                                $set('type', 'Dealers');
                                $set('department', $empDepart->department);
                                $set('organizer', $organizerExist->organizer);
                                $set('inter_unit', null);
                                $set('mobile_number', $organizerExist->mobile_number);
                                $set('mode_of_travel', $organizerExist->mode_of_travel);
                            } else {
                                $set('name', null);
                                $set('mobile_number', null);
                                $set('inter_unit', null);
                                $set('company', null);
                                $set('type', null);
                                $set('number_of_person', null);
                                $set('purpose_of_visit', null);
                                $set('department', null);
                                // $set('employee_master_id', null);
                                $set('code', null);
                                $set('mode_of_travel', null);
                            }
                        }
                        else
                        {
                            $set('name', null);
                            $set('company', null);
                            $set('type', null);
                            $set('number_of_person', null);
                            $set('purpose_of_visit', null);
                            $set('mode_of_travel', null);
                            $set('mobile_number', null);

                        }
                    }),
                Forms\Components\TextInput::make('mobile_number')
                    ->label('Mobile Number')
                    ->length(10)
                    ->reactive()
                    ->extraInputAttributes([
                        'oninput' => 'this.value = this.value.replace(/[^0-9]/g, "").slice(0, 10)', // blocks non-numbers + limits to 10 chars
                        'maxlength' => 10,
                    ])
                    ->required()
                    ->readOnly(fn (callable $get) => filled($get('inter_unit')))
                    ->extraAttributes([
                        'id' => 'mobile_number_input',
                        'x-data' => '{ value: "" }',
                        'x-model' => 'value',
                        'wire:keydown.enter.prevent' => 'processMobile(value)',
                    ]),
                Forms\Components\TextInput::make('name')
                    ->label('Name')
                    ->required()
                    ->reactive()
                    ->readOnly(fn (callable $get) => filled($get('inter_unit')))
                    ->extraInputAttributes([
                        'oninput' => 'this.value = this.value.replace(/[^a-zA-Z\s]/g, "")',
                    ]),
                Forms\Components\TextInput::make('company')
                    ->label('Company')
                    ->readOnly(fn (callable $get) => filled($get('inter_unit')))
                    ->required(),
                Forms\Components\Select::make('type')
                    ->label('Type')
                    ->reactive()
                    ->options([
                        'Student' => 'Student',
                        'Consultant' => 'Consultant',
                        'Supplier' => 'Supplier',
                        'InterUnitStaff' => 'Inter Unit Staff',
                        'InterviewCandidates' => 'Interview Candidates',
                        'Customers' => 'Customers',
                        'Dealers' => 'Dealers',
                        'Bankers' => 'Bankers',
                        'ServiceProviders' => 'Service Providers',
                        'GovermentOfficials' => 'Government Officials',
                        'Other' => 'Other',
                    ])
                    ->required()
                    ->dehydrateStateUsing(function ($state, callable $get) {
                        return $state == 'Other'
                            ? $get('other_type')
                            : $state;
                    })
                    ->afterStateUpdated(function (callable $set, callable $get, $state) {

                        $code = $get('inter_unit');

                        if($code){
                            $set('inter_unit', null);
                            $set('name', null);
                            $set('mobile_number', null);
                            $set('company', null);
                        }
                    }),
                Forms\Components\TextInput::make('other_type')
                    ->label('Specify Type')
                    ->reactive()
                    ->visible(fn (callable $get) => $get('type') == 'Other')
                    ->required(fn (callable $get) => $get('type') == 'Other')
                    ->dehydrated(false),
                Forms\Components\Select::make('department')
                    ->label('Employee Department')
                    ->options(
                        EmployeeMaster::distinct()
                            ->orderBy('department')
                            ->pluck('department', 'department')
                    )
                    ->searchable()
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set) {
                        $set('employee_master_id', null);
                        $set('code', null);
                    }),
                // Forms\Components\Select::make('employee_master_id')
                //     ->label('Recipient Employee')
                //     ->required()
                //     ->options(function (callable $get) {
                //         $department = $get('department');

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

                //         return \App\Models\EmployeeMaster::where('department', $department)
                //             ->pluck('name', 'id');
                //     })
                //     ->reactive()
                //     ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                //         $department = $get('department');

                //         $employee = \App\Models\EmployeeMaster::where('id', $state)
                //             ->where('department', $department)
                //             ->first();

                //         $set('code', $employee ? $employee->code : '');
                //     }),

                Forms\Components\Select::make('employee_master_id')
                    ->label('Recipient Employee')
                    ->required()
                    ->searchable()
                    ->options(function (callable $get) {
                        $department = $get('department');

                        if (!$department) {
                            return [];
                        }

                        // Always load ALL employees, filter by department if set
                        if ($department) {
                            return EmployeeMaster::where('department', $department)
                                ->pluck('name', 'id');
                        }
                        // Fallback: load all so fill() can always match the ID
                        return EmployeeMaster::pluck('name', 'id');
                    })
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, ?string $state) {
                        $employee = EmployeeMaster::find($state);
                        $set('code', $employee?->code ?? '');
                    }),

                Forms\Components\TextInput::make('code')
                    ->label('Employee Code')
                    ->readOnly(),
                Forms\Components\Textarea::make('purpose_of_visit')
                    ->label('Purpose of Visit')
                    ->required(),
                Forms\Components\TextInput::make('number_of_person')
                    ->numeric()
                    ->default(1)
                    ->required(),
                Forms\Components\Select::make('mode_of_travel')
                    ->label('Mode of Travel')
                    ->options([
                        'Rental' => 'Rental',
                        'Car' => 'Car',
                        'Bike' => 'Bike',
                    ])
                    ->reactive()
                    ->placeholder('Select Mode of Travel'),
                Forms\Components\DateTimePicker::make('in_time')
                    ->label('In Time')
                    ->required()
                    ->default(now()),
                Forms\Components\DateTimePicker::make('out_time')
                    ->label('Out Time'),
                Forms\Components\DateTimePicker::make('valid_upto')
                    ->label('Valid Upto')
                    ->after('in_time')
                    ->validationMessages([
                        'after' => 'Valid Upto must be after the In Time.',
                    ]),
                Forms\Components\Hidden::make('organizer')
                    ->label('Organizer'),
                Forms\Components\View::make('components.webcam-field')
                    ->columnSpanFull(),
                Forms\Components\Hidden::make('photo'),
                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),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            // ->modifyQueryUsing(fn (Builder $query) => $query->whereDate('created_at', today()))
            ->columns([
                Tables\Columns\TextColumn::make('No.')
                    ->label('NO')
                    ->alignCenter()
                    ->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\ImageColumn::make('photo')
                    ->label('Photo')
                    ->disk('public')
                    ->height(50)
                    ->width(50)
                    // ->defaultImageUrl('https://ui-avatars.com/api/?name=Visitor&background=555&color=fff')
                    ->defaultImageUrl(asset('images/profile.png'))
                    ->alignCenter()
                    ->extraImgAttributes(['style' => 'border-radius: 6px; object-fit: cover;']),
                Tables\Columns\TextColumn::make('register_id')
                    ->label('Register ID')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('type')
                    ->label('Visitor Type')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('organizer')
                    ->label('Organizer')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('mobile_number')
                    ->label('Mobile Number')
                    ->alignCenter()
                    ->searchable()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('name')
                    ->label('Visitor Name')
                    ->sortable()
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('company')
                    ->label('Visitor Company')
                    ->sortable()
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('employeeMaster.plant.name')
                    ->label('Visited Plant')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('employeeMaster.name')
                    ->label('Recipient Name')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('employeeMaster.code')
                    ->label('Receipient ID')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('employeeMaster.department')
                    ->label('Receipient Department')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('number_of_person')
                    ->label('Number of Person')
                    ->numeric()
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('purpose_of_visit')
                    ->label('Purpose of Visit')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('mode_of_travel')
                    ->label('Mode of Travel')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('in_time')
                    ->label('In Time')
                    ->searchable()
                    ->dateTime()
                    ->sortable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('out_time')
                    ->label('Out Time')
                    ->searchable()
                    ->dateTime()
                    ->sortable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('valid_upto')
                    ->label('Valid Upto')
                    ->searchable()
                    ->dateTime()
                    ->sortable()
                    ->alignCenter()
                    ->color(fn ($record) => $record->valid_upto && \Carbon\Carbon::parse($record->valid_upto)->isPast()
                        ? 'danger'
                        : 'success'
                    ),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->alignCenter(),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
                Filter::make('advanced_filters')
                    ->label('Advanced Filters')
                    ->form([
                        TextInput::make('register_id')
                            ->label('Register ID')
                            ->reactive()
                            ->placeholder('Enter Register ID')
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('type', null);
                            }),
                        Select::make('type')
                            ->label('Type')
                            ->reactive()
                            ->options([
                                'Student' => 'Student',
                                'Consultant' => 'Consultant',
                                'Supplier' => 'Supplier',
                                'InterviewCandidates' => 'Interview Candidates',
                                'Customers/Dealers' => 'Customers/Dealers',
                                'Bankers' => 'Bankers',
                                'ServiceProviders' => 'Service Providers',
                                'GovermentOfficials' => 'Government Officials',
                                'Other' => 'Other',
                            ])
                            ->placeholder('Choose Type')
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('name', null);
                            }),
                        TextInput::make('other_type')
                            ->label('Specify Type')
                            ->placeholder('Enter Type')
                            ->visible(fn (callable $get) => $get('type') == 'Other')
                            ->required(fn (callable $get) => $get('type') == 'Other'),
                        TextInput::make('name')
                            ->label('Visitor Name')
                            ->reactive()
                            ->placeholder('Enter Visitor Name')
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('company', null);
                            }),
                        TextInput::make('company')
                            ->label('Visitor Company')
                            ->reactive()
                            ->placeholder('Enter Visitor Company')
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('employee_master_id', null);
                            }),
                        Select::make('employee_department')
                            ->label('Employee Department')
                            ->options(function () {
                                return EmployeeMaster::query()
                                    ->whereNotNull('department')
                                    ->distinct()
                                    ->orderBy('department')
                                    ->pluck('department', 'department')
                                    ->toArray();
                            })
                            ->searchable()
                            ->preload()
                            ->reactive()
                            ->placeholder('Select Department')
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('employee_master_id', null);
                            }),
                        Select::make('employee_master_id')
                            ->label('Employee Name')
                            ->relationship('employeeMaster', 'name')
                            ->searchable()
                            ->preload()
                            ->reactive()
                            ->placeholder('Select Employee')
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('Rework', null);
                            }),
                        DateTimePicker::make('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['register_id']) && empty($data['type']) && empty($data['name']) && empty($data['company']) && empty($data['employee_master_id']) && empty($data['created_from']) && empty($data['created_to'])) {
                        //     $query->where(function ($q) {
                        //     });
                        // }

                        $hasAnyFilter = !empty($data['register_id'])
                            || !empty($data['type'])
                            || !empty($data['name'])
                            || !empty($data['company'])
                            || !empty($data['employee_master_id'])
                            || !empty($data['employee_department'])
                            || !empty($data['created_from'])
                            || !empty($data['created_to']);

                        if (!$hasAnyFilter) {
                            // $query->whereDate('created_at', today());
                            $query->whereDate('visitor_entries.created_at', today())
                            ->whereNull('out_time');
                            return;
                        }

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

                        if (! empty($data['type'])) {
                            if ($data['type'] == 'Other') {
                                $query->where('type', 'like', '%'.$data['other_type'].'%');
                            }
                            else{
                                $query->where('type', $data['type']);
                            }
                        }

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

                        if (! empty($data['name'])) {
                            $query->whereRaw(
                                'LOWER(name) LIKE ?',
                                ['%' . strtolower($data['name']) . '%']
                            );
                        }

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

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

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

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

                        if (! empty($data['created_to'])) {
                            $query->where('created_at', '<=', $data['created_to']);
                        }
                        // $query->orderBy('created_at', 'asc');
                    })
                    ->indicateUsing(function (array $data) {
                        $indicators = [];

                        if (! empty($data['register_id'])) {
                            $indicators[] = 'Register ID: '.$data['register_id'];
                        }

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

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

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

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

                        if (! empty($data['employee_department'])) {
                            $indicators[] = 'Employee Department: '.$data['employee_department'];
                        }

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

                        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()
                    ->importer(VisitorEntryImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import visitor entries');
                    }),
                ExportAction::make()
                    ->exporter(VisitorEntryExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export visitor entries');
                    }),
            ]);
    }

    public static function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([

                // ── Visitor Photo (full width at the top) ──
                Section::make('Visitor Photo')
                    ->schema([
                        ImageEntry::make('photo')
                            ->label('')
                            ->disk('public')
                            ->height(220)
                            ->defaultImageUrl(asset('images/profile.png'))
                            ->extraImgAttributes([
                                'style' => 'border-radius: 10px; object-fit: cover;'
                            ]),
                    ])
                    ->columnSpanFull(),

                // ── Visitor Details ──
                Section::make('Visitor Details')
                    ->schema([
                        TextEntry::make('register_id')
                            ->label('Register ID'),
                        TextEntry::make('name')
                            ->label('Visitor Name'),
                        TextEntry::make('mobile_number')
                            ->label('Mobile Number'),
                        TextEntry::make('type')
                            ->label('Visitor Type')
                            ->badge()
                            ->color(fn (string $state): string => match ($state) {
                                'internal' => 'success',
                                'external' => 'warning',
                                default    => 'gray',
                            }),
                        TextEntry::make('company')
                            ->label('Company'),
                        TextEntry::make('purpose_of_visit')
                            ->label('Purpose of Visit')
                            ->columnSpanFull(),
                    ])
                    ->columns(2),

                // ── Employee Details ──
                Section::make('Recipient Details')
                    ->schema([
                        TextEntry::make('employeeMaster.name')
                            ->label('Recipient Employee'),
                        TextEntry::make('code')
                            ->label('Employee Code'),
                        TextEntry::make('employeeMaster.department')
                            ->label('Department'),
                        TextEntry::make('number_of_person')
                            ->label('Number of Persons'),
                    ])
                    ->columns(2),

                // ── Visit Timing ──
                Section::make('Visit Timing')
                    ->schema([
                        TextEntry::make('in_time')
                            ->label('In Time')
                            ->dateTime(),
                        TextEntry::make('out_time')
                            ->label('Out Time')
                            ->dateTime(),
                        TextEntry::make('valid_upto')
                            ->label('Valid Upto')
                            ->dateTime()
                            ->badge()
                            ->color(fn ($record) => $record->valid_upto && \Carbon\Carbon::parse($record->valid_upto)->isPast()
                                ? 'danger'
                                : 'success'
                            ),
                    ])
                    ->columns(2),

            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListVisitorEntries::route('/'),
            'create' => Pages\CreateVisitorEntry::route('/create'),
            'view' => Pages\ViewVisitorEntry::route('/{record}'),
            'edit' => Pages\EditVisitorEntry::route('/{record}/edit'),
        ];
    }

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

}
