<?php
require_once __DIR__.'/../../config/auth.php';$id=filter_input(INPUT_GET,'id',FILTER_VALIDATE_INT)?:0;
if(($_SERVER['REQUEST_METHOD']??'GET')==='POST'){
 if(($_POST['accion']??'')==='nuevo'){$nombre=limpiar($_POST['nombre']??'');if($nombre!==''){$s=$conn->prepare('INSERT INTO roles(nombre) VALUES(?)');$s->bind_param('s',$nombre);$s->execute();$nuevo=$s->insert_id;$s->close();$s=$conn->prepare("INSERT INTO rol_menus(rol_id,menu_id,habilitado) SELECT ?,id,IF(clave='informes_avisos' OR grupo='Informes y Avisos',1,0) FROM menus_sistema");$s->bind_param('i',$nuevo);$s->execute();$s->close();header("Location: /HM/modules/roles/index.php?id=$nuevo&creado=1");exit;}}
 $id=(int)($_POST['rol_id']??0);$seleccionados=array_map('intval',$_POST['menus']??[]);if($id>0){$conn->begin_transaction();try{$rol=$conn->query("SELECT nombre FROM roles WHERE id=$id")->fetch_assoc();$s=$conn->prepare('UPDATE rol_menus SET habilitado=? WHERE rol_id=?');$valor=(($rol['nombre']??'')==='Administrador')?1:0;$s->bind_param('ii',$valor,$id);$s->execute();$s->close();if(!$valor){$s=$conn->prepare('UPDATE rol_menus SET habilitado=1 WHERE rol_id=? AND menu_id=?');foreach($seleccionados as $menuId){$s->bind_param('ii',$id,$menuId);$s->execute();}$s->close();}$conn->commit();header("Location: /HM/modules/roles/index.php?id=$id&permisos=1");exit;}catch(Throwable $e){$conn->rollback();throw $e;}}
}
$roles=$conn->query('SELECT * FROM roles ORDER BY nombre');if(!$id&&$primero=$roles->fetch_assoc())$id=$primero['id'];$roles=$conn->query('SELECT * FROM roles ORDER BY nombre');$rolActual=$conn->query('SELECT nombre FROM roles WHERE id='.(int)$id)->fetch_assoc();$esAdmin=($rolActual['nombre']??'')==='Administrador';$menus=$conn->query('SELECT m.*,COALESCE(rm.habilitado,0) habilitado FROM menus_sistema m LEFT JOIN rol_menus rm ON rm.menu_id=m.id AND rm.rol_id='.(int)$id.' WHERE m.activo=1 ORDER BY grupo,nombre');include __DIR__.'/../../includes/header.php';include __DIR__.'/../../includes/sidebar.php';?>
<main class="main"><?php include __DIR__.'/../../includes/topbar.php';?><div class="content"><h3 class="page-title">Definición de roles</h3><?php if(isset($_GET['creado'])):?><div class="alert alert-success">Rol creado correctamente. Sus menús están inicialmente deshabilitados.</div><?php endif;?><?php if(isset($_GET['permisos'])):?><div class="alert alert-success">Permisos guardados correctamente.</div><?php endif;?><div class="row g-3"><div class="col-md-4"><form class="card card-body mb-3" method="post"><input type="hidden" name="accion" value="nuevo"><label class="form-label">Nuevo rol</label><div class="input-group"><input class="form-control" name="nombre" required><button class="btn btn-hm">Crear</button></div></form><div class="list-group"><?php while($rol=$roles->fetch_assoc()):?><a class="list-group-item <?=$id==$rol['id']?'active':''?>" href="?id=<?=$rol['id']?>"><?=e($rol['nombre'])?></a><?php endwhile;?></div></div><div class="col-md-8"><form method="post"><input type="hidden" name="rol_id" value="<?=$id?>"><div class="card card-hm"><div class="card-body"><?php if($esAdmin):?><div class="alert alert-info">El rol Administrador tiene todos los menús habilitados automáticamente.</div><?php endif;?><table class="table"><thead><tr><th>Grupo</th><th>Menú</th><th>Habilitado</th></tr></thead><tbody><?php while($menu=$menus->fetch_assoc()):?><tr><td><?=e($menu['grupo'])?></td><td><?=e($menu['nombre'])?></td><td><input class="form-check-input" type="checkbox" name="menus[]" value="<?=$menu['id']?>" <?=$menu['habilitado']?'checked':''?> <?=$esAdmin?'disabled':''?>></td></tr><?php endwhile;?></tbody></table><?php if(!$esAdmin):?><button class="btn btn-hm">Guardar permisos</button><?php endif;?></div></div></form></div></div></div></main><?php include __DIR__.'/../../includes/footer.php';?>
