<?php

namespace App\Filament\Pages;

use App\Mail\VisitorOutMail;
use App\Models\EmployeeMaster;
use App\Models\Plant;
use App\Models\VisitorEntry;
use Carbon\Carbon;
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;
use App\Mail\VisitorMail;
use Illuminate\Support\Facades\Mail;

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([
                        Select::make('scan_out_gate_pass')
                            ->label('Scan Gate Pass')
                            ->required()
                            ->reactive()
                            ->options([
                                'In'  => 'In',
                                'Out' => 'Out',
                            ]),
                        TextInput::make('scan_out_gate_pass_in')
                            ->label('Scan In Gate Pass')
                            ->required()
                            ->reactive()
                            ->visible(fn ($get) => $get('scan_out_gate_pass') == 'In')
                            ->extraAttributes([
                                'wire:keydown.enter' => 'processGatePassIn($event.target.value)',
                            ]),
                        TextInput::make('scan_out_gate_pass_out')
                            ->label('Scan Out Gate Pass')
                            ->required()
                            ->reactive()
                            ->visible(fn ($get) => $get('scan_out_gate_pass') == 'Out')
                            ->extraAttributes([
                                'wire:keydown.enter' => 'processGatePassOut($event.target.value)',
                            ]),
                    ])
                    ->columns(5)
            ]);
    }

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

        if ($entry)
        {
            if($entry->in_time && !$entry->out_time && (empty($entry->valid_upto) || $entry->valid_upto == '' || $entry->valid_upto == null)){
                Notification::make()
                    ->title('Already Entered')
                    ->body('Gate pass In has already been processed for entry.')
                    ->warning()
                    ->send();
                $this->filters['scan_out_gate_pass_in'] = '';
                return;
            }
            elseif (
                !empty($entry->valid_upto) &&
                Carbon::parse($entry->valid_upto)->endOfDay()->gte(now())
            ){
                if (empty($entry->out_time)) {
                    Notification::make()
                        ->title('Gate In Not Allowed')
                        ->body("Previous gate-out has not been punched. Please complete gate-out first for ID ' . $gatePass . '.")
                        ->warning()
                        ->send();

                    $this->filters['scan_out_gate_pass_in'] = '';
                    return;
                }
                else{
                    $newEntry = $entry->replicate();
                    $newEntry->in_time = now();
                    $newEntry->out_time = null;

                    $newEntry->save();

                    Notification::make()
                        ->title('Gate In')
                        ->body('Gate in has been successfully processed. Visitor marked as entered.')
                        ->success()
                        ->send();
                    $this->filters['scan_out_gate_pass_in'] = '';
                }
            }
            else{
                Notification::make()
                    ->title('Visitor Pass Expired')
                    ->body('Your visitor pass validity has expired.')
                    ->danger()
                    ->send();
                $this->filters['scan_out_gate_pass_in'] = '';
                return;
            }
        }
        else
        {
            Notification::make()
                ->title('Invalid Gate Pass')
                ->body('Scanned gate in pass is not valid.')
                ->danger()
                ->send();
                return;
        }
    }

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

        if (!$entry) {
            Notification::make()
                ->title('Invalid Gate Pass')
                ->body('Scanned gate out pass is not valid.')
                ->danger()
                ->send();
            $this->filters['scan_out_gate_pass_out'] = '';
            return;
        }

        if (empty($entry->valid_upto) || $entry->valid_upto == '' || $entry->valid_upto == null) {

            if (!empty($entry->out_time)) {
                Notification::make()
                    ->title('Already Exited')
                    ->body('Gate pass has already been processed.')
                    ->warning()
                    ->send();
                    $this->filters['scan_out_gate_pass_out'] = '';
                    return;
            }
            else
            {
                $entry->out_time = now();
                $entry->save();

                $employee = EmployeeMaster::find($entry->employee_master_id);

                if ($employee && !empty($employee->email)) {
                    Mail::to($employee->email)
                        ->send(new VisitorOutMail($entry)); // or ->send()
                }
                else{
                    \Log::warning('No email found for employee ID: ' . $entry->employee_master_id);
                }

                Notification::make()
                    ->title('Gate Pass Processed')
                    ->body('Visitor marked as exited.')
                    ->success()
                    ->send();

                $this->filters['scan_out_gate_pass_out'] = '';
                return;
            }
        }
        elseif ((empty($entry->valid_upto) || $entry->valid_upto != '' || $entry->valid_upto != null))
        {
            if (Carbon::parse($entry->valid_upto)->endOfDay()->lt(now()))
            {
                Notification::make()
                    ->title('Visitor Pass Expired')
                    ->body('Your visitor pass validity has expired.')
                    ->danger()
                    ->send();
                $this->filters['scan_out_gate_pass_out'] = '';
                return;
            }
            if (!empty($entry->out_time)) {
                Notification::make()
                    ->title('Already Exited')
                    ->body('Gate pass has already been processed.')
                    ->warning()
                    ->send();
                    $this->filters['scan_out_gate_pass_out'] = '';
                    return;
            }
            else{
                $entry->out_time = now();
                $entry->save();

                Notification::make()
                    ->title('Gate Out')
                    ->body('Visitor marked as exited.')
                    ->success()
                    ->send();
                $this->filters['scan_out_gate_pass_out'] = '';
            }
        }
    }

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