<?php
namespace App\Http\Controllers;

use App\Models\Role;
use App\Models\Modulo;
use Illuminate\Http\Request;

class ModuloRolController extends Controller
{
    public function index()
    {
        $roles = Role::where('estado', 1)->get();
        $modulos = Modulo::all();

        return view('admin.modulo_roles.index', compact('roles', 'modulos'));
    }

    public function getModulosPorRol($rol_id)
    {
        $rol = Role::with('modulos')->findOrFail($rol_id);
        return response()->json($rol->modulos->pluck('id')); // solo IDs
    }

    public function asignar(Request $request)
    {
        $rol = Role::findOrFail($request->rol_id);
        $modulos = $request->input('modulo_ids', []);
        $rol->modulos()->sync($modulos); // elimina los que ya no están

        return response()->json(['success' => true, 'message' => 'Módulos asignados correctamente.']);
    }
}
