<?php
// ══════════════════════════════════
// PROSES POST sebelum include header
// ══════════════════════════════════
$rootDir   = str_replace('\\', '/', dirname(__DIR__));
$uploadUrl = 'uploads/foto_users/';
$uploadAbs = $rootDir . '/uploads/foto_users/';

function autoCreateUserSiswa(PDO $pdo, int $siswaId, string $nis, string $nama): array {
    $username = $nis; $password = $nis;
    $cek = $pdo->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
    $cek->execute([$username]);
    if ($cek->fetch()) {
        $pdo->prepare("UPDATE users SET siswa_id=? WHERE username=? AND (siswa_id IS NULL OR siswa_id=0)")->execute([$siswaId, $username]);
        return ['created' => false, 'username' => $username, 'password' => $password];
    }
    $hash = password_hash($password, PASSWORD_BCRYPT);
    $pdo->prepare("INSERT INTO users (username, password, nama, role, siswa_id, is_active) VALUES (?, ?, ?, 'siswa', ?, 1)")->execute([$username, $hash, $nama, $siswaId]);
    return ['created' => true, 'username' => $username, 'password' => $password];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $act = $_POST['action'] ?? '';
    if ($act === 'sinkron_users') {
        $stSiswa = $pdo->query("SELECT s.id, s.nis, s.nama FROM siswa s WHERE s.status = 'aktif' AND NOT EXISTS (SELECT 1 FROM users u WHERE u.siswa_id = s.id) ORDER BY s.nama");
        $siswaTanpaUser = $stSiswa->fetchAll(); $dibuat = 0;
        foreach ($siswaTanpaUser as $s) { $result = autoCreateUserSiswa($pdo, (int)$s['id'], $s['nis'], $s['nama']); if ($result['created']) $dibuat++; }
        $_SESSION['toast'] = $dibuat > 0 ? "✅ Sinkronisasi selesai: {$dibuat} akun baru dibuat (username & password = NIS masing-masing siswa)" : '✅ Semua siswa aktif sudah memiliki akun login';
        redirect('index.php?page=users');
    }
    if ($act === 'tambah') {
        $username = trim($_POST['username'] ?? ''); $nama = trim($_POST['nama'] ?? '');
        $password = $_POST['password'] ?? ''; $role = $_POST['role'] ?? 'siswa';
        $siswaId = !empty($_POST['siswa_id']) ? (int)$_POST['siswa_id'] : null;
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        if ($username && $password) {
            $cek = $pdo->prepare("SELECT id FROM users WHERE username=?"); $cek->execute([$username]);
            if ($cek->fetch()) { $_SESSION['toast'] = '⚠️ Username sudah digunakan'; }
            else { $hash = password_hash($password, PASSWORD_BCRYPT); $pdo->prepare("INSERT INTO users (username,password,nama,role,siswa_id,is_active) VALUES (?,?,?,?,?,?)")->execute([$username, $hash, $nama, $role, $siswaId, $isActive]); $_SESSION['toast'] = '✅ User berhasil ditambahkan'; }
        } else { $_SESSION['toast'] = '⚠️ Username dan password wajib diisi'; }
    } elseif ($act === 'edit') {
        $id = (int)($_POST['id'] ?? 0); $username = trim($_POST['username'] ?? ''); $nama = trim($_POST['nama'] ?? '');
        $role = $_POST['role'] ?? 'siswa'; $siswaId = !empty($_POST['siswa_id']) ? (int)$_POST['siswa_id'] : null;
        $isActive = isset($_POST['is_active']) ? 1 : 0; $password = $_POST['password'] ?? '';
        $cek = $pdo->prepare("SELECT id FROM users WHERE username=? AND id!=?"); $cek->execute([$username, $id]);
        if ($cek->fetch()) { $_SESSION['toast'] = '⚠️ Username sudah digunakan user lain'; }
        else {
            if ($password) { $hash = password_hash($password, PASSWORD_BCRYPT); $pdo->prepare("UPDATE users SET username=?,nama=?,role=?,siswa_id=?,is_active=?,password=? WHERE id=?")->execute([$username,$nama,$role,$siswaId,$isActive,$hash,$id]); }
            else { $pdo->prepare("UPDATE users SET username=?,nama=?,role=?,siswa_id=?,is_active=? WHERE id=?")->execute([$username,$nama,$role,$siswaId,$isActive,$id]); }
            $_SESSION['toast'] = '✅ User berhasil diperbarui';
        }
    } elseif ($act === 'hapus') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id === (int)($_SESSION['admin_id'] ?? 0)) { $_SESSION['toast'] = '⚠️ Tidak bisa menghapus akun sendiri'; }
        else { $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$id]); $_SESSION['toast'] = '🗑️ User berhasil dihapus'; }
    } elseif ($act === 'toggle_aktif') {
        $id = (int)($_POST['id'] ?? 0); $stat = (int)($_POST['is_active'] ?? 0);
        $pdo->prepare("UPDATE users SET is_active=? WHERE id=?")->execute([$stat ? 0 : 1, $id]);
        $_SESSION['toast'] = $stat ? '⛔ User dinonaktifkan' : '✅ User diaktifkan';
    } elseif ($act === 'reset_password') {
        $id = (int)($_POST['id'] ?? 0);
        $stU = $pdo->prepare("SELECT u.username, s.nis FROM users u LEFT JOIN siswa s ON u.siswa_id=s.id WHERE u.id=?"); $stU->execute([$id]); $uRow = $stU->fetch();
        if ($uRow) { $newPass = $uRow['nis'] ?: $uRow['username']; $hash = password_hash($newPass, PASSWORD_BCRYPT); $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([$hash, $id]); $_SESSION['toast'] = "🔑 Password direset ke: {$newPass}"; }
    }
    redirect('index.php?page=users');
}

require_once 'layout/header.php';

$search  = trim($_GET['q']      ?? '');
$roleF   = $_GET['role']        ?? '';
$statusF = $_GET['status']      ?? '';
$perPage   = (int)($_GET['per_page'] ?? 20);
$allowedPP = [10, 20, 50, 100];
if (!in_array($perPage, $allowedPP)) $perPage = 20;
$currentPage = max(1, (int)($_GET['p'] ?? 1));

$whereSQL = " WHERE 1=1"; $params = [];
if ($search)         { $whereSQL .= " AND (u.nama LIKE ? OR u.username LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }
if ($roleF)          { $whereSQL .= " AND u.role=?";       $params[] = $roleF; }
if ($statusF !== '') { $whereSQL .= " AND u.is_active=?";  $params[] = (int)$statusF; }

$stmtC = $pdo->prepare("SELECT COUNT(*) FROM users u LEFT JOIN siswa s ON u.siswa_id=s.id" . $whereSQL);
$stmtC->execute($params); $totalRows = (int)$stmtC->fetchColumn(); $stmtC->closeCursor();
$totalPages = max(1, (int)ceil($totalRows / $perPage));
if ($currentPage > $totalPages) $currentPage = $totalPages;
$offset = ($currentPage - 1) * $perPage;

$stmtD = $pdo->prepare("SELECT u.*, s.nama as nama_siswa, s.nis, s.kelas, s.foto as foto_siswa FROM users u LEFT JOIN siswa s ON u.siswa_id=s.id" . $whereSQL . " ORDER BY u.role, u.nama LIMIT ? OFFSET ?");
foreach ($params as $pi => $pv) { $stmtD->bindValue($pi + 1, $pv, PDO::PARAM_STR); }
$stmtD->bindValue(count($params) + 1, (int)$perPage, PDO::PARAM_INT);
$stmtD->bindValue(count($params) + 2, (int)$offset,  PDO::PARAM_INT);
$stmtD->execute(); $users = $stmtD->fetchAll(); $stmtD->closeCursor();

$siswas         = $pdo->query("SELECT id, nama, nis, kelas FROM siswa WHERE status='aktif' ORDER BY nama")->fetchAll();
$totalAll       = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$totalAdmin     = $pdo->query("SELECT COUNT(*) FROM users WHERE role='admin'")->fetchColumn();
$totalSiswa     = $pdo->query("SELECT COUNT(*) FROM users WHERE role='siswa'")->fetchColumn();
$totalAktif     = $pdo->query("SELECT COUNT(*) FROM users WHERE is_active=1")->fetchColumn();
$siswaTanpaAkun = (int)$pdo->query("SELECT COUNT(*) FROM siswa s WHERE s.status='aktif' AND NOT EXISTS (SELECT 1 FROM users u WHERE u.siswa_id=s.id)")->fetchColumn();

$toast = $_SESSION['toast'] ?? ''; unset($_SESSION['toast']);
$avatarColors  = ['#FF6B9D','#A855F7','#38BDF8','#34D399','#FB923C','#FBBF24','#818CF8','#F472B6'];
$fotoSiswaAbs  = $rootDir . '/uploads/foto_siswa/';
$fotoSiswaUrl  = 'uploads/foto_siswa/';

function usersPageUrl($p, $search, $roleF, $statusF, $perPage) {
    return 'index.php?page=users&q='.urlencode($search).'&role='.urlencode($roleF).'&status='.urlencode($statusF).'&per_page='.$perPage.'&p='.$p;
}
function usersPageWindow($current, $total, $w = 2) {
    $s = max(1, $current - $w); $e = min($total, $current + $w);
    if ($e - $s < $w * 2) { if ($s === 1) $e = min($total, $s + $w * 2); else $s = max(1, $e - $w * 2); }
    return range($s, $e);
}
?>
<?php if($toast): ?><script>window.onload=()=>showToast('<?= addslashes($toast) ?>')</script><?php endif ?>

<style>
/* ══════════════════════════════════════════
   USERS PAGE — Aurora Premium Design
══════════════════════════════════════════ */

/* ── Hero Banner ── */
.u-hero {
  background: linear-gradient(135deg, #0D1B35 0%, #1A2E5A 50%, #0D2240 100%);
  border-radius: 20px; padding: 26px 30px; margin-bottom: 22px;
  display: flex; align-items: center; justify-content: space-between;
  flex-wrap: wrap; gap: 18px; position: relative; overflow: hidden;
  box-shadow: 0 10px 40px rgba(13,27,53,.4);
}
.u-hero::before {
  content: ''; position: absolute; inset: 0; pointer-events: none;
  background: radial-gradient(ellipse 55% 70% at 90% 40%, rgba(79,110,247,.2) 0%, transparent 60%),
              radial-gradient(ellipse 35% 50% at 10% 80%, rgba(16,185,129,.1) 0%, transparent 55%);
}
.u-hero::after {
  content: ''; position: absolute; top: -80px; right: -80px;
  width: 260px; height: 260px; border-radius: 50%;
  background: rgba(79,110,247,.07); pointer-events: none;
}
.u-hero-left { position: relative; z-index: 1; }
.u-hero-badge {
  display: inline-flex; align-items: center; gap: 6px;
  background: rgba(79,110,247,.18); border: 1px solid rgba(79,110,247,.3);
  color: #93B8FF; border-radius: 99px; padding: 3px 12px;
  font-size: 11px; font-weight: 700; letter-spacing: 1px; text-transform: uppercase;
  margin-bottom: 8px;
}
.u-hero-title { font-size: 26px; font-weight: 800; color: #fff; letter-spacing: -.4px; margin-bottom: 4px; }
.u-hero-title span { color: #60A5FA; }
.u-hero-sub { font-size: 13px; color: rgba(255,255,255,.5); }
.u-hero-actions { display: flex; gap: 10px; flex-wrap: wrap; position: relative; z-index: 1; }
.u-btn-primary {
  display: inline-flex; align-items: center; gap: 8px;
  background: linear-gradient(135deg,#4F6EF7,#7C9FFF);
  color: #fff; border: none; border-radius: 11px;
  padding: 11px 22px; font-size: 13.5px; font-weight: 700;
  cursor: pointer; font-family: inherit; white-space: nowrap;
  box-shadow: 0 4px 18px rgba(79,110,247,.4); transition: all .2s;
}
.u-btn-primary:hover { transform: translateY(-2px); box-shadow: 0 8px 28px rgba(79,110,247,.5); }
.u-btn-sync {
  display: inline-flex; align-items: center; gap: 8px;
  background: rgba(255,255,255,.1); border: 1.5px solid rgba(255,255,255,.2);
  color: #fff; border-radius: 11px; padding: 10px 18px;
  font-size: 13px; font-weight: 600; cursor: pointer; font-family: inherit; transition: all .2s;
}
.u-btn-sync:hover { background: rgba(255,255,255,.18); }

/* ── Alert sinkron ── */
.sync-banner {
  background: linear-gradient(135deg,#FFFBEB,#FEF9C3);
  border: 1.5px solid #FCD34D; border-radius: 14px;
  padding: 13px 16px; margin-bottom: 18px;
  display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
}
.sync-banner-text { flex: 1; min-width: 200px; font-size: 13px; color: #78350F; }
.sync-banner-text strong { color: #92400E; }
.sync-dot { width: 9px; height: 9px; border-radius: 50%; background: #F59E0B; flex-shrink: 0; animation: sdot 2s infinite; }
@keyframes sdot { 0%,100%{transform:scale(1);opacity:1} 50%{transform:scale(1.5);opacity:.6} }

.info-default-pass {
  background: #EFF6FF; border: 1.5px solid #BFDBFE; border-radius: 12px;
  padding: 12px 15px; margin-bottom: 18px;
  font-size: 12.5px; color: #1E40AF;
  display: flex; align-items: flex-start; gap: 9px; line-height: 1.55;
}

/* ── Stats ── */
.u-stats { display: grid; grid-template-columns: repeat(4,1fr); gap: 14px; margin-bottom: 22px; }
@media(max-width:640px){ .u-stats{grid-template-columns:repeat(2,1fr);gap:10px;} }
.u-stat {
  background: var(--surface); border: 1.5px solid var(--border);
  border-radius: 16px; padding: 18px 20px; position: relative; overflow: hidden;
  transition: transform .2s, box-shadow .2s;
}
.u-stat:hover { transform: translateY(-3px); box-shadow: 0 8px 24px rgba(0,0,0,.08); }
.u-stat-top { position: absolute; top: 0; left: 0; right: 0; height: 3px; border-radius: 16px 16px 0 0; }
.u-stat-icon { font-size: 22px; margin-bottom: 12px; margin-top: 4px; }
.u-stat-num { font-size: 28px; font-weight: 800; letter-spacing: -1.5px; font-family: 'DM Mono',monospace; line-height: 1; margin-bottom: 4px; }
.u-stat-lbl { font-size: 11.5px; color: var(--text3); font-weight: 500; }

/* ── Toolbar ── */
.u-toolbar {
  background: var(--surface); border: 1.5px solid var(--border);
  border-radius: 16px; padding: 14px 16px; margin-bottom: 18px;
  display: flex; gap: 10px; flex-wrap: wrap; align-items: center;
}
.u-toolbar-top { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; width: 100%; }
.u-toolbar-filters { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; width: 100%; }
.u-search { flex: 1; min-width: 200px; position: relative; }
.u-search input {
  width: 100%; padding: 9px 14px 9px 38px;
  border: 1.5px solid var(--border); border-radius: 10px;
  background: var(--bg3); font-size: 13px; color: var(--text);
  font-family: inherit; outline: none; transition: all .2s;
}
.u-search input:focus { border-color: var(--indigo); background: #fff; box-shadow: 0 0 0 3px rgba(79,110,247,.1); }
.u-search-ico { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: var(--text3); pointer-events: none; }
.u-sel {
  padding: 9px 12px; border: 1.5px solid var(--border); border-radius: 10px;
  background: var(--bg3); color: var(--text2); font-size: 13px;
  font-family: inherit; cursor: pointer; outline: none; transition: border-color .2s;
}
.u-sel:focus { border-color: var(--indigo); }
.u-pp { display: flex; align-items: center; gap: 5px; font-size: 12px; color: var(--text3); flex-shrink: 0; }
.u-pp select { padding: 7px 8px; border: 1.5px solid var(--border); border-radius: 8px; background: var(--surface); color: var(--text2); font-size: 12px; font-family: inherit; cursor: pointer; }
.u-vtoggle { display: flex; background: var(--bg3); border-radius: 10px; padding: 3px; gap: 2px; }
.u-vbtn {
  padding: 7px 14px; border: none; border-radius: 8px; cursor: pointer;
  font-size: 12px; font-weight: 600; font-family: inherit;
  background: transparent; color: var(--text3); transition: all .15s;
  display: flex; align-items: center; gap: 5px;
}
.u-vbtn.active { background: var(--surface); color: var(--indigo); box-shadow: 0 1px 5px rgba(0,0,0,.1); }
@media(max-width:600px){ .u-vbtn span{display:none;} }

/* ── Main card ── */
.u-main { background: var(--surface); border: 1.5px solid var(--border); border-radius: 16px; overflow: hidden; }
.u-main-hdr {
  padding: 14px 18px; border-bottom: 1px solid var(--border);
  display: flex; align-items: center; justify-content: space-between;
  background: var(--surface2); flex-wrap: wrap; gap: 8px;
}
.u-main-hdr-title { font-size: 14px; font-weight: 700; color: var(--text); display: flex; align-items: center; gap: 8px; }
.u-main-count { background: var(--indigo-light); color: var(--indigo); border-radius: 99px; padding: 2px 11px; font-size: 12px; font-weight: 700; }

/* ── Table ── */
.u-tbl-wrap { overflow-x: auto; max-height: 500px; scrollbar-width: thin; }
.u-tbl-wrap::-webkit-scrollbar { width: 5px; height: 5px; }
.u-tbl-wrap::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 99px; }
.u-tbl-wrap table { min-width: 720px; }
.u-tbl-wrap thead { position: sticky; top: 0; z-index: 2; }
.u-tbl-wrap thead th { background: var(--surface2)!important; box-shadow: 0 2px 0 var(--border); }
.u-ava { width: 36px; height: 36px; border-radius: 10px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 800; color: #fff; }
.u-mono { font-family: 'DM Mono',monospace; font-size: 12px; background: var(--bg3); padding: 2px 8px; border-radius: 6px; color: var(--text2); }
.u-role { display: inline-flex; align-items: center; gap: 4px; padding: 3px 10px; border-radius: 99px; font-size: 11.5px; font-weight: 700; }
.u-role-sa { background: #FEF3C7; color: #92400E; }
.u-role-ad { background: #EDE9FE; color: #5B21B6; }
.u-role-si { background: #DBEAFE; color: #1E40AF; }
.u-son  { background: #D1FAE5; color: #065F46; border-radius: 99px; padding: 3px 10px; font-size: 11px; font-weight: 700; display: inline-flex; align-items: center; gap: 4px; }
.u-soff { background: #FEE2E2; color: #991B1B; border-radius: 99px; padding: 3px 10px; font-size: 11px; font-weight: 700; display: inline-flex; align-items: center; gap: 4px; }
.u-dot { width: 5px; height: 5px; border-radius: 50%; flex-shrink: 0; display: inline-block; }

/* ── Card grid ── */
.u-grid { display: grid; grid-template-columns: repeat(auto-fill,minmax(270px,1fr)); gap: 14px; padding: 16px; }
@media(max-width:560px){ .u-grid{grid-template-columns:1fr;} }
.u-card {
  background: var(--surface); border: 1.5px solid var(--border);
  border-radius: 18px; overflow: hidden; display: flex; flex-direction: column;
  transition: transform .18s, box-shadow .18s, border-color .18s;
}
.u-card:hover { transform: translateY(-3px); box-shadow: 0 10px 30px rgba(0,0,0,.1); border-color: var(--border2); }
.u-card-bar { height: 4px; }
.u-card-body { padding: 16px; flex: 1; display: flex; flex-direction: column; gap: 11px; }
.u-card-head { display: flex; align-items: center; gap: 12px; }
.u-card-ava { width: 46px; height: 46px; border-radius: 14px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; font-size: 19px; font-weight: 800; color: #fff; }
.u-card-name { font-size: 14px; font-weight: 700; color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.u-card-uname { font-family: 'DM Mono',monospace; font-size: 11px; background: var(--bg3); color: var(--text3); padding: 2px 7px; border-radius: 5px; display: inline-block; margin-top: 3px; }
.u-card-num { width: 26px; height: 26px; border-radius: 8px; background: var(--bg3); display: flex; align-items: center; justify-content: center; font-size: 10.5px; font-weight: 700; color: var(--text3); flex-shrink: 0; margin-left: auto; }
.u-card-siswa { background: var(--surface2); border: 1px solid var(--border); border-radius: 10px; padding: 8px 11px; }
.u-card-foot { padding: 10px 16px 14px; border-top: 1px solid var(--border); background: var(--surface2); display: flex; gap: 6px; }
.u-card-foot .btn { flex: 1; font-size: 11.5px; justify-content: center; }

/* ── Pagination ── */
.u-pager {
  display: flex; align-items: center; justify-content: space-between;
  flex-wrap: wrap; gap: 10px; padding: 13px 18px;
  border-top: 1px solid var(--border); background: var(--surface2);
}
.u-pager-btns { display: flex; gap: 3px; flex-wrap: wrap; }
.u-pb {
  min-width: 34px; height: 34px; padding: 0 9px;
  border: 1.5px solid var(--border); border-radius: 9px;
  background: var(--surface); color: var(--text2); font-size: 13px;
  cursor: pointer; font-family: inherit;
  display: inline-flex; align-items: center; justify-content: center;
  text-decoration: none; transition: all .15s;
}
.u-pb:hover:not(.u-active):not(.u-dis) { background: var(--indigo-light); color: var(--indigo); border-color: var(--indigo); }
.u-active { background: var(--indigo)!important; color: #fff!important; border-color: var(--indigo)!important; font-weight: 700; box-shadow: 0 2px 10px rgba(79,110,247,.35); }
.u-dis { opacity: .35; pointer-events: none; }
.u-dots { height: 34px; display: inline-flex; align-items: center; padding: 0 4px; color: var(--text3); }

/* ── Sticky pagination ── */
.pgn-sticky {
  position: sticky; bottom: 0; z-index: 20;
  background: var(--bg); border-top: 1.5px solid var(--border);
  padding: 10px 0 6px;
  box-shadow: 0 -4px 16px rgba(0,0,0,.06);
}
.pgn-wrap { display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.pgn-info { font-size: 12.5px; color: var(--text3); white-space: nowrap; }
.pgn-info strong { color: var(--text2); font-weight: 600; }
.pgn-controls { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; }
.pgn-btn {
  display: inline-flex; align-items: center; justify-content: center;
  min-width: 32px; height: 32px; padding: 0 7px;
  border: 1.5px solid var(--border); border-radius: 8px;
  background: var(--surface); color: var(--text2);
  font-size: 13px; font-weight: 500; text-decoration: none; transition: all .15s;
}
.pgn-btn:hover:not(.pgn-active):not(.pgn-disabled) { background: var(--indigo-light); color: var(--indigo); border-color: var(--indigo); }
.pgn-btn.pgn-active { background: var(--indigo); color: #fff; border-color: var(--indigo); font-weight: 700; box-shadow: 0 2px 8px rgba(79,110,247,.35); pointer-events: none; }
.pgn-btn.pgn-disabled { opacity: .35; pointer-events: none; }
.pgn-dots { display: inline-flex; align-items: flex-end; justify-content: center; min-width: 28px; height: 32px; padding-bottom: 4px; color: var(--text3); font-size: 14px; }
@media(max-width:600px){ .pgn-wrap{justify-content:center;} .pgn-info{width:100%;text-align:center;} .pgn-controls{justify-content:center;} }

/* ── Scroll container ── */
.u-scroll-container { position: relative; }
.u-scroll-wrap {
  max-height: 62vh; min-height: 120px;
  overflow-y: auto; overflow-x: hidden;
  border-radius: 14px; scrollbar-width: thin;
  scrollbar-color: var(--border2) transparent;
}
.u-scroll-wrap::-webkit-scrollbar { width: 5px; }
.u-scroll-wrap::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 99px; }
.u-scroll-fade {
  position: absolute; bottom: 0; left: 0; right: 0; height: 32px;
  background: linear-gradient(to bottom, transparent, var(--bg));
  pointer-events: none; z-index: 5; border-radius: 0 0 14px 14px;
  opacity: 1; transition: opacity .2s;
}
.u-scroll-fade.hidden { opacity: 0; }

/* ── Empty state ── */
.u-empty { padding: 56px 24px; text-align: center; }
.u-empty-ico { font-size: 44px; margin-bottom: 14px; }

/* ── Self badge ── */
.badge-self { font-size: 10px; background: #FEF3C7; color: #92400E; padding: 1px 7px; border-radius: 99px; font-weight: 700; margin-left: 4px; vertical-align: middle; }

#viewCard  { display: none; }
#viewTable { display: block; }
</style>

<!-- ═══ HERO BANNER ═══ -->
<div class="u-hero">
  <div class="u-hero-left">
    <div class="u-hero-badge">
      <svg width="8" height="8" viewBox="0 0 8 8"><circle cx="4" cy="4" r="4" fill="currentColor"/></svg>
      Manajemen Akun
    </div>
    <div class="u-hero-title">Users <span>Siswa</span></div>
    <div class="u-hero-sub">Kelola akun login siswa, admin, dan superadmin &mdash; <?= number_format($totalAll) ?> total akun</div>
  </div>
  <div class="u-hero-actions">
    <?php if($siswaTanpaAkun > 0): ?>
    <form method="POST" onsubmit="return confirm('Buat akun otomatis untuk <?= $siswaTanpaAkun ?> siswa yang belum punya akun?\n\nUsername & password = NIS masing-masing siswa.')">
      <input type="hidden" name="action" value="sinkron_users">
      <button type="submit" class="u-btn-sync">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
        Sinkron (<?= $siswaTanpaAkun ?>)
      </button>
    </form>
    <?php endif ?>
    <button class="u-btn-primary" onclick="openModal('modalTambah')">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
      Tambah User
    </button>
  </div>
</div>

<!-- ═══ ALERT SINKRON ═══ -->
<?php if($siswaTanpaAkun > 0): ?>
<div class="sync-banner">
  <div class="sync-dot"></div>
  <div class="sync-banner-text">
    <strong><?= $siswaTanpaAkun ?> siswa aktif</strong> belum memiliki akun login.
    Klik <strong>"Sinkron"</strong> untuk membuat akun otomatis &mdash;
    username &amp; password = <strong>NIS masing-masing siswa</strong>.
  </div>
</div>
<?php endif ?>

<div class="info-default-pass">
  <span style="font-size:18px;flex-shrink:0">🔑</span>
  <div><strong>Akun otomatis:</strong> Saat siswa baru ditambahkan, akun login dibuat otomatis dengan <strong>username = NIS</strong> dan <strong>password = NIS</strong>. Siswa dapat mengganti password setelah login pertama.</div>
</div>

<!-- ═══ STAT CARDS ═══ -->
<div class="u-stats">
  <?php
  $stats = [
    ['👥',$totalAll,  'Total Users','#4F6EF7','linear-gradient(135deg,#4F6EF7,#818CF8)'],
    ['👑',$totalAdmin,'Admin',      '#7C3AED','linear-gradient(135deg,#7C3AED,#A78BFA)'],
    ['🎒',$totalSiswa,'Siswa',      '#0EA5E9','linear-gradient(135deg,#0EA5E9,#38BDF8)'],
    ['✅',$totalAktif,'Aktif',      '#10B981','linear-gradient(135deg,#10B981,#34D399)'],
  ];
  foreach($stats as $i=>$s): ?>
  <div class="u-stat">
    <div class="u-stat-top" style="background:<?= $s[4] ?>"></div>
    <div class="u-stat-icon"><?= $s[0] ?></div>
    <div class="u-stat-num" style="color:<?= $s[3] ?>"><?= $s[1] ?></div>
    <div class="u-stat-lbl"><?= $s[2] ?></div>
  </div>
  <?php endforeach ?>
</div>

<!-- ═══ TOOLBAR ═══ -->
<div class="u-toolbar">
  <div class="u-toolbar-top">
    <div class="u-search">
      <svg class="u-search-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
      <form method="GET" action="index.php">
        <input type="hidden" name="page"     value="users">
        <input type="hidden" name="role"     value="<?= e($roleF) ?>">
        <input type="hidden" name="status"   value="<?= e($statusF) ?>">
        <input type="hidden" name="per_page" value="<?= $perPage ?>">
        <input type="text" name="q" value="<?= e($search) ?>" placeholder="Cari nama atau username...">
      </form>
    </div>
    <div class="u-pp">
      Tampil
      <select id="perPageUsers" onchange="usersChangePerPage(this.value)">
        <?php foreach($allowedPP as $pp): ?>
        <option value="<?= $pp ?>" <?= $pp===$perPage?'selected':'' ?>><?= $pp ?></option>
        <?php endforeach ?>
      </select>
      / hal
    </div>
    <div class="u-vtoggle">
      <button class="u-vbtn active" id="btnTable" onclick="setView('table')" title="Tabel">
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M3 15h18M9 3v18"/></svg>
        <span>Tabel</span>
      </button>
      <button class="u-vbtn" id="btnCard" onclick="setView('card')" title="Kartu">
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="8" height="8" rx="1.5"/><rect x="13" y="3" width="8" height="8" rx="1.5"/><rect x="3" y="13" width="8" height="8" rx="1.5"/><rect x="13" y="13" width="8" height="8" rx="1.5"/></svg>
        <span>Kartu</span>
      </button>
    </div>
  </div>
  <div class="u-toolbar-filters">
    <select class="u-sel" onchange="location='<?= 'index.php?page=users&q='.urlencode($search).'&status='.urlencode($statusF).'&per_page='.$perPage.'&p=1' ?>&role='+this.value">
      <option value="" <?= !$roleF?'selected':'' ?>>👥 Semua Role</option>
      <option value="admin"      <?= $roleF==='admin'?'selected':'' ?>>👑 Admin</option>
      <option value="superadmin" <?= $roleF==='superadmin'?'selected':'' ?>>🌟 Superadmin</option>
      <option value="siswa"      <?= $roleF==='siswa'?'selected':'' ?>>🎒 Siswa</option>
    </select>
    <select class="u-sel" onchange="location='<?= 'index.php?page=users&q='.urlencode($search).'&role='.urlencode($roleF).'&per_page='.$perPage.'&p=1' ?>&status='+this.value">
      <option value=""  <?= $statusF===''?'selected':'' ?>>🔘 Semua Status</option>
      <option value="1" <?= $statusF==='1'?'selected':'' ?>>✅ Aktif</option>
      <option value="0" <?= $statusF==='0'?'selected':'' ?>>⛔ Nonaktif</option>
    </select>
    <?php if($totalRows > 0): ?>
    <span style="font-size:12px;color:var(--text3)">
      <strong style="color:var(--text2)"><?= number_format($totalRows) ?></strong> user ditemukan
      <?php if($totalPages > 1): ?>&nbsp;&middot;&nbsp; hal <strong style="color:var(--text2)"><?= $currentPage ?>/<?= $totalPages ?></strong><?php endif ?>
    </span>
    <?php endif ?>
  </div>
</div>

<?php
$avc = ['#FF6B9D','#A855F7','#38BDF8','#34D399','#FB923C','#FBBF24','#818CF8','#F472B6'];
$roleBar = ['superadmin'=>'linear-gradient(90deg,#F59E0B,#FCD34D)','admin'=>'linear-gradient(90deg,#7C3AED,#A78BFA)','siswa'=>'linear-gradient(90deg,#0EA5E9,#38BDF8)'];
$roleCls = ['superadmin'=>'u-role-sa','admin'=>'u-role-ad','siswa'=>'u-role-si'];
$roleLbl = ['superadmin'=>'🌟 Superadmin','admin'=>'👑 Admin','siswa'=>'🎒 Siswa'];
?>

<!-- ═══ MAIN CARD ═══ -->
<div class="u-main">
  <div class="u-main-hdr">
    <div class="u-main-hdr-title">
      Daftar User
      <span class="u-main-count"><?= number_format($totalRows) ?></span>
    </div>
  </div>

  <?php if(empty($users)): ?>
  <div class="u-empty">
    <div class="u-empty-ico">👤</div>
    <div style="font-size:16px;font-weight:700;color:var(--text2);margin-bottom:6px">Belum ada user</div>
    <div style="font-size:13px;color:var(--text3)">Klik "Tambah User" atau "Sinkron" untuk membuat akun</div>
  </div>
  <?php else: ?>

  <!-- SCROLL CONTAINER -->
  <div class="u-scroll-container">
    <div class="u-scroll-wrap" id="uContentWrap">

      <!-- TABLE VIEW -->
      <div id="viewTable">
        <div class="u-tbl-wrap">
          <table>
            <thead>
              <tr>
                <th style="width:36px">#</th>
                <th style="min-width:200px">Pengguna</th>
                <th style="min-width:130px">Username</th>
                <th>Role</th>
                <th style="min-width:155px">Data Siswa</th>
                <th>Status</th>
                <th>Bergabung</th>
                <th style="width:150px">Aksi</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($users as $i=>$u):
                $c      = $avc[$i % count($avc)];
                $isSelf = ((int)$u['id'] === (int)($_SESSION['admin_id'] ?? 0));
                $rowNum = $offset + $i + 1;
                $rc     = $roleCls[$u['role']] ?? 'u-role-si';
                $rl     = $roleLbl[$u['role']]  ?? ucfirst($u['role']);
                $fotoFile = $u['foto_siswa'] ?? '';
                $hasFoto  = $fotoFile && file_exists($fotoSiswaAbs.$fotoFile);
              ?>
              <tr>
                <td><div style="width:28px;height:28px;border-radius:8px;background:var(--surface2);display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:var(--text3)"><?= $rowNum ?></div></td>
                <td>
                  <div style="display:flex;align-items:center;gap:10px">
                    <?php if($hasFoto): ?>
                    <img src="<?= e($fotoSiswaUrl.$fotoFile) ?>"
                         style="width:36px;height:36px;border-radius:10px;object-fit:cover;flex-shrink:0;border:2px solid var(--border)"
                         onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">
                    <div class="u-ava" style="background:<?= $c ?>;display:none"><?= mb_strtoupper(mb_substr($u['nama']??$u['username'],0,1)) ?></div>
                    <?php else: ?>
                    <div class="u-ava" style="background:<?= $c ?>"><?= mb_strtoupper(mb_substr($u['nama']??$u['username'],0,1)) ?></div>
                    <?php endif ?>
                    <div>
                      <div style="font-weight:700;font-size:13.5px;color:var(--text)"><?= e($u['nama']?:$u['username']) ?><?php if($isSelf): ?><span class="badge-self">Anda</span><?php endif ?></div>
                    </div>
                  </div>
                </td>
                <td><span class="u-mono"><?= e($u['username']) ?></span></td>
                <td><span class="u-role <?= $rc ?>"><?= $rl ?></span></td>
                <td>
                  <?php if($u['siswa_id']): ?>
                  <div style="font-size:12.5px;font-weight:600;color:var(--text)"><?= e($u['nama_siswa']??'—') ?></div>
                  <div style="font-size:11px;color:var(--text3)"><?= e($u['nis']??'') ?> · Kelas <?= e($u['kelas']??'') ?></div>
                  <?php else: ?><span style="color:var(--text3);font-size:12px">—</span><?php endif ?>
                </td>
                <td>
                  <?php if($u['is_active']): ?>
                  <span class="u-son"><span class="u-dot" style="background:#10B981"></span>Aktif</span>
                  <?php else: ?>
                  <span class="u-soff"><span class="u-dot" style="background:#EF4444"></span>Nonaktif</span>
                  <?php endif ?>
                </td>
                <td style="font-size:12px;color:var(--text2)"><?= date('d M Y',strtotime($u['created_at'])) ?></td>
                <td>
                  <div style="display:flex;gap:5px">
                    <button class="btn btn-outline btn-sm" onclick='bukaEdit(<?= json_encode(['id'=>$u['id'],'username'=>$u['username'],'nama'=>$u['nama'],'role'=>$u['role'],'siswa_id'=>$u['siswa_id'],'is_active'=>$u['is_active']]) ?>)' title="Edit">✏️</button>
                    <form method="POST" style="display:inline" onsubmit="return confirm('Reset password user ini ke NIS/username-nya?')">
                      <input type="hidden" name="action" value="reset_password">
                      <input type="hidden" name="id" value="<?= $u['id'] ?>">
                      <button class="btn btn-sm" style="background:#EFF6FF;color:#1E40AF;border:none" title="Reset password ke NIS">🔑</button>
                    </form>
                    <?php if(!$isSelf): ?>
                    <form method="POST" style="display:inline">
                      <input type="hidden" name="action" value="toggle_aktif">
                      <input type="hidden" name="id" value="<?= $u['id'] ?>">
                      <input type="hidden" name="is_active" value="<?= $u['is_active'] ?>">
                      <button class="btn btn-sm" style="background:<?= $u['is_active']?'#FEF3C7':'#D1FAE5' ?>;color:<?= $u['is_active']?'#92400E':'#065F46' ?>;border:none"><?= $u['is_active']?'🚫':'✅' ?></button>
                    </form>
                    <form method="POST" style="display:inline" onsubmit="return confirm('Hapus user <?= addslashes(e($u['username'])) ?>?')">
                      <input type="hidden" name="action" value="hapus">
                      <input type="hidden" name="id" value="<?= $u['id'] ?>">
                      <button class="btn btn-danger btn-sm">🗑️</button>
                    </form>
                    <?php endif ?>
                  </div>
                </td>
              </tr>
              <?php endforeach ?>
            </tbody>
          </table>
        </div>
      </div>

      <!-- CARD VIEW -->
      <div id="viewCard">
        <div class="u-grid">
          <?php foreach($users as $i=>$u):
            $c      = $avc[$i % count($avc)];
            $isSelf = ((int)$u['id'] === (int)($_SESSION['admin_id'] ?? 0));
            $rowNum = $offset + $i + 1;
            $bar    = $roleBar[$u['role']] ?? 'linear-gradient(90deg,#4F6EF7,#818CF8)';
            $rc     = $roleCls[$u['role']] ?? 'u-role-si';
            $rl     = $roleLbl[$u['role']]  ?? ucfirst($u['role']);
            $fotoFile2 = $u['foto_siswa'] ?? '';
            $hasFoto2  = $fotoFile2 && file_exists($fotoSiswaAbs.$fotoFile2);
          ?>
          <div class="u-card">
            <div class="u-card-bar" style="background:<?= $bar ?>"></div>
            <div class="u-card-body">
              <div class="u-card-head">
                <?php if($hasFoto2): ?>
                <img src="<?= e($fotoSiswaUrl.$fotoFile2) ?>"
                     style="width:46px;height:46px;border-radius:14px;object-fit:cover;flex-shrink:0;border:2px solid var(--border)"
                     onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">
                <div class="u-card-ava" style="background:<?= $c ?>;display:none"><?= mb_strtoupper(mb_substr($u['nama']??$u['username'],0,1)) ?></div>
                <?php else: ?>
                <div class="u-card-ava" style="background:<?= $c ?>"><?= mb_strtoupper(mb_substr($u['nama']??$u['username'],0,1)) ?></div>
                <?php endif ?>
                <div style="flex:1;min-width:0">
                  <div class="u-card-name"><?= e($u['nama']?:$u['username']) ?><?php if($isSelf): ?><span class="badge-self">Anda</span><?php endif ?></div>
                  <span class="u-card-uname">@<?= e($u['username']) ?></span>
                </div>
                <div class="u-card-num"><?= $rowNum ?></div>
              </div>
              <div style="display:flex;gap:6px;flex-wrap:wrap">
                <span class="u-role <?= $rc ?>"><?= $rl ?></span>
                <?php if($u['is_active']): ?>
                <span class="u-son"><span class="u-dot" style="background:#10B981"></span>Aktif</span>
                <?php else: ?>
                <span class="u-soff"><span class="u-dot" style="background:#EF4444"></span>Nonaktif</span>
                <?php endif ?>
              </div>
              <?php if($u['siswa_id']): ?>
              <div class="u-card-siswa">
                <div style="font-weight:600;font-size:12.5px;color:var(--text)"><?= e($u['nama_siswa']??'—') ?></div>
                <div style="font-size:11px;color:var(--text3);margin-top:2px"><?= e($u['nis']??'') ?> · Kelas <?= e($u['kelas']??'') ?></div>
              </div>
              <?php endif ?>
              <div style="font-size:11.5px;color:var(--text3);display:flex;align-items:center;gap:5px">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                <?= date('d M Y',strtotime($u['created_at'])) ?>
              </div>
            </div>
            <div class="u-card-foot">
              <button class="btn btn-outline btn-sm" onclick='bukaEdit(<?= json_encode(['id'=>$u['id'],'username'=>$u['username'],'nama'=>$u['nama'],'role'=>$u['role'],'siswa_id'=>$u['siswa_id'],'is_active'=>$u['is_active']]) ?>)'>✏️ Edit</button>
              <form method="POST" style="display:contents" onsubmit="return confirm('Reset password ke NIS/username?')">
                <input type="hidden" name="action" value="reset_password">
                <input type="hidden" name="id" value="<?= $u['id'] ?>">
                <button class="btn btn-sm" style="flex:1;background:#EFF6FF;color:#1E40AF;border:none">🔑 Reset</button>
              </form>
              <?php if(!$isSelf): ?>
              <form method="POST" style="display:contents">
                <input type="hidden" name="action" value="toggle_aktif">
                <input type="hidden" name="id" value="<?= $u['id'] ?>">
                <input type="hidden" name="is_active" value="<?= $u['is_active'] ?>">
                <button class="btn btn-sm" style="flex:1;background:<?= $u['is_active']?'#FEF3C7':'#D1FAE5' ?>;color:<?= $u['is_active']?'#92400E':'#065F46' ?>;border:none"><?= $u['is_active']?'🚫':'✅' ?></button>
              </form>
              <form method="POST" style="display:contents" onsubmit="return confirm('Hapus user <?= addslashes(e($u['username'])) ?>?')">
                <input type="hidden" name="action" value="hapus">
                <input type="hidden" name="id" value="<?= $u['id'] ?>">
                <button class="btn btn-danger btn-sm">🗑️</button>
              </form>
              <?php endif ?>
            </div>
          </div>
          <?php endforeach ?>
        </div>
      </div>

    </div><!-- /u-scroll-wrap -->
    <div class="u-scroll-fade" id="uScrollFade"></div>
  </div><!-- /u-scroll-container -->

  <?php endif ?>
</div><!-- /u-main -->

<!-- ═══ PAGINATION ═══ -->
<?php if($totalPages > 1): ?>
<?php
  $icoL  = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>';
  $icoR  = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>';
  $icoLL = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="11 17 6 12 11 7"/><polyline points="18 17 13 12 18 7"/></svg>';
  $icoRR = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="13 17 18 12 13 7"/><polyline points="6 17 11 12 6 7"/></svg>';
  $pages = usersPageWindow($currentPage, $totalPages);
  $from  = $totalRows > 0 ? $offset + 1 : 0;
  $to    = min($offset + $perPage, $totalRows);
?>
<div class="pgn-sticky">
  <div class="pgn-wrap">
    <div class="pgn-info">Menampilkan <strong><?= $from ?>–<?= $to ?></strong> dari <strong><?= number_format($totalRows) ?></strong> user</div>
    <div class="pgn-controls">
      <a href="<?= usersPageUrl(1,$search,$roleF,$statusF,$perPage) ?>" class="pgn-btn <?= $currentPage<=1?'pgn-disabled':'' ?>"><?= $icoLL ?></a>
      <a href="<?= usersPageUrl(max(1,$currentPage-1),$search,$roleF,$statusF,$perPage) ?>" class="pgn-btn <?= $currentPage<=1?'pgn-disabled':'' ?>"><?= $icoL ?></a>
      <?php if($pages[0]>1): ?><a href="<?= usersPageUrl(1,$search,$roleF,$statusF,$perPage) ?>" class="pgn-btn">1</a><?php if($pages[0]>2): ?><span class="pgn-dots">···</span><?php endif ?><?php endif ?>
      <?php foreach($pages as $pg): ?><a href="<?= usersPageUrl($pg,$search,$roleF,$statusF,$perPage) ?>" class="pgn-btn <?= $pg===$currentPage?'pgn-active':'' ?>"><?= $pg ?></a><?php endforeach ?>
      <?php if($pages[count($pages)-1]<$totalPages): ?><?php if($pages[count($pages)-1]<$totalPages-1): ?><span class="pgn-dots">···</span><?php endif ?><a href="<?= usersPageUrl($totalPages,$search,$roleF,$statusF,$perPage) ?>" class="pgn-btn"><?= $totalPages ?></a><?php endif ?>
      <a href="<?= usersPageUrl(min($totalPages,$currentPage+1),$search,$roleF,$statusF,$perPage) ?>" class="pgn-btn <?= $currentPage>=$totalPages?'pgn-disabled':'' ?>"><?= $icoR ?></a>
      <a href="<?= usersPageUrl($totalPages,$search,$roleF,$statusF,$perPage) ?>" class="pgn-btn <?= $currentPage>=$totalPages?'pgn-disabled':'' ?>"><?= $icoRR ?></a>
    </div>
  </div>
</div>
<?php endif ?>

<!-- ═══ MODAL TAMBAH ═══ -->
<div class="modal-overlay" id="modalTambah">
  <div class="modal" style="max-width:520px">
    <div class="modal-header" style="background:linear-gradient(135deg,#0D1B35,#1A2E5A);border-radius:16px 16px 0 0">
      <h3 style="color:#fff">➕ Tambah User Baru</h3>
      <button class="modal-close" onclick="closeModal('modalTambah')" style="color:#fff;background:rgba(255,255,255,.12);border-color:rgba(255,255,255,.2)">×</button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="tambah">
      <div class="modal-body">
        <div style="background:#F0FDF4;border:1.5px solid #BBF7D0;border-radius:10px;padding:10px 13px;margin-bottom:14px;font-size:12.5px;color:#065F46;display:flex;gap:8px">
          <span style="font-size:16px;flex-shrink:0">💡</span>
          <span>Untuk siswa, username &amp; password dibuat otomatis dari NIS. Form ini untuk tambah user secara manual.</span>
        </div>
        <div class="form-row">
          <div class="form-group"><label>Username <span style="color:#E11D48">*</span></label><input name="username" required placeholder="username_login"></div>
          <div class="form-group"><label>Nama Lengkap</label><input name="nama" placeholder="Nama tampilan"></div>
        </div>
        <div class="form-row">
          <div class="form-group">
            <label>Password <span style="color:#E11D48">*</span></label>
            <div style="position:relative">
              <input type="password" name="password" id="passT" required placeholder="Minimal 6 karakter" style="padding-right:42px">
              <button type="button" onclick="togglePass('passT','eyeT')" style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;font-size:16px" id="eyeT">👁️</button>
            </div>
          </div>
          <div class="form-group">
            <label>Role</label>
            <select name="role" id="roleTambah" onchange="toggleSiswaField('siswaFieldT',this.value)">
              <option value="siswa">🎒 Siswa</option>
              <option value="admin">👑 Admin</option>
              <option value="superadmin">🌟 Superadmin</option>
            </select>
          </div>
        </div>
        <div class="form-group" id="siswaFieldT">
          <label>Link ke Data Siswa (opsional)</label>
          <select name="siswa_id">
            <option value="">– Tidak dilink –</option>
            <?php foreach($siswas as $s): ?><option value="<?= $s['id'] ?>"><?= e($s['nama']) ?> (<?= e($s['nis']) ?>) – Kelas <?= e($s['kelas']) ?></option><?php endforeach ?>
          </select>
        </div>
        <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;color:var(--text);text-transform:none;letter-spacing:0;font-weight:500">
          <input type="checkbox" name="is_active" value="1" checked style="width:16px;height:16px;accent-color:var(--indigo)">
          Aktifkan user ini
        </label>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('modalTambah')">Batal</button>
        <button type="submit" class="btn btn-primary">💾 Simpan</button>
      </div>
    </form>
  </div>
</div>

<!-- ═══ MODAL EDIT ═══ -->
<div class="modal-overlay" id="modalEdit">
  <div class="modal" style="max-width:520px">
    <div class="modal-header" style="background:linear-gradient(135deg,#1A1A2E,#2D1B69);border-radius:16px 16px 0 0">
      <h3 style="color:#fff">✏️ Edit User</h3>
      <button class="modal-close" onclick="closeModal('modalEdit')" style="color:#fff;background:rgba(255,255,255,.12);border-color:rgba(255,255,255,.2)">×</button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="id" id="editId">
      <div class="modal-body">
        <div class="form-row">
          <div class="form-group"><label>Username <span style="color:#E11D48">*</span></label><input name="username" id="editUsername" required></div>
          <div class="form-group"><label>Nama Lengkap</label><input name="nama" id="editNama"></div>
        </div>
        <div class="form-group">
          <label>Password Baru <span style="font-weight:400;text-transform:none;letter-spacing:0;color:var(--text3)">(kosongkan jika tidak ganti)</span></label>
          <div style="position:relative">
            <input type="password" name="password" id="passE" placeholder="Isi untuk ganti password" style="padding-right:42px">
            <button type="button" onclick="togglePass('passE','eyeE')" style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;font-size:16px" id="eyeE">👁️</button>
          </div>
        </div>
        <div class="form-row">
          <div class="form-group">
            <label>Role</label>
            <select name="role" id="editRole" onchange="toggleSiswaField('siswaFieldE',this.value)">
              <option value="siswa">🎒 Siswa</option>
              <option value="admin">👑 Admin</option>
              <option value="superadmin">🌟 Superadmin</option>
            </select>
          </div>
          <div class="form-group" style="display:flex;align-items:flex-end">
            <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;color:var(--text);text-transform:none;letter-spacing:0;font-weight:500;margin-bottom:0">
              <input type="checkbox" name="is_active" id="editAktif" value="1" style="width:16px;height:16px;accent-color:var(--indigo)">
              User aktif
            </label>
          </div>
        </div>
        <div class="form-group" id="siswaFieldE">
          <label>Link ke Data Siswa</label>
          <select name="siswa_id" id="editSiswaId">
            <option value="">– Tidak dilink –</option>
            <?php foreach($siswas as $s): ?><option value="<?= $s['id'] ?>"><?= e($s['nama']) ?> (<?= e($s['nis']) ?>) – Kelas <?= e($s['kelas']) ?></option><?php endforeach ?>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('modalEdit')">Batal</button>
        <button type="submit" class="btn btn-primary">💾 Simpan Perubahan</button>
      </div>
    </form>
  </div>
</div>

<script>
const VIEW_KEY = 'users_view_pref';

function setView(mode) {
  const isSmall = window.innerWidth <= 640;
  const effective = isSmall ? 'card' : mode;
  document.getElementById('viewTable').style.display = effective === 'table' ? 'block' : 'none';
  document.getElementById('viewCard').style.display  = effective === 'card'  ? 'block' : 'none';
  document.getElementById('btnTable').classList.toggle('active', effective === 'table');
  document.getElementById('btnCard').classList.toggle('active',  effective === 'card');
  if (!isSmall) localStorage.setItem(VIEW_KEY, mode);
  const wrap = document.getElementById('uContentWrap');
  if (wrap) wrap.scrollTop = 0;
  updateScrollFade();
}
function initView() {
  const isSmall = window.innerWidth <= 640;
  if (isSmall) { setView('card'); return; }
  setView(localStorage.getItem(VIEW_KEY) || 'table');
}
let resizeTimer;
window.addEventListener('resize', () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(initView, 120); });
initView();

function updateScrollFade() {
  const wrap = document.getElementById('uContentWrap');
  const fade = document.getElementById('uScrollFade');
  if (!wrap || !fade) return;
  const atBottom = wrap.scrollHeight - wrap.scrollTop <= wrap.clientHeight + 8;
  fade.classList.toggle('hidden', atBottom || wrap.scrollHeight <= wrap.clientHeight);
}
document.addEventListener('DOMContentLoaded', function() {
  const wrap = document.getElementById('uContentWrap');
  if (wrap) wrap.addEventListener('scroll', updateScrollFade);
  updateScrollFade();
});

function bukaEdit(u) {
  document.getElementById('editId').value       = u.id;
  document.getElementById('editUsername').value = u.username;
  document.getElementById('editNama').value     = u.nama || '';
  document.getElementById('editRole').value     = u.role;
  document.getElementById('editAktif').checked  = u.is_active == 1;
  document.getElementById('editSiswaId').value  = u.siswa_id || '';
  document.getElementById('passE').value        = '';
  toggleSiswaField('siswaFieldE', u.role);
  openModal('modalEdit');
}
function toggleSiswaField(fieldId, role) {
  document.getElementById(fieldId).style.display = role === 'siswa' ? 'block' : 'none';
}
function togglePass(inputId, btnId) {
  var inp = document.getElementById(inputId), btn = document.getElementById(btnId);
  inp.type = inp.type === 'password' ? 'text' : 'password';
  btn.textContent = inp.type === 'password' ? '👁️' : '🙈';
}
function usersChangePerPage(val) {
  var url = new URL(window.location.href);
  url.searchParams.set('per_page', val);
  url.searchParams.set('p', '1');
  window.location.href = url.toString();
}
document.getElementById('siswaFieldE').style.display = 'none';
</script>

<?php require_once 'layout/footer.php'; ?>