<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller; // <-- Asegúrate de tener esta línea
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Http\Requests\StoreRoleRequest;

class RoleController extends Controller
{
    public function index()
    {
        $this->authorize('viewAny', Role::class);

        $roles = Role::withCount('users')->paginate(10);
        return view('roles.index', compact('roles'));
    }

    public function create()
    {
        $this->authorize('create roles');
        $permissions = Permission::all(['id', 'name']);
        return view('roles.create', compact('permissions'));
    }

    public function store(Request $request)
    {
        /*$role = Role::create($request->only('name'));
        $role->syncPermissions($request->permissions);
        
        return redirect()->route('roles.index')
            ->with('success', 'Rol creado exitosamente');*/

        $this->authorize('create', Role::class);
    
        $request->validate([
            'name' => 'required|unique:roles',
            'description' => 'required'
        ]);

        Role::create($request->all());
        
        return redirect()->route('roles.index');
    }

    public function edit(Role $role)
    {
        $this->authorize('update', $role);
        $permissions = Permission::all()->groupBy('group');
        $rolePermissions = $role->permissions->pluck('id')->toArray();
        
        return view('roles.edit', compact('role', 'permissions', 'rolePermissions'));
    }

    public function update(Request $request, Role $role)
    {
        $role->update($request->only('name'));
        $role->syncPermissions($request->permissions);
        
        return redirect()->route('roles.index')
            ->with('success', 'Rol actualizado correctamente');
    }

    public function destroy(Role $role)
    {
        $this->authorize('delete', $role);
        
        if($role->is_protected) {
            return redirect()->back()
                ->with('error', 'No se puede eliminar un rol protegido');
        }
        
        $role->delete();
        return redirect()->route('roles.index')
            ->with('success', 'Rol eliminado correctamente');
    }

    public function syncPermissions(Request $request, Role $role)
    {
        $this->authorize('update', $role);
        $request->validate([
            'permissions' => 'required|array',
            'permissions.*' => 'exists:permissions,id'
        ]);
        
        $role->syncPermissions($request->permissions);
        return response()->json(['message' => 'Permisos actualizados correctamente']);
    }
}