<?php
session_start();
date_default_timezone_set('Asia/Jakarta');
if(!isset($_SESSION['login'])){ header("Location: login.php"); exit(); }
if($_SESSION['role'] !== 'admin'){ header("Location: dashboard.php?err=forbidden"); exit(); }
include 'koneksi.php';
$success=''; $error='';

// ── helper upload foto ──────────────────────────────
function uploadFoto($fileKey, &$errMsg){
    if(empty($_FILES[$fileKey]['name'])) return '';
    $f=$_FILES[$fileKey];
    $allowed=['image/jpeg','image/jpg','image/png','image/gif','image/webp'];
    if(!in_array($f['type'],$allowed)){ $errMsg='Format foto tidak didukung (jpg/png/gif/webp)!'; return false; }
    if($f['size']>2*1024*1024){ $errMsg='Ukuran foto maksimal 2 MB!'; return false; }
    $dir='uploads/foto_user/';
    if(!is_dir($dir)) mkdir($dir,0755,true);
    $ext=pathinfo($f['name'],PATHINFO_EXTENSION);
    $nama_file='usr_'.time().'_'.mt_rand(100,999).'.'.$ext;
    if(!move_uploaded_file($f['tmp_name'],$dir.$nama_file)){ $errMsg='Gagal menyimpan foto!'; return false; }
    return $dir.$nama_file;
}

if(isset($_POST['act']) && $_POST['act']==='tambah'){
    $nama=trim(mysqli_real_escape_string($conn,$_POST['nama']??''));
    $username=trim(mysqli_real_escape_string($conn,$_POST['username']??''));
    $password=trim($_POST['password']??'');
    $role=in_array($_POST['role']??'',['admin','guru','staff','tu'])?$_POST['role']:'guru';
    $email=trim(mysqli_real_escape_string($conn,$_POST['email']??''));
    $no_telp=trim(mysqli_real_escape_string($conn,$_POST['no_telp']??''));
    $status=($_POST['status']??'Aktif')==='Nonaktif'?'Nonaktif':'Aktif';
    if(empty($nama)||empty($username)||empty($password)){
        $error='Nama, username, dan password wajib diisi!';
    } else {
        $cek=mysqli_query($conn,"SELECT id FROM users WHERE username='$username' LIMIT 1");
        if(mysqli_num_rows($cek)>0){ $error="Username <b>$username</b> sudah digunakan!"; }
        else {
            $foto=uploadFoto('foto',$error);
            if($foto===false){ /* error set by helper */ }
            else {
                $foto_val=mysqli_real_escape_string($conn,$foto);
                if(mysqli_query($conn,"INSERT INTO users (nama,username,password,role,email,no_telp,status,foto,created_at) VALUES ('$nama','$username','".md5($password)."','$role','$email','$no_telp','$status','$foto_val',NOW())"))
                    $success="Pengguna <b>$nama</b> berhasil ditambahkan.";
                else $error='Gagal: '.mysqli_error($conn);
            }
        }
    }
}
if(isset($_POST['act']) && $_POST['act']==='edit'){
    $id=intval($_POST['id']??0);
    $nama=trim(mysqli_real_escape_string($conn,$_POST['nama']??''));
    $username=trim(mysqli_real_escape_string($conn,$_POST['username']??''));
    $password=trim($_POST['password']??'');
    $role=in_array($_POST['role']??'',['admin','guru','staff','tu'])?$_POST['role']:'guru';
    $email=trim(mysqli_real_escape_string($conn,$_POST['email']??''));
    $no_telp=trim(mysqli_real_escape_string($conn,$_POST['no_telp']??''));
    $status=($_POST['status']??'Aktif')==='Nonaktif'?'Nonaktif':'Aktif';
    if($id<1||empty($nama)||empty($username)){ $error='Data tidak valid!'; }
    else {
        $cek=mysqli_query($conn,"SELECT id FROM users WHERE username='$username' AND id<>$id LIMIT 1");
        if(mysqli_num_rows($cek)>0){ $error="Username sudah dipakai pengguna lain!"; }
        else {
            $p=["nama='$nama'","username='$username'","role='$role'","email='$email'","no_telp='$no_telp'","status='$status'","updated_at=NOW()"];
            if(!empty($password)) $p[]="password='".md5($password)."'";
            $foto=uploadFoto('foto',$error);
            if($foto===false){ /* error set */ }
            else {
                if($foto){
                    $rOld=mysqli_query($conn,"SELECT foto FROM users WHERE id=$id LIMIT 1");
                    if($rOld&&$rw=mysqli_fetch_assoc($rOld)) if(!empty($rw['foto'])&&file_exists($rw['foto'])) @unlink($rw['foto']);
                    $p[]="foto='".mysqli_real_escape_string($conn,$foto)."'";
                }
                if(mysqli_query($conn,"UPDATE users SET ".implode(',',$p)." WHERE id=$id")){
                    $success="Data <b>$nama</b> berhasil diperbarui.";
                    if($id==$_SESSION['user_id']) $_SESSION['nama']=$nama;
                } else $error='Gagal: '.mysqli_error($conn);
            }
        }
    }
}
if(isset($_GET['hapus'])){
    $id=intval($_GET['hapus']);
    if($id==$_SESSION['user_id']){ $error='Tidak bisa hapus akun sendiri!'; }
    elseif($id>0){
        $r=mysqli_query($conn,"SELECT nama,foto FROM users WHERE id=$id LIMIT 1");
        $nd=''; $fotoOld='';
        if($r&&$row=mysqli_fetch_assoc($r)){ $nd=$row['nama']; $fotoOld=$row['foto']??''; }
        if(mysqli_query($conn,"DELETE FROM users WHERE id=$id")){
            if($fotoOld&&file_exists($fotoOld)) @unlink($fotoOld);
            $success="<b>".htmlspecialchars($nd)."</b> berhasil dihapus.";
        } else $error='Gagal: '.mysqli_error($conn);
    }
}
if(isset($_GET['toggle'])){
    $id=intval($_GET['toggle']);
    if($id==$_SESSION['user_id']){ $error='Tidak bisa nonaktifkan akun sendiri!'; }
    elseif($id>0){
        $r=mysqli_query($conn,"SELECT status,nama FROM users WHERE id=$id LIMIT 1");
        if($r&&$row=mysqli_fetch_assoc($r)){
            $ns=$row['status']==='Aktif'?'Nonaktif':'Aktif';
            mysqli_query($conn,"UPDATE users SET status='$ns',updated_at=NOW() WHERE id=$id");
            $success="Status <b>".htmlspecialchars($row['nama'])."</b> diubah ke <b>$ns</b>.";
        }
    }
}
$editData=null;
if(isset($_GET['edit'])){ $r=mysqli_query($conn,"SELECT * FROM users WHERE id=".intval($_GET['edit'])." LIMIT 1"); if($r) $editData=mysqli_fetch_assoc($r); }
$search=trim(mysqli_real_escape_string($conn,$_GET['q']??''));
$filterRole=$_GET['role']??'';
$where="1=1";
if($search) $where.=" AND (nama LIKE '%$search%' OR username LIKE '%$search%' OR email LIKE '%$search%')";
if($filterRole) $where.=" AND role='".mysqli_real_escape_string($conn,$filterRole)."'";
$users=[];
$qU=mysqli_query($conn,"SELECT * FROM users WHERE $where ORDER BY FIELD(role,'admin','guru','staff','tu'),nama ASC");
if($qU) while($row=mysqli_fetch_assoc($qU)) $users[]=$row;
$statQ=mysqli_query($conn,"SELECT role,COUNT(*) c,SUM(status='Aktif') aktif FROM users GROUP BY role");
$stats=[];
while($r=mysqli_fetch_assoc($statQ)) $stats[$r['role']]=$r;
$totalUsers=array_sum(array_column($stats,'c'));
$totalAktif=array_sum(array_column($stats,'aktif'));

/* ── Setup untuk navbar.php ── */
$page_title  = 'Manajemen Pengguna — MA As-Syafi\'iyah 02';
$active_menu = 'user';
$loader_text = 'Memuat Data Pengguna';
include 'navbar.php';
?>

<div class="main">

    <!-- ══ PAGE HEADER ══ -->
    <div class="page-header">
        <div class="ph-left">
            <div class="ph-icon">🔐</div>
            <div>
                <h1 class="ph-title">Manajemen Pengguna</h1>
                <p class="ph-sub">Kelola akun &amp; hak akses pengguna sistem</p>
            </div>
        </div>
        <div class="ph-actions">
            <a href="dashboard.php" class="btn-ghost">← Dashboard</a>
            <button class="btn-gold" onclick="openModal()">+ Tambah Pengguna</button>
        </div>
    </div>

    <div class="wrap">

        <!-- Alerts -->
        <?php if($success): ?>
        <div class="alert alert-ok fade-up"><span>✓</span> <span><?=$success?></span><button class="alert-x" onclick="this.parentNode.remove()">✕</button></div>
        <?php endif; ?>
        <?php if($error): ?>
        <div class="alert alert-err fade-up"><span>!</span> <span><?=$error?></span><button class="alert-x" onclick="this.parentNode.remove()">✕</button></div>
        <?php endif; ?>

        <!-- ══ STAT CARDS ══ -->
        <div class="stats-grid fade-up">
            <div class="stat-card stat-all">
                <div class="sc-label">Total Pengguna</div>
                <div class="sc-val"><?=$totalUsers?></div>
                <div class="sc-sub"><?=$totalAktif?> aktif saat ini</div>
            </div>
            <?php foreach([
                'admin'=>['Admin','sc-admin','🔐'],
                'guru' =>['Guru','sc-guru','👨‍🏫'],
                'staff'=>['Staff','sc-staff','👔'],
                'tu'   =>['Tata Usaha','sc-tu','📋'],
            ] as $r=>[$lbl,$cls,$ico]): ?>
            <div class="stat-card <?=$cls?>">
                <div class="sc-label"><?=$ico?> <?=$lbl?></div>
                <div class="sc-val"><?=$stats[$r]['c']??0?></div>
                <div class="sc-sub"><?=$stats[$r]['aktif']??0?> aktif</div>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- ══ TOOLBAR ══ -->
        <form method="GET" action="user.php" class="toolbar fade-up">
            <div class="search-wrap">
                <span class="search-icon">🔍</span>
                <input type="text" name="q" class="search-input" placeholder="Cari nama, username, email…" value="<?=htmlspecialchars($search)?>">
            </div>
            <div class="filter-wrap">
                <select name="role" class="filter-select" onchange="this.form.submit()">
                    <option value="">Semua Role</option>
                    <option value="admin" <?=$filterRole==='admin'?'selected':''?>>Admin</option>
                    <option value="guru"  <?=$filterRole==='guru' ?'selected':''?>>Guru</option>
                    <option value="staff" <?=$filterRole==='staff'?'selected':''?>>Staff</option>
                    <option value="tu"    <?=$filterRole==='tu'   ?'selected':''?>>Tata Usaha</option>
                </select>
            </div>
            <button type="submit" class="btn-ghost">Cari</button>
        </form>

        <!-- ══ TABLE CARD ══ -->
        <div class="tcard fade-up">
            <div class="tcard-head">
                <div class="tcard-title">Daftar Pengguna</div>
                <span class="tcard-badge"><?=count($users)?> pengguna</span>
            </div>

            <?php if(count($users)>0): ?>

            <!-- Desktop table -->
            <div class="tscroll">
            <table>
                <thead>
                <tr>
                    <th>#</th>
                    <th>Nama</th>
                    <th>Username</th>
                    <th>Role</th>
                    <th>Email</th>
                    <th>Telepon</th>
                    <th>Status</th>
                    <th>Login Terakhir</th>
                    <th>Aksi</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach($users as $i=>$u):
                    $isSelf=($u['id']==$_SESSION['user_id']);
                    $bclass=['admin'=>'b-admin','guru'=>'b-guru','staff'=>'b-staff','tu'=>'b-tu'][$u['role']]??'b-staff';
                    $ico=['admin'=>'🔐','guru'=>'👨‍🏫','staff'=>'👔','tu'=>'📋'][$u['role']]??'👤';
                ?>
                <tr>
                    <td class="td-num"><?=$i+1?></td>
                    <td>
                        <div class="u-cell">
                            <?php if(!empty($u['foto'])&&file_exists($u['foto'])): ?>
                            <img class="u-photo" src="<?=htmlspecialchars($u['foto'])?>" alt="">
                            <?php else: ?>
                            <div class="u-ava"><?=strtoupper(mb_substr($u['nama'],0,1))?></div>
                            <?php endif; ?>
                            <div>
                                <div class="u-name">
                                    <?=htmlspecialchars($u['nama'])?>
                                    <?php if($isSelf): ?><span class="self-tag">Anda</span><?php endif; ?>
                                </div>
                                <div class="u-date"><?=date('d/m/Y',strtotime($u['created_at']))?></div>
                            </div>
                        </div>
                    </td>
                    <td><span class="mono-tag"><?=htmlspecialchars($u['username'])?></span></td>
                    <td><span class="badge <?=$bclass?>"><?=$ico?> <?=ucfirst($u['role'])?></span></td>
                    <td class="td-muted"><?=!empty($u['email'])?htmlspecialchars($u['email']):'-'?></td>
                    <td class="td-mono"><?=!empty($u['no_telp'])?htmlspecialchars($u['no_telp']):'-'?></td>
                    <td>
                        <div class="status-pill <?=$u['status']==='Aktif'?'s-on':'s-off'?>">
                            <span class="sdot"></span><?=$u['status']?>
                        </div>
                    </td>
                    <td class="td-mono td-muted"><?=!empty($u['last_login'])?date('d/m H:i',strtotime($u['last_login'])):'—'?></td>
                    <td>
                        <div class="act-row">
                            <button class="btn-sm btn-edit" onclick="openEdit(<?=htmlspecialchars(json_encode($u))?>)">✏ Edit</button>
                            <?php if(!$isSelf): ?>
                            <a href="user.php?toggle=<?=$u['id']?><?=$search?"&q=$search":''?><?=$filterRole?"&role=$filterRole":''?>"
                               class="btn-sm <?=$u['status']==='Aktif'?'btn-warn':'btn-ok'?>"
                               onclick="return confirm('Ubah status <?=addslashes(htmlspecialchars($u['nama']))?>')">
                                <?=$u['status']==='Aktif'?'Nonaktif':'Aktifkan'?>
                            </a>
                            <a href="user.php?hapus=<?=$u['id']?><?=$search?"&q=$search":''?><?=$filterRole?"&role=$filterRole":''?>"
                               class="btn-sm btn-del"
                               onclick="return confirm('Hapus <?=addslashes(htmlspecialchars($u['nama']))?> secara permanen?')">
                                Hapus
                            </a>
                            <?php else: ?>
                            <span class="locked-txt">🔒 Akun Anda</span>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            </div>

            <!-- Mobile cards -->
            <div class="mobile-cards">
            <?php foreach($users as $i=>$u):
                $isSelf=($u['id']==$_SESSION['user_id']);
                $bclass=['admin'=>'b-admin','guru'=>'b-guru','staff'=>'b-staff','tu'=>'b-tu'][$u['role']]??'b-staff';
                $ico=['admin'=>'🔐','guru'=>'👨‍🏫','staff'=>'👔','tu'=>'📋'][$u['role']]??'👤';
            ?>
            <div class="m-card">
                <div class="m-card-head">
                    <?php if(!empty($u['foto'])&&file_exists($u['foto'])): ?>
                    <img class="u-photo" src="<?=htmlspecialchars($u['foto'])?>" alt="">
                    <?php else: ?>
                    <div class="u-ava"><?=strtoupper(mb_substr($u['nama'],0,1))?></div>
                    <?php endif; ?>
                    <div class="m-card-info">
                        <div class="m-name">
                            <?=htmlspecialchars($u['nama'])?>
                            <?php if($isSelf): ?><span class="self-tag">Anda</span><?php endif; ?>
                        </div>
                        <div class="m-user">@<?=htmlspecialchars($u['username'])?></div>
                    </div>
                    <div class="status-pill <?=$u['status']==='Aktif'?'s-on':'s-off'?>" style="flex-shrink:0">
                        <span class="sdot"></span><?=$u['status']?>
                    </div>
                </div>
                <div class="m-meta">
                    <span class="badge <?=$bclass?>"><?=$ico?> <?=ucfirst($u['role'])?></span>
                    <span class="m-date">Dibuat <?=date('d/m/Y',strtotime($u['created_at']))?></span>
                </div>
                <?php if(!empty($u['email'])): ?>
                <div class="m-row"><span>Email</span><?=htmlspecialchars($u['email'])?></div>
                <?php endif; ?>
                <?php if(!empty($u['no_telp'])): ?>
                <div class="m-row"><span>Telp</span><span class="td-mono"><?=htmlspecialchars($u['no_telp'])?></span></div>
                <?php endif; ?>
                <div class="m-actions">
                    <button class="btn-sm btn-edit" onclick="openEdit(<?=htmlspecialchars(json_encode($u))?>)">✏ Edit</button>
                    <?php if(!$isSelf): ?>
                    <a href="user.php?toggle=<?=$u['id']?><?=$search?"&q=$search":''?><?=$filterRole?"&role=$filterRole":''?>"
                       class="btn-sm <?=$u['status']==='Aktif'?'btn-warn':'btn-ok'?>"
                       onclick="return confirm('Ubah status <?=addslashes(htmlspecialchars($u['nama']))?>')">
                        <?=$u['status']==='Aktif'?'⏸ Nonaktif':'▶ Aktifkan'?>
                    </a>
                    <a href="user.php?hapus=<?=$u['id']?><?=$search?"&q=$search":''?><?=$filterRole?"&role=$filterRole":''?>"
                       class="btn-sm btn-del"
                       onclick="return confirm('Hapus <?=addslashes(htmlspecialchars($u['nama']))?> secara permanen?')">
                        🗑 Hapus
                    </a>
                    <?php else: ?>
                    <span class="locked-txt">🔒 Akun Anda</span>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
            </div>

            <?php else: ?>
            <div class="empty-state">
                <span class="empty-ico">👤</span>
                <div class="empty-title">Tidak ada pengguna ditemukan</div>
                <div class="empty-sub">Coba ubah filter pencarian atau tambah pengguna baru</div>
            </div>
            <?php endif; ?>
        </div>

    </div><!-- /wrap -->
</div><!-- /main -->

<!-- ══ MODAL TAMBAH / EDIT ══ -->
<div class="modal-bg" id="modalBg" onclick="if(event.target===this)closeModal()">
<div class="modal">
    <div class="modal-head">
        <div>
            <div class="modal-title" id="mTitle">Tambah Pengguna</div>
            <div class="modal-sub"   id="mSub">Isi semua field yang diperlukan</div>
        </div>
        <button class="modal-close" onclick="closeModal()">✕</button>
    </div>
    <form method="POST" action="user.php" enctype="multipart/form-data">
    <div class="modal-body">
        <input type="hidden" name="act" id="fAct" value="tambah">
        <input type="hidden" name="id"  id="fId"  value="">

        <div class="fg-row">
            <div class="fg">
                <label class="flbl">Nama Lengkap <span class="fstar">*</span></label>
                <div class="fi-wrap"><span class="fi-icon">👤</span>
                    <input type="text" name="nama" id="fNama" class="fi" placeholder="Nama lengkap" required autocomplete="off">
                </div>
            </div>
            <div class="fg">
                <label class="flbl">Role <span class="fstar">*</span></label>
                <div class="fi-sel-wrap"><span class="fi-icon">🏷</span>
                    <select name="role" id="fRole" class="fi-sel" required>
                        <option value="admin">Admin</option>
                        <option value="guru" selected>Guru</option>
                        <option value="staff">Staff</option>
                        <option value="tu">Tata Usaha</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="fg-row">
            <div class="fg">
                <label class="flbl">Username <span class="fstar">*</span></label>
                <div class="fi-wrap"><span class="fi-icon">@</span>
                    <input type="text" name="username" id="fUsername" class="fi" placeholder="username" autocomplete="off" required>
                </div>
            </div>
            <div class="fg">
                <label class="flbl">Status</label>
                <div class="fi-sel-wrap"><span class="fi-icon">◉</span>
                    <select name="status" id="fStatus" class="fi-sel">
                        <option value="Aktif">Aktif</option>
                        <option value="Nonaktif">Nonaktif</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="fg">
            <label class="flbl">
                Password <span class="fstar" id="passReq">*</span>
                <span id="passNote" style="display:none;font-weight:400;color:var(--txl)"> — kosongkan jika tidak diubah</span>
            </label>
            <div class="fi-wrap"><span class="fi-icon">🔒</span>
                <input type="password" name="password" id="fPass" class="fi" placeholder="Password" autocomplete="new-password">
                <button type="button" class="fi-eye" onclick="togglePw()">👁</button>
            </div>
            <div class="pbar"><div class="pbar-fill" id="pFill"></div></div>
            <div class="fi-hint" id="pHint">Minimal 6 karakter</div>
        </div>

        <div class="fg">
            <label class="flbl">Foto Profil</label>
            <div class="foto-wrap" id="fotoWrap" onclick="document.getElementById('fFoto').click()">
                <img id="fotoPreview" src="" alt="" style="display:none">
                <div id="fotoPlaceholder">
                    <div class="foto-ico">📷</div>
                    <div class="foto-txt">Klik untuk upload foto</div>
                    <div class="foto-sub">JPG, PNG, WEBP — maks. 2 MB</div>
                </div>
                <button type="button" class="foto-remove" id="fotoRemoveBtn" onclick="removeFoto(event)" style="display:none">✕</button>
            </div>
            <input type="file" name="foto" id="fFoto" accept="image/*" style="display:none" onchange="previewFoto(this)">
            <input type="hidden" name="hapus_foto" id="hapusFoto" value="0">
        </div>

        <div class="form-divider"></div>

        <div class="fg-row">
            <div class="fg">
                <label class="flbl">Email</label>
                <div class="fi-wrap"><span class="fi-icon">✉</span>
                    <input type="email" name="email" id="fEmail" class="fi" placeholder="email@sekolah.com" autocomplete="off">
                </div>
            </div>
            <div class="fg">
                <label class="flbl">No. Telepon</label>
                <div class="fi-wrap"><span class="fi-icon">📱</span>
                    <input type="text" name="no_telp" id="fNoTelp" class="fi" placeholder="08xx-xxxx-xxxx" autocomplete="off">
                </div>
            </div>
        </div>
    </div>
    <div class="modal-foot">
        <button type="button" class="btn-ghost" onclick="closeModal()">Batal</button>
        <button type="submit" class="btn-gold"><span id="mSaveTxt">Simpan Pengguna</span></button>
    </div>
    </form>
</div>
</div>

<?php if($editData): ?>
<script>document.addEventListener('DOMContentLoaded',()=>openEdit(<?=json_encode($editData)?>))</script>
<?php endif; ?>

<!-- ══ PAGE-SPECIFIC STYLES ══ -->
<style>
/* ════════════════════════════════════════════════════════
   PAGE HEADER
════════════════════════════════════════════════════════ */
.page-header {
    background:var(--ob); border-bottom:1px solid rgba(201,168,76,.12);
    padding:1.5rem 2.5rem;
    display:flex; align-items:center; justify-content:space-between;
    flex-wrap:wrap; gap:1rem;
}
.ph-left { display:flex; align-items:center; gap:1rem; }
.ph-icon {
    width:48px; height:48px; border-radius:14px; flex-shrink:0;
    background:rgba(201,168,76,.15); border:1.5px solid rgba(201,168,76,.3);
    display:flex; align-items:center; justify-content:center; font-size:1.4rem;
}
.ph-title { font-family:'DM Serif Display',serif; font-size:1.3rem; color:var(--g-fg); line-height:1.2; }
.ph-sub   { font-size:.8rem; color:rgba(255,255,255,.4); margin-top:.2rem; }
.ph-actions { display:flex; align-items:center; gap:.75rem; flex-wrap:wrap; }

/* ════════════════════════════════════════════════════════
   BUTTONS
════════════════════════════════════════════════════════ */
.btn-ghost {
    display:inline-flex; align-items:center; gap:.375rem;
    padding:.5rem 1rem; border-radius:9px;
    border:1.5px solid var(--bd); background:var(--sf);
    font-family:'Outfit',sans-serif; font-size:.825rem; font-weight:600;
    color:var(--txm); cursor:pointer; text-decoration:none;
    transition:all .18s;
}
.btn-ghost:hover { border-color:var(--bd-d); color:var(--tx); background:var(--sf2); }
.btn-gold {
    display:inline-flex; align-items:center; gap:.375rem;
    padding:.5rem 1.25rem; border-radius:9px; border:none;
    background:linear-gradient(135deg, var(--g), var(--g-l));
    font-family:'Outfit',sans-serif; font-size:.825rem; font-weight:700;
    color:var(--ob); cursor:pointer; transition:all .2s;
}
.btn-gold:hover { transform:translateY(-2px); box-shadow:0 6px 20px rgba(201,168,76,.35); }

/* ════════════════════════════════════════════════════════
   ALERTS
════════════════════════════════════════════════════════ */
.alert {
    display:flex; align-items:flex-start; gap:.625rem;
    padding:.75rem 1rem; border-radius:10px;
    margin-bottom:1rem; font-size:.825rem; font-weight:500;
    border:1px solid;
}
.alert-ok  { background:#F0FDF4; color:#15803D; border-color:#BBF7D0; }
.alert-err { background:#FEF2F2; color:#B91C1C; border-color:#FECACA; }
.alert-x { margin-left:auto; background:none; border:none; cursor:pointer; color:inherit; opacity:.5; font-size:.875rem; padding:2px; flex-shrink:0; }
.alert-x:hover { opacity:1; }

/* ════════════════════════════════════════════════════════
   STAT CARDS
════════════════════════════════════════════════════════ */
.stats-grid {
    display:grid;
    grid-template-columns:repeat(5,1fr);
    gap:.875rem; margin-bottom:1.5rem;
}
.stat-card {
    background:var(--sf); border:1px solid var(--bd);
    border-radius:14px; padding:1.25rem 1.25rem 1rem;
    transition:box-shadow .18s, transform .18s;
    position:relative; overflow:hidden;
}
.stat-card::before {
    content:''; position:absolute; top:0; left:0; right:0; height:3px;
    border-radius:14px 14px 0 0;
}
.stat-all::before  { background:linear-gradient(90deg,var(--g),var(--g-l)); }
.sc-admin::before  { background:#DC2626; }
.sc-guru::before   { background:#2563EB; }
.sc-staff::before  { background:#16A34A; }
.sc-tu::before     { background:#7C3AED; }
.stat-card:hover   { box-shadow:0 4px 16px var(--sh-m); transform:translateY(-2px); }
.sc-label { font-size:.7rem; font-weight:700; letter-spacing:.08em; text-transform:uppercase; color:var(--txl); margin-bottom:.625rem; }
.sc-val   { font-family:'DM Mono',monospace; font-size:2rem; font-weight:500; line-height:1; color:var(--tx); margin-bottom:.25rem; }
.sc-sub   { font-size:.75rem; color:var(--txl); }
.sc-admin .sc-val { color:#DC2626; }
.sc-guru  .sc-val { color:#2563EB; }
.sc-staff .sc-val { color:#16A34A; }
.sc-tu    .sc-val { color:#7C3AED; }

/* ════════════════════════════════════════════════════════
   TOOLBAR
════════════════════════════════════════════════════════ */
.toolbar {
    display:flex; align-items:center; gap:.75rem;
    flex-wrap:wrap; margin-bottom:1.25rem;
}
.search-wrap { flex:1; min-width:180px; position:relative; }
.search-icon { position:absolute; left:.75rem; top:50%; transform:translateY(-50%); font-size:.8rem; pointer-events:none; }
.search-input {
    width:100%; padding:.625rem .75rem .625rem 2.25rem;
    border:1.5px solid var(--bd); border-radius:9px;
    font-family:'Outfit',sans-serif; font-size:.875rem; color:var(--tx);
    background:var(--sf); outline:none; transition:border .15s;
}
.search-input:focus { border-color:var(--g); box-shadow:0 0 0 3px rgba(201,168,76,.12); }
.search-input::placeholder { color:var(--txl); }
.filter-wrap { flex-shrink:0; }
.filter-select {
    padding:.625rem 2rem .625rem .875rem; border:1.5px solid var(--bd); border-radius:9px;
    font-family:'Outfit',sans-serif; font-size:.875rem; color:var(--tx);
    background:var(--sf); outline:none; cursor:pointer;
    appearance:none; -webkit-appearance:none;
    background-image:url("data:image/svg+xml,%3Csvg width='10' height='6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0l5 6 5-6z' fill='%239BA4B5'/%3E%3C/svg%3E");
    background-repeat:no-repeat; background-position:right .625rem center;
    transition:border .15s;
}
.filter-select:focus { border-color:var(--g); }

/* ════════════════════════════════════════════════════════
   TABLE CARD
════════════════════════════════════════════════════════ */
.tcard {
    background:var(--sf); border:1px solid var(--bd);
    border-radius:14px; overflow:hidden;
    box-shadow:0 2px 12px var(--sh);
}
.tcard-head {
    display:flex; align-items:center; justify-content:space-between;
    padding:1rem 1.25rem; border-bottom:1px solid var(--bd); flex-wrap:wrap; gap:.5rem;
}
.tcard-title { font-size:.9rem; font-weight:700; color:var(--tx); }
.tcard-badge {
    font-size:.75rem; font-weight:600; color:var(--txm);
    padding:.25rem .75rem; background:var(--bg); border:1px solid var(--bd);
    border-radius:50px;
}
.tscroll { overflow-x:auto; -webkit-overflow-scrolling:touch; }
.tscroll::-webkit-scrollbar { height:4px; }
.tscroll::-webkit-scrollbar-thumb { background:var(--bd-d); border-radius:4px; }

table { width:100%; border-collapse:collapse; min-width:760px; }
thead tr { background:var(--bg); border-bottom:1px solid var(--bd); }
th {
    padding:.625rem 1rem; text-align:left;
    font-size:.7rem; font-weight:700; color:var(--txl);
    text-transform:uppercase; letter-spacing:.06em; white-space:nowrap;
}
tbody tr { border-bottom:1px solid var(--bd); transition:background .1s; }
tbody tr:last-child { border-bottom:none; }
tbody tr:hover { background:var(--sf2); }
td { padding:.875rem 1rem; font-size:.825rem; color:var(--tx); vertical-align:middle; }
.td-num  { color:var(--txl); font-family:'DM Mono',monospace; font-size:.75rem; }
.td-muted{ color:var(--txm); font-size:.8rem; }
.td-mono { font-family:'DM Mono',monospace; font-size:.78rem; color:var(--txm); }

/* User cell */
.u-cell  { display:flex; align-items:center; gap:.75rem; }
.u-ava   {
    width:38px; height:38px; border-radius:50%; flex-shrink:0;
    background:linear-gradient(135deg, var(--g-d), var(--g));
    display:flex; align-items:center; justify-content:center;
    font-size:.9rem; font-weight:700; color:var(--ob);
    border:2px solid rgba(201,168,76,.25);
}
.u-photo { width:38px; height:38px; border-radius:50%; object-fit:cover; border:2px solid var(--bd); flex-shrink:0; }
.u-name  { font-weight:700; font-size:.825rem; color:var(--tx); }
.u-date  { font-size:.7rem; color:var(--txl); font-family:'DM Mono',monospace; margin-top:.1rem; }
.self-tag {
    display:inline-block; font-size:.625rem; font-weight:700;
    padding:.1rem .4rem; border-radius:50px; margin-left:.3rem;
    background:rgba(201,168,76,.15); color:var(--g); border:1px solid rgba(201,168,76,.3);
    vertical-align:middle;
}

/* Badges */
.mono-tag {
    font-family:'DM Mono',monospace; font-size:.75rem;
    padding:.15rem .625rem; background:var(--bg); border:1px solid var(--bd);
    border-radius:5px; color:var(--txm); white-space:nowrap;
}
.badge {
    display:inline-flex; align-items:center; gap:.3rem;
    padding:.25rem .625rem; border-radius:50px; font-size:.7rem; font-weight:700;
    border:1px solid; white-space:nowrap;
}
.b-admin { background:#FEF2F2; color:#DC2626; border-color:#FECACA; }
.b-guru  { background:#EFF6FF; color:#2563EB; border-color:#BFDBFE; }
.b-staff { background:#F0FDF4; color:#16A34A; border-color:#BBF7D0; }
.b-tu    { background:#F5F3FF; color:#7C3AED; border-color:#DDD6FE; }

/* Status */
.status-pill {
    display:inline-flex; align-items:center; gap:.4rem;
    font-size:.75rem; font-weight:600; white-space:nowrap;
}
.sdot { width:6px; height:6px; border-radius:50%; flex-shrink:0; }
.s-on  { color:#16A34A; } .s-on  .sdot { background:#16A34A; }
.s-off { color:#DC2626; } .s-off .sdot { background:#DC2626; }

/* Action buttons */
.act-row { display:flex; align-items:center; gap:.3rem; flex-wrap:wrap; }
.btn-sm  {
    display:inline-flex; align-items:center; gap:.3rem;
    padding:.3rem .7rem; border-radius:7px; font-size:.72rem; font-weight:600;
    cursor:pointer; border:1px solid; transition:all .12s;
    font-family:'Outfit',sans-serif; text-decoration:none; white-space:nowrap;
}
.btn-edit { background:var(--bg);   color:var(--txm); border-color:var(--bd); }
.btn-edit:hover { background:var(--bd); color:var(--tx); }
.btn-warn { background:#FFFBEB; color:#D97706; border-color:#FDE68A; }
.btn-warn:hover { background:#FEF3C7; }
.btn-ok   { background:#F0FDF4; color:#16A34A; border-color:#BBF7D0; }
.btn-ok:hover { background:#DCFCE7; }
.btn-del  { background:#FEF2F2; color:#DC2626; border-color:#FECACA; }
.btn-del:hover { background:#FEE2E2; }
.locked-txt { font-size:.72rem; color:var(--txl); padding:.3rem; white-space:nowrap; }

/* Empty state */
.empty-state { text-align:center; padding:3.5rem 1.5rem; }
.empty-ico   { font-size:2.5rem; opacity:.25; margin-bottom:.75rem; display:block; }
.empty-title { font-size:.9rem; font-weight:700; color:var(--txm); margin-bottom:.3rem; }
.empty-sub   { font-size:.825rem; color:var(--txl); }

/* ════════════════════════════════════════════════════════
   MOBILE CARDS
════════════════════════════════════════════════════════ */
.mobile-cards { display:none; padding:.875rem; }
.m-card {
    background:var(--sf); border:1px solid var(--bd);
    border-radius:12px; padding:1rem; margin-bottom:.75rem;
}
.m-card-head {
    display:flex; align-items:center; gap:.75rem; margin-bottom:.75rem;
}
.m-card-info { flex:1; min-width:0; }
.m-name  { font-size:.9rem; font-weight:700; color:var(--tx); display:flex; align-items:center; gap:.4rem; flex-wrap:wrap; }
.m-user  { font-family:'DM Mono',monospace; font-size:.72rem; color:var(--txl); margin-top:.15rem; }
.m-meta  { display:flex; gap:.5rem; align-items:center; flex-wrap:wrap; margin-bottom:.625rem; }
.m-date  { font-size:.7rem; color:var(--txl); font-family:'DM Mono',monospace; }
.m-row   { display:flex; align-items:baseline; gap:.5rem; font-size:.78rem; color:var(--txm); margin-bottom:.3rem; }
.m-row span:first-child { color:var(--txl); min-width:52px; font-size:.72rem; }
.m-actions {
    display:flex; gap:.5rem; flex-wrap:wrap;
    padding-top:.75rem; border-top:1px solid var(--bd);
}
.m-actions .btn-sm { flex:1; min-width:fit-content; justify-content:center; }

/* ════════════════════════════════════════════════════════
   MODAL
════════════════════════════════════════════════════════ */
.modal-bg {
    display:none; position:fixed; inset:0; z-index:500;
    background:rgba(8,12,20,.55); backdrop-filter:blur(4px);
    align-items:flex-start; justify-content:center;
    padding:1.25rem; overflow-y:auto;
}
.modal-bg.open { display:flex; }
.modal {
    background:var(--sf); border:1px solid var(--bd);
    border-radius:16px; width:100%; max-width:520px;
    box-shadow:0 24px 60px rgba(0,0,0,.18);
    margin:auto; position:relative;
}
.modal-head {
    display:flex; align-items:center; justify-content:space-between;
    padding:1.125rem 1.5rem; border-bottom:1px solid var(--bd);
    position:sticky; top:0; background:var(--sf); z-index:1;
    border-radius:16px 16px 0 0;
}
.modal-title { font-size:.975rem; font-weight:700; color:var(--tx); }
.modal-sub   { font-size:.75rem; color:var(--txl); margin-top:.2rem; }
.modal-close {
    width:30px; height:30px; border-radius:7px;
    background:none; border:1.5px solid var(--bd);
    cursor:pointer; font-size:.8rem; color:var(--txl);
    display:flex; align-items:center; justify-content:center;
    transition:all .15s; flex-shrink:0;
}
.modal-close:hover { background:#FEF2F2; border-color:#FECACA; color:#DC2626; }
.modal-body { padding:1.25rem 1.5rem; }
.modal-foot {
    display:flex; gap:.625rem; justify-content:flex-end;
    padding:1rem 1.5rem; border-top:1px solid var(--bd);
    background:var(--bg); border-radius:0 0 16px 16px; flex-wrap:wrap;
}

/* Form elements */
.fg   { display:flex; flex-direction:column; gap:.375rem; margin-bottom:1rem; }
.fg-row { display:grid; grid-template-columns:1fr 1fr; gap:1rem; }
.flbl { font-size:.75rem; font-weight:700; color:var(--txm); display:flex; align-items:center; gap:.3rem; flex-wrap:wrap; }
.fstar { color:#DC2626; }
.fi-wrap { position:relative; }
.fi-icon {
    position:absolute; left:.75rem; top:50%; transform:translateY(-50%);
    font-size:.8rem; pointer-events:none; color:var(--txl);
}
.fi {
    width:100%; padding:.625rem .75rem .625rem 2.25rem;
    border:1.5px solid var(--bd); border-radius:9px;
    font-family:'Outfit',sans-serif; font-size:.875rem; color:var(--tx);
    background:var(--sf); outline:none; transition:border .15s;
    /* prevent iOS zoom */ font-size:max(.875rem,16px); -webkit-appearance:none;
}
.fi:focus { border-color:var(--g); box-shadow:0 0 0 3px rgba(201,168,76,.12); }
.fi::placeholder { color:var(--txl); }
.fi-eye {
    position:absolute; right:.625rem; top:50%; transform:translateY(-50%);
    background:none; border:none; cursor:pointer; font-size:.8rem; color:var(--txl); padding:.25rem;
}
.fi-eye:hover { color:var(--tx); }
.fi-sel-wrap { position:relative; }
.fi-sel-wrap .fi-icon { z-index:1; }
.fi-sel {
    width:100%; padding:.625rem 2rem .625rem 2.25rem;
    border:1.5px solid var(--bd); border-radius:9px;
    font-family:'Outfit',sans-serif; font-size:max(.875rem,16px); color:var(--tx);
    background:var(--sf); outline:none; cursor:pointer;
    appearance:none; -webkit-appearance:none;
    background-image:url("data:image/svg+xml,%3Csvg width='10' height='6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0l5 6 5-6z' fill='%239BA4B5'/%3E%3C/svg%3E");
    background-repeat:no-repeat; background-position:right .75rem center;
    transition:border .15s;
}
.fi-sel:focus { border-color:var(--g); box-shadow:0 0 0 3px rgba(201,168,76,.12); }
.fi-hint { font-size:.7rem; color:var(--txl); }
.pbar { height:3px; background:var(--bd); border-radius:50px; overflow:hidden; margin-top:.375rem; }
.pbar-fill { height:100%; border-radius:50px; transition:width .3s; width:0; }
.form-divider { height:1px; background:var(--bd); margin:1.25rem 0; }

/* Foto upload */
.foto-wrap {
    position:relative; border:2px dashed var(--bd-d); border-radius:12px;
    padding:1.5rem; text-align:center; cursor:pointer;
    transition:all .18s; background:var(--bg); overflow:hidden; min-height:90px;
    display:flex; align-items:center; justify-content:center;
}
.foto-wrap:hover { border-color:var(--g); background:rgba(201,168,76,.05); }
.foto-wrap.has-foto { border-style:solid; border-color:var(--bd); padding:0; }
.foto-wrap.has-foto:hover { border-color:var(--g); }
.foto-wrap img#fotoPreview { width:100%; height:150px; object-fit:cover; border-radius:10px; display:block; }
.foto-ico { font-size:1.75rem; margin-bottom:.4rem; }
.foto-txt { font-size:.825rem; font-weight:700; color:var(--txm); }
.foto-sub { font-size:.7rem; color:var(--txl); margin-top:.2rem; }
.foto-remove {
    position:absolute; top:.5rem; right:.5rem;
    width:26px; height:26px; border-radius:50%;
    background:rgba(0,0,0,.55); color:#fff; border:none;
    cursor:pointer; font-size:.75rem; font-weight:700;
    display:flex; align-items:center; justify-content:center;
    transition:background .15s; z-index:5;
}
.foto-remove:hover { background:#DC2626; }

/* ════════════════════════════════════════════════════════
   RESPONSIVE
════════════════════════════════════════════════════════ */
@media(max-width:1300px) {
    .stats-grid { grid-template-columns:repeat(3,1fr); }
}
@media(max-width:1024px) {
    .stats-grid { grid-template-columns:repeat(3,1fr); }
    .page-header { padding:1.25rem 1.5rem; }
}
@media(max-width:768px) {
    .page-header { padding:1rem; }
    .ph-title { font-size:1.1rem; }
    .ph-icon  { width:40px; height:40px; font-size:1.1rem; }
    .stats-grid { grid-template-columns:1fr 1fr; gap:.625rem; margin-bottom:1rem; }
    .sc-val { font-size:1.6rem; }
    .toolbar { flex-direction:column; }
    .search-wrap { width:100%; }
    .filter-wrap { width:100%; }
    .filter-select { width:100%; }
    /* Switch table → cards */
    .tscroll { display:none; }
    .mobile-cards { display:block; }
    /* Modal bottom sheet */
    .modal-bg { padding:0; align-items:flex-end; }
    .modal { border-radius:16px 16px 0 0; max-width:100%; max-height:92vh; overflow-y:auto; }
    .modal-head { border-radius:16px 16px 0 0; }
    .modal-foot { justify-content:stretch; }
    .modal-foot .btn-ghost,
    .modal-foot .btn-gold { flex:1; justify-content:center; }
}
@media(max-width:480px) {
    .stats-grid { grid-template-columns:1fr 1fr; gap:.5rem; }
    .stat-card  { padding:1rem .875rem .75rem; }
    .sc-val     { font-size:1.4rem; }
    .ph-actions .btn-ghost { display:none; }
    .fg-row { grid-template-columns:1fr; gap:.75rem; }
    .modal-body  { padding:1rem; }
    .modal-foot  { padding:.875rem 1rem; }
}
@supports(padding:max(0px)) {
    .page-header { padding-left:max(1.5rem, env(safe-area-inset-left)); padding-right:max(1.5rem, env(safe-area-inset-right)); }
    .wrap        { padding-left:max(1.5rem, env(safe-area-inset-left)); padding-right:max(1.5rem, env(safe-area-inset-right)); }
    .modal-foot  { padding-bottom:max(1rem, env(safe-area-inset-bottom)); }
}
</style>

<!-- ══ PAGE JAVASCRIPT ══ -->
<script>
// ── Modal ──────────────────────────────────────────
function openModal(){
    ['fNama','fUsername','fPass','fEmail','fNoTelp'].forEach(id=>document.getElementById(id).value='');
    document.getElementById('fAct').value='tambah';
    document.getElementById('fId').value='';
    document.getElementById('fRole').value='guru';
    document.getElementById('fStatus').value='Aktif';
    document.getElementById('mTitle').textContent='Tambah Pengguna';
    document.getElementById('mSub').textContent='Isi semua field yang diperlukan';
    document.getElementById('mSaveTxt').textContent='Simpan Pengguna';
    document.getElementById('passReq').style.display='';
    document.getElementById('passNote').style.display='none';
    document.getElementById('fPass').required=true;
    resetPbar();
    clearFotoPreview();
    document.getElementById('hapusFoto').value='0';
    document.getElementById('modalBg').classList.add('open');
    document.body.style.overflow='hidden';
    setTimeout(()=>document.getElementById('fNama').focus(),150);
}
function openEdit(u){
    document.getElementById('fAct').value='edit';
    document.getElementById('fId').value=u.id;
    document.getElementById('fNama').value=u.nama||'';
    document.getElementById('fUsername').value=u.username||'';
    document.getElementById('fPass').value='';
    document.getElementById('fEmail').value=u.email||'';
    document.getElementById('fNoTelp').value=u.no_telp||'';
    document.getElementById('fRole').value=u.role||'guru';
    document.getElementById('fStatus').value=u.status||'Aktif';
    document.getElementById('mTitle').textContent='Edit Pengguna';
    document.getElementById('mSub').textContent='Mengubah: '+u.nama;
    document.getElementById('mSaveTxt').textContent='Simpan Perubahan';
    document.getElementById('passReq').style.display='none';
    document.getElementById('passNote').style.display='';
    document.getElementById('fPass').required=false;
    resetPbar();
    if(u.foto){ setFotoPreview(u.foto); } else { clearFotoPreview(); }
    document.getElementById('hapusFoto').value='0';
    document.getElementById('modalBg').classList.add('open');
    document.body.style.overflow='hidden';
    setTimeout(()=>document.getElementById('fNama').focus(),150);
}
function closeModal(){
    document.getElementById('modalBg').classList.remove('open');
    document.body.style.overflow='';
}
document.addEventListener('keydown',e=>{ if(e.key==='Escape') closeModal(); });

// ── Password strength ──────────────────────────────
let pwVis=false;
function togglePw(){
    const i=document.getElementById('fPass');
    pwVis=!pwVis; i.type=pwVis?'text':'password';
    event.currentTarget.textContent=pwVis?'🙈':'👁';
}
const pC=['#DC2626','#D97706','#D97706','#16A34A','#16A34A'];
const pH=['Sangat lemah','Lemah','Sedang','Kuat','Sangat kuat'];
function resetPbar(){
    document.getElementById('pFill').style.cssText='width:0';
    document.getElementById('pHint').textContent='Minimal 6 karakter';
    document.getElementById('pHint').style.color='';
}
document.getElementById('fPass').addEventListener('input',function(){
    if(!this.value){ resetPbar(); return; }
    let s=0;
    if(this.value.length>=6) s++;
    if(this.value.length>=10) s++;
    if(/[A-Z]/.test(this.value)) s++;
    if(/[0-9]/.test(this.value)) s++;
    if(/[^A-Za-z0-9]/.test(this.value)) s++;
    document.getElementById('pFill').style.cssText='width:'+(s*20)+'%;background:'+pC[s-1];
    document.getElementById('pHint').textContent=pH[s-1]||pH[0];
    document.getElementById('pHint').style.color=pC[s-1]||pC[0];
});

// ── Photo preview ──────────────────────────────────
function previewFoto(input){
    if(!input.files||!input.files[0]) return;
    const reader=new FileReader();
    reader.onload=e=>setFotoPreview(e.target.result);
    reader.readAsDataURL(input.files[0]);
}
function setFotoPreview(src){
    document.getElementById('fotoPreview').src=src;
    document.getElementById('fotoPreview').style.display='block';
    document.getElementById('fotoPlaceholder').style.display='none';
    document.getElementById('fotoRemoveBtn').style.display='flex';
    document.getElementById('fotoWrap').classList.add('has-foto');
}
function clearFotoPreview(){
    document.getElementById('fotoPreview').src='';
    document.getElementById('fotoPreview').style.display='none';
    document.getElementById('fotoPlaceholder').style.display='block';
    document.getElementById('fotoRemoveBtn').style.display='none';
    document.getElementById('fotoWrap').classList.remove('has-foto');
    document.getElementById('fFoto').value='';
}
function removeFoto(e){
    e.stopPropagation();
    clearFotoPreview();
    document.getElementById('hapusFoto').value='1';
}

// ── Auto-hide alerts ───────────────────────────────
setTimeout(()=>{
    document.querySelectorAll('.alert').forEach(el=>{
        el.style.transition='opacity .5s,transform .5s';
        el.style.opacity='0';
        el.style.transform='translateY(-8px)';
        setTimeout(()=>el.remove(),500);
    });
},6000);
</script>