<?php

namespace App\Filament\Pages;

use App\Models\Plant;
use App\Models\VisitorEntry;
use Filament\Facades\Filament;
use Filament\Pages\Page;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Form;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;

class GateOutEntry extends Page implements HasForms
{
    protected static ?string $navigationIcon = 'heroicon-o-document-text';

    protected static string $view = 'filament.pages.gate-out-entry';

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


    public $pId, $invoiceNumber;

    public array $invoiceOverviewData = [];

    public array $filters = [];

    public function form(Form $form): Form
    {
        return $form
            ->statePath('filters')
            ->schema([
                Section::make('') // You can give your section a title or leave it blank
                    ->schema([
                        TextInput::make('scan_out_gate_pass')
                            ->label('Scan Out Gate Pass')
                            ->required()
                            ->reactive()
                            ->extraAttributes([
                                'wire:keydown.enter' => 'processGatePass($event.target.value)',
                            ]),
                    ])
                    ->columns(5)
            ]);
    }

    public function processGatePass($gatePass)
    {
        $entry = VisitorEntry::where('register_id', $gatePass)->first();

        if ($entry) {
            $entry->out_time = now();
            $entry->save();

            Notification::make()
                ->title('Gate Pass Processed')
                ->body('Gate pass has been successfully processed. Visitor marked as exited.')
                ->success()
                ->send();
            $this->filters['scan_out_gate_pass'] = '';
        } else {
            Notification::make()
                ->title('Invalid Gate Pass')
                ->body('The scanned gate pass is not valid. Please try again.')
                ->danger()
                ->send();
        }
    }

    public static function canAccess(): bool
    {
        return Auth::check() && Auth::user()->can('view gate entry page');
    }
}
