<?php

namespace App\Filament\Pages;

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 InvoiceQuantityDashboard extends Page
{
    use HasFiltersForm;
    protected static ?string $navigationIcon = 'heroicon-o-document-text';

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

    protected static string $view = 'filament.pages.invoice-quantity-dashboard';


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


   public function filtersForm(Form $form): Form
    {
        return $form
            ->statePath('filters') // Explicitly set where to store form data
            ->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(['selec_plant' => $state]);
                        $this->dispatch('invoiceChart');
                    }),
                Select::make('invoice')
                    ->options([
                        'serial_invoice' => 'Serial Invoice',
                        'individual_material' => 'Individual Material Invoice',
                        'bundle_material' => 'Bundle Material Invoice',
                    ])
                    ->label('Select Invoice')
                    ->reactive()
                    ->default(0)
                    ->afterStateUpdated(function ($state) {
                        session(['select_invoice' => $state]);
                        $this->dispatch('invoiceChart');
                    })
            ])
            ->columns(2);
    }
    public static function getNavigationLabel(): string
    {
        return 'Invoice Quantity';
    }

    public static function canAccess(): bool
    {
        return Auth::check() && Auth::user()->can('view invoice serial quantity dashboard');
    }
}
