<?php

namespace App\Filament\Resources;

use App\Filament\Resources\VentaResource\Pages;
use App\Filament\Resources\VentaResource\RelationManagers;
use App\Filament\Resources\VentaResource\RelationManagers\DetallesRelationManagerRelationManager;
use App\Models\Venta;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Actions\Action;
use Filament\Support\Enums\ActionSize;

class VentaResource extends Resource
{
    protected static ?string $model = Venta::class;
    protected static ?string $navigationGroup = 'Operación'; // 

    protected static ?string $navigationIcon = 'heroicon-o-shopping-cart';

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

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('cliente_id')
                    ->relationship('cliente', 'id'),
                Forms\Components\TextInput::make('total')
                    ->required()
                    ->numeric(),
                Forms\Components\TextInput::make('tipo_pago')
                    ->required(),
                Forms\Components\TextInput::make('estado')
                    ->required(),
            ]);
    }



    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('cliente.numero_documento')
                    ->label('Cliente')
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('total')
                    ->money('COP')
                    ->sortable(),
                Tables\Columns\TextColumn::make('tipo_pago')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'Efectivo' => 'success',
                        'Transferencia' => 'info',
                        default => 'gray',
                    }),
                Tables\Columns\TextColumn::make('estado')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'Pagado' => 'success',
                        'Pendiente' => 'warning',
                        'Cancelado' => 'danger',
                        default => 'gray',
                    }),
                Tables\Columns\TextColumn::make('bodegas_usadas')
                    ->label('Bodegas')
                    ->getStateUsing(function ($record) {
                        $bodegas = $record->detalles()
                            ->whereNotNull('bodega_id')
                            ->with('bodega')
                            ->get()
                            ->pluck('bodega.nombre')
                            ->unique()
                            ->filter()
                            ->values();
                        
                        if ($bodegas->isEmpty()) {
                            return 'Stock directo';
                        }
                        
                        return $bodegas->join(', ');
                    })
                    ->badge()
                    ->color('info')
                    ->tooltip('Bodegas de donde se descontó el stock'),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Fecha')
                    ->dateTime('d/m/Y H:i')
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
             ->paginated(true)
            //->paginationPageOptions([50])
            ->defaultSort('created_at', 'desc')
            ->actions([
                Tables\Actions\EditAction::make(),
                Action::make('recibo')
                    ->label('Recibo')
                    ->icon('heroicon-o-printer')
                    ->color('secondary')
                    ->url(fn($record) => route('imprimir-recibo', ['venta' => $record->id]))
                    ->openUrlInNewTab()
            ])
            
            
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }


    public static function getRelations(): array
    {
        return [
            DetallesRelationManagerRelationManager::class,
        ];
    }

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