<?php

namespace App\Filament\Pages;

use App\Filament\Widgets\GuardPatrolDayChart;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Pages\Page;
use Filament\Pages\Dashboard\Concerns\HasFiltersForm;
use Filament\Forms\Form;
use Filament\Forms\Components\Select;
use Illuminate\Support\Facades\Auth;

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

    protected static string $view = 'filament.pages.guard-patrol-day-count';

    protected static ?string $navigationGroup = 'Guard DashBoard';

    use HasFiltersForm;

    public function mount(): void
    {
        session()->forget(['selected_plant']);
        $this->filtersForm->fill([
            'plant' => null
        ]);
    }

    public function filtersForm(Form $form): Form
    {
       return $form
           ->statePath('filters')
           ->schema([
               Select::make('plant')
                    ->label('Select Plant')
                    // ->options(Plant::pluck('name', 'id'))
                    ->options(function (callable $get) {
                        $userHas = Filament::auth()->user()->plant_id;
                        return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                    })
                    ->reactive()
                    ->afterStateUpdated(function ($state) {
                        session(['selected_plant' => $state]);
                        $this->dispatch('patrolEntryChart');
                    }),
                ]);

    }


    public static function getNavigationLabel(): string
    {
        return 'Guard Patrol Day Count';
    }

    public function getHeading(): string
    {
        return 'Guard Patrol Day Chart';
    }

    public function getWidgets(): array
    {
        return [
            GuardPatrolDayChart::class,
        ];
    }

    public static function canAccess(): bool
    {
        return Auth::check() && Auth::user()->can('view guard patrol day count dashboard');
    }

}
