<?php
/* ══════════════════════════════════════════════════════
   guru.php — Data Guru & Tenaga Pengajar
   MA As-Syafi'iyah 02 Bekasi
   Integrasi: navbar.php (sidebar + topbar + loader)
══════════════════════════════════════════════════════ */
$page_title  = "Data Guru — MA As-Syafi'iyah 02";
$active_menu = 'guru';
$loader_text = 'Memuat Data Guru';
include 'navbar.php';
include 'koneksi.php';
date_default_timezone_set('Asia/Jakarta');

$success=''; $error='';

/* ── EKSPOR CSV ── */
if(isset($_GET['export']) && $_GET['export']==='csv'){
    $result = mysqli_query($conn, "SELECT * FROM guru ORDER BY nama");
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="data_guru_'.date('Ymd_His').'.csv"');
    header('Cache-Control: no-cache, must-revalidate');
    $out = fopen('php://output','w');
    fputs($out, "\xEF\xBB\xBF");
    fputcsv($out, ['NIP','Nama','Jenis Kelamin','Tempat Lahir','Tanggal Lahir','Alamat','No. Telepon','Email','Pendidikan','Mata Pelajaran','Status']);
    while($row = mysqli_fetch_assoc($result)){
        fputcsv($out,[$row['nip']??'',$row['nama']??'',$row['jk']??'',$row['tempat_lahir']??'',$row['tanggal_lahir']??'',$row['alamat']??'',$row['no_telp']??'',$row['email']??'',$row['pendidikan']??'',$row['mapel']??'',$row['status']??'']);
    }
    fclose($out); exit();
}

/* ── EKSPOR EXCEL ── */
if(isset($_GET['export']) && $_GET['export']==='excel'){
    $result = mysqli_query($conn, "SELECT * FROM guru ORDER BY nama");
    header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
    header('Content-Disposition: attachment; filename="data_guru_'.date('Ymd_His').'.xls"');
    header('Cache-Control: no-cache, must-revalidate');
    echo "\xEF\xBB\xBF";
    echo '<table border="1" style="border-collapse:collapse"><thead><tr style="background:#0E1520;color:white">';
    foreach(['No','NIP','Nama','JK','Tempat Lahir','Tgl Lahir','Alamat','No. Telp','Email','Pendidikan','Mata Pelajaran','Status'] as $h)
        echo '<th style="padding:6px 10px">'.htmlspecialchars($h).'</th>';
    echo '</tr></thead><tbody>';
    $no=1;
    while($row=mysqli_fetch_assoc($result)){
        $bg=($no%2==0)?'#F7F5F2':'#FFFFFF';
        echo '<tr style="background:'.$bg.'"><td style="padding:5px 8px;text-align:center">'.$no++.'</td>';
        foreach(['nip','nama','jk','tempat_lahir','tanggal_lahir','alamat','no_telp','email','pendidikan','mapel','status'] as $col)
            echo '<td style="padding:5px 8px">'.htmlspecialchars($row[$col]??'').'</td>';
        echo '</tr>';
    }
    echo '</tbody></table>'; exit();
}

/* ── DOWNLOAD TEMPLATE ── */
if(isset($_GET['export']) && $_GET['export']==='template'){
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="template_import_guru.csv"');
    header('Cache-Control: no-cache');
    $out=fopen('php://output','w'); fputs($out,"\xEF\xBB\xBF");
    fputcsv($out,['NIP','Nama','Jenis Kelamin','Tempat Lahir','Tanggal Lahir','Alamat','No. Telepon','Email','Pendidikan','Mata Pelajaran','Status']);
    fputcsv($out,['198501012010011001','Drs. Ahmad Fauzi','L','Jakarta','1985-01-01','Jl. Mawar No. 5 Jakarta','081234567890','ahmad.fauzi@email.com','S1','Matematika','Aktif']);
    fputcsv($out,['199002152015012002','Siti Rahmawati S.Pd','P','Bandung','1990-02-15','Jl. Melati No. 12 Bandung','082345678901','siti.r@email.com','S1','Bahasa Indonesia','Aktif']);
    fclose($out); exit();
}

/* ── IMPOR CSV ── */
$import_result=null;
if(isset($_POST['import_guru'])){
    $csv_err=$_FILES['csv_file']['error']??4;
    if($csv_err!==0){
        $em=[1=>'File terlalu besar (server)',2=>'File terlalu besar',3=>'Upload tidak selesai',4=>'Tidak ada file dipilih'];
        $import_result=['error'=>$em[$csv_err]??'Gagal upload (kode: '.$csv_err.')'];
    }elseif(strtolower(pathinfo($_FILES['csv_file']['name'],PATHINFO_EXTENSION))!=='csv'){
        $import_result=['error'=>'File harus berformat .CSV!'];
    }elseif($_FILES['csv_file']['size']>5*1024*1024){
        $import_result=['error'=>'Ukuran file maksimal 5MB!'];
    }else{
        $content=file_get_contents($_FILES['csv_file']['tmp_name']);
        if(substr($content,0,3)==="\xEF\xBB\xBF")$content=substr($content,3);
        $tmp=tempnam(sys_get_temp_dir(),'guru_csv_'); file_put_contents($tmp,$content);
        $h=fopen($tmp,'r'); $header=fgetcsv($h,0,','); $delim=',';
        if(count($header)<=1){fclose($h);$h=fopen($tmp,'r');$header=fgetcsv($h,0,';');$delim=';';}
        $ok=0;$fail=0;$errors=[];$row_num=1;
        $col_keys=['nip','nama','jk','tempat_lahir','tanggal_lahir','alamat','no_telp','email','pendidikan','mapel','status'];
        while(($row=fgetcsv($h,0,$delim))!==false){
            $row_num++; if(count($row)===1&&trim($row[0])==='')continue;
            while(count($row)<11)$row[]='';
            $d=[]; foreach($col_keys as $i=>$k)$d[$k]=trim($row[$i]??'');
            if(empty($d['nip'])||empty($d['nama'])){$fail++;$errors[]="Baris $row_num: NIP atau Nama kosong";continue;}
            if(!empty($d['tanggal_lahir'])&&strpos($d['tanggal_lahir'],'/')!==false){
                $p=explode('/',$d['tanggal_lahir']);
                if(count($p)===3)$d['tanggal_lahir']=$p[2].'-'.str_pad($p[1],2,'0',STR_PAD_LEFT).'-'.str_pad($p[0],2,'0',STR_PAD_LEFT);
            }
            if(!preg_match('/^\d{4}-\d{2}-\d{2}$/',$d['tanggal_lahir']??''))$d['tanggal_lahir']='';
            if(empty($d['status']))$d['status']='Aktif';
            $esc=fn($v)=>mysqli_real_escape_string($conn,$v);
            $chk=mysqli_query($conn,"SELECT id FROM guru WHERE nip='".$esc($d['nip'])."' LIMIT 1");
            if(mysqli_num_rows($chk)>0){
                $q="UPDATE guru SET nama='".$esc($d['nama'])."',jk='".$esc($d['jk'])."',tempat_lahir='".$esc($d['tempat_lahir'])."',tanggal_lahir='".$esc($d['tanggal_lahir'])."',alamat='".$esc($d['alamat'])."',no_telp='".$esc($d['no_telp'])."',email='".$esc($d['email'])."',pendidikan='".$esc($d['pendidikan'])."',mapel='".$esc($d['mapel'])."',status='".$esc($d['status'])."',updated_at=NOW() WHERE nip='".$esc($d['nip'])."'";
            }else{
                $q="INSERT INTO guru (nip,nama,jk,tempat_lahir,tanggal_lahir,alamat,no_telp,email,pendidikan,mapel,status,created_at) VALUES('".$esc($d['nip'])."','".$esc($d['nama'])."','".$esc($d['jk'])."','".$esc($d['tempat_lahir'])."','".$esc($d['tanggal_lahir'])."','".$esc($d['alamat'])."','".$esc($d['no_telp'])."','".$esc($d['email'])."','".$esc($d['pendidikan'])."','".$esc($d['mapel'])."','".$esc($d['status'])."',NOW())";
            }
            if(mysqli_query($conn,$q))$ok++;
            else{$fail++;$errors[]="Baris $row_num ({$d['nama']}): ".mysqli_error($conn);}
        }
        fclose($h); @unlink($tmp);
        $import_result=['success'=>$ok,'fail'=>$fail,'errors'=>$errors];
    }
}

/* ── TAMBAH ── */
if(isset($_POST['act'])&&$_POST['act']==='tambah'){
    $nip=trim(mysqli_real_escape_string($conn,$_POST['nip']??''));
    $nama=trim(mysqli_real_escape_string($conn,$_POST['nama']??''));
    $jk=$_POST['jk']??''; $tempat_lahir=trim(mysqli_real_escape_string($conn,$_POST['tempat_lahir']??''));
    $tanggal_lahir=$_POST['tanggal_lahir']??''; $alamat=trim(mysqli_real_escape_string($conn,$_POST['alamat']??''));
    $no_telp=trim(mysqli_real_escape_string($conn,$_POST['no_telp']??'')); $email=trim(mysqli_real_escape_string($conn,$_POST['email']??''));
    $pendidikan=trim(mysqli_real_escape_string($conn,$_POST['pendidikan']??'')); $mapel=trim(mysqli_real_escape_string($conn,$_POST['mapel']??''));
    $status=$_POST['status']??'Aktif';
    if(empty($nip)||empty($nama)){$error='NIP dan Nama wajib diisi!';}
    else{
        $cek=mysqli_query($conn,"SELECT id FROM guru WHERE nip='$nip' LIMIT 1");
        if(mysqli_num_rows($cek)>0){$error="NIP <strong>$nip</strong> sudah terdaftar!";}
        else{
            $foto='';
            if(isset($_FILES['foto'])&&$_FILES['foto']['error']==0){
                $upload_dir='uploads/guru/'; if(!is_dir($upload_dir))mkdir($upload_dir,0755,true);
                $ext=strtolower(pathinfo($_FILES['foto']['name'],PATHINFO_EXTENSION));
                $fn=time().'_'.uniqid().'.'.$ext; $tgt=$upload_dir.$fn;
                if(move_uploaded_file($_FILES['foto']['tmp_name'],$tgt))$foto=$tgt;
            }
            $q="INSERT INTO guru (nip,nama,jk,tempat_lahir,tanggal_lahir,alamat,no_telp,email,pendidikan,mapel,foto,status,created_at) VALUES('$nip','$nama','$jk','$tempat_lahir','$tanggal_lahir','$alamat','$no_telp','$email','$pendidikan','$mapel','$foto','$status',NOW())";
            if(mysqli_query($conn,$q))$success="Guru <strong>$nama</strong> berhasil ditambahkan!";
            else $error='Gagal menyimpan: '.mysqli_error($conn);
        }
    }
}

/* ── EDIT ── */
if(isset($_POST['act'])&&$_POST['act']==='edit'){
    $id=intval($_POST['id']??0);
    $nip=trim(mysqli_real_escape_string($conn,$_POST['nip']??''));
    $nama=trim(mysqli_real_escape_string($conn,$_POST['nama']??''));
    $jk=$_POST['jk']??''; $tempat_lahir=trim(mysqli_real_escape_string($conn,$_POST['tempat_lahir']??''));
    $tanggal_lahir=$_POST['tanggal_lahir']??''; $alamat=trim(mysqli_real_escape_string($conn,$_POST['alamat']??''));
    $no_telp=trim(mysqli_real_escape_string($conn,$_POST['no_telp']??'')); $email=trim(mysqli_real_escape_string($conn,$_POST['email']??''));
    $pendidikan=trim(mysqli_real_escape_string($conn,$_POST['pendidikan']??'')); $mapel=trim(mysqli_real_escape_string($conn,$_POST['mapel']??''));
    $status=$_POST['status']??'Aktif';
    if($id<1||empty($nama)){$error='Data tidak valid!';}
    else{
        $cek=mysqli_query($conn,"SELECT id FROM guru WHERE nip='$nip' AND id<>$id LIMIT 1");
        if(mysqli_num_rows($cek)>0){$error="NIP <strong>$nip</strong> sudah digunakan guru lain!";}
        else{
            $foto_clause='';
            if(isset($_FILES['foto'])&&$_FILES['foto']['error']==0){
                $upload_dir='uploads/guru/'; if(!is_dir($upload_dir))mkdir($upload_dir,0755,true);
                $ext=strtolower(pathinfo($_FILES['foto']['name'],PATHINFO_EXTENSION));
                $fn=time().'_'.uniqid().'.'.$ext; $tgt=$upload_dir.$fn;
                if(move_uploaded_file($_FILES['foto']['tmp_name'],$tgt)){
                    $old=mysqli_fetch_array(mysqli_query($conn,"SELECT foto FROM guru WHERE id=$id"));
                    if(!empty($old['foto'])&&file_exists($old['foto']))unlink($old['foto']);
                    $foto_clause=",foto='$tgt'";
                }
            }
            $q="UPDATE guru SET nip='$nip',nama='$nama',jk='$jk',tempat_lahir='$tempat_lahir',tanggal_lahir='$tanggal_lahir',alamat='$alamat',no_telp='$no_telp',email='$email',pendidikan='$pendidikan',mapel='$mapel',status='$status'$foto_clause,updated_at=NOW() WHERE id=$id";
            if(mysqli_query($conn,$q))$success="Data guru <strong>$nama</strong> berhasil diperbarui!";
            else $error='Gagal update: '.mysqli_error($conn);
        }
    }
}

/* ── DELETE ── */
if(isset($_GET['delete'])){
    $id=intval($_GET['delete']);
    $r=mysqli_query($conn,"SELECT nama,foto FROM guru WHERE id=$id LIMIT 1");
    if($r&&$row=mysqli_fetch_array($r)){
        if(!empty($row['foto'])&&file_exists($row['foto']))unlink($row['foto']);
        mysqli_query($conn,"DELETE FROM guru WHERE id=$id");
        $success="Guru <strong>".htmlspecialchars($row['nama'])."</strong> berhasil dihapus!";
    }
}

/* ── DATA ── */
$search=trim(mysqli_real_escape_string($conn,$_GET['q']??''));
$filter_status=$_GET['status']??'';
$filter_mapel=$_GET['mapel']??'';
$where="1=1";
if($search)$where.=" AND (nama LIKE '%$search%' OR nip LIKE '%$search%' OR email LIKE '%$search%')";
if($filter_status)$where.=" AND status='".mysqli_real_escape_string($conn,$filter_status)."'";
if($filter_mapel)$where.=" AND mapel='".mysqli_real_escape_string($conn,$filter_mapel)."'";

$total=mysqli_fetch_array(mysqli_query($conn,"SELECT COUNT(*) t FROM guru WHERE $where"))['t'];
$aktif=mysqli_fetch_array(mysqli_query($conn,"SELECT COUNT(*) t FROM guru WHERE status='Aktif'"))['t'];
$nonaktif=mysqli_fetch_array(mysqli_query($conn,"SELECT COUNT(*) t FROM guru WHERE status='Nonaktif'"))['t'];

$mapel_list=[];
$mq=mysqli_query($conn,"SELECT DISTINCT mapel FROM guru WHERE mapel<>'' ORDER BY mapel");
while($r=mysqli_fetch_array($mq))if(!empty($r['mapel']))$mapel_list[]=$r['mapel'];

$guru=mysqli_query($conn,"SELECT * FROM guru WHERE $where ORDER BY nama ASC LIMIT 100");

$editData=null;
if(isset($_GET['edit'])){
    $id=intval($_GET['edit']);
    $r=mysqli_query($conn,"SELECT * FROM guru WHERE id=$id LIMIT 1");
    if($r)$editData=mysqli_fetch_assoc($r);
}
?>
<style>
/* ════════════════════════════════════════════════════════
   STYLE LOKAL guru.php — prefix gu-
   Token navbar sudah tersedia: --ob, --ob-m, --ob-l, --ob-ll,
   --g, --g-l, --g-d, --g-fg, --bg, --sf, --sf2,
   --tx, --txm, --txl, --bd, --bd-d, --sw
════════════════════════════════════════════════════════ */
:root{
  --gu-em:#0C6B58; --gu-eml:#D1FAE5;
  --gu-sc:#1D4ED8; --gu-scl:#DBEAFE;
  --gu-ru:#9B1C1C; --gu-rul:#FEE2E2;
  --gu-am:#B45309; --gu-aml:#FEF3C7;
  --gu-pu:#5B21B6; --gu-pul:#EDE9FE; --gu-pum:#7C3AED;
  --gu-sh:rgba(8,12,20,.06); --gu-shs:rgba(8,12,20,.14);
}

.main{ background:var(--bg); overflow-x:hidden; }
.main .wrap{ font-family:'Outfit',sans-serif; overflow-x:hidden; }

@keyframes guFadeUp { from{opacity:0;transform:translateY(22px)} to{opacity:1;transform:translateY(0)} }
@keyframes guSlideD { from{opacity:0;transform:translateY(-10px)} to{opacity:1;transform:translateY(0)} }

/* ════ PAGE HEADER ════ */
.gu-ph{
  display:flex; align-items:center; justify-content:space-between;
  gap:1rem; flex-wrap:wrap; margin-bottom:1.75rem;
  animation:guFadeUp .5s ease-out;
}
.gu-ph-title{ font-family:'DM Serif Display',serif; font-size:1.75rem; color:var(--tx); margin-bottom:.2rem; }
.gu-ph-sub  { font-size:.82rem; color:var(--txl); }
.gu-ph-r    { display:flex; align-items:center; gap:.75rem; flex-wrap:wrap; }

.gu-btn{
  display:inline-flex; align-items:center; gap:.5rem;
  padding:.6rem 1.375rem; border-radius:50px;
  font-size:.8rem; font-weight:700; font-family:'Outfit',sans-serif;
  cursor:pointer; text-decoration:none; border:none; transition:all .25s;
}
.gu-btn-back{ background:var(--sf); border:1.5px solid var(--bd); color:var(--txm); }
.gu-btn-back:hover{ background:var(--ob); color:white; border-color:var(--ob); }
.gu-btn-add{
  background:linear-gradient(135deg,var(--g-d),var(--g));
  color:white; box-shadow:0 4px 14px rgba(201,168,76,.3);
}
.gu-btn-add:hover{ transform:translateY(-2px); box-shadow:0 8px 24px rgba(201,168,76,.4); }

/* ════ ALERTS ════ */
.gu-al{
  display:flex; align-items:center; gap:.75rem;
  padding:1rem 1.25rem; border-radius:14px;
  margin-bottom:1.375rem; font-size:.875rem; font-weight:700;
  animation:guSlideD .4s ease-out; border-left:4px solid;
}
.gu-aok  { background:#F0FDF4; color:#166534; border-color:#4ADE80; }
.gu-aerr { background:#FEF2F2; color:#991B1B; border-color:#FCA5A5; }
.gu-al-x{ cursor:pointer;background:none;border:none;font-size:1.1rem;color:inherit;margin-left:auto;opacity:.6;font-weight:900;padding:0;line-height:1; }
.gu-al-x:hover{ opacity:1; }

/* ════ IMPOR RESULT ════ */
.gu-imr{
  background:var(--gu-pul); border:1.5px solid #C4B5FD;
  border-radius:16px; padding:1.125rem 1.375rem;
  margin-bottom:1.5rem; animation:guSlideD .4s ease-out;
}
.gu-imr-t{ font-size:.9rem; font-weight:800; color:var(--gu-pu); margin-bottom:.5rem; }
.gu-imr-b{ font-size:.84rem; color:#4C1D95; font-weight:600; }
.gu-imr-e{ margin-top:.625rem;max-height:130px;overflow-y:auto;font-size:.74rem;color:#6D28D9;line-height:1.7;border-top:1px solid #C4B5FD;padding-top:.5rem; }

/* ════ PANEL EKSPOR & IMPOR ════ */
.gu-ei{
  background:var(--sf); border-radius:20px; border:1px solid var(--bd);
  margin-bottom:1.75rem; overflow:hidden;
  box-shadow:0 4px 20px var(--gu-sh);
  animation:guFadeUp .4s ease-out;
}
.gu-ei-hd{
  padding:1.125rem 1.75rem;
  background:linear-gradient(135deg,#1E0A3C 0%,var(--gu-pu) 55%,var(--gu-pum) 100%);
  display:flex; align-items:center; gap:.875rem;
}
.gu-ei-hico{
  width:42px; height:42px; border-radius:12px;
  background:rgba(255,255,255,.15); border:1px solid rgba(255,255,255,.25);
  display:flex; align-items:center; justify-content:center; font-size:1.25rem; flex-shrink:0;
}
.gu-ei-htit{ font-family:'DM Serif Display',serif; font-size:1.05rem; color:white; }
.gu-ei-hsub{ font-size:.68rem; font-weight:600; color:rgba(255,255,255,.65); margin-top:.15rem; }
.gu-ei-body{ display:flex; flex-wrap:wrap; }
.gu-ei-col{ flex:1; min-width:260px; padding:1.375rem 1.75rem; }
.gu-ei-col+.gu-ei-col{ border-left:1px solid var(--bd); }
.gu-ei-clbl{ font-size:.65rem; font-weight:800; letter-spacing:.12em; text-transform:uppercase; color:var(--txl); margin-bottom:.875rem; }

.gu-exp-row{ display:flex; flex-wrap:wrap; gap:.5rem; margin-bottom:.75rem; }
.gu-ebtn{
  display:inline-flex; align-items:center; gap:.4rem;
  padding:.55rem 1.125rem; border-radius:10px;
  font-family:'Outfit',sans-serif; font-size:.78rem; font-weight:700;
  text-decoration:none; border:1.5px solid; transition:all .22s; cursor:pointer; background:none;
}
.gu-ebtn:hover{ transform:translateY(-2px); }
.gu-eb-g{ background:#F0FDF4; color:#166534; border-color:#86EFAC; }
.gu-eb-g:hover{ background:#DCFCE7; box-shadow:0 4px 14px rgba(22,163,74,.18); }
.gu-eb-b{ background:var(--gu-scl); color:var(--gu-sc); border-color:#93C5FD; }
.gu-eb-b:hover{ background:#BFDBFE; box-shadow:0 4px 14px rgba(29,78,216,.15); }
.gu-eb-p{ background:var(--gu-pul); color:var(--gu-pu); border-color:#C4B5FD; }
.gu-eb-p:hover{ background:#DDD6FE; box-shadow:0 4px 14px rgba(91,33,182,.15); }
.gu-ei-note{ font-size:.72rem; color:var(--txl); line-height:1.65; }

.gu-imz{
  border:2px dashed #C4B5FD; border-radius:14px; padding:1.25rem;
  background:#FAFAFF; text-align:center; transition:all .22s; cursor:pointer; user-select:none;
}
.gu-imz.drag{ border-color:var(--gu-pum); background:var(--gu-pul); }
.gu-imz-ico{ font-size:2.25rem; margin-bottom:.3rem; display:block; transition:transform .25s; }
.gu-imz.drag .gu-imz-ico{ transform:scale(1.2); }
.gu-imz-msg{ font-size:.82rem; font-weight:700; color:var(--txm); margin-bottom:.375rem; }
.gu-imz-msg span{ color:var(--gu-pum); text-decoration:underline; }
.gu-imz-hint{ font-size:.68rem; color:var(--txl); margin-bottom:.5rem; }
.gu-im-badge{
  display:inline-flex; align-items:center; gap:.4rem;
  background:var(--gu-pul); border:1.5px solid #C4B5FD;
  border-radius:8px; padding:.25rem .7rem;
  font-size:.75rem; font-weight:700; color:var(--gu-pu); margin:.5rem 0; max-width:100%; word-break:break-all;
}
.gu-im-warn{
  font-size:.7rem; color:var(--gu-am); font-weight:700;
  background:var(--gu-aml); border:1px solid #FDE68A;
  border-radius:8px; padding:.35rem .75rem; margin:.625rem 0;
}
.gu-im-btn{
  width:100%; padding:.75rem; border-radius:11px;
  background:linear-gradient(135deg,var(--gu-pu),var(--gu-pum));
  color:white; font-weight:800; font-size:.84rem; font-family:'Outfit',sans-serif;
  border:none; cursor:pointer; transition:all .25s;
  display:flex; align-items:center; justify-content:center; gap:.5rem; margin-top:.5rem;
}
.gu-im-btn:hover:not(:disabled){ transform:translateY(-2px); box-shadow:0 6px 20px rgba(91,33,182,.3); }
.gu-im-btn:disabled{ opacity:.6; cursor:not-allowed; }
input[type="file"]#csvFile{ display:none; }

/* ════ FILTER ════ */
.gu-filter{
  background:var(--sf); border-radius:20px; border:1px solid var(--bd);
  padding:1.5rem; margin-bottom:1.75rem;
  box-shadow:0 4px 20px var(--gu-sh);
  animation:guFadeUp .45s ease-out;
}
.gu-ftit{ font-family:'DM Serif Display',serif; font-size:1rem; color:var(--tx); margin-bottom:1.125rem; display:flex; align-items:center; gap:.5rem; }
.gu-fgrid{ display:grid; grid-template-columns:2fr 1fr 1fr auto; gap:1rem; align-items:end; }
.gu-fg{ display:flex; flex-direction:column; gap:.4rem; }
.gu-flbl{ font-size:.7rem; font-weight:700; text-transform:uppercase; letter-spacing:.08em; color:var(--txm); }
.gu-finp,.gu-fsel{
  padding:.7rem .9rem; background:var(--bg); border:1px solid var(--bd);
  border-radius:12px; font-family:'Outfit',sans-serif;
  font-size:.85rem; font-weight:600; color:var(--tx);
  transition:all .2s; outline:none; width:100%; appearance:none;
}
.gu-finp:focus,.gu-fsel:focus{ border-color:var(--g); background:white; }
.gu-btn-f{
  padding:.7rem 1.5rem; background:var(--ob); color:white;
  border:none; border-radius:12px; font-size:.85rem; font-weight:700;
  cursor:pointer; transition:all .22s; font-family:'Outfit',sans-serif;
}
.gu-btn-f:hover{ background:var(--ob-m); transform:translateY(-1px); }

/* ════ STAT CARDS ════ */
.gu-srow{
  display:grid; grid-template-columns:repeat(3,1fr);
  gap:1.25rem; margin-bottom:1.75rem;
}
.gu-sc{
  background:var(--sf); border-radius:20px; border:1px solid var(--bd);
  padding:1.625rem 1.75rem; position:relative; overflow:hidden;
  box-shadow:0 4px 20px var(--gu-sh);
  transition:all .35s cubic-bezier(.34,1.56,.64,1);
  animation:guFadeUp .4s ease-out backwards; cursor:default;
}
.gu-sc:hover{ transform:translateY(-8px); box-shadow:0 16px 40px var(--gu-shs); }
.gu-sc:nth-child(1){animation-delay:.05s}
.gu-sc:nth-child(2){animation-delay:.1s}
.gu-sc:nth-child(3){animation-delay:.15s}
.gu-sc::before{
  content:''; position:absolute; top:0; left:0; right:0;
  height:4px; border-radius:20px 20px 0 0; transition:height .3s;
}
.gu-sc:hover::before{ height:6px; }
.gu-sc.c1::before{ background:linear-gradient(90deg,#1D4ED8,#3B82F6); }
.gu-sc.c2::before{ background:linear-gradient(90deg,#0C6B58,#10B981); }
.gu-sc.c3::before{ background:linear-gradient(90deg,#9B1C1C,#DC2626); }
.gu-sc-top{ display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:1.25rem; }
.gu-sc-lbl{ font-size:.65rem; font-weight:700; letter-spacing:.1em; text-transform:uppercase; color:var(--txl); }
.gu-sc-ico{ width:48px; height:48px; border-radius:14px; display:flex; align-items:center; justify-content:center; font-size:1.5rem; transition:transform .3s; }
.gu-sc:hover .gu-sc-ico{ transform:rotate(-10deg) scale(1.15); }
.gu-sc.c1 .gu-sc-ico{ background:linear-gradient(135deg,#DBEAFE,#BFDBFE); }
.gu-sc.c2 .gu-sc-ico{ background:linear-gradient(135deg,#D1FAE5,#A7F3D0); }
.gu-sc.c3 .gu-sc-ico{ background:linear-gradient(135deg,#FEE2E2,#FECACA); }
.gu-sc-val{ font-family:'DM Serif Display',serif; font-size:2.75rem; color:var(--tx); line-height:1; margin-bottom:.375rem; }
.gu-sc-cap{ font-size:.8rem; font-weight:500; color:var(--txm); }

/* ════ GRID KARTU GURU ════ */
.gu-grid{
  display:grid;
  grid-template-columns:repeat(auto-fill,minmax(280px,1fr));
  gap:1.25rem;
}
.gu-card{
  background:var(--sf); border-radius:20px; border:1px solid var(--bd);
  padding:1.75rem; transition:all .3s;
  box-shadow:0 4px 20px var(--gu-sh);
  animation:guFadeUp .4s ease-out backwards;
  position:relative; overflow:hidden;
}
.gu-card:hover{ transform:translateY(-6px); box-shadow:0 16px 40px var(--gu-shs); border-color:var(--bd-d); }
.gu-card::before{
  content:''; position:absolute; left:0; top:0; bottom:0; width:4px;
  background:linear-gradient(180deg,var(--g),var(--g-d));
}
.gu-card-hd{ display:flex; gap:1rem; margin-bottom:1.125rem; }
.gu-ava{
  width:60px; height:60px; border-radius:16px;
  background:linear-gradient(135deg,var(--g-d),var(--g));
  display:flex; align-items:center; justify-content:center;
  font-size:1.625rem; overflow:hidden; border:2px solid var(--bd); flex-shrink:0;
}
.gu-ava img{ width:60px; height:60px; object-fit:cover; }
.gu-card-meta{ flex:1; min-width:0; }
.gu-card-nip  { font-family:'DM Mono',monospace; font-size:.7rem; color:var(--txl); margin-bottom:.25rem; }
.gu-card-name {
  font-family:'DM Serif Display',serif; font-size:1.05rem;
  color:var(--tx); font-weight:600; margin-bottom:.25rem;
  white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
}
.gu-card-mapel{ font-size:.75rem; color:var(--g-d); font-weight:600; }
.gu-card-info { display:flex; flex-direction:column; gap:.5rem; margin-bottom:1.125rem; }
.gu-card-row  { display:flex; align-items:center; gap:.5rem; font-size:.78rem; color:var(--txm); }
.gu-card-ft   { display:flex; align-items:center; justify-content:space-between; padding-top:1rem; border-top:1px solid var(--bd); }
.gu-badge{
  display:inline-flex; align-items:center; gap:.3rem;
  padding:.25rem .75rem; border-radius:50px;
  font-size:.7rem; font-weight:700; border:1px solid;
}
.gu-st-aktif   { background:var(--gu-eml); color:var(--gu-em); border-color:#A7F3D0; }
.gu-st-nonaktif{ background:var(--gu-rul); color:var(--gu-ru); border-color:#FCA5A5; }
.gu-acts{ display:flex; gap:.5rem; }
.gu-abtn{
  display:inline-flex; align-items:center; gap:.3rem;
  padding:.3rem .7rem; border-radius:8px;
  font-size:.7rem; font-weight:700; cursor:pointer;
  border:1px solid transparent; transition:all .2s; text-decoration:none;
}
.gu-abtn-e{ background:var(--bg); color:var(--tx); border-color:var(--bd); }
.gu-abtn-e:hover{ background:var(--ob); color:white; }
.gu-abtn-d{ background:var(--gu-rul); color:var(--gu-ru); border-color:#FCA5A5; }
.gu-abtn-d:hover{ background:var(--gu-ru); color:white; }

/* ════ MODAL ════ */
.gu-modal{
  display:none; position:fixed; inset:0; z-index:500;
  background:rgba(8,12,20,.7); backdrop-filter:blur(6px);
  align-items:center; justify-content:center; padding:1rem;
}
.gu-modal.open{ display:flex; animation:guFadeUp .3s ease-out; }
.gu-mcon{
  background:var(--sf); border-radius:24px; border:2px solid var(--bd);
  box-shadow:0 24px 80px rgba(0,0,0,.3);
  width:100%; max-width:640px; max-height:90vh; overflow-y:auto;
}
.gu-mhd{
  padding:1.5rem 1.75rem; background:var(--ob);
  display:flex; align-items:center; justify-content:space-between;
  position:sticky; top:0; z-index:1;
}
.gu-mhd-t{ font-family:'DM Serif Display',serif; font-size:1.1rem; color:white; }
.gu-mclose{
  background:rgba(255,255,255,.1); border:1px solid rgba(255,255,255,.2);
  border-radius:50%; width:36px; height:36px; font-size:1.1rem;
  cursor:pointer; display:flex; align-items:center; justify-content:center;
  transition:all .2s; color:white;
}
.gu-mclose:hover{ background:var(--gu-ru); border-color:var(--gu-ru); }
.gu-mbdy{ padding:1.75rem; }
.gu-mfg { display:flex; flex-direction:column; gap:.45rem; margin-bottom:1.125rem; }
.gu-mfgr{ display:grid; grid-template-columns:1fr 1fr; gap:1rem; }
.gu-mflbl{ font-size:.7rem; font-weight:800; text-transform:uppercase; letter-spacing:.08em; color:var(--tx); }
.gu-mfi{
  width:100%; padding:.8rem .9rem;
  background:var(--bg); border:1px solid var(--bd);
  border-radius:12px; font-family:'Outfit',sans-serif;
  font-size:.9rem; font-weight:600; color:var(--tx);
  transition:all .2s; outline:none;
}
.gu-mfi:focus{ border-color:var(--g); background:white; }
.gu-mft{
  display:flex; gap:.75rem; justify-content:flex-end;
  padding:1.25rem 1.75rem; border-top:1px solid var(--bd);
  position:sticky; bottom:0; background:var(--sf); z-index:1;
}
.gu-mcancel{
  padding:.75rem 1.5rem; background:var(--bg); border:1px solid var(--bd);
  border-radius:12px; font-family:'Outfit',sans-serif;
  font-size:.875rem; font-weight:700; cursor:pointer; color:var(--tx); transition:all .2s;
}
.gu-mcancel:hover{ background:var(--bd); }
.gu-msave{
  padding:.75rem 1.75rem; background:linear-gradient(135deg,var(--g-d),var(--g));
  color:white; border:none; border-radius:12px;
  font-family:'Outfit',sans-serif; font-size:.875rem; font-weight:700;
  cursor:pointer; transition:all .25s; box-shadow:0 4px 14px rgba(201,168,76,.3);
}
.gu-msave:hover{ transform:translateY(-2px); box-shadow:0 8px 24px rgba(201,168,76,.4); }

/* ════════════════════════════════════════════════════════
   RESPONSIVE — navbar sidebar 272px/240px/0px

   ≥1200px  → filter 4 kolom, stats 3 kolom, kartu auto-fill
   1024-1199px (sidebar 240px, efektif ~784px)
              → filter 2 kolom, stats 3 kolom, kartu auto-fill
   769-1023px (sidebar 240px, efektif ~529-783px)
              → filter 2 kolom, stats 2 kolom, kartu 1 kolom
   ≤768px   → sidebar hilang (topbar 60px), full width
              → filter 1 kolom, stats 1 kolom
   ≤480px   → kompak
════════════════════════════════════════════════════════ */

/* ── 1024–1199px ── */
@media(min-width:1024px) and (max-width:1199px){
  .gu-fgrid{ grid-template-columns:1fr 1fr; gap:.875rem; }
  .gu-ei-col+.gu-ei-col{ border-left:none; border-top:1px solid var(--bd); }
}

/* ── 769–1023px ── */
@media(min-width:769px) and (max-width:1023px){
  .gu-fgrid{ grid-template-columns:1fr 1fr; gap:.875rem; }
  .gu-srow { grid-template-columns:1fr 1fr; }
  .gu-grid { grid-template-columns:1fr; }
  .gu-ei-col+.gu-ei-col{ border-left:none; border-top:1px solid var(--bd); }
  .gu-sc-val{ font-size:2.25rem; }
}

/* ── ≤768px — mobile ── */
@media(max-width:768px){
  .gu-ph   { flex-direction:column; align-items:flex-start; }
  .gu-fgrid{ grid-template-columns:1fr; gap:.75rem; }
  .gu-srow { grid-template-columns:1fr; }
  .gu-grid { grid-template-columns:1fr; }
  .gu-ei-col+.gu-ei-col{ border-left:none; border-top:1px solid var(--bd); }
  .gu-sc-val{ font-size:2.25rem; }
  .gu-mfgr { grid-template-columns:1fr; }
}

/* ── ≤480px ── */
@media(max-width:480px){
  .gu-ph-r{ width:100%; }
  .gu-btn { padding:.55rem 1.125rem; font-size:.75rem; }
  .gu-sc  { padding:1.25rem; }
  .gu-sc-val{ font-size:2rem; }
  .gu-ei-col{ padding:1.125rem 1.25rem; }
}
</style>

<!-- ════════════════════════════════════════════════════════
     KONTEN UTAMA
════════════════════════════════════════════════════════ -->
<div class="main">
<div class="wrap fade-up">

<!-- ══ PAGE HEADER ══ -->
<div class="gu-ph">
  <div>
    <div class="gu-ph-title">👨‍🏫 Data Guru</div>
    <div class="gu-ph-sub">Manajemen Data Guru &amp; Tenaga Pengajar</div>
  </div>
  <div class="gu-ph-r">
    <a href="dashboard.php" class="gu-btn gu-btn-back">← Dashboard</a>
    <button class="gu-btn gu-btn-add" onclick="guOpenModal()">✚ Tambah Guru</button>
  </div>
</div>

<!-- ══ ALERTS ══ -->
<?php if($success): ?>
<div class="gu-al gu-aok">
  <span style="font-size:1.25rem">✅</span>
  <span><?= $success ?></span>
  <button class="gu-al-x" onclick="this.parentNode.remove()">✕</button>
</div>
<?php endif; ?>
<?php if($error): ?>
<div class="gu-al gu-aerr">
  <span style="font-size:1.25rem">❌</span>
  <span><?= $error ?></span>
  <button class="gu-al-x" onclick="this.parentNode.remove()">✕</button>
</div>
<?php endif; ?>

<!-- ══ HASIL IMPOR ══ -->
<?php if($import_result): ?>
  <?php if(isset($import_result['error'])): ?>
  <div class="gu-al gu-aerr">
    <span style="font-size:1.25rem">❌</span>
    <span><strong>Impor gagal:</strong> <?= htmlspecialchars($import_result['error']) ?></span>
    <button class="gu-al-x" onclick="this.parentNode.remove()">✕</button>
  </div>
  <?php else: ?>
  <div class="gu-imr">
    <div class="gu-imr-t">📥 Hasil Impor CSV</div>
    <div class="gu-imr-b">
      ✅ Berhasil: <strong><?= $import_result['success'] ?></strong> data &nbsp;&nbsp;
      <?php if($import_result['fail']>0): ?>❌ Gagal: <strong><?= $import_result['fail'] ?></strong> data<?php endif; ?>
    </div>
    <?php if(!empty($import_result['errors'])): ?>
    <div class="gu-imr-e"><strong>Detail error:</strong><br><?= implode('<br>',array_map('htmlspecialchars',$import_result['errors'])) ?></div>
    <?php endif; ?>
  </div>
  <?php endif; ?>
<?php endif; ?>

<!-- ══ PANEL EKSPOR & IMPOR ══ -->
<div class="gu-ei">
  <div class="gu-ei-hd">
    <div class="gu-ei-hico">📊</div>
    <div>
      <div class="gu-ei-htit">Ekspor &amp; Impor Data Guru</div>
      <div class="gu-ei-hsub">Unduh semua data atau unggah data massal via file CSV</div>
    </div>
  </div>
  <div class="gu-ei-body">

    <!-- Ekspor -->
    <div class="gu-ei-col">
      <div class="gu-ei-clbl">📤 Ekspor Data</div>
      <div class="gu-exp-row">
        <a href="guru.php?export=excel"    class="gu-ebtn gu-eb-g">📊 Excel (.xls)</a>
        <a href="guru.php?export=csv"      class="gu-ebtn gu-eb-b">📄 CSV</a>
        <a href="guru.php?export=template" class="gu-ebtn gu-eb-p">📋 Template</a>
      </div>
      <div class="gu-ei-note">
        Unduh seluruh data guru sebagai <strong>Excel</strong> atau <strong>CSV</strong>.<br>
        Gunakan <strong>Template</strong> sebagai panduan format kolom sebelum impor data massal.
      </div>
    </div>

    <!-- Impor -->
    <div class="gu-ei-col">
      <div class="gu-ei-clbl">📥 Impor Data CSV</div>
      <form method="POST" enctype="multipart/form-data" action="guru.php" id="importForm">
        <input type="hidden" name="import_guru" value="1">
        <div class="gu-imz" id="dropzone"
             ondragover="event.preventDefault();this.classList.add('drag')"
             ondragleave="this.classList.remove('drag')"
             ondrop="guHandleDrop(event)"
             onclick="document.getElementById('csvFile').click()">
          <span class="gu-imz-ico" id="dropIco">📂</span>
          <div class="gu-imz-msg">Seret &amp; lepas, atau <span>klik untuk memilih file</span></div>
          <div class="gu-imz-hint">Format: .CSV · Maksimal 5 MB</div>
          <div id="fileBadge" style="display:none">
            <div class="gu-im-badge">📄 <span id="fileName"></span></div>
          </div>
        </div>
        <input type="file" id="csvFile" name="csv_file" accept=".csv,.CSV">
        <div class="gu-im-warn">⚠️ Data dengan NIP yang sama akan <u>diperbarui</u>, bukan diduplikat.</div>
        <button type="submit" class="gu-im-btn" id="impBtn">
          <span id="impBtnTxt">📥 Mulai Impor</span>
        </button>
      </form>
    </div>

  </div>
</div>

<!-- ══ FILTER ══ -->
<form method="GET" action="guru.php">
<div class="gu-filter">
  <div class="gu-ftit">🔍 Cari &amp; Filter</div>
  <div class="gu-fgrid">
    <div class="gu-fg">
      <label class="gu-flbl">Cari Guru</label>
      <input type="text" name="q" class="gu-finp"
        placeholder="Nama, NIP, atau email..."
        value="<?= htmlspecialchars($search) ?>">
    </div>
    <div class="gu-fg">
      <label class="gu-flbl">Status</label>
      <select name="status" class="gu-fsel">
        <option value="">Semua</option>
        <option value="Aktif"    <?= $filter_status=='Aktif'?'selected':'' ?>>Aktif</option>
        <option value="Nonaktif" <?= $filter_status=='Nonaktif'?'selected':'' ?>>Nonaktif</option>
      </select>
    </div>
    <div class="gu-fg">
      <label class="gu-flbl">Mata Pelajaran</label>
      <select name="mapel" class="gu-fsel">
        <option value="">Semua</option>
        <?php foreach($mapel_list as $mp): ?>
        <option value="<?= htmlspecialchars($mp) ?>"
          <?= $filter_mapel==$mp?'selected':'' ?>><?= htmlspecialchars($mp) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="gu-fg">
      <button type="submit" class="gu-btn-f">Cari</button>
    </div>
  </div>
</div>
</form>

<!-- ══ STAT CARDS ══ -->
<div class="gu-srow">
  <div class="gu-sc c1">
    <div class="gu-sc-top"><div class="gu-sc-lbl">Total Guru</div><div class="gu-sc-ico">👨‍🏫</div></div>
    <div class="gu-sc-val"><?= $total ?></div>
    <div class="gu-sc-cap">Terdaftar di sistem</div>
  </div>
  <div class="gu-sc c2">
    <div class="gu-sc-top"><div class="gu-sc-lbl">Guru Aktif</div><div class="gu-sc-ico">✅</div></div>
    <div class="gu-sc-val"><?= $aktif ?></div>
    <div class="gu-sc-cap">Status aktif mengajar</div>
  </div>
  <div class="gu-sc c3">
    <div class="gu-sc-top"><div class="gu-sc-lbl">Nonaktif</div><div class="gu-sc-ico">⏸️</div></div>
    <div class="gu-sc-val"><?= $nonaktif ?></div>
    <div class="gu-sc-cap">Cuti atau keluar</div>
  </div>
</div>

<!-- ══ GRID KARTU GURU ══ -->
<div class="gu-grid">
<?php
$delay=0;
if(mysqli_num_rows($guru)>0):
  while($g=mysqli_fetch_array($guru)):
?>
<div class="gu-card" style="animation-delay:<?= $delay ?>s">
  <div class="gu-card-hd">
    <div class="gu-ava">
      <?php if(!empty($g['foto'])&&file_exists($g['foto'])): ?>
      <img src="<?= htmlspecialchars($g['foto']) ?>" alt="">
      <?php else: ?>
      <?= $g['jk']=='L'?'👨':'👩' ?>
      <?php endif; ?>
    </div>
    <div class="gu-card-meta">
      <div class="gu-card-nip">NIP: <?= htmlspecialchars($g['nip']) ?></div>
      <div class="gu-card-name"><?= htmlspecialchars($g['nama']) ?></div>
      <?php if(!empty($g['mapel'])): ?>
      <div class="gu-card-mapel">📚 <?= htmlspecialchars($g['mapel']) ?></div>
      <?php endif; ?>
    </div>
  </div>
  <div class="gu-card-info">
    <?php if(!empty($g['email'])): ?>
    <div class="gu-card-row">📧 <?= htmlspecialchars($g['email']) ?></div>
    <?php endif; ?>
    <?php if(!empty($g['no_telp'])): ?>
    <div class="gu-card-row">📱 <?= htmlspecialchars($g['no_telp']) ?></div>
    <?php endif; ?>
    <?php if(!empty($g['pendidikan'])): ?>
    <div class="gu-card-row">🎓 <?= htmlspecialchars($g['pendidikan']) ?></div>
    <?php endif; ?>
  </div>
  <div class="gu-card-ft">
    <span class="gu-badge gu-st-<?= strtolower($g['status']) ?>">
      <?= $g['status']=='Aktif'?'🟢':'🔴' ?> <?= $g['status'] ?>
    </span>
    <div class="gu-acts">
      <button class="gu-abtn gu-abtn-e" onclick="guOpenEdit(<?= htmlspecialchars(json_encode($g)) ?>)">✏️</button>
      <a href="guru.php?delete=<?= $g['id'] ?>" class="gu-abtn gu-abtn-d"
         onclick="return confirm('Hapus guru ini?')">🗑️</a>
    </div>
  </div>
</div>
<?php $delay+=0.04;endwhile;
else: ?>
<div style="grid-column:1/-1;text-align:center;padding:4rem 2rem;color:var(--txl)">
  <div style="font-size:4rem;margin-bottom:1rem">👨‍🏫</div>
  <div style="font-weight:700;font-size:1rem">Belum ada data guru</div>
</div>
<?php endif; ?>
</div>

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

<!-- ══ MODAL TAMBAH / EDIT ══ -->
<div class="gu-modal" id="gu-modal">
  <div class="gu-mcon">
    <div class="gu-mhd">
      <div class="gu-mhd-t" id="gu-mTitle">✚ Tambah Guru</div>
      <button class="gu-mclose" onclick="guCloseModal()">✕</button>
    </div>
    <form method="POST" action="guru.php" enctype="multipart/form-data">
      <div class="gu-mbdy">
        <input type="hidden" name="act" id="guFAct" value="tambah">
        <input type="hidden" name="id"  id="guFId"  value="">
        <div class="gu-mfgr">
          <div class="gu-mfg">
            <label class="gu-mflbl">NIP *</label>
            <input type="text" name="nip" id="guFNip" class="gu-mfi" placeholder="NIP" required>
          </div>
          <div class="gu-mfg">
            <label class="gu-mflbl">Nama Lengkap *</label>
            <input type="text" name="nama" id="guFNama" class="gu-mfi" placeholder="Nama lengkap" required>
          </div>
        </div>
        <div class="gu-mfgr">
          <div class="gu-mfg">
            <label class="gu-mflbl">Jenis Kelamin</label>
            <select name="jk" id="guFJk" class="gu-mfi">
              <option value="">Pilih</option>
              <option value="L">Laki-laki</option>
              <option value="P">Perempuan</option>
            </select>
          </div>
          <div class="gu-mfg">
            <label class="gu-mflbl">Tanggal Lahir</label>
            <input type="date" name="tanggal_lahir" id="guFTgl" class="gu-mfi">
          </div>
        </div>
        <div class="gu-mfg">
          <label class="gu-mflbl">Tempat Lahir</label>
          <input type="text" name="tempat_lahir" id="guFTempat" class="gu-mfi" placeholder="Tempat lahir">
        </div>
        <div class="gu-mfg">
          <label class="gu-mflbl">Alamat</label>
          <textarea name="alamat" id="guFAlamat" class="gu-mfi" rows="2" placeholder="Alamat lengkap"></textarea>
        </div>
        <div class="gu-mfgr">
          <div class="gu-mfg">
            <label class="gu-mflbl">No. Telepon</label>
            <input type="text" name="no_telp" id="guFTelp" class="gu-mfi" placeholder="08xx-xxxx-xxxx">
          </div>
          <div class="gu-mfg">
            <label class="gu-mflbl">Email</label>
            <input type="email" name="email" id="guFEmail" class="gu-mfi" placeholder="email@example.com">
          </div>
        </div>
        <div class="gu-mfgr">
          <div class="gu-mfg">
            <label class="gu-mflbl">Pendidikan</label>
            <input type="text" name="pendidikan" id="guFPendidikan" class="gu-mfi" placeholder="S1, S2, dll">
          </div>
          <div class="gu-mfg">
            <label class="gu-mflbl">Mata Pelajaran</label>
            <input type="text" name="mapel" id="guFMapel" class="gu-mfi" placeholder="Matematika, Fisika, dll">
          </div>
        </div>
        <div class="gu-mfgr">
          <div class="gu-mfg">
            <label class="gu-mflbl">Status</label>
            <select name="status" id="guFStatus" class="gu-mfi">
              <option value="Aktif">Aktif</option>
              <option value="Nonaktif">Nonaktif</option>
            </select>
          </div>
          <div class="gu-mfg">
            <label class="gu-mflbl">Foto</label>
            <input type="file" name="foto" class="gu-mfi" accept="image/*">
          </div>
        </div>
      </div>
      <div class="gu-mft">
        <button type="button" class="gu-mcancel" onclick="guCloseModal()">Batal</button>
        <button type="submit" class="gu-msave">💾 Simpan</button>
      </div>
    </form>
  </div>
</div>

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

<script>
/* ══ MODAL ══ */
function guOpenModal(){
  ['guFNip','guFNama','guFTempat','guFTgl','guFAlamat','guFTelp','guFEmail','guFPendidikan','guFMapel'].forEach(id=>{
    document.getElementById(id).value='';
  });
  document.getElementById('guFAct').value='tambah';
  document.getElementById('guFId').value='';
  document.getElementById('guFJk').value='';
  document.getElementById('guFStatus').value='Aktif';
  document.getElementById('gu-mTitle').textContent='✚ Tambah Guru';
  document.getElementById('gu-modal').classList.add('open');
}
function guOpenEdit(g){
  document.getElementById('guFAct').value='edit';
  document.getElementById('guFId').value=g.id;
  document.getElementById('guFNip').value=g.nip||'';
  document.getElementById('guFNama').value=g.nama||'';
  document.getElementById('guFJk').value=g.jk||'';
  document.getElementById('guFTempat').value=g.tempat_lahir||'';
  document.getElementById('guFTgl').value=g.tanggal_lahir||'';
  document.getElementById('guFAlamat').value=g.alamat||'';
  document.getElementById('guFTelp').value=g.no_telp||'';
  document.getElementById('guFEmail').value=g.email||'';
  document.getElementById('guFPendidikan').value=g.pendidikan||'';
  document.getElementById('guFMapel').value=g.mapel||'';
  document.getElementById('guFStatus').value=g.status||'Aktif';
  document.getElementById('gu-mTitle').textContent='✏️ Edit Guru';
  document.getElementById('gu-modal').classList.add('open');
}
function guCloseModal(){ document.getElementById('gu-modal').classList.remove('open'); }
document.addEventListener('keydown', e=>{ if(e.key==='Escape') guCloseModal(); });

/* ══ IMPOR FILE ══ */
const csvFileInput = document.getElementById('csvFile');
const fileBadge    = document.getElementById('fileBadge');
const fileNameEl   = document.getElementById('fileName');
const dropIco      = document.getElementById('dropIco');
const impBtn       = document.getElementById('impBtn');
const impBtnTxt    = document.getElementById('impBtnTxt');

function guApplyFile(file){
  if(!file) return;
  if(file.name.split('.').pop().toLowerCase()!=='csv'){
    alert('⚠️ Hanya file .CSV yang diizinkan!'); return;
  }
  if(file.size>5*1024*1024){ alert('⚠️ Ukuran file maksimal 5 MB!'); return; }
  const dt=new DataTransfer(); dt.items.add(file);
  csvFileInput.files=dt.files;
  fileNameEl.textContent=file.name;
  fileBadge.style.display='block';
  if(dropIco)dropIco.textContent='✅';
}
csvFileInput?.addEventListener('change',function(){ if(this.files[0]) guApplyFile(this.files[0]); });
function guHandleDrop(e){
  e.preventDefault();
  document.getElementById('dropzone').classList.remove('drag');
  if(e.dataTransfer.files[0]) guApplyFile(e.dataTransfer.files[0]);
}
document.getElementById('importForm')?.addEventListener('submit',function(e){
  if(!csvFileInput||!csvFileInput.files[0]){
    e.preventDefault(); alert('⚠️ Pilih file CSV terlebih dahulu!'); return;
  }
  if(impBtnTxt)impBtnTxt.textContent='⏳ Sedang mengimpor...';
  if(impBtn){impBtn.disabled=true;impBtn.style.opacity='.65';}
});

/* ══ AUTO-DISMISS ALERTS 5 detik ══ */
document.querySelectorAll('.gu-al').forEach(al=>{
  setTimeout(()=>{
    al.style.transition='opacity .5s';
    al.style.opacity='0';
    setTimeout(()=>al.remove(),500);
  },5000);
});
</script>