<?php
$authApp = 'usuarios';
require __DIR__ . '/../../config/auth.php';
require __DIR__ . '/../../config/db2.php';
require_once __DIR__ . '/../../lib/helpers.php';

// Obtener id propio para proteger eliminación
$selfStmt = $pdo->prepare("SELECT id FROM mrbs_users WHERE name = ? LIMIT 1");
$selfStmt->execute([$_SESSION['usuario']]);
$selfId = (int)$selfStmt->fetchColumn();

// ── Eliminar (antes de menu.php) ──────────────────────────────────────────────
if (isset($_GET['eliminar'])) {
    if (!perm('usuarios', 'borrar')) { http_response_code(403); exit('Sin permiso'); }
    $delId = (int)$_GET['eliminar'];
    if ($delId !== $selfId && $delId > 0) {
        $pdo->prepare("DELETE FROM mrbs_users WHERE id = ?")->execute([$delId]);
    }
    header('Location: listarUsuarios.php?' . http_build_query([
        'f_name'    => $_GET['f_name']    ?? '',
        'f_display' => $_GET['f_display'] ?? '',
        'f_email'   => $_GET['f_email']   ?? '',
        'f_level'   => $_GET['f_level']   ?? '',
    ]));
    exit;
}

// ── Filtros ───────────────────────────────────────────────────────────────────
$f = [
    'name'    => trim($_GET['f_name']    ?? ''),
    'display' => trim($_GET['f_display'] ?? ''),
    'email'   => trim($_GET['f_email']   ?? ''),
    'level'   => $_GET['f_level'] ?? '',
];
$filtros = array_filter([
    'f_name'    => $f['name'],
    'f_display' => $f['display'],
    'f_email'   => $f['email'],
    'f_level'   => $f['level'],
]);

$where  = [];
$params = [];
if ($f['name'])         { $where[] = "name LIKE ?";         $params[] = '%' . $f['name']    . '%'; }
if ($f['display'])      { $where[] = "display_name LIKE ?"; $params[] = '%' . $f['display'] . '%'; }
if ($f['email'])        { $where[] = "email LIKE ?";        $params[] = '%' . $f['email']   . '%'; }
if ($f['level'] !== '') { $where[] = "level = ?";           $params[] = (int)$f['level']; }
$wSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

// ── Ordenamiento ──────────────────────────────────────────────────────────────
$sortOk  = ['name', 'display_name', 'email', 'level', 'last_login', 'timestamp'];
$sort    = in_array($_GET['sort'] ?? '', $sortOk, true) ? $_GET['sort'] : 'name';
$dir     = strtoupper($_GET['dir'] ?? 'ASC') === 'DESC' ? 'DESC' : 'ASC';
$nextDir = $dir === 'ASC' ? 'DESC' : 'ASC';

function colHdr(string $col, string $lbl, string $sort, string $dir, string $nextDir, array $filtros): string {
    $ind = $sort === $col ? ($dir === 'ASC' ? ' ▲' : ' ▼') : '';
    $p   = array_merge($filtros, ['sort' => $col, 'dir' => ($sort === $col ? $nextDir : 'ASC')]);
    return '<a href="?' . http_build_query($p) . '">' . htmlspecialchars($lbl) . $ind . '</a>';
}

$stmt = $pdo->prepare(
    "SELECT id, name, display_name, email, level, last_login, timestamp
     FROM mrbs_users $wSql ORDER BY $sort $dir"
);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$paginaActual = 'configuracion';
require __DIR__ . '/../../config/menu.php';
?>
<div class="ph">
  <div>
    <h1>Usuarios</h1>
    <div class="bc">
      <a href="<?=BASE_URL?>/index.php">Inicio</a> ›
      <a href="<?=BASE_URL?>/public/configuracion/listarSalas.php">Configuración</a> ›
      Usuarios
    </div>
  </div>
  <div style="display:flex;gap:6px">
    <?php if (perm('usuarios', 'agregar')): ?>
    <a href="formUsuario.php" class="btn btn-s">+ Nuevo usuario</a>
    <?php endif; ?>
  </div>
</div>

<?php if (isset($_GET['ok'])): ?>
<div class="msg msg-ok">Guardado correctamente.</div>
<?php endif; ?>

<div class="card">
  <form id="fForm" method="get" action="">
    <div class="fb">
      <div class="fi">
        <label>Usuario</label>
        <input type="text" name="f_name" value="<?=htmlspecialchars($f['name'])?>">
      </div>
      <div class="fi">
        <label>Nombre completo</label>
        <input type="text" name="f_display" value="<?=htmlspecialchars($f['display'])?>">
      </div>
      <div class="fi">
        <label>Email</label>
        <input type="text" name="f_email" value="<?=htmlspecialchars($f['email'])?>">
      </div>
      <div class="fi" style="max-width:120px">
        <label>Nivel</label>
        <select name="f_level">
          <option value="">Todos</option>
          <?php for ($l = 0; $l <= 10; $l++): ?>
          <option value="<?=$l?>" <?=$f['level']===(string)$l?'selected':''?>><?=$l?></option>
          <?php endfor; ?>
        </select>
      </div>
      <div class="fi" style="align-self:flex-end">
        <button type="submit" class="btn btn-p">Buscar</button>
        <a href="listarUsuarios.php" class="btn btn-g" style="margin-left:4px">Limpiar</a>
      </div>
    </div>
  </form>

  <p style="font-size:12px;color:#64748b;margin-bottom:8px"><?=count($rows)?> resultado(s)</p>

  <div class="tw">
    <table id="tUsuarios">
      <thead><tr>
        <th><?=colHdr('name',         'Usuario',        $sort,$dir,$nextDir,$filtros)?></th>
        <th><?=colHdr('display_name', 'Nombre completo',$sort,$dir,$nextDir,$filtros)?></th>
        <th><?=colHdr('email',        'Email',          $sort,$dir,$nextDir,$filtros)?></th>
        <th style="width:70px"><?=colHdr('level','Nivel',$sort,$dir,$nextDir,$filtros)?></th>
        <th style="width:140px"><?=colHdr('last_login','Último acceso',$sort,$dir,$nextDir,$filtros)?></th>
        <th style="width:110px">Acciones</th>
      </tr></thead>
      <tbody>
        <?php if (empty($rows)): ?>
        <tr><td colspan="6" style="text-align:center;color:#94a3b8;padding:20px">Sin resultados</td></tr>
        <?php endif; ?>
        <?php foreach ($rows as $row): ?>
        <?php $esPropioUsuario = ((int)$row['id'] === $selfId); ?>
        <tr <?=$esPropioUsuario ? 'style="background:#eff6ff"' : ''?>>
          <td>
            <?=htmlspecialchars($row['name'])?>
            <?php if ($esPropioUsuario): ?><span class="bp bp-l" style="margin-left:4px">yo</span><?php endif; ?>
          </td>
          <td><?=htmlspecialchars($row['display_name'] ?? '')?></td>
          <td><?=htmlspecialchars($row['email'] ?? '')?></td>
          <td style="text-align:center">
            <span class="bp" style="background:#e0e7ff;color:#3730a3"><?=(int)$row['level']?></span>
          </td>
          <td style="color:#64748b;font-size:12px">
            <?= $row['last_login'] ? date('d/m/Y H:i', (int)$row['last_login']) : '—' ?>
          </td>
          <td>
            <div class="ac">
              <?php if (perm('usuarios', 'editar')): ?>
              <a href="formUsuario.php?id=<?=$row['id']?>&<?=http_build_query($filtros)?>"
                 class="btn btn-i btn-sm">Editar</a>
              <?php endif; ?>
              <?php if (perm('usuarios', 'borrar') && !$esPropioUsuario): ?>
              <a href="?eliminar=<?=$row['id']?>&<?=http_build_query($filtros)?>"
                 class="btn btn-r btn-sm"
                 onclick="return confirm('¿Eliminar usuario «<?=htmlspecialchars(addslashes($row['name']))?>»?')">Eliminar</a>
              <?php endif; ?>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<script>
(function(){
  const f = document.getElementById('fForm');
  f.querySelectorAll('select').forEach(el =>
    el.addEventListener('change', () => f.submit())
  );
  f.querySelectorAll('input[type=text]').forEach(el => {
    el.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); f.submit(); } });
    el.addEventListener('blur', () => f.submit());
  });
})();
</script>
