<?php
declare(strict_types=1);
require_once __DIR__.'/../app/layout.php';
require_once __DIR__.'/../app/config_system.php';
require_once __DIR__.'/../app/notifications.php';

$u        = require_role('ADMIN');
$pdo      = app_pdo();
$year     = (int)date('Y');
$per_page = (int)sys_cfg('admin_per_page', 30);

/* ══════════════════════════════════════════════════════════
   POST — acciones AJAX
   ══════════════════════════════════════════════════════════ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $act = $_POST['act'] ?? '';

    if ($act === 'change_role') {
        $id      = (int)($_POST['id']   ?? 0);
        $role    = $_POST['role']       ?? '';
        $allowed = ['ADMIN','DOCENTE','ALUMNO'];
        if (!in_array($role, $allowed, true)) json_err('Rol inválido.');
        if ($id === (int)$u['id'])            json_err('No puedes cambiar tu propio rol.');
        $pdo->prepare("UPDATE users SET role=? WHERE id=?")->execute([$role, $id]);
        json_ok('Rol actualizado.', ['role' => $role]);
    }

    if ($act === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id === (int)$u['id']) json_err('No puedes desactivar tu propia cuenta.');
        $pdo->prepare('UPDATE users SET is_active = 1 - is_active WHERE id=?')->execute([$id]);
        $is = (int)$pdo->query("SELECT is_active FROM users WHERE id=$id")->fetchColumn();
        json_ok($is ? 'Usuario activado.' : 'Usuario desactivado.', ['is_active' => $is]);
    }

    if ($act === 'reset_pass') {
        $id  = (int)($_POST['id']  ?? 0);
        $new = trim($_POST['pass'] ?? '');
        if (strlen($new) < 4) json_err('Mínimo 4 caracteres.');
        $pdo->prepare("UPDATE users SET password_hash=? WHERE id=?")
            ->execute([password_hash($new, PASSWORD_DEFAULT), $id]);
        json_ok('Contraseña restablecida.');
    }

    if ($act === 'edit') {
        $id    = (int)($_POST['id']       ?? 0);
        $name  = trim($_POST['full_name'] ?? '');
        $email = trim($_POST['email']     ?? '');
        $phone = trim($_POST['phone']     ?? '');
        $dni   = preg_replace('/\D/', '', $_POST['dni'] ?? '');

        if (!$id || strlen($name) < 3)         json_err('Datos inválidos.');
        if (!preg_match('/^\d{7,12}$/', $dni)) json_err('DNI inválido.');

        $dup = $pdo->prepare('SELECT id FROM users WHERE dni=? AND id<>?');
        $dup->execute([$dni, $id]);
        if ($dup->fetchColumn()) json_err("El DNI $dni ya existe.");

        $pdo->prepare("UPDATE users SET dni=?,full_name=?,email=?,phone=? WHERE id=?")
            ->execute([$dni, $name, $email ?: null, $phone ?: null, $id]);

        $row = $pdo->query("SELECT id,dni,full_name,email,phone,role,is_active,last_login
                            FROM users WHERE id=$id")->fetch();
        json_ok('Usuario actualizado.', ['user' => $row]);
    }

    if ($act === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id === (int)$u['id']) json_err('No puedes eliminarte a ti mismo.');
        $chk = $pdo->query("SELECT role FROM users WHERE id=$id")->fetchColumn();
        if ($chk === 'ADMIN') json_err('No se puede eliminar a otro administrador.');
        $pdo->prepare("UPDATE users SET is_active=0, dni=CONCAT('del_',id,'_',dni),
                       email=NULL WHERE id=?")->execute([$id]);
        json_ok('Usuario eliminado (desactivado).');
    }

    if ($act === 'notif_bulk') {
        $roles = $_POST['roles'] ?? [];
        $title = trim($_POST['title'] ?? '');
        $body  = trim($_POST['body']  ?? '');
        if (!$title || !$roles) json_err('Completa todos los campos.');
        $in   = implode(',', array_map(fn($r) => $pdo->quote($r), $roles));
        $uids = $pdo->query("SELECT id FROM users WHERE role IN($in) AND is_active=1")
                    ->fetchAll(PDO::FETCH_COLUMN);
        $count = 0;
        foreach ($uids as $uid) {
            notif_create((int)$uid, 'announcement', $title, $body, '', (int)$u['id']);
            $count++;
        }
        json_ok("Notificación enviada a $count usuario(s).");
    }

    if ($act === 'export_csv') {
        $role_f = $_POST['role_filter'] ?? '';
        $where  = $role_f
            ? "WHERE role=" . $pdo->quote($role_f) . " AND is_active=1"
            : "WHERE is_active=1";

        /* Detectar si existen columnas opcionales */
        $cols = $pdo->query("SHOW COLUMNS FROM users")->fetchAll(PDO::FETCH_COLUMN);
        $has_created  = in_array('created_at', $cols);
        $has_login    = in_array('last_login',  $cols);
        $sel_created  = $has_created ? "DATE_FORMAT(created_at,'%d/%m/%Y')" : "NULL";
        $sel_login    = $has_login   ? "DATE_FORMAT(last_login,'%d/%m/%Y %H:%i')" : "NULL";

        $rows = $pdo->query("
            SELECT dni, full_name, email, phone, role, is_active,
                   $sel_created AS creado,
                   $sel_login   AS ultimo_acceso
            FROM users $where ORDER BY role, full_name
        ")->fetchAll();

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="usuarios_'.date('Ymd').'.csv"');
        $out = fopen('php://output', 'w');
        fputs($out, "\xEF\xBB\xBF"); // ✅ BOM UTF-8 real (3 bytes)
        fputcsv($out, ['DNI','Nombre','Email','Teléfono','Rol','Activo','Creado','Último acceso']);
        foreach ($rows as $r) fputcsv($out, $r);
        fclose($out);
        exit;
    }
}

/* ══════════════════════════════════════════════════════════
   GET — Detectar columnas disponibles en tabla users
   ══════════════════════════════════════════════════════════ */
$_cols       = $pdo->query("SHOW COLUMNS FROM users")->fetchAll(PDO::FETCH_COLUMN);
$has_login   = in_array('last_login',  $_cols);
$has_created = in_array('created_at',  $_cols);
$has_phone   = in_array('phone',       $_cols);

/* ══════════════════════════════════════════════════════════
   GET — filtros + paginación
   ══════════════════════════════════════════════════════════ */
$q_search = trim($_GET['q']     ?? '');
$f_role   = $_GET['role']       ?? '';
$f_status = $_GET['status']     ?? 'active';
$f_login  = $_GET['login']      ?? '';
$page     = max(1, (int)($_GET['page'] ?? 1));

$where  = [];
$params = [];

if ($q_search) {
    $like    = "%$q_search%";
    $where[] = "(full_name LIKE ? OR dni LIKE ? OR email LIKE ?)";
    $params  = array_merge($params, [$like, $like, $like]);
}
if ($f_role)                  { $where[] = 'role=?';     $params[] = $f_role; }
if ($f_status === 'active')     $where[] = 'is_active=1';
if ($f_status === 'inactive')   $where[] = 'is_active=0';
if ($has_login) {
    if ($f_login === 'never')   $where[] = 'last_login IS NULL';
    if ($f_login === 'recent')  $where[] = 'last_login >= DATE_SUB(NOW(), INTERVAL 7 DAY)';
}

$whereSQL = $where ? 'WHERE ' . implode(' AND ', $where) : '';

/* ── Query 1: Total ── */
try {
    $total_q = $pdo->prepare("SELECT COUNT(*) FROM users $whereSQL");
    $total_q->execute($params);
    $total = (int)$total_q->fetchColumn();
} catch (Throwable $e) {
    die('<pre style="background:#ffebee;color:#c62828;padding:20px;border-radius:8px">
❌ ERROR en COUNT: ' . $e->getMessage() . '
SQL: SELECT COUNT(*) FROM users ' . $whereSQL . '
Params: ' . print_r($params, true) . '</pre>');
}

$pages  = max(1, (int)ceil($total / $per_page));
$offset = ($page - 1) * $per_page;

/* ── Construir SELECT dinámico según columnas existentes ── */
$sel_login   = $has_login   ? 'last_login'                                    : 'NULL AS last_login';
$sel_created = $has_created ? "DATE_FORMAT(created_at,'%d/%m/%Y') AS creado"  : "NULL AS creado";
$sel_phone   = $has_phone   ? 'phone'                                          : 'NULL AS phone';

/* ── Query 2: Usuarios paginados ── */
try {
    $stmt = $pdo->prepare("
        SELECT id, dni, full_name, email, $sel_phone, role,
               is_active, $sel_login, $sel_created
        FROM users $whereSQL
        ORDER BY FIELD(role,'ADMIN','DOCENTE','ALUMNO'), full_name
        LIMIT $per_page OFFSET $offset
    ");
    $stmt->execute($params);
    $users = $stmt->fetchAll();
} catch (Throwable $e) {
    die('<pre style="background:#ffebee;color:#c62828;padding:20px;border-radius:8px">
❌ ERROR en USUARIOS: ' . $e->getMessage() . '</pre>');
}

/* ── Query 3: Stats ── */
try {
    $sel_sin_acceso       = $has_login ? 'SUM(last_login IS NULL AND is_active=1)' : '0';
    $sel_activos_recientes = $has_login
        ? "SUM(last_login >= DATE_SUB(NOW(),INTERVAL 7 DAY))" : '0';

    $stats = $pdo->query("
        SELECT
            COUNT(*)                             AS total,
            SUM(role='ADMIN'   AND is_active=1)  AS admins,
            SUM(role='DOCENTE' AND is_active=1)  AS docentes,
            SUM(role='ALUMNO'  AND is_active=1)  AS alumnos,
            SUM(is_active=0)                     AS inactivos,
            $sel_sin_acceso                      AS sin_acceso,
            $sel_activos_recientes               AS activos_recientes
        FROM users
    ")->fetch();
} catch (Throwable $e) {
    die('<pre style="background:#ffebee;color:#c62828;padding:20px;border-radius:8px">
❌ ERROR en STATS: ' . $e->getMessage() . '</pre>');
}

layout_start('Gestión de Usuarios', $u);
$csrf = htmlspecialchars(csrf_token());

function role_badge(string $role): string {
    return match($role) {
        'ADMIN'   => '<span class="bdg" style="background:#e8eaf6;color:#3949ab">⚙️ Admin</span>',
        'DOCENTE' => '<span class="bdg" style="background:#e0f2f1;color:#00796b">👨‍🏫 Docente</span>',
        'ALUMNO'  => '<span class="bdg" style="background:#e8f5e9;color:#2e7d32">🎓 Alumno</span>',
        default   => '<span class="bdg">' . $role . '</span>',
    };
}
?>

<!-- CABECERA -->
<div style="display:flex;align-items:center;justify-content:space-between;
     flex-wrap:wrap;gap:12px;margin-bottom:20px">
  <div>
    <h2 style="font-size:18px;font-weight:800;color:var(--navy)">👥 Gestión de Usuarios</h2>
    <p class="txt-muted">Todos los usuarios del sistema</p>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <button class="btn btn-outline btn-sm" onclick="openModal('m-notif-bulk')">📢 Notif. masiva</button>
    <form method="post" style="display:inline" id="f-export">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="act"  value="export_csv">
      <input type="hidden" name="role_filter" value="<?= htmlspecialchars($f_role) ?>" id="exp-role">
      <button type="submit" class="btn btn-outline btn-sm">📊 Exportar CSV</button>
    </form>
    <a href="docentes.php" class="btn btn-teal btn-sm">➕ Nuevo Docente</a>
    <a href="alumnos.php"  class="btn btn-navy btn-sm">➕ Nuevo Alumno</a>
  </div>
</div>

<!-- STATS -->
<div class="stats-row" style="margin-bottom:18px">
<?php
$st_items = [
    ['👥','Total',            $stats['total'],             'var(--navy)'],
    ['⚙️','Admins',           $stats['admins'],            '#3949ab'],
    ['👨‍🏫','Docentes',        $stats['docentes'],          'var(--teal)'],
    ['🎓','Alumnos',          $stats['alumnos'],           'var(--green)'],
    ['⚠️','Sin acceso aún',   $stats['sin_acceso'],        'var(--orange)'],
    ['🟢','Activos (7 días)', $stats['activos_recientes'], 'var(--green)'],
    ['🔴','Inactivos',        $stats['inactivos'],         'var(--red)'],
];
foreach ($st_items as [$ic,$lb,$val,$color]): ?>
  <div class="stat-card" style="border-top-color:<?= $color ?>">
    <div class="sv" style="color:<?= $color ?>"><?= (int)$val ?></div>
    <div class="sl"><?= $ic ?> <?= $lb ?></div>
  </div>
<?php endforeach; ?>
</div>

<!-- FILTROS -->
<div class="card" style="padding:12px 16px;margin-bottom:14px">
  <form method="get" style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end">
    <div class="tbl-search" style="flex:1;min-width:200px">
      <span class="tbl-sico">🔍</span>
      <input name="q" value="<?= htmlspecialchars($q_search) ?>" placeholder="Nombre, DNI o email...">
    </div>
    <div class="fg" style="min-width:130px">
      <label style="font-size:11px;font-weight:700;color:var(--navy)">Rol</label>
      <select name="role" onchange="this.form.submit()">
        <option value="">Todos</option>
        <option value="ADMIN"   <?= $f_role==='ADMIN'  ?'selected':'' ?>>⚙️ Admin</option>
        <option value="DOCENTE" <?= $f_role==='DOCENTE'?'selected':'' ?>>👨‍🏫 Docente</option>
        <option value="ALUMNO"  <?= $f_role==='ALUMNO' ?'selected':'' ?>>🎓 Alumno</option>
      </select>
    </div>
    <div class="fg" style="min-width:130px">
      <label style="font-size:11px;font-weight:700;color:var(--navy)">Estado</label>
      <select name="status">
        <option value=""         <?= $f_status===''        ?'selected':'' ?>>Todos</option>
        <option value="active"   <?= $f_status==='active'  ?'selected':'' ?>>Activos</option>
        <option value="inactive" <?= $f_status==='inactive'?'selected':'' ?>>Inactivos</option>
      </select>
    </div>
    <?php if ($has_login): ?>
    <div class="fg" style="min-width:150px">
      <label style="font-size:11px;font-weight:700;color:var(--navy)">Último acceso</label>
      <select name="login">
        <option value=""       <?= $f_login===''      ?'selected':'' ?>>Todos</option>
        <option value="recent" <?= $f_login==='recent'?'selected':'' ?>>Últimos 7 días</option>
        <option value="never"  <?= $f_login==='never' ?'selected':'' ?>>Nunca ingresaron</option>
      </select>
    </div>
    <?php endif; ?>
    <div style="display:flex;gap:6px;align-items:flex-end">
      <button type="submit" class="btn btn-navy btn-sm">🔍 Filtrar</button>
      <a href="?" class="btn btn-outline btn-sm">✕ Limpiar</a>
    </div>
  </form>
</div>

<!-- INFO + VISTA TOGGLE -->
<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;margin-bottom:10px">
  <div class="txt-muted"><?= $total ?> usuario(s) · Página <?= $page ?> de <?= $pages ?></div>
  <div style="display:flex;gap:6px">
    <button class="btn btn-outline btn-xs" id="btn-card-v" onclick="setUsrView('cards')">⊞</button>
    <button class="btn btn-outline btn-xs" id="btn-list-v" onclick="setUsrView('list')">☰</button>
  </div>
</div>

<!-- ════ VISTA TARJETAS ════ -->
<div id="uv-cards">
  <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px;margin-bottom:16px">
  <?php foreach ($users as $usr):
    $active = (int)$usr['is_active'];
    $is_me  = (int)$usr['id'] === (int)$u['id'];
    $role_colors = [
        'ADMIN'   => ['#3949ab','#e8eaf6'],
        'DOCENTE' => ['#00796b','#e0f2f1'],
        'ALUMNO'  => ['#2e7d32','#e8f5e9'],
    ];
    [$rc,$rbg] = $role_colors[$usr['role']] ?? ['var(--navy)','var(--bg)'];
  ?>
    <div class="usr-card <?= $active?'':'usr-inactive' ?>" id="uc-<?= (int)$usr['id'] ?>"
         style="border-top:3px solid <?= $rc ?>">
      <div style="display:flex;align-items:flex-start;gap:10px;margin-bottom:10px">
        <div style="width:40px;height:40px;border-radius:50%;background:<?= $rc ?>;color:#fff;
             flex-shrink:0;display:flex;align-items:center;justify-content:center;
             font-size:15px;font-weight:800">
          <?= mb_strtoupper(mb_substr($usr['full_name'],0,2)) ?>
        </div>
        <div style="flex:1;min-width:0">
          <div style="font-size:13px;font-weight:800;color:var(--navy);
               white-space:nowrap;overflow:hidden;text-overflow:ellipsis">
            <?= htmlspecialchars($usr['full_name']) ?>
            <?= $is_me ? '<span style="font-size:10px;background:#fff3e0;color:var(--orange);padding:1px 6px;border-radius:10px;margin-left:4px">Tú</span>' : '' ?>
          </div>
          <div class="txt-muted" style="font-size:11px">🪪 <?= htmlspecialchars($usr['dni']) ?></div>
        </div>
        <span class="bdg <?= $active?'bdg-on':'bdg-off' ?>" id="ub-<?= (int)$usr['id'] ?>"
              style="flex-shrink:0;font-size:10px">
          <?= $active?'Activo':'Inact.' ?>
        </span>
      </div>

      <div style="margin-bottom:10px">
        <?= role_badge($usr['role']) ?>
        <?php if (!empty($usr['email'])): ?>
          <div class="txt-muted" style="font-size:11px;margin-top:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">
            ✉️ <?= htmlspecialchars($usr['email']) ?>
          </div>
        <?php endif; ?>
        <div class="txt-muted" style="font-size:10px;margin-top:3px">
          <?php if (!empty($usr['last_login'])): ?>
            🕐 <?= date('d/m/Y H:i', strtotime($usr['last_login'])) ?>
          <?php elseif ($has_login): ?>
            ⚠️ Nunca ingresó
          <?php endif; ?>
          <?php if (!empty($usr['creado'])): ?>
            · 📅 <?= $usr['creado'] ?>
          <?php endif; ?>
        </div>
      </div>

      <div style="display:flex;gap:5px;flex-wrap:wrap">
        <?php if (!$is_me): ?>
        <select class="role-sel btn-xs"
          style="flex:1;min-width:80px;border-radius:8px;border:1.5px solid var(--border);
                 padding:4px 6px;font-size:11px;font-weight:700;font-family:var(--font);
                 color:var(--navy);background:var(--bg);cursor:pointer"
          onchange="changeRole(<?= (int)$usr['id'] ?>,this)">
          <option value="ADMIN"   <?= $usr['role']==='ADMIN'  ?'selected':'' ?>>⚙️ Admin</option>
          <option value="DOCENTE" <?= $usr['role']==='DOCENTE'?'selected':'' ?>>👨‍🏫 Docente</option>
          <option value="ALUMNO"  <?= $usr['role']==='ALUMNO' ?'selected':'' ?>>🎓 Alumno</option>
        </select>
        <?php endif; ?>
        <button class="btn btn-outline btn-xs"
                onclick='openEditUsr(<?= htmlspecialchars(json_encode([
                  "id"        => (int)$usr["id"],
                  "dni"       => $usr["dni"],
                  "full_name" => $usr["full_name"],
                  "email"     => $usr["email"] ?? "",
                  "phone"     => $usr["phone"] ?? "",
                ], JSON_HEX_APOS|JSON_HEX_QUOT)) ?>)'>✏️</button>
        <button class="btn btn-outline btn-xs"
                onclick="openResetUsr(<?= (int)$usr['id'] ?>,'<?= addslashes($usr['full_name']) ?>')">🔑</button>
        <?php if (!$is_me): ?>
        <button class="btn btn-orange btn-xs" id="utb-<?= (int)$usr['id'] ?>"
                onclick="togUsr(<?= (int)$usr['id'] ?>,this)"><?= $active?'↓':'↑' ?></button>
        <button class="btn btn-red btn-xs" onclick="delUsr(<?= (int)$usr['id'] ?>)">🗑</button>
        <?php endif; ?>
      </div>
    </div>
  <?php endforeach; ?>
  <?php if (!$users): ?>
    <div style="grid-column:1/-1;text-align:center;padding:40px;color:var(--muted)">
      <div style="font-size:40px;margin-bottom:10px">👥</div>
      No se encontraron usuarios.
    </div>
  <?php endif; ?>
  </div>
</div>

<!-- ════ VISTA LISTA ════ -->
<div id="uv-list" style="display:none">
  <div class="card" style="padding:0;overflow:hidden;margin-bottom:16px">
    <div class="table-wrap">
      <table id="t-usuarios">
        <thead>
          <tr>
            <th>#</th><th>Usuario</th><th>DNI</th><th>Rol</th>
            <th>Email</th>
            <?php if ($has_login): ?><th>Último acceso</th><?php endif; ?>
            <th>Estado</th>
            <th style="text-align:center">Acciones</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($users as $i => $usr):
          $active = (int)$usr['is_active'];
          $is_me  = (int)$usr['id'] === (int)$u['id'];
        ?>
        <tr id="utr-<?= (int)$usr['id'] ?>" <?= $active?'':'style="opacity:.6"' ?>>
          <td class="txt-muted"><?= $offset+$i+1 ?></td>
          <td>
            <div style="display:flex;align-items:center;gap:8px">
              <div style="width:32px;height:32px;border-radius:50%;background:var(--navy);
                   display:flex;align-items:center;justify-content:center;
                   font-size:12px;font-weight:800;color:#fff;flex-shrink:0">
                <?= mb_strtoupper(mb_substr($usr['full_name'],0,1)) ?>
              </div>
              <div>
                <div style="font-size:13px;font-weight:700;color:var(--navy)">
                  <?= htmlspecialchars($usr['full_name']) ?>
                  <?= $is_me ? '<span style="font-size:10px;background:#fff3e0;color:var(--orange);padding:1px 5px;border-radius:8px;margin-left:3px">Tú</span>' : '' ?>
                </div>
                <?php if (!empty($usr['creado'])): ?>
                <div class="txt-muted">📅 <?= $usr['creado'] ?></div>
                <?php endif; ?>
              </div>
            </div>
          </td>
          <td class="txt-muted"><?= htmlspecialchars($usr['dni']) ?></td>
          <td id="urt-<?= (int)$usr['id'] ?>"><?= role_badge($usr['role']) ?></td>
          <td class="txt-muted"><?= htmlspecialchars($usr['email'] ?? '—') ?></td>
          <?php if ($has_login): ?>
          <td class="txt-muted" style="font-size:11px">
            <?php if (!empty($usr['last_login'])): ?>
              🕐 <?= date('d/m/Y H:i', strtotime($usr['last_login'])) ?>
            <?php else: ?>
              <span style="color:var(--orange)">⚠️ Nunca</span>
            <?php endif; ?>
          </td>
          <?php endif; ?>
          <td>
            <span class="bdg <?= $active?'bdg-on':'bdg-off' ?>" id="ulb-<?= (int)$usr['id'] ?>">
              <?= $active?'Activo':'Inactivo' ?>
            </span>
          </td>
          <td>
            <div style="display:flex;gap:4px;justify-content:center;flex-wrap:wrap">
              <button class="btn btn-outline btn-xs"
                      onclick='openEditUsr(<?= htmlspecialchars(json_encode([
                        "id"        => (int)$usr["id"],
                        "dni"       => $usr["dni"],
                        "full_name" => $usr["full_name"],
                        "email"     => $usr["email"] ?? "",
                        "phone"     => $usr["phone"] ?? "",
                      ], JSON_HEX_APOS|JSON_HEX_QUOT)) ?>)'>✏️</button>
              <button class="btn btn-outline btn-xs"
                      onclick="openResetUsr(<?= (int)$usr['id'] ?>,'<?= addslashes($usr['full_name']) ?>')">🔑</button>
              <?php if (!$is_me): ?>
              <button class="btn btn-orange btn-xs" id="ultb-<?= (int)$usr['id'] ?>"
                      onclick="togUsr(<?= (int)$usr['id'] ?>,this)"><?= $active?'↓':'↑' ?></button>
              <button class="btn btn-red btn-xs" onclick="delUsr(<?= (int)$usr['id'] ?>)">🗑</button>
              <?php endif; ?>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- PAGINACIÓN -->
<?php if ($pages > 1): ?>
<div style="display:flex;gap:6px;justify-content:center;flex-wrap:wrap;margin-bottom:20px">
  <?php $rs=max(1,$page-3); $re=min($pages,$page+3); ?>
  <?php if ($rs>1): ?>
    <a href="?<?= http_build_query(array_merge($_GET,['page'=>1])) ?>" class="btn btn-outline btn-sm">1</a>
    <?php if ($rs>2): ?><span style="padding:8px;color:var(--muted)">…</span><?php endif; ?>
  <?php endif; ?>
  <?php for ($p=$rs;$p<=$re;$p++): ?>
    <a href="?<?= http_build_query(array_merge($_GET,['page'=>$p])) ?>"
       class="btn <?= $p===$page?'btn-navy':'btn-outline' ?> btn-sm"><?= $p ?></a>
  <?php endfor; ?>
  <?php if ($re<$pages): ?>
    <?php if ($re<$pages-1): ?><span style="padding:8px;color:var(--muted)">…</span><?php endif; ?>
    <a href="?<?= http_build_query(array_merge($_GET,['page'=>$pages])) ?>" class="btn btn-outline btn-sm"><?= $pages ?></a>
  <?php endif; ?>
</div>
<?php endif; ?>

<!-- ════ MODALES ════ -->
<div class="modal-ov" id="m-edit-usr">
  <div class="modal" style="max-width:460px">
    <h3>✏️ Editar Usuario</h3>
    <form id="f-edit-usr" method="post">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="act"  value="edit">
      <input type="hidden" name="id"   id="eu-id">
      <div class="form-grid">
        <div class="fg">
          <label>DNI *</label>
          <input name="dni" id="eu-dni" required maxlength="12">
        </div>
        <div class="fg" style="grid-column:1/-1">
          <label>Nombre completo *</label>
          <input name="full_name" id="eu-name" required>
        </div>
        <div class="fg">
          <label>Email</label>
          <input name="email" id="eu-email" type="email">
        </div>
        <div class="fg">
          <label>Teléfono</label>
          <input name="phone" id="eu-phone" type="tel">
        </div>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline" onclick="closeModal('m-edit-usr')">Cancelar</button>
        <button type="submit" class="btn btn-navy">💾 Guardar</button>
      </div>
    </form>
  </div>
</div>

<div class="modal-ov" id="m-pass-usr">
  <div class="modal" style="max-width:360px">
    <h3>🔑 Restablecer Contraseña</h3>
    <p class="txt-muted" id="pu-name" style="margin-bottom:14px"></p>
    <form id="f-pass-usr" method="post">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="act"  value="reset_pass">
      <input type="hidden" name="id"   id="pu-id">
      <div class="fg" style="margin-bottom:14px">
        <label>Nueva contraseña</label>
        <input name="pass" type="text" required minlength="4" placeholder="Mínimo 4 caracteres">
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline" onclick="closeModal('m-pass-usr')">Cancelar</button>
        <button type="submit" class="btn btn-navy">🔑 Restablecer</button>
      </div>
    </form>
  </div>
</div>

<div class="modal-ov" id="m-notif-bulk">
  <div class="modal" style="max-width:440px">
    <h3>📢 Notificación Masiva</h3>
    <form id="f-notif-bulk" method="post">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="act"  value="notif_bulk">
      <div class="fg" style="margin-bottom:12px">
        <label>Enviar a roles</label>
        <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:4px">
          <?php foreach (['ADMIN'=>'⚙️ Admin','DOCENTE'=>'👨‍🏫 Docentes','ALUMNO'=>'🎓 Alumnos'] as $rv=>$rl): ?>
          <label style="display:flex;align-items:center;gap:5px;font-size:13px;cursor:pointer;font-weight:400">
            <input type="checkbox" name="roles[]" value="<?= $rv ?>" style="width:auto"> <?= $rl ?>
          </label>
          <?php endforeach; ?>
        </div>
      </div>
      <div class="fg" style="margin-bottom:12px">
        <label>Título *</label>
        <input name="title" type="text" required placeholder="Asunto del anuncio">
      </div>
      <div class="fg" style="margin-bottom:12px">
        <label>Mensaje</label>
        <textarea name="body" rows="3" placeholder="Cuerpo del mensaje"></textarea>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline" onclick="closeModal('m-notif-bulk')">Cancelar</button>
        <button type="submit" class="btn btn-navy">📤 Enviar a todos</button>
      </div>
    </form>
  </div>
</div>

<style>
.usr-card {
  background:var(--card);border-radius:var(--r);padding:14px;
  box-shadow:var(--sh);transition:var(--tr);border:1.5px solid var(--border)
}
.usr-card:hover { transform:translateY(-2px);box-shadow:0 7px 22px rgba(0,0,0,.1) }
.usr-inactive   { opacity:.6 }
</style>

<script>
var CSRF = '<?= $csrf ?>';
var _uv  = localStorage.getItem('usr_view') || 'cards';
setUsrView(_uv, true);

function setUsrView(v, silent) {
  _uv = v;
  if (!silent) localStorage.setItem('usr_view', v);
  document.getElementById('uv-cards').style.display = v === 'cards' ? '' : 'none';
  document.getElementById('uv-list').style.display  = v === 'list'  ? '' : 'none';
  document.getElementById('btn-card-v').className = 'btn btn-xs ' + (v==='cards'?'btn-navy':'btn-outline');
  document.getElementById('btn-list-v').className = 'btn btn-xs ' + (v==='list' ?'btn-navy':'btn-outline');
}
function openModal(id)  { document.getElementById(id).classList.add('show'); }
function closeModal(id) { document.getElementById(id).classList.remove('show'); }
document.querySelectorAll('.modal-ov').forEach(function(ov) {
  ov.addEventListener('click', function(e) { if (e.target===this) this.classList.remove('show'); });
});

function openEditUsr(d) {
  document.getElementById('eu-id').value    = d.id;
  document.getElementById('eu-dni').value   = d.dni;
  document.getElementById('eu-name').value  = d.full_name;
  document.getElementById('eu-email').value = d.email;
  document.getElementById('eu-phone').value = d.phone;
  openModal('m-edit-usr');
}
ajaxForm(document.getElementById('f-edit-usr'), function(d) {
  closeModal('m-edit-usr'); toast(d.msg, 'ok');
  if (d.user) {
    var c = document.getElementById('uc-' + d.user.id);
    if (c) {
      var nm = c.querySelector('[style*="font-weight:800"]');
      if (nm) nm.firstChild.textContent = d.user.full_name;
    }
  }
});

function togUsr(id, btn) {
  btn.disabled = true;
  var fd = new FormData();
  fd.append('csrf',CSRF); fd.append('act','toggle'); fd.append('id',id);
  fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd})
  .then(r=>r.json()).then(d=>{
    toast(d.msg, d.ok?'ok':'err');
    if (d.ok) {
      document.getElementById('uc-'+id)?.classList.toggle('usr-inactive',!d.is_active);
      ['ub-','ulb-'].forEach(function(p){
        var b=document.getElementById(p+id); if(!b)return;
        b.className='bdg '+(d.is_active?'bdg-on':'bdg-off');
        b.textContent=d.is_active?'Activo':'Inact.';
      });
      btn.innerHTML=d.is_active?'↓':'↑';
      var b2=document.getElementById('utb-'+id); if(b2) b2.innerHTML=d.is_active?'↓':'↑';
    }
    btn.disabled=false;
  });
}

function changeRole(id, sel) {
  var role=sel.value;
  confirmModal('¿Cambiar rol a '+role+'?', function(){
    var fd=new FormData();
    fd.append('csrf',CSRF); fd.append('act','change_role');
    fd.append('id',id);    fd.append('role',role);
    fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd})
    .then(r=>r.json()).then(d=>{
      toast(d.msg,d.ok?'ok':'err');
      if(!d.ok){location.reload();return;}
      var rt=document.getElementById('urt-'+id);
      if(rt){
        var labels={ADMIN:'⚙️ Admin',DOCENTE:'👨‍🏫 Docente',ALUMNO:'🎓 Alumno'};
        var colors={ADMIN:'#3949ab;background:#e8eaf6',DOCENTE:'#00796b;background:#e0f2f1',ALUMNO:'#2e7d32;background:#e8f5e9'};
        rt.innerHTML='<span class="bdg" style="color:'+colors[role]+'">'+labels[role]+'</span>';
      }
    });
  },'🔄 Cambiar rol');
}

function delUsr(id) {
  confirmModal('¿Eliminar este usuario? La acción es irreversible.', function(){
    var fd=new FormData();
    fd.append('csrf',CSRF); fd.append('act','delete'); fd.append('id',id);
    fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd})
    .then(r=>r.json()).then(d=>{
      toast(d.msg,d.ok?'ok':'err');
      if(d.ok){
        document.getElementById('uc-'+id)?.remove();
        document.getElementById('utr-'+id)?.remove();
      }
    });
  },'🗑️ Eliminar usuario');
}

function openResetUsr(id, name) {
  document.getElementById('pu-id').value         = id;
  document.getElementById('pu-name').textContent = '👤 '+name;
  openModal('m-pass-usr');
}
ajaxForm(document.getElementById('f-pass-usr'),   function(d){closeModal('m-pass-usr');  toast(d.msg,'ok');});
ajaxForm(document.getElementById('f-notif-bulk'), function(d){closeModal('m-notif-bulk');toast(d.msg,'ok');});
</script>
<?php layout_end(); ?>