<?php
require __DIR__ . '/../init.php';
require_login();
$pdo = pdo();

/**
 * admin/users.php - Gestión de usuarios/roles/permiso (archivo reparado)
 * - Operaciones server-side: save_role, delete_role, save_permissions (AJAX), save_user, delete_user
 * - Endpoint GET action=fetch_user devuelve JSON para rellenar modal
 * - Detecta columnas opcionales: password, full_name, active, role (texto)
 */

/* ------------- Helpers ------------- */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
function col_exists(PDO $pdo, string $table, string $col): bool {
    $st = $pdo->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?");
    $st->execute([$table, $col]);
    return (int)$st->fetchColumn() > 0;
}
function first_existing_col(PDO $pdo, string $table, array $candidates): ?string {
    foreach ($candidates as $c) if (col_exists($pdo, $table, $c)) return $c;
    return null;
}
function flash($msg, $type='ok') {
    if ($type === 'ok') $_SESSION['flash_ok'] = $msg; else $_SESSION['flash_error'] = $msg;
}

/* detect optional columns (consistent names) */
$pwdCol = first_existing_col($pdo, 'users', ['password','password_hash','passwd','pass']);
$roleCol = first_existing_col($pdo, 'users', ['role','user_role','role_name']);
$fullNameCol = first_existing_col($pdo, 'users', ['full_name','name','display_name','fullname']);
$activeCol = first_existing_col($pdo, 'users', ['active','is_active','enabled']);

/* ------------- Actions (POST / AJAX) ------------- */
$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    // Save role
    if ($action === 'save_role') {
        $id = isset($_POST['role_id']) ? (int)$_POST['role_id'] : 0;
        $name = trim($_POST['name'] ?? '');
        $desc = trim($_POST['description'] ?? '');
        if ($name === '') { flash('El nombre del rol es requerido.','error'); header('Location:' . site('admin/users.php')); exit; }
        if ($id > 0) {
            $pdo->prepare("UPDATE roles SET name = ?, description = ? WHERE id = ?")->execute([$name,$desc,$id]);
            flash('Rol actualizado.');
        } else {
            $pdo->prepare("INSERT INTO roles (name, description) VALUES (?, ?)")->execute([$name,$desc]);
            flash('Rol creado.');
        }
        header('Location:' . site('admin/users.php')); exit;
    }

    // Delete role
    if ($action === 'delete_role') {
        $id = isset($_POST['role_id']) ? (int)$_POST['role_id'] : 0;
        if ($id > 0) {
            $pdo->beginTransaction();
            $pdo->prepare("DELETE FROM role_permissions WHERE role_id = ?")->execute([$id]);
            $pdo->prepare("DELETE FROM user_roles WHERE role_id = ?")->execute([$id]);
            $pdo->prepare("DELETE FROM roles WHERE id = ?")->execute([$id]);
            $pdo->commit();
            flash('Rol eliminado.');
        } else flash('Rol inválido.','error');
        header('Location:' . site('admin/users.php')); exit;
    }

    // Save permissions (AJAX, accepts JSON)
    if ($action === 'save_permissions') {
        $data = json_decode(file_get_contents('php://input'), true) ?: $_POST;
        $role_id = isset($data['role_id']) ? (int)$data['role_id'] : 0;
        $perms = is_array($data['permissions']) ? $data['permissions'] : (isset($data['permissions']) ? [$data['permissions']] : []);
        $perms = array_values(array_filter(array_map(function($v){ return is_numeric($v) ? (int)$v : null; }, $perms)));
        if ($role_id <= 0) { header('Content-Type:application/json'); echo json_encode(['ok'=>0,'msg'=>'role_id requerido']); exit; }
        // validate permission ids
        $validPerms = [];
        if (!empty($perms)) {
            $ph = implode(',', array_fill(0, count($perms), '?'));
            $st = $pdo->prepare("SELECT id FROM permissions WHERE id IN ($ph)");
            $st->execute($perms);
            $validPerms = array_map('intval', $st->fetchAll(PDO::FETCH_COLUMN,0));
        }
        $pdo->beginTransaction();
        $pdo->prepare("DELETE FROM role_permissions WHERE role_id = ?")->execute([$role_id]);
        if (!empty($validPerms)) {
            $ins = $pdo->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
            foreach ($validPerms as $pid) $ins->execute([$role_id,$pid]);
        }
        $pdo->commit();
        header('Content-Type:application/json'); echo json_encode(['ok'=>1,'msg'=>'Permisos actualizados']); exit;
    }

    // Save user (create/update)
    if ($action === 'save_user') {
        $id = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
        $username = trim($_POST['username'] ?? '');
        $full_name = trim($_POST['full_name'] ?? '');
        $password = $_POST['password'] ?? '';

        // normalize roles input (array or single) - accept IDs only (select options send IDs)
        $rawRoles = $_POST['roles'] ?? [];
        if (!is_array($rawRoles)) $rawRoles = $rawRoles === '' ? [] : [$rawRoles];
        $roleCandidates = array_values(array_filter(array_map(function($v){ return is_numeric($v) ? (int)$v : null; }, $rawRoles), function($v){ return $v !== null && $v > 0; }));

        $active = isset($_POST['active']) ? 1 : 0;

        if ($username === '') { flash('El usuario (username) es requerido.','error'); header('Location:' . site('admin/users.php')); exit; }

        // uniqueness
        if ($id === 0) {
            $st = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
            $st->execute([$username]);
            if ((int)$st->fetchColumn() > 0) { flash('El nombre de usuario ya existe.','error'); header('Location:' . site('admin/users.php')); exit; }
        } else {
            $st = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ? AND id != ?");
            $st->execute([$username,$id]);
            if ((int)$st->fetchColumn() > 0) { flash('El nombre de usuario ya existe.','error'); header('Location:' . site('admin/users.php')); exit; }
        }

        $pdo->beginTransaction();
        if ($id > 0) {
            // update
            $parts = []; $params = [];
            $parts[] = "username = ?"; $params[] = $username;
            if ($fullNameCol) { $parts[] = "{$fullNameCol} = ?"; $params[] = $full_name; }
            if ($pwdCol && $password !== '') { $parts[] = "{$pwdCol} = ?"; $params[] = password_hash($password, PASSWORD_DEFAULT); }
            if ($activeCol) { $parts[] = "{$activeCol} = ?"; $params[] = $active; }
            if (!empty($parts)) {
                $params[] = $id;
                $sql = "UPDATE users SET " . implode(', ', $parts) . " WHERE id = ?";
                $pdo->prepare($sql)->execute($params);
            }
            $newUserId = $id;
            flash('Usuario actualizado.');
        } else {
            // insert
            $cols = ['username']; $place = ['?']; $params = [$username];
            if ($fullNameCol) { $cols[] = $fullNameCol; $place[] = '?'; $params[] = $full_name; }
            if ($pwdCol) { $cols[] = $pwdCol; $place[] = '?'; $params[] = password_hash($password ?: bin2hex(random_bytes(4)), PASSWORD_DEFAULT); }
            if ($activeCol) { $cols[] = $activeCol; $place[] = '?'; $params[] = $active; }
            $sql = "INSERT INTO users (" . implode(',', $cols) . ") VALUES (" . implode(',', $place) . ")";
            $pdo->prepare($sql)->execute($params);
            $newUserId = $pdo->lastInsertId();
            flash('Usuario creado.' . ($pwdCol ? '' : ' (Aviso: tabla users no tiene columna de contraseña; la contraseña no fue guardada.)'));
        }

        // Validate and attach roles
        $validRoleIds = [];
        if (!empty($roleCandidates)) {
            $ph = implode(',', array_fill(0, count($roleCandidates), '?'));
            $st = $pdo->prepare("SELECT id FROM roles WHERE id IN ($ph)");
            $st->execute($roleCandidates);
            $validRoleIds = array_map('intval', $st->fetchAll(PDO::FETCH_COLUMN,0));
            $validRoleIds = array_values(array_unique($validRoleIds));
        }

        // replace user_roles
        $pdo->prepare("DELETE FROM user_roles WHERE user_id = ?")->execute([$newUserId]);
        if (!empty($validRoleIds)) {
            $ins = $pdo->prepare("INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)");
            foreach ($validRoleIds as $rid) $ins->execute([$newUserId, $rid]);
        }

        // update users.role text column (if present) reading FROM the relation (most reliable)
        if ($roleCol) {
            $st = $pdo->prepare("SELECT r.name FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ? ORDER BY r.id");
            $st->execute([$newUserId]);
            $names = $st->fetchAll(PDO::FETCH_COLUMN, 0);
            if (!empty($names)) {
                $roleText = implode(',', $names);
                $upd = $pdo->prepare("UPDATE users SET {$roleCol} = ? WHERE id = ?");
                $upd->execute([$roleText, $newUserId]);
            } else {
                $upd = $pdo->prepare("UPDATE users SET {$roleCol} = NULL WHERE id = ?");
                $upd->execute([$newUserId]);
            }
        }

        $pdo->commit();
        header('Location:' . site('admin/users.php')); exit;
    }

    // delete user
    if ($action === 'delete_user') {
        $id = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
        if ($id > 0) {
            $pdo->beginTransaction();
            $pdo->prepare("DELETE FROM user_roles WHERE user_id = ?")->execute([$id]);
            $pdo->prepare("DELETE FROM users WHERE id = ?")->execute([$id]);
            $pdo->commit();
            flash('Usuario eliminado.');
        } else flash('Usuario inválido.','error');
        header('Location:' . site('admin/users.php')); exit;
    }

    // fetch_user endpoint (GET) - returns JSON for modal fill
    if (isset($_GET['action']) && $_GET['action'] === 'fetch_user' && isset($_GET['user_id'])) {
        $uid = (int)$_GET['user_id'];
        $select = ["id","username"];
        $select[] = $fullNameCol ? "{$fullNameCol} AS full_name" : "'' AS full_name";
        $select[] = $activeCol ? "{$activeCol} AS active" : "1 AS active";
        $st = $pdo->prepare("SELECT " . implode(', ', $select) . " FROM users WHERE id = ?");
        $st->execute([$uid]);
        $u = $st->fetch(PDO::FETCH_ASSOC) ?: null;
        $rids = [];
        $st2 = $pdo->prepare("SELECT role_id FROM user_roles WHERE user_id = ?");
        $st2->execute([$uid]);
        while ($row = $st2->fetch(PDO::FETCH_ASSOC)) $rids[] = (int)$row['role_id'];
        header('Content-Type: application/json');
        echo json_encode(['ok'=>1,'user'=>$u,'roles'=>$rids]);
        exit;
    }

} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    error_log("admin/users.php error: " . $e->getMessage());
    flash('Error al procesar la solicitud: ' . $e->getMessage(), 'error');
    header('Location:' . site('admin/users.php')); exit;
}

/* ------------- Render data for UI ------------- */
try {
    $roles = $pdo->query("SELECT * FROM roles ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
    $permissions = $pdo->query("SELECT * FROM permissions ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);

    $selectParts = ["id","username"];
    $selectParts[] = $fullNameCol ? "{$fullNameCol} AS full_name" : "'' AS full_name";
    $selectParts[] = $activeCol ? "{$activeCol} AS active" : "1 AS active";
    $usersSql = "SELECT " . implode(', ', $selectParts) . " FROM users ORDER BY username";
    $users = $pdo->query($usersSql)->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    error_log("admin/users.php (render) SQL error: " . $e->getMessage());
    $users = []; $roles = []; $permissions = [];
    flash('Error al cargar datos: revise error_log.', 'error');
}

$rolePermStmt = $pdo->query("SELECT role_id, permission_id FROM role_permissions");
$rolePerms = []; while ($r = $rolePermStmt->fetch(PDO::FETCH_ASSOC)) $rolePerms[$r['role_id']][] = $r['permission_id'];

$userRolesStmt = $pdo->query("SELECT user_id, role_id FROM user_roles");
$userRoles = []; while ($r = $userRolesStmt->fetch(PDO::FETCH_ASSOC)) $userRoles[$r['user_id']][] = $r['role_id'];

$flashOk = $_SESSION['flash_ok'] ?? null; $flashError = $_SESSION['flash_error'] ?? null;
unset($_SESSION['flash_ok'], $_SESSION['flash_error']);
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Usuarios - Admin</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>.user-avatar{width:40px;height:40px;border-radius:6px;background:#f1f5f9;display:inline-flex;align-items:center;justify-content:center;font-weight:700;color:#495057;}.role-selected{border:2px solid #0d6efd;}</style>
</head>
<body class="bg-light">
<nav class="navbar navbar-light bg-white shadow-sm mb-3">
  <div class="container-fluid">
    <a class="navbar-brand" href="<?= esc(site('admin/index.php')) ?>">Panel Admin</a>
    <div>
      <a class="btn btn-outline-secondary btn-sm" href="<?= esc(site('pos/index.php')) ?>">Abrir POS</a>
      <a class="btn btn-outline-secondary btn-sm" href="<?= esc(site('admin_logout.php')) ?>">Salir</a>
    </div>
  </div>
</nav>

<div class="container">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="mb-0">Usuarios, Roles y Permisos</h3>
    <div>
      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#userModal" onclick="openUserModal()">Crear usuario</button>
      <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#roleModal" onclick="openRoleModal()">Crear rol</button>
    </div>
  </div>

  <?php if ($flashOk): ?><div class="alert alert-success"><?= esc($flashOk) ?></div><?php endif; ?>
  <?php if ($flashError): ?><div class="alert alert-danger"><?= esc($flashError) ?></div><?php endif; ?>

  <div class="row g-3">
    <!-- Roles -->
    <div class="col-md-4">
      <div class="card mb-3"><div class="card-body">
        <h6>Roles</h6>
        <div class="list-group" id="rolesList">
          <?php foreach ($roles as $r): ?>
            <div class="list-group-item d-flex justify-content-between align-items-center role-item" data-role-id="<?= $r['id'] ?>">
              <div>
                <div class="fw-bold"><?= esc($r['name']) ?></div>
                <div class="small text-muted"><?= esc($r['description']) ?></div>
              </div>
              <div class="btn-group btn-group-sm" role="group">
                <button class="btn btn-outline-secondary" onclick="editRole(event, <?= $r['id'] ?>)">Editar</button>
                <form method="post" style="display:inline" onsubmit="return confirm('Eliminar rol?')">
                  <input type="hidden" name="action" value="delete_role">
                  <input type="hidden" name="role_id" value="<?= $r['id'] ?>">
                  <button class="btn btn-outline-danger">Eliminar</button>
                </form>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      </div></div>
      <div class="card"><div class="card-body"><h6>Permisos disponibles</h6>
        <?php foreach ($permissions as $p): ?>
          <div class="py-1"><strong><?= esc($p['name']) ?></strong> <div class="small text-muted"><?= esc($p['description']) ?></div></div><hr class="my-1">
        <?php endforeach; ?>
      </div></div>
    </div>

    <!-- Permissions editor -->
    <div class="col-md-4">
      <div class="card mb-3"><div class="card-body">
        <h6>Permisos del rol seleccionado</h6>
        <div id="selectedRoleInfo" class="mb-2 text-muted">Seleccione un rol en la lista izquierda.</div>
        <div id="permEditor" style="display:none">
          <form id="permForm" onsubmit="return false;">
            <input type="hidden" id="perm_role_id" value="">
            <div class="permission-list mb-2" id="permCheckboxes">
              <?php foreach ($permissions as $p): ?>
                <div class="form-check">
                  <input class="form-check-input perm-checkbox" type="checkbox" value="<?= $p['id'] ?>" id="perm_<?= $p['id'] ?>">
                  <label class="form-check-label" for="perm_<?= $p['id'] ?>"><?= esc($p['name']) ?></label>
                </div>
              <?php endforeach; ?>
            </div>
            <div class="d-flex gap-2">
              <button type="button" class="btn btn-primary" id="savePermsBtn">Guardar permisos</button>
              <button type="button" class="btn btn-secondary" id="cancelPermsBtn">Cancelar</button>
            </div>
          </form>
        </div>
      </div></div>
    </div>

    <!-- Users -->
    <div class="col-md-4">
      <div class="card mb-3"><div class="card-body">
        <h6>Usuarios</h6>
        <div class="list-group" id="usersList">
          <?php if (empty($users)): ?>
            <div class="text-muted">No se encontraron usuarios.</div>
          <?php else: ?>
            <?php foreach ($users as $u): ?>
              <div class="list-group-item d-flex justify-content-between align-items-center">
                <div class="d-flex gap-2 align-items-center">
                  <div class="user-avatar"><?= esc(strtoupper(substr($u['username'],0,1))) ?></div>
                  <div>
                    <div class="fw-bold"><?= esc($u['username']) ?> <?= ((int)($u['active'] ?? 1)) ? '' : '<span class="badge bg-danger ms-1">Inactivo</span>' ?></div>
                    <div class="small text-muted"><?= esc($u['full_name'] ?? '') ?></div>
                    <div class="small text-muted">Roles: <?= esc(implode(', ', array_map(function($rid) use ($pdo){ $st = $pdo->prepare("SELECT name FROM roles WHERE id = ?"); $st->execute([$rid]); return $st->fetchColumn(); }, $userRoles[$u['id']] ?? [])) ?: '—') ?></div>
                  </div>
                </div>
                <div class="btn-group" role="group">
                  <button class="btn btn-sm btn-outline-secondary" onclick="openUserModal(<?= $u['id'] ?>)">Editar</button>
                  <form method="post" style="display:inline" onsubmit="return confirm('Eliminar usuario?')">
                    <input type="hidden" name="action" value="delete_user">
                    <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                    <button class="btn btn-sm btn-outline-danger">Eliminar</button>
                  </form>
                </div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div></div>
    </div>
  </div>
</div>

<!-- Role Modal -->
<div class="modal fade" id="roleModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form class="modal-content" method="post" id="roleForm">
      <input type="hidden" name="action" value="save_role">
      <input type="hidden" name="role_id" id="role_id" value="">
      <div class="modal-header"><h5 class="modal-title" id="roleModalTitle">Crear rol</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <div class="mb-2"><label class="form-label">Nombre</label><input class="form-control" name="name" id="role_name" required></div>
        <div class="mb-2"><label class="form-label">Descripción</label><textarea class="form-control" name="description" id="role_desc" rows="3"></textarea></div>
      </div>
      <div class="modal-footer"><button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancelar</button><button class="btn btn-primary" type="submit">Guardar</button></div>
    </form>
  </div>
</div>

<!-- User Modal -->
<div class="modal fade" id="userModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <form class="modal-content" method="post" id="userForm">
      <input type="hidden" name="action" value="save_user">
      <input type="hidden" name="user_id" id="user_id" value="">
      <div class="modal-header"><h5 class="modal-title" id="userModalTitle">Crear usuario</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <div class="row g-2">
          <div class="col-md-6"><label class="form-label">Usuario</label><input class="form-control" name="username" id="username" required></div>
          <div class="col-md-6"><label class="form-label">Nombre completo</label><input class="form-control" name="full_name" id="full_name"></div>
          <div class="col-md-6"><label class="form-label">Contraseña</label><input class="form-control" name="password" id="password" placeholder="Dejar vacío para no cambiar"></div>
          <div class="col-md-6"><label class="form-label">Roles</label>
            <select class="form-select" id="user_roles" name="roles[]" multiple>
              <?php foreach ($roles as $r): ?>
                <option value="<?= $r['id'] ?>"><?= esc($r['name']) ?></option>
              <?php endforeach; ?>
            </select>
            <div class="form-text">Mantén presionada Ctrl/Cmd para seleccionar varios.</div>
          </div>
          <div class="col-12">
            <div class="form-check mt-2">
              <input class="form-check-input" type="checkbox" id="user_active" name="active" <?= $activeCol ? 'checked' : '' ?> <?= $activeCol ? '' : 'disabled' ?>>
              <label class="form-check-label" for="user_active">Activo <?= $activeCol ? '' : '(no disponible en DB)' ?></label>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer"><button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancelar</button><button class="btn btn-primary" type="submit">Guardar usuario</button></div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// --- Client-side: robust, failsafe JS ---
// Avoid letting any JS error block UI: wrap risky code in try/catch

// Role item click: select role and load its permissions
try {
  document.querySelectorAll('.role-item').forEach(el=>{
    el.addEventListener('click', function(e){
      // ignore if clicked on inner button (edit/delete) - buttons stopPropagation
      if (e.target.tagName === 'BUTTON' || e.target.closest('form')) return;
      const rid = this.dataset.roleId;
      selectRole(parseInt(rid,10));
    });
  });
} catch(err){ console.error('role-item handler error', err); }

// Select role and populate permission checkboxes
function selectRole(roleId){
  document.querySelectorAll('.role-item').forEach(el=> el.classList.toggle('role-selected', el.dataset.roleId == roleId));
  document.getElementById('permEditor').style.display = 'block';
  document.getElementById('selectedRoleInfo').textContent = 'Editando permisos del rol ID ' + roleId;
  document.getElementById('perm_role_id').value = roleId;
  // clear checkboxes
  document.querySelectorAll('.perm-checkbox').forEach(cb => cb.checked = false);
  // mark checked based on rolePerms (server rendered)
  try {
    const rolePerms = <?= json_encode($rolePerms ?: []) ?>;
    (rolePerms[roleId] || []).forEach(pid=>{
      const el = document.getElementById('perm_' + pid);
      if (el) el.checked = true;
    });
  } catch(e){ console.error(e); }
}

// Edit role button
function editRole(e, id){
  e.stopPropagation(); e.preventDefault();
  const role = <?= json_encode($roles ?: []) ?>.find(r => r.id == id);
  if (!role) return alert('Rol no encontrado');
  document.getElementById('role_id').value = id;
  document.getElementById('role_name').value = role.name || '';
  document.getElementById('role_desc').value = role.description || '';
  new bootstrap.Modal(document.getElementById('roleModal')).show();
}

// open role modal for new
function openRoleModal(){
  document.getElementById('roleForm').reset();
  document.getElementById('role_id').value = '';
  document.getElementById('roleModalTitle').textContent = 'Crear rol';
  new bootstrap.Modal(document.getElementById('roleModal')).show();
}

// Save permissions (AJAX)
document.getElementById('savePermsBtn').addEventListener('click', async function(){
  const roleId = parseInt(document.getElementById('perm_role_id').value || 0, 10);
  if (!roleId) return alert('Seleccione un rol.');
  const checked = Array.from(document.querySelectorAll('.perm-checkbox:checked')).map(cb => parseInt(cb.value,10));
  try {
    const res = await fetch('<?= esc(site('admin/users.php')) ?>?action=save_permissions', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({ role_id: roleId, permissions: checked })
    });
    const j = await res.json();
    if (j.ok) { alert('Permisos guardados.'); location.reload(); } else alert('Error: ' + (j.msg||''));
  } catch(e){ console.error(e); alert('Error guardando permisos'); }
});
document.getElementById('cancelPermsBtn').addEventListener('click', function(){ document.getElementById('permEditor').style.display = 'none'; document.getElementById('selectedRoleInfo').textContent = 'Seleccione un rol en la lista izquierda.'; document.querySelectorAll('.role-item').forEach(el=> el.classList.remove('role-selected')); });

// Open user modal (create or edit)
async function openUserModal(userId = 0){
  document.getElementById('userForm').reset();
  document.getElementById('user_id').value = '';
  Array.from(document.getElementById('user_roles').options).forEach(o => o.selected = false);
  document.getElementById('userModalTitle').textContent = userId ? 'Editar usuario' : 'Crear usuario';
  if (userId) {
    try {
      const res = await fetch('<?= esc(site('admin/users.php')) ?>?action=fetch_user&user_id=' + userId);
      const j = await res.json();
      if (j.ok && j.user) {
        document.getElementById('user_id').value = j.user.id;
        document.getElementById('username').value = j.user.username;
        document.getElementById('full_name').value = j.user.full_name || '';
        document.getElementById('password').value = '';
        try { document.getElementById('user_active').checked = j.user.active ? true : false; } catch(e){}
        if (Array.isArray(j.roles)) j.roles.forEach(rid => {
          const opt = document.querySelector('#user_roles option[value="'+rid+'"]');
          if (opt) opt.selected = true;
        });
      } else {
        alert('No se pudo cargar la información del usuario.');
      }
    } catch(e){ console.error(e); alert('Error cargando usuario'); }
  }
  new bootstrap.Modal(document.getElementById('userModal')).show();
}

// Ensure forms use normal POST submit (no JS override) - nothing else needed

</script>
</body>
</html>