<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;

class PermissionController extends Controller
{
    use AuthorizesRequests; // <-- Añade este trait

    public function index()
    {
        $this->authorize('viewAny', Permission::class);
        $permissions = Permission::all()->groupBy('group');
        return view('permissions.index', compact('permissions'));
    }

    public function store(Request $request)
    {
        $this->authorize('create', Permission::class);
        
        $request->validate([
            'name' => 'required|string|max:255|unique:permissions,name',
            'group' => 'required|string|max:255'
        ]);
        
        Permission::create($request->only('name', 'group'));
        
        return redirect()->route('permissions.index')
            ->with('success', 'Permiso creado exitosamente');
    }

    public function update(Request $request, Permission $permission)
    {
        $this->authorize('update', $permission);
        
        $request->validate([
            'name' => 'required|string|max:255|unique:permissions,name,'.$permission->id,
            'group' => 'required|string|max:255'
        ]);
        
        $permission->update($request->only('name', 'group'));
        
        return redirect()->route('permissions.index')
            ->with('success', 'Permiso actualizado correctamente');
    }

    public function updateRoles(User $user, Request $request)
    {
        $this->authorize('managePermissions', $user);
        // Usar UserPolicy para autorizar
    }
}
