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

// --- Handle POST actions (roles/users) ---
$action = $_POST['action'] ?? $_GET['action'] ?? '';

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

if ($action === 'delete_role') {
    $id = isset($_POST['role_id']) ? (int)$_POST['role_id'] : 0;
    if ($id > 0) {
        $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]);
        $_SESSION['flash_ok'] = 'Rol eliminado.';
    }
    header('Location: ' . site('admin/users.php'));
    exit;
}

if ($action === 'save_permissions') {
    // AJAX endpoint: assign permissions to a role
    $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']) ? array_map('intval', $data['permissions']) : [];
    if ($role_id <= 0) {
        header('Content-Type: application/json');
        echo json_encode(['ok' => 0, 'msg' => 'role_id requerido']);
        exit;
    }
    $pdo->beginTransaction();
    $pdo->prepare("DELETE FROM role_permissions WHERE role_id = ?")->execute([$role_id]);
    if (!empty($perms)) {
        $ins = $pdo->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
        foreach ($perms as $pid) $ins->execute([$role_id, $pid]);
    }
    $pdo->commit();
    header('Content-Type: application/json');
    echo json_encode(['ok' => 1, 'msg' => 'Permisos actualizados']);
    exit;
}

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'] ?? '';
    $active = isset($_POST['active']) ? 1 : 0;
    $roles = isset($_POST['roles']) && is_array($_POST['roles']) ? array_map('intval', $_POST['roles']) : [];

    if ($username === '') {
        $_SESSION['flash_error'] = 'El usuario (username) es requerido.';
        header('Location: ' . site('admin/users.php'));
        exit;
    }

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

    if ($id > 0) {
        if ($password !== '') {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET username = ?, full_name = ?, password = ?, active = ? WHERE id = ?");
            $stmt->execute([$username, $full_name, $hash, $active, $id]);
        } else {
            $stmt = $pdo->prepare("UPDATE users SET username = ?, full_name = ?, active = ? WHERE id = ?");
            $stmt->execute([$username, $full_name, $active, $id]);
        }
        $_SESSION['flash_ok'] = 'Usuario actualizado.';
    } else {
        $hash = password_hash($password ?: bin2hex(random_bytes(4)), PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO users (username, full_name, password, active) VALUES (?,?,?,?)");
        $stmt->execute([$username, $full_name, $hash, $active]);
        $id = $pdo->lastInsertId();
        $_SESSION['flash_ok'] = 'Usuario creado.';
    }

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

    header('Location: ' . site('admin/users.php'));
    exit;
}

if ($action === 'delete_user') {
    $id = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
    if ($id > 0) {
        $pdo->prepare("DELETE FROM user_roles WHERE user_id = ?")->execute([$id]);
        $pdo->prepare("DELETE FROM users WHERE id = ?")->execute([$id]);
        $_SESSION['flash_ok'] = 'Usuario eliminado.';
    }
    header('Location: ' . site('admin/users.php'));
    exit;
}

// --- Fetch data for display ---
$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);
$users = $pdo->query("SELECT id, username, full_name, active FROM users ORDER BY username")->fetchAll(PDO::FETCH_ASSOC);

// role -> permission ids map
$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'];
}

// user -> roles map
$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'];
}

// flash messages
$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>Administración de Usuarios - FuelPOS</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>
.card-role { cursor: pointer; }
.role-selected { border: 2px solid #0d6efd; box-shadow: 0 6px 18px rgba(13,110,253,0.08); }
.permission-list { max-height: 320px; overflow:auto; }
.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; }
</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="<?= site('admin/index.php') ?>">Panel Admin</a>
    <div>
      <a class="btn btn-outline-secondary btn-sm" href="<?= site('admin/reports.php') ?>">Reportes</a>
      <a class="btn btn-outline-secondary btn-sm" href="<?= site('pos/index.php') ?>">Abrir POS</a>
      <a class="btn btn-outline-danger btn-sm" href="<?= site('admin_logout.php') ?>">Salir</a>
    </div>
  </div>
</nav>

<div class="container">
  <div class="mb-3 d-flex justify-content-between align-items-center">
    <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"><?= htmlentities($flashOk) ?></div>
  <?php endif; ?>
  <?php if ($flashError): ?>
    <div class="alert alert-danger"><?= htmlentities($flashError) ?></div>
  <?php endif; ?>

  <div class="row g-3">
    <!-- Roles column -->
    <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): ?>
              <a href="#" class="list-group-item list-group-item-action 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>
              </a>
            <?php endforeach; ?>
          </div>
        </div>
      </div>

      <div class="card">
        <div class="card-body">
          <h6>Permisos disponibles</h6>
          <div class="permission-list">
            <?php foreach ($permissions as $p): ?>
              <div class="d-flex justify-content-between align-items-center py-1">
                <div>
                  <strong><?= esc($p['name']) ?></strong>
                  <div class="small text-muted"><?= esc($p['description']) ?></div>
                </div>
                <div class="text-muted small">#<?= $p['id'] ?></div>
              </div>
              <hr class="my-1">
            <?php endforeach; ?>
          </div>
        </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 para editar sus permisos.</div>
          <div id="permEditor" style="display:none">
            <form id="permForm">
              <input type="hidden" name="role_id" id="perm_role_id" value="">
              <div class="mb-2 permission-list" 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'] ?>">
                      <strong><?= esc($p['name']) ?></strong> <span class="text-muted small"><?= esc($p['description']) ?></span>
                    </label>
                  </div>
                <?php endforeach; ?>
              </div>
              <div class="d-flex gap-2">
                <button type="button" class="btn btn-primary" onclick="savePermissions()">Guardar permisos</button>
                <button type="button" class="btn btn-secondary" onclick="clearRoleSelection()">Cancelar</button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <div class="card">
        <div class="card-body">
          <h6>Descripción rápida</h6>
          <p class="small text-muted">Aquí puedes crear roles, asignarles permisos y luego vincular roles a usuarios. Permisos disponibles controlan el acceso a funciones como "Acceder POS", "Ver reportes", "Administrar usuarios", etc.</p>
        </div>
      </div>
    </div>

    <!-- Users column -->
    <div class="col-md-4">
      <div class="card mb-3">
        <div class="card-body">
          <h6>Usuarios</h6>
          <div class="list-group">
            <?php foreach ($users as $u): $avatar = strtoupper(substr($u['username'],0,1)); ?>
              <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($avatar) ?></div>
                  <div>
                    <div class="fw-bold"><?= esc($u['username']) ?> <?= $u['active'] ? '' : '<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:
                      <?php
                        $rnames = [];
                        if (!empty($userRoles[$u['id']])) {
                          $placeholders = implode(',', array_fill(0, count($userRoles[$u['id']]), '?'));
                          $st = $pdo->prepare("SELECT name FROM roles WHERE id IN ($placeholders)");
                          $st->execute($userRoles[$u['id']]);
                          $rnames = array_column($st->fetchAll(PDO::FETCH_ASSOC), 'name');
                        }
                        echo esc(implode(', ', $rnames) ?: '—');
                      ?>
                    </div>
                  </div>
                </div>
                <div class="btn-group btn-group-sm" role="group">
                  <button class="btn 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-outline-danger">Eliminar</button>
                  </form>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
      </div>

      <div class="card">
        <div class="card-body">
          <h6>Notas</h6>
          <p class="small text-muted">Los cambios se aplican inmediatamente. Si mueves la aplicación a otro dominio solo debes actualizar <code>config.php</code> (base_url) y la zona horaria si es necesario.</p>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Role Modal (create/edit) -->
<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" aria-label="Cerrar"></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" aria-label="Cerrar"></button>
      </div>
      <div class="modal-body">
        <div class="row g-2">
          <div class="col-md-6">
            <label class="form-label">Usuario (username)</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" checked>
              <label class="form-check-label" for="user_active">Activo</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>
// helper
function esc(s){ return String(s===null||s===undefined ? '' : s); }

// role selection handling
document.querySelectorAll('.role-item').forEach(el=>{
  el.addEventListener('click', function(e){
    e.preventDefault();
    const rid = this.dataset.roleId;
    selectRole(parseInt(rid,10));
  });
});

let currentRoleId = null;
const rolePerms = <?php echo json_encode($rolePerms ?: []); ?>;
const permsAvailable = <?php echo json_encode(array_column($permissions, null, 'id')); ?>;

function selectRole(roleId) {
  currentRoleId = 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);
  const list = rolePerms[roleId] || [];
  list.forEach(pid => {
    const el = document.getElementById('perm_' + pid);
    if (el) el.checked = true;
  });
}

// save permissions via AJAX
async function savePermissions(){
  const roleId = parseInt(document.getElementById('perm_role_id').value || 0, 10);
  if (!roleId) { alert('Seleccione un rol.'); return; }
  const checked = Array.from(document.querySelectorAll('.perm-checkbox:checked')).map(cb => parseInt(cb.value,10));
  try {
    const res = await fetch('<?php echo site("admin/users.php"); ?>?action=save_permissions', {
      method: 'POST', // admin/users.php accepts JSON or POST; use JSON
      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.');
  }
}

// clear role selection
function clearRoleSelection(){
  currentRoleId = null;
  document.getElementById('permEditor').style.display = 'none';
  document.getElementById('selectedRoleInfo').textContent = 'Seleccione un rol para editar sus permisos.';
  document.querySelectorAll('.role-item').forEach(el=> el.classList.remove('role-selected'));
}

// open role modal for create/edit
function openRoleModal(id = 0){
  document.getElementById('role_id').value = '';
  document.getElementById('role_name').value = '';
  document.getElementById('role_desc').value = '';
  document.getElementById('roleModalTitle').textContent = id ? 'Editar rol' : 'Crear rol';
  if (id) {
    // fetch role data from DOM (simple approach)
    const el = document.querySelector(`.role-item[data-role-id="${id}"]`);
    if (el) {
      document.getElementById('role_name').value = el.querySelector('.fw-bold')?.innerText || '';
      document.getElementById('role_desc').value = el.querySelector('.small')?.innerText || '';
      document.getElementById('role_id').value = id;
    }
  }
}

// edit role handler
function editRole(e, id){
  e.stopPropagation(); e.preventDefault();
  openRoleModal(id);
  const modal = new bootstrap.Modal(document.getElementById('roleModal'));
  modal.show();
}

// user modal (create/edit)
function openUserModal(userId = 0) {
  document.getElementById('userForm').reset();
  document.getElementById('user_id').value = '';
  document.getElementById('userModalTitle').textContent = userId ? 'Editar usuario' : 'Crear usuario';
  // clear roles select
  const rolesSelect = document.getElementById('user_roles');
  Array.from(rolesSelect.options).forEach(o => o.selected = false);

  if (userId) {
    // fetch user data via AJAX to populate modal (simple server call to fetch minimal JSON)
    fetch('<?php echo site("admin/users.php"); ?>?action=fetch_user&user_id=' + userId)
      .then(r => r.json())
      .then(j => {
        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 = '';
          document.getElementById('user_active').checked = j.user.active ? true : false;
          // select roles
          if (j.roles && Array.isArray(j.roles)) {
            j.roles.forEach(rid => {
              const opt = rolesSelect.querySelector('option[value="'+rid+'"]');
              if (opt) opt.selected = true;
            });
          }
        } else {
          alert('No se pudo obtener la información del usuario.');
        }
      }).catch(err => { console.error(err); alert('Error cargando usuario'); });
  }

  const modal = new bootstrap.Modal(document.getElementById('userModal'));
  modal.show();
}

// fetch_user endpoint handler (server-side): we handle via GET below
</script>

<?php
// Provide a small server-side JSON endpoint for fetch_user (GET)
if (isset($_GET['action']) && $_GET['action'] === 'fetch_user' && isset($_GET['user_id'])) {
    $uid = (int)$_GET['user_id'];
    $st = $pdo->prepare("SELECT id, username, full_name, active FROM users WHERE id = ?");
    $st->execute([$uid]);
    $u = $st->fetch(PDO::FETCH_ASSOC);
    $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;
}
?>

</body>
</html>