<?php

namespace App\Filament\Resources;

use App\Filament\Resources\OjalResource\Pages;
use App\Models\Ojal;
use Filament\Forms;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\DatePicker;

class OjalResource extends Resource
{
    protected static ?string $model = Ojal::class;
    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    protected static ?string $navigationGroup = 'Producción';
    protected static bool $shouldRegisterNavigation = false; // Ocultar del menú

    public static function canViewAny(): bool
    {
        return auth()->user()?->can('ver ojals') ?? false;
    }

    public static function form(Forms\Form $form): Forms\Form
    {
        return $form->schema([
            Select::make('proveedor_id')->relationship('proveedor', 'nombre', fn(\Illuminate\Database\Eloquent\Builder $q) => $q->where('categoria', 'ojal'))->searchable()->preload()->nullable(),
            Select::make('orden_produccion_id')->relationship('ordenProduccion', 'numero_orden')->searchable()->preload()->required(),
            DatePicker::make('fecha_envio')->default(now()),
            TextInput::make('cantidad_enviada')->numeric()->required()->minValue(1),
            DatePicker::make('fecha_recepcion'),
            TextInput::make('cantidad_recibida')->numeric()->nullable(),
            TextInput::make('perdidas')->numeric()->default(0),
        ]);
    }

    public static function table(Tables\Table $table): Tables\Table
    {
        return $table->columns([
            Tables\Columns\TextColumn::make('id')->label('#'),
            Tables\Columns\TextColumn::make('proveedor.nombre')->label('Proveedor'),
            Tables\Columns\TextColumn::make('ordenProduccion.numero_orden')->label('OP'),
            Tables\Columns\TextColumn::make('cantidad_enviada'),
            Tables\Columns\TextColumn::make('cantidad_recibida'),
            Tables\Columns\TextColumn::make('perdidas'),
            Tables\Columns\TextColumn::make('fecha_envio')->date(),
            Tables\Columns\TextColumn::make('fecha_recepcion')->date(),
        ])->defaultSort('created_at', 'desc');
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListOjales::route('/'),
            'create' => Pages\CreateOjal::route('/create'),
            'edit' => Pages\EditOjal::route('/{record}/edit'),
        ];
    }
}
