<?php

namespace App\Filament\Resources;

use Filament\Forms;
use Filament\Tables;
use Filament\Forms\Form;
use Filament\Tables\Table;
use Filament\Resources\Resource;
use Spatie\Permission\Models\Role;
use Illuminate\Database\Eloquent\Builder;
use App\Filament\Resources\RoleResource\Pages;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use App\Filament\Resources\RoleResource\RelationManagers;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Columns\TextColumn;
use Illuminate\Database\Eloquent\Model;
use Filament\Tables\Actions\EditAction;
use Filament\Tables\Actions\DeleteAction;
use Filament\Tables\Actions\BulkActionGroup;
use Filament\Tables\Actions\DeleteBulkAction;
use Illuminate\Support\Str;

use Spatie\Permission\Models\Permission;
use Filament\Forms\Components\Fieldset;
use Filament\Forms\Components\CheckboxList;


use App\Models\Rol;




class RoleResource extends Resource
{
    protected static ?string $model = Role::class;

    protected static ?string $navigationIcon = 'heroicon-o-shield-check'; // ícono opcional
    protected static ?int $navigationSort = 2;


    public static function canViewAny(): bool   { return self::check('role.view'); }
    public static function canCreate(): bool    { return self::check('role.create'); }
    public static function canEdit(Model $r): bool  { return self::check('role.update'); }
    public static function canDelete(Model $r): bool { return self::check('role.delete'); }


   public static function form(Form $form): Form
    {
        $permissions = Permission::all()->groupBy(function ($permission) {
            return Str::before($permission->name, '.');
        });

        $fieldsetComponents = [];

        foreach ($permissions as $group => $perms) {
            $fieldsetComponents[] = Fieldset::make(Str::ucfirst($group))
                ->schema([
                    CheckboxList::make("permissions_{$group}")
                        ->label(false)
                        ->options(
                            $perms->mapWithKeys(function ($perm) {
                                $translated = __('permissions.' . $perm->name);
                                return [$perm->id => $translated];
                            })->toArray()
                        )
                        ->columns(2)
                        ->bulkToggleable(),
                ]);
        }

        return $form->schema([
            Forms\Components\TextInput::make('name')
                ->label('Nombre del Rol')
                ->required()
                ->unique(ignoreRecord: true),
            ...$fieldsetComponents
        ]);
    }


    public static function table(Table $table): Table
    {
        return $table

             ->columns([
            Tables\Columns\TextColumn::make('name')->label('Rol'),
            Tables\Columns\TextColumn::make('permissions.name')
                ->label('Permisos')
                ->badge()
                ->limit(4),
        ])
            ->filters([
                //
            ])
              ->actions([
                Tables\Actions\EditAction::make()
                    ->visible(fn () => auth()->user()?->can('role.update')),

                Tables\Actions\DeleteAction::make()
                    ->visible(fn () => auth()->user()?->can('role.delete')),

            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()->visible(fn () => auth()->user()?->can('role.delete')),

                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListRoles::route('/'),
            'create' => Pages\CreateRole::route('/create'),
            'edit' => Pages\EditRole::route('/{record}/edit'),
        ];
    }
    public static function getNavigationGroup(): ?string
    {
        return 'Gestionar usuarios';
    }

     protected static function check(string $perm): bool
    {
        return auth()->user()?->can($perm);
    }



}




