<?php
session_start();
if(!isset($_SESSION['login'])){ header("Location: login.php"); exit(); }
include 'koneksi.php';

function uploadFoto($file,$old_foto=''){
    if($file['error']==0){
        $allowed=['jpg','jpeg','png','webp'];
        $ext=strtolower(pathinfo($file['name'],PATHINFO_EXTENSION));
        if(!in_array($ext,$allowed)) return ['error'=>'Format harus JPG, PNG, atau WEBP'];
        if($file['size']>2*1024*1024) return ['error'=>'Ukuran maksimal 2MB'];
        $dir='uploads/siswa/';
        if(!is_dir($dir)) mkdir($dir,0755,true);
        $fn='siswa_'.time().'_'.mt_rand(1000,9999).'.'.$ext;
        if(move_uploaded_file($file['tmp_name'],$dir.$fn)){
            if(!empty($old_foto)&&file_exists($old_foto)) unlink($old_foto);
            return ['success'=>$dir.$fn];
        }
        return ['error'=>'Gagal upload'];
    }
    return ['success'=>$old_foto];
}

/* ===================== EKSPOR CSV ===================== */
if(isset($_GET['export']) && $_GET['export']=='csv'){
    $result = mysqli_query($conn,"SELECT * FROM siswa ORDER BY nama");
    $filename = 'data_siswa_'.date('Ymd_His').'.csv';
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    header('Cache-Control: no-cache');
    $out = fopen('php://output','w');
    fputs($out, "\xEF\xBB\xBF");
    $headers = ['NIS','NISN','Nama','Jenis Kelamin','Tempat Lahir','Tanggal Lahir','Kelas','Tahun Masuk','Agama',
        'Alamat','RT','RW','Kelurahan','Kecamatan','Kota','Provinsi','Kode Pos','Email',
        'No. Telepon Siswa','Anak Ke','Jumlah Saudara','Tinggi Badan','Berat Badan','Golongan Darah',
        'Nama Ayah','Nama Ibu','Pekerjaan Ayah','Pekerjaan Ibu','Pendidikan Ayah','Pendidikan Ibu',
        'No. Telp Ortu','Nama Wali','Hubungan Wali','Riwayat Penyakit','Alergi','Prestasi','Catatan Khusus','Tanggal Daftar'];
    fputcsv($out, $headers);
    while($row = mysqli_fetch_assoc($result)){
        fputcsv($out,[
            $row['nis'],$row['nisn'],$row['nama'],$row['jk'],$row['tempat_lahir'],$row['tanggal_lahir'],
            $row['kelas'],$row['tahun_masuk'],$row['agama'],$row['alamat'],$row['rt'],$row['rw'],
            $row['kelurahan'],$row['kecamatan'],$row['kota'],$row['provinsi'],$row['kode_pos'],$row['email'],
            $row['no_telp'],$row['anak_ke'],$row['jumlah_saudara'],$row['tinggi_badan'],$row['berat_badan'],
            $row['golongan_darah'],$row['nama_ayah'],$row['nama_ibu'],$row['pekerjaan_ayah'],$row['pekerjaan_ibu'],
            $row['pendidikan_ayah'],$row['pendidikan_ibu'],$row['no_telp_ortu'],$row['nama_wali'],
            $row['hubungan_wali'],$row['riwayat_penyakit'],$row['alergi'],$row['prestasi'],
            $row['catatan_khusus'],$row['tanggal_daftar']
        ]);
    }
    fclose($out); exit();
}

/* ===================== EKSPOR EXCEL ===================== */
if(isset($_GET['export']) && $_GET['export']=='excel'){
    $result = mysqli_query($conn,"SELECT * FROM siswa ORDER BY nama");
    $filename = 'data_siswa_'.date('Ymd_His').'.xls';
    header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    header('Cache-Control: no-cache');
    echo "\xEF\xBB\xBF";
    echo '<table border="1"><thead><tr>';
    $headers=['No','NIS','NISN','Nama','JK','Tempat Lahir','Tgl Lahir','Kelas','Tahun Masuk','Agama',
        'Alamat','RT','RW','Kelurahan','Kecamatan','Kota','Provinsi','Kode Pos','Email','No. HP Siswa',
        'Anak Ke','Jml Saudara','Tinggi (cm)','Berat (kg)','Gol. Darah',
        'Nama Ayah','Nama Ibu','Pekerjaan Ayah','Pekerjaan Ibu','Pendidikan Ayah','Pendidikan Ibu',
        'No. HP Ortu','Nama Wali','Hubungan Wali','Riwayat Penyakit','Alergi','Prestasi','Catatan Khusus','Tgl Daftar'];
    foreach($headers as $h) echo '<th>'.htmlspecialchars($h).'</th>';
    echo '</tr></thead><tbody>';
    $no=1;
    while($row=mysqli_fetch_assoc($result)){
        echo '<tr><td>'.$no++.'</td>';
        $cols=['nis','nisn','nama','jk','tempat_lahir','tanggal_lahir','kelas','tahun_masuk','agama',
               'alamat','rt','rw','kelurahan','kecamatan','kota','provinsi','kode_pos','email','no_telp',
               'anak_ke','jumlah_saudara','tinggi_badan','berat_badan','golongan_darah',
               'nama_ayah','nama_ibu','pekerjaan_ayah','pekerjaan_ibu','pendidikan_ayah','pendidikan_ibu',
               'no_telp_ortu','nama_wali','hubungan_wali','riwayat_penyakit','alergi','prestasi','catatan_khusus','tanggal_daftar'];
        foreach($cols as $c) echo '<td>'.htmlspecialchars($row[$c]??'').'</td>';
        echo '</tr>';
    }
    echo '</tbody></table>'; exit();
}

/* ===================== TEMPLATE CSV ===================== */
if(isset($_GET['export']) && $_GET['export']=='template'){
    $filename = 'template_import_siswa.csv';
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    $out = fopen('php://output','w');
    fputs($out, "\xEF\xBB\xBF");
    $headers=['NIS','NISN','Nama','Jenis Kelamin','Tempat Lahir','Tanggal Lahir','Kelas','Tahun Masuk','Agama',
        'Alamat','RT','RW','Kelurahan','Kecamatan','Kota','Provinsi','Kode Pos','Email',
        'No. Telepon Siswa','Anak Ke','Jumlah Saudara','Tinggi Badan','Berat Badan','Golongan Darah',
        'Nama Ayah','Nama Ibu','Pekerjaan Ayah','Pekerjaan Ibu','Pendidikan Ayah','Pendidikan Ibu',
        'No. Telp Ortu','Nama Wali','Hubungan Wali','Riwayat Penyakit','Alergi','Prestasi','Catatan Khusus','Tanggal Daftar'];
    fputcsv($out, $headers);
    fputcsv($out,['001','1234567890','Contoh Nama Siswa','Laki-laki','Jakarta','2008-05-15','X IPA 1',date('Y'),'Islam',
        'Jl. Merdeka No. 1','001','002','Kelurahan Maju','Kecamatan Sukses','Kota Mandiri','DKI Jakarta','12345','siswa@email.com',
        '08123456789','1','2','165','55','A','Nama Ayah','Nama Ibu','Wiraswasta','Ibu Rumah Tangga','S1/D4','SMA/SMK/Sederajat',
        '08987654321','','','','','','',date('Y-m-d')]);
    fclose($out); exit();
}

/* ===================== IMPOR CSV ===================== */
$import_result = null;
if(isset($_POST['import_csv'])){
    $csv_err = $_FILES['csv_file']['error'] ?? 4;
    if($csv_err !== 0){
        $err_map=[1=>'File terlalu besar (php.ini)',2=>'File terlalu besar',3=>'Upload tidak selesai',4=>'Tidak ada file dipilih'];
        $import_result=['error'=> $err_map[$csv_err] ?? 'Gagal upload file (kode: '.$csv_err.')'];
    } else {
        $ext = strtolower(pathinfo($_FILES['csv_file']['name'],PATHINFO_EXTENSION));
        if($ext !== 'csv'){
            $import_result=['error'=>'File harus berformat .CSV!'];
        } elseif($_FILES['csv_file']['size'] > 5*1024*1024){
            $import_result=['error'=>'Ukuran file maksimal 5MB!'];
        } else {
            $tmp = $_FILES['csv_file']['tmp_name'];
            $content = file_get_contents($tmp);
            if(substr($content,0,3)==="\xEF\xBB\xBF") $content=substr($content,3);
            $tmpClean = tempnam(sys_get_temp_dir(),'csv_');
            file_put_contents($tmpClean,$content);
            $handle = fopen($tmpClean,'r');
            $header_row = fgetcsv($handle,0,',');
            if(count($header_row)<=1){ fclose($handle); $handle=fopen($tmpClean,'r'); $header_row=fgetcsv($handle,0,';'); $delim=';'; } else { $delim=','; }
            $success=0; $fail=0; $errors=[]; $row_num=1;
            $col_keys=['nis','nisn','nama','jk','tempat_lahir','tanggal_lahir','kelas','tahun_masuk','agama',
                       'alamat','rt','rw','kelurahan','kecamatan','kota','provinsi','kode_pos','email',
                       'no_telp','anak_ke','jumlah_saudara','tinggi_badan','berat_badan','golongan_darah',
                       'nama_ayah','nama_ibu','pekerjaan_ayah','pekerjaan_ibu','pendidikan_ayah','pendidikan_ibu',
                       'no_telp_ortu','nama_wali','hubungan_wali','riwayat_penyakit','alergi','prestasi','catatan_khusus','tanggal_daftar'];
            while(($row=fgetcsv($handle,0,$delim))!==false){
                $row_num++;
                if(count($row)===1&&trim($row[0])==='') continue;
                while(count($row)<38) $row[]='';
                $d=[];
                foreach($col_keys as $i=>$k) $d[$k]=trim($row[$i]??'');
                $esc=function($v)use($conn){return mysqli_real_escape_string($conn,$v);};
                if($d['nis']===''||$d['nama']===''){$fail++;$errors[]="Baris $row_num: NIS atau Nama tidak boleh kosong";continue;}
                foreach(['tanggal_lahir','tanggal_daftar'] as $df){
                    if($d[$df]!==''&&strpos($d[$df],'/')!==false){$parts=explode('/',$d[$df]);if(count($parts)===3)$d[$df]=$parts[2].'-'.str_pad($parts[1],2,'0',STR_PAD_LEFT).'-'.str_pad($parts[0],2,'0',STR_PAD_LEFT);}
                    if($d[$df]!==''&&!preg_match('/^\d{4}-\d{2}-\d{2}$/',$d[$df]))$d[$df]='';
                }
                if($d['tanggal_daftar']==='')$d['tanggal_daftar']=date('Y-m-d');
                $chk=mysqli_query($conn,"SELECT id FROM siswa WHERE nis='".$esc($d['nis'])."'");
                if(mysqli_num_rows($chk)>0){
                    $q="UPDATE siswa SET nisn='{$esc($d['nisn'])}',nama='{$esc($d['nama'])}',jk='{$esc($d['jk'])}',tempat_lahir='{$esc($d['tempat_lahir'])}',tanggal_lahir='{$esc($d['tanggal_lahir'])}',kelas='{$esc($d['kelas'])}',tahun_masuk='{$esc($d['tahun_masuk'])}',agama='{$esc($d['agama'])}',alamat='{$esc($d['alamat'])}',rt='{$esc($d['rt'])}',rw='{$esc($d['rw'])}',kelurahan='{$esc($d['kelurahan'])}',kecamatan='{$esc($d['kecamatan'])}',kota='{$esc($d['kota'])}',provinsi='{$esc($d['provinsi'])}',kode_pos='{$esc($d['kode_pos'])}',email='{$esc($d['email'])}',no_telp='{$esc($d['no_telp'])}',anak_ke='{$esc($d['anak_ke'])}',jumlah_saudara='{$esc($d['jumlah_saudara'])}',tinggi_badan='{$esc($d['tinggi_badan'])}',berat_badan='{$esc($d['berat_badan'])}',golongan_darah='{$esc($d['golongan_darah'])}',nama_ayah='{$esc($d['nama_ayah'])}',nama_ibu='{$esc($d['nama_ibu'])}',pekerjaan_ayah='{$esc($d['pekerjaan_ayah'])}',pekerjaan_ibu='{$esc($d['pekerjaan_ibu'])}',pendidikan_ayah='{$esc($d['pendidikan_ayah'])}',pendidikan_ibu='{$esc($d['pendidikan_ibu'])}',no_telp_ortu='{$esc($d['no_telp_ortu'])}',nama_wali='{$esc($d['nama_wali'])}',hubungan_wali='{$esc($d['hubungan_wali'])}',riwayat_penyakit='{$esc($d['riwayat_penyakit'])}',alergi='{$esc($d['alergi'])}',prestasi='{$esc($d['prestasi'])}',catatan_khusus='{$esc($d['catatan_khusus'])}',tanggal_daftar='{$esc($d['tanggal_daftar'])}' WHERE nis='{$esc($d['nis'])}'";
                } else {
                    $q="INSERT INTO siswa (nis,nisn,nama,jk,tempat_lahir,tanggal_lahir,kelas,tahun_masuk,agama,alamat,rt,rw,kelurahan,kecamatan,kota,provinsi,kode_pos,email,no_telp,anak_ke,jumlah_saudara,tinggi_badan,berat_badan,golongan_darah,nama_ayah,nama_ibu,pekerjaan_ayah,pekerjaan_ibu,pendidikan_ayah,pendidikan_ibu,no_telp_ortu,nama_wali,hubungan_wali,riwayat_penyakit,alergi,prestasi,catatan_khusus,tanggal_daftar,created_at) VALUES('{$esc($d['nis'])}','{$esc($d['nisn'])}','{$esc($d['nama'])}','{$esc($d['jk'])}','{$esc($d['tempat_lahir'])}','{$esc($d['tanggal_lahir'])}','{$esc($d['kelas'])}','{$esc($d['tahun_masuk'])}','{$esc($d['agama'])}','{$esc($d['alamat'])}','{$esc($d['rt'])}','{$esc($d['rw'])}','{$esc($d['kelurahan'])}','{$esc($d['kecamatan'])}','{$esc($d['kota'])}','{$esc($d['provinsi'])}','{$esc($d['kode_pos'])}','{$esc($d['email'])}','{$esc($d['no_telp'])}','{$esc($d['anak_ke'])}','{$esc($d['jumlah_saudara'])}','{$esc($d['tinggi_badan'])}','{$esc($d['berat_badan'])}','{$esc($d['golongan_darah'])}','{$esc($d['nama_ayah'])}','{$esc($d['nama_ibu'])}','{$esc($d['pekerjaan_ayah'])}','{$esc($d['pekerjaan_ibu'])}','{$esc($d['pendidikan_ayah'])}','{$esc($d['pendidikan_ibu'])}','{$esc($d['no_telp_ortu'])}','{$esc($d['nama_wali'])}','{$esc($d['hubungan_wali'])}','{$esc($d['riwayat_penyakit'])}','{$esc($d['alergi'])}','{$esc($d['prestasi'])}','{$esc($d['catatan_khusus'])}','{$esc($d['tanggal_daftar'])}',NOW())";
                }
                if(mysqli_query($conn,$q)) $success++; else {$fail++;$errors[]="Baris $row_num ({$d['nama']}): ".mysqli_error($conn);}
            }
            fclose($handle); @unlink($tmpClean);
            $import_result=['success'=>$success,'fail'=>$fail,'errors'=>$errors];
        }
    }
}

if(isset($_POST['simpan'])){
    $f=function($k)use($conn){return mysqli_real_escape_string($conn,$_POST[$k]??'');};
    $foto='';
    if(isset($_FILES['foto'])&&$_FILES['foto']['error']!=4){ $up=uploadFoto($_FILES['foto']); if(isset($up['error'])){echo $up['error'];exit();} $foto=$up['success']; }
    $foto=mysqli_real_escape_string($conn,$foto);
    $q="INSERT INTO siswa (nis,nisn,nama,jk,tempat_lahir,tanggal_lahir,alamat,rt,rw,kelurahan,kecamatan,kota,provinsi,kode_pos,email,tahun_masuk,agama,kelas,anak_ke,jumlah_saudara,tinggi_badan,berat_badan,golongan_darah,nama_ayah,nama_ibu,pekerjaan_ayah,pekerjaan_ibu,pendidikan_ayah,pendidikan_ibu,no_telp,no_telp_ortu,nama_wali,hubungan_wali,riwayat_penyakit,alergi,prestasi,catatan_khusus,tanggal_daftar,foto,created_at) VALUES ('{$f('nis')}','{$f('nisn')}','{$f('nama')}','{$f('jk')}','{$f('tempat_lahir')}','{$f('tanggal_lahir')}','{$f('alamat')}','{$f('rt')}','{$f('rw')}','{$f('kelurahan')}','{$f('kecamatan')}','{$f('kota')}','{$f('provinsi')}','{$f('kode_pos')}','{$f('email')}','{$f('tahun_masuk')}','{$f('agama')}','{$f('kelas')}','{$f('anak_ke')}','{$f('jumlah_saudara')}','{$f('tinggi_badan')}','{$f('berat_badan')}','{$f('golongan_darah')}','{$f('nama_ayah')}','{$f('nama_ibu')}','{$f('pekerjaan_ayah')}','{$f('pekerjaan_ibu')}','{$f('pendidikan_ayah')}','{$f('pendidikan_ibu')}','{$f('no_telp')}','{$f('no_telp_ortu')}','{$f('nama_wali')}','{$f('hubungan_wali')}','{$f('riwayat_penyakit')}','{$f('alergi')}','{$f('prestasi')}','{$f('catatan_khusus')}','{$f('tanggal_daftar')}','$foto',NOW())";
    if(mysqli_query($conn,$q)){header("Location: siswa.php?success=add");exit();}
    else{echo "Error: ".mysqli_error($conn);exit();}
}

if(isset($_POST['update'])){
    $f=function($k)use($conn){return mysqli_real_escape_string($conn,$_POST[$k]??'');};
    $id=$f('id');$old_foto=$f('old_foto');$foto=$old_foto;
    if(isset($_FILES['foto'])&&$_FILES['foto']['error']!=4){ $up=uploadFoto($_FILES['foto'],$old_foto); if(isset($up['error'])){echo $up['error'];exit();} $foto=$up['success']; }
    $foto=mysqli_real_escape_string($conn,$foto);
    $q="UPDATE siswa SET nis='{$f('nis')}',nisn='{$f('nisn')}',nama='{$f('nama')}',jk='{$f('jk')}',tempat_lahir='{$f('tempat_lahir')}',tanggal_lahir='{$f('tanggal_lahir')}',alamat='{$f('alamat')}',rt='{$f('rt')}',rw='{$f('rw')}',kelurahan='{$f('kelurahan')}',kecamatan='{$f('kecamatan')}',kota='{$f('kota')}',provinsi='{$f('provinsi')}',kode_pos='{$f('kode_pos')}',email='{$f('email')}',tahun_masuk='{$f('tahun_masuk')}',agama='{$f('agama')}',kelas='{$f('kelas')}',anak_ke='{$f('anak_ke')}',jumlah_saudara='{$f('jumlah_saudara')}',tinggi_badan='{$f('tinggi_badan')}',berat_badan='{$f('berat_badan')}',golongan_darah='{$f('golongan_darah')}',nama_ayah='{$f('nama_ayah')}',nama_ibu='{$f('nama_ibu')}',pekerjaan_ayah='{$f('pekerjaan_ayah')}',pekerjaan_ibu='{$f('pekerjaan_ibu')}',pendidikan_ayah='{$f('pendidikan_ayah')}',pendidikan_ibu='{$f('pendidikan_ibu')}',no_telp='{$f('no_telp')}',no_telp_ortu='{$f('no_telp_ortu')}',nama_wali='{$f('nama_wali')}',hubungan_wali='{$f('hubungan_wali')}',riwayat_penyakit='{$f('riwayat_penyakit')}',alergi='{$f('alergi')}',prestasi='{$f('prestasi')}',catatan_khusus='{$f('catatan_khusus')}',tanggal_daftar='{$f('tanggal_daftar')}',foto='$foto' WHERE id='$id'";
    if(mysqli_query($conn,$q)){header("Location: siswa.php?success=update");exit();}
    else{echo "Error: ".mysqli_error($conn);exit();}
}

if(isset($_GET['hapus'])){
    $id=mysqli_real_escape_string($conn,$_GET['hapus']);
    $r=mysqli_query($conn,"SELECT foto FROM siswa WHERE id='$id'");
    if($r&&$row=mysqli_fetch_array($r)) if(!empty($row['foto'])&&file_exists($row['foto'])) unlink($row['foto']);
    if(mysqli_query($conn,"DELETE FROM siswa WHERE id='$id'")){header("Location: siswa.php?success=delete");exit();}
    else{echo "Error: ".mysqli_error($conn);exit();}
}

$edit_data=null;
if(isset($_GET['edit'])){
    $id=mysqli_real_escape_string($conn,$_GET['edit']);
    $edit_data=mysqli_fetch_array(mysqli_query($conn,"SELECT * FROM siswa WHERE id='$id'"));
}

$data=mysqli_query($conn,"SELECT * FROM siswa ORDER BY nama");
$total_siswa=mysqli_num_rows($data);
$lk=0;$pr=0;
mysqli_data_seek($data,0);
while($tmp=mysqli_fetch_array($data)){ if($tmp['jk']=='Laki-laki') $lk++; else $pr++; }
mysqli_data_seek($data,0);

$pekerjaan_list=['PNS','TNI/Polri','Pegawai Swasta','Wiraswasta','Petani','Nelayan','Buruh','Pedagang','Guru/Dosen','Dokter/Tenaga Medis','Pengacara/Notaris','Arsitek/Insinyur','Seniman/Kreator','Ibu Rumah Tangga','Pensiunan','Tidak Bekerja','Lainnya'];
$pendidikan_list=['Tidak Sekolah','SD/Sederajat','SMP/Sederajat','SMA/SMK/Sederajat','D1/D2/D3','S1/D4','S2','S3'];

$page_title  = "Buku Induk Siswa — MA As-Syafi'iyah 02";
$active_menu = 'siswa';
$loader_text = 'Memuat Data Siswa';
include 'navbar.php';
?>

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800;900&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">

<div class="main">
<div class="sw-wrap" id="sw-root">
<style>
/* ═══════════════════════════════════════════
   RESET & TOKENS
═══════════════════════════════════════════ */
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
#sw-root,#sw-root *{font-family:'Outfit',sans-serif}

:root{
  /* Brand */
  --c-blue:   #1D4ED8;
  --c-blue2:  #2563EB;
  --c-blue3:  #3B82F6;
  --c-blue-l: #EFF6FF;
  --c-blue-m: #BFDBFE;
  --c-teal:   #0F766E;
  --c-teal2:  #14B8A6;
  --c-teal-l: #F0FDFA;
  --c-teal-m: #99F6E4;
  --c-rose:   #BE123C;
  --c-rose2:  #E11D48;
  --c-rose-l: #FFF1F2;
  --c-rose-m: #FECDD3;
  --c-amber:  #B45309;
  --c-amber2: #D97706;
  --c-amb-l:  #FFFBEB;
  --c-amb-m:  #FDE68A;
  --c-green:  #15803D;
  --c-grn2:   #16A34A;
  --c-grn-l:  #F0FDF4;
  --c-grn-m:  #BBF7D0;
  --c-pur:    #6D28D9;
  --c-pur2:   #7C3AED;
  --c-pur-l:  #F5F3FF;
  --c-pur-m:  #DDD6FE;
  /* Neutrals */
  --c-bg:     #F8FAFC;
  --c-sur:    #FFFFFF;
  --c-bd:     #E2E8F0;
  --c-bd2:    #CBD5E1;
  --c-tx:     #0F172A;
  --c-tx2:    #1E293B;
  --c-tx3:    #475569;
  --c-tx4:    #94A3B8;
  --c-tx5:    #CBD5E1;
  /* Shadows */
  --sh-xs: 0 1px 2px rgba(0,0,0,.05);
  --sh-s:  0 1px 4px rgba(0,0,0,.06),0 2px 8px rgba(0,0,0,.04);
  --sh-m:  0 4px 12px rgba(0,0,0,.07),0 2px 4px rgba(0,0,0,.04);
  --sh-l:  0 8px 32px rgba(0,0,0,.09),0 2px 8px rgba(0,0,0,.05);
  --sh-xl: 0 20px 60px rgba(0,0,0,.12),0 4px 12px rgba(0,0,0,.06);
  /* Radii */
  --r-sm: 8px;
  --r:    12px;
  --r-l:  16px;
  --r-xl: 20px;
  --r-2xl:24px;
}

/* ═══════════════════════════════════════════
   LAYOUT
═══════════════════════════════════════════ */
#sw-root{
  padding: clamp(12px, 3vw, 24px);
  max-width: 1440px;
  background: var(--c-bg);
  min-height: 100vh;
}

/* ═══════════════════════════════════════════
   ANIMATIONS
═══════════════════════════════════════════ */
@keyframes fadeUp{
  from{opacity:0;transform:translateY(16px)}
  to{opacity:1;transform:translateY(0)}
}
@keyframes pulse-glow{
  0%,100%{box-shadow:0 0 0 0 rgba(37,99,235,.3)}
  50%{box-shadow:0 0 0 8px rgba(37,99,235,0)}
}
.anim-0{animation:fadeUp .5s cubic-bezier(.22,1,.36,1) both}
.anim-1{animation:fadeUp .5s cubic-bezier(.22,1,.36,1) .08s both}
.anim-2{animation:fadeUp .5s cubic-bezier(.22,1,.36,1) .16s both}
.anim-3{animation:fadeUp .5s cubic-bezier(.22,1,.36,1) .24s both}

/* ═══════════════════════════════════════════
   HERO BANNER
═══════════════════════════════════════════ */
.sw-hero{
  background: linear-gradient(135deg, #0C1D5E 0%, #1D4ED8 50%, #0891B2 100%);
  border-radius: var(--r-2xl);
  padding: clamp(20px, 4vw, 36px) clamp(20px, 4vw, 40px);
  margin-bottom: 16px;
  position: relative;
  overflow: hidden;
  box-shadow: var(--sh-xl);
}
.sw-hero::before{
  content:'';
  position:absolute;inset:0;
  background: radial-gradient(ellipse at 80% 50%, rgba(14,165,233,.25) 0%, transparent 60%),
              radial-gradient(ellipse at 10% 80%, rgba(99,102,241,.2) 0%, transparent 50%);
  pointer-events:none;
}
.sw-hero::after{
  content:'';
  position:absolute;
  top:-60px;right:-60px;
  width:220px;height:220px;
  border-radius:50%;
  background:rgba(255,255,255,.06);
  pointer-events:none;
}
.hero-inner{
  position:relative;z-index:2;
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:20px;
  flex-wrap:wrap;
}
.hero-left{flex:1;min-width:0}
.hero-badge{
  display:inline-flex;align-items:center;gap:6px;
  background:rgba(255,255,255,.15);
  border:1px solid rgba(255,255,255,.25);
  border-radius:50px;
  padding:5px 14px;
  font-size:11px;font-weight:700;
  color:rgba(255,255,255,.9);
  letter-spacing:.08em;text-transform:uppercase;
  margin-bottom:12px;
  backdrop-filter:blur(8px);
}
.hero-title{
  font-size:clamp(1.5rem, 3.5vw, 2.25rem);
  font-weight:900;
  color:#fff;
  line-height:1.15;
  margin-bottom:6px;
  letter-spacing:-.02em;
}
.hero-title span{
  background:linear-gradient(90deg,#FCD34D,#6EE7F7);
  -webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;
}
.hero-desc{font-size:clamp(.8rem,.9vw,.92rem);color:rgba(255,255,255,.65);font-weight:500}
.hero-right{
  display:flex;flex-direction:column;align-items:flex-end;gap:12px;
  flex-shrink:0;
}
.hero-kelas-btn{
  display:inline-flex;align-items:center;gap:7px;
  padding:10px 20px;
  background:rgba(255,255,255,.18);
  border:1.5px solid rgba(255,255,255,.35);
  border-radius:50px;
  color:#fff;font-weight:700;font-size:13px;
  text-decoration:none;
  backdrop-filter:blur(10px);
  transition:all .25s;
  white-space:nowrap;
}
.hero-kelas-btn:hover{background:rgba(255,255,255,.28);transform:translateY(-2px);box-shadow:0 6px 20px rgba(0,0,0,.2)}
.hero-stats{display:flex;gap:10px;flex-wrap:wrap}
.hstat{
  background:rgba(255,255,255,.12);
  border:1px solid rgba(255,255,255,.18);
  border-radius:14px;
  padding:12px 18px;
  min-width:90px;
  text-align:center;
  backdrop-filter:blur(8px);
  transition:background .2s;
}
.hstat:hover{background:rgba(255,255,255,.2)}
.hstat-n{
  font-size:clamp(1.4rem,3vw,2rem);
  font-weight:900;color:#fff;
  font-family:'JetBrains Mono',monospace;
  line-height:1;
}
.hstat-l{
  font-size:10px;font-weight:700;
  color:rgba(255,255,255,.6);
  text-transform:uppercase;letter-spacing:.1em;
  margin-top:3px;
}

/* ═══════════════════════════════════════════
   ALERTS / TOASTS
═══════════════════════════════════════════ */
.sw-alerts{display:flex;flex-direction:column;gap:10px;margin-bottom:16px}
.sw-alert{
  display:flex;align-items:flex-start;gap:12px;
  padding:13px 16px;
  border-radius:var(--r);
  border:1.5px solid;
  font-size:14px;font-weight:600;
  animation:fadeUp .4s cubic-bezier(.34,1.56,.64,1) both;
}
.sw-alert-icon{font-size:16px;flex-shrink:0;margin-top:1px}
.sw-alert a{font-weight:800;color:inherit;text-decoration:underline}
.a-ok  {background:var(--c-grn-l);color:#14532D;border-color:var(--c-grn-m)}
.a-del {background:var(--c-rose-l);color:#9F1239;border-color:var(--c-rose-m)}
.a-edit{background:var(--c-amb-l);color:#78350F;border-color:var(--c-amb-m)}
.a-pur {background:var(--c-pur-l);color:#4C1D95;border-color:var(--c-pur-m)}

/* ═══════════════════════════════════════════
   CARD CONTAINER
═══════════════════════════════════════════ */
.sw-card{
  background:var(--c-sur);
  border-radius:var(--r-xl);
  border:1.5px solid var(--c-bd);
  box-shadow:var(--sh-m);
  overflow:hidden;
  margin-bottom:16px;
}
.sw-card-head{
  display:flex;align-items:center;justify-content:space-between;
  gap:12px;flex-wrap:wrap;
  padding:clamp(14px,2vw,18px) clamp(16px,2.5vw,24px);
  border-bottom:1.5px solid var(--c-bd);
}
.sw-card-head-l{display:flex;align-items:center;gap:12px}
.sw-card-icon{
  width:42px;height:42px;
  border-radius:12px;
  display:flex;align-items:center;justify-content:center;
  font-size:18px;flex-shrink:0;
}
.sw-card-title{font-size:15px;font-weight:800;color:var(--c-tx);letter-spacing:-.01em}
.sw-card-sub{font-size:12px;font-weight:500;color:var(--c-tx3);margin-top:2px}
.sw-card-body{padding:clamp(16px,2.5vw,24px)}

/* Icon color presets */
.ic-blue  {background:var(--c-blue-l);color:var(--c-blue)}
.ic-teal  {background:var(--c-teal-l);color:var(--c-teal)}
.ic-amber {background:var(--c-amb-l);color:var(--c-amber)}
.ic-rose  {background:var(--c-rose-l);color:var(--c-rose)}
.ic-pur   {background:var(--c-pur-l);color:var(--c-pur)}
.ic-green {background:var(--c-grn-l);color:var(--c-green)}

/* ═══════════════════════════════════════════
   BUTTONS
═══════════════════════════════════════════ */
.sw-btn{
  display:inline-flex;align-items:center;justify-content:center;gap:6px;
  padding:9px 15px;
  border-radius:10px;
  font-family:'Outfit',sans-serif;
  font-size:13px;font-weight:700;
  cursor:pointer;border:1.5px solid transparent;
  text-decoration:none;white-space:nowrap;
  transition:all .22s cubic-bezier(.34,1.56,.64,1);
  line-height:1;
}
.sw-btn:hover{transform:translateY(-2px)}
.sw-btn:active{transform:translateY(0) scale(.97)}

.btn-primary{
  background:linear-gradient(135deg,var(--c-blue2),var(--c-blue));
  color:#fff;border-color:var(--c-blue);
  box-shadow:0 4px 14px rgba(29,78,216,.3);
}
.btn-primary:hover{box-shadow:0 8px 22px rgba(29,78,216,.4)}

.btn-green{background:var(--c-grn-l);color:var(--c-green);border-color:var(--c-grn-m)}
.btn-green:hover{background:#DCFCE7;box-shadow:0 4px 12px rgba(21,128,61,.2)}

.btn-blue{background:var(--c-blue-l);color:var(--c-blue);border-color:var(--c-blue-m)}
.btn-blue:hover{background:#DBEAFE;box-shadow:0 4px 12px rgba(29,78,216,.2)}

.btn-teal{background:var(--c-teal-l);color:var(--c-teal);border-color:var(--c-teal-m)}
.btn-teal:hover{background:#CCFBF1;box-shadow:0 4px 12px rgba(15,118,110,.2)}

.btn-pur{background:var(--c-pur-l);color:var(--c-pur);border-color:var(--c-pur-m)}
.btn-pur:hover{background:#EDE9FE;box-shadow:0 4px 12px rgba(109,40,217,.2)}

.btn-amber{background:var(--c-amb-l);color:var(--c-amber);border-color:var(--c-amb-m)}
.btn-amber:hover{background:#FEF3C7;box-shadow:0 4px 12px rgba(180,83,9,.2)}

.btn-danger{background:var(--c-rose-l);color:var(--c-rose2);border-color:var(--c-rose-m)}
.btn-danger:hover{background:#FFE4E6;box-shadow:0 4px 12px rgba(190,18,60,.2)}

.btn-ghost{background:var(--c-bg);color:var(--c-tx2);border-color:var(--c-bd)}
.btn-ghost:hover{border-color:var(--c-bd2);background:#F1F5F9}

.btn-lg{padding:13px 24px;font-size:15px;border-radius:12px}
.btn-w100{width:100%;justify-content:center}

/* ═══════════════════════════════════════════
   EXPORT / IMPORT SECTION
═══════════════════════════════════════════ */
.ei-grid{
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:0;
}
.ei-col{padding:clamp(16px,2.5vw,24px)}
.ei-col:first-child{border-right:1.5px solid var(--c-bd)}
.ei-section-label{
  font-size:11px;font-weight:800;
  text-transform:uppercase;letter-spacing:.1em;
  color:var(--c-tx3);
  margin-bottom:14px;
  display:flex;align-items:center;gap:6px;
}
.btn-row{display:flex;flex-wrap:wrap;gap:8px}
.note-text{
  font-size:13px;color:var(--c-tx3);
  line-height:1.7;margin-top:12px;
}
/* Dropzone */
.sw-dropzone{
  border:2px dashed var(--c-blue-m);
  border-radius:var(--r);
  padding:clamp(18px,3vw,28px) 16px;
  background:var(--c-blue-l);
  text-align:center;
  transition:all .2s;
  cursor:pointer;
}
.sw-dropzone:hover,.sw-dropzone.drag{
  border-color:var(--c-blue2);
  background:#DBEAFE;
}
.sw-dropzone input{display:none}
.dz-icon{font-size:2.2rem;margin-bottom:8px;display:block;line-height:1}
.dz-text{font-size:13px;font-weight:600;color:var(--c-tx3)}
.dz-text span{color:var(--c-blue2);text-decoration:underline;cursor:pointer;font-weight:700}
.dz-hint{font-size:11px;color:var(--c-tx4);margin-top:4px}
.file-badge{
  display:inline-flex;align-items:center;gap:6px;
  background:#fff;border:1.5px solid var(--c-blue-m);border-radius:8px;
  padding:5px 12px;font-size:12px;font-weight:700;color:var(--c-blue);
  margin-top:10px;word-break:break-all;
}

/* ═══════════════════════════════════════════
   FORM
═══════════════════════════════════════════ */
.form-section{margin-bottom:24px}
.section-header{
  display:flex;align-items:center;gap:8px;
  padding:9px 14px;
  border-radius:10px;
  background:var(--c-bg);
  border-left:3px solid var(--c-blue);
  margin-bottom:16px;
}
.section-header.c-teal {border-left-color:var(--c-teal)}
.section-header.c-rose {border-left-color:var(--c-rose2)}
.section-header.c-amber{border-left-color:var(--c-amber2)}
.section-header.c-pur  {border-left-color:var(--c-pur2)}
.section-header.c-green{border-left-color:var(--c-grn2)}
.section-header-text{font-size:13px;font-weight:800;color:var(--c-tx)}

.fgrid{
  display:grid;
  grid-template-columns:repeat(auto-fill,minmax(220px,1fr));
  gap:14px;
}
.fw{grid-column:1/-1}

.fg{display:flex;flex-direction:column;gap:5px}
.flbl{
  font-size:11px;font-weight:700;
  text-transform:uppercase;letter-spacing:.07em;
  color:var(--c-tx2);
  display:flex;align-items:center;gap:4px;
}
.freq{color:var(--c-rose2);font-size:13px;line-height:1}
.fopt{
  background:var(--c-blue-l);color:var(--c-blue);
  border:1px solid var(--c-blue-m);border-radius:50px;
  padding:1px 7px;font-size:10px;font-weight:700;
}

.fi,.fsel,.fta{
  width:100%;padding:10px 13px;
  background:#fff;border:1.5px solid var(--c-bd);border-radius:10px;
  font-family:'Outfit',sans-serif;font-size:14px;font-weight:500;color:var(--c-tx);
  outline:none;transition:border-color .18s,box-shadow .18s;
  -webkit-appearance:none;
}
.fi:focus,.fsel:focus,.fta:focus{
  border-color:var(--c-blue2);
  box-shadow:0 0 0 3px rgba(37,99,235,.12);
  background:#FAFCFF;
}
.fi::placeholder,.fta::placeholder{color:var(--c-tx5)}
.fta{resize:vertical;min-height:80px;line-height:1.6}
.fsel{
  cursor:pointer;
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%2364748B' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
  background-repeat:no-repeat;
  background-position:right 12px center;
  padding-right:36px;
}

/* Foto */
.foto-wrap{display:flex;align-items:flex-start;gap:16px;flex-wrap:wrap}
.foto-frame{
  width:90px;height:112px;
  border-radius:10px;
  border:2px dashed var(--c-bd);
  background:var(--c-bg);
  overflow:hidden;flex-shrink:0;
  display:flex;align-items:center;justify-content:center;
}
.foto-frame img{width:100%;height:100%;object-fit:cover}
.foto-ph{text-align:center;color:var(--c-tx4);font-size:12px;padding:8px}
.foto-ph-icon{font-size:2rem;display:block;margin-bottom:4px}
.foto-side{flex:1;min-width:130px}
input[type="file"]{display:none}
.foto-note{font-size:12px;color:var(--c-tx3);line-height:1.8;margin-top:10px}

/* Form actions */
.form-actions{
  display:flex;gap:10px;flex-wrap:wrap;
  padding-top:20px;
  border-top:2px dashed var(--c-bd);
  margin-top:8px;
}
.btn-save-main{
  display:inline-flex;align-items:center;gap:8px;
  padding:14px 28px;font-size:15px;font-weight:800;
  border-radius:12px;cursor:pointer;border:none;
  font-family:'Outfit',sans-serif;
  background:linear-gradient(135deg,var(--c-blue2),var(--c-blue));
  color:#fff;box-shadow:0 5px 18px rgba(29,78,216,.35);
  transition:all .28s cubic-bezier(.34,1.56,.64,1);
}
.btn-save-main:hover{transform:translateY(-3px);box-shadow:0 10px 28px rgba(29,78,216,.45)}
.btn-update-main{
  display:inline-flex;align-items:center;gap:8px;
  padding:14px 28px;font-size:15px;font-weight:800;
  border-radius:12px;cursor:pointer;border:none;
  font-family:'Outfit',sans-serif;
  background:linear-gradient(135deg,var(--c-amber2),var(--c-amber));
  color:#fff;box-shadow:0 5px 18px rgba(180,83,9,.35);
  transition:all .28s cubic-bezier(.34,1.56,.64,1);
}
.btn-update-main:hover{transform:translateY(-3px);box-shadow:0 10px 28px rgba(180,83,9,.45)}

/* ═══════════════════════════════════════════
   TABLE SECTION
═══════════════════════════════════════════ */
.tbl-topbar{
  display:flex;align-items:center;gap:10px;
  padding:14px clamp(16px,2.5vw,24px);
  border-bottom:1.5px solid var(--c-bd);
  flex-wrap:wrap;
}
.search-wrap{position:relative;flex:1;min-width:180px;max-width:380px}
.search-wrap::before{
  content:'🔍';position:absolute;left:13px;top:50%;
  transform:translateY(-50%);font-size:13px;pointer-events:none;
  line-height:1;
}
.search-input{
  width:100%;padding:10px 14px 10px 38px;
  border-radius:50px;border:1.5px solid var(--c-bd);
  background:var(--c-bg);font-family:'Outfit',sans-serif;
  font-size:13px;font-weight:600;outline:none;
  transition:all .2s;
}
.search-input:focus{
  border-color:var(--c-blue2);background:#fff;
  box-shadow:0 0 0 3px rgba(37,99,235,.1);
}
.count-pill{
  background:var(--c-blue-l);color:var(--c-blue);
  border:1px solid var(--c-blue-m);border-radius:50px;
  padding:5px 14px;font-size:12px;font-weight:700;
  white-space:nowrap;flex-shrink:0;
}

/* Table scroll */
.tbl-scroll{overflow-x:auto;-webkit-overflow-scrolling:touch}
.tbl-scroll::-webkit-scrollbar{height:4px}
.tbl-scroll::-webkit-scrollbar-track{background:var(--c-bg)}
.tbl-scroll::-webkit-scrollbar-thumb{background:var(--c-bd2);border-radius:10px}

table.sw-table{
  width:100%;border-collapse:collapse;
  min-width:960px;
}
.sw-table thead tr{background:var(--c-bg)}
.sw-table th{
  padding:11px 13px;text-align:left;
  font-size:11px;font-weight:800;color:var(--c-tx3);
  text-transform:uppercase;letter-spacing:.08em;
  white-space:nowrap;border-bottom:2px solid var(--c-bd);
}
.sw-table tbody tr{
  border-bottom:1px solid var(--c-bd);
  transition:background .15s;
}
.sw-table tbody tr:hover{background:#F8FAFF}
.sw-table tbody tr:last-child{border-bottom:none}
.sw-table td{
  padding:12px 13px;font-size:13px;
  color:var(--c-tx);vertical-align:top;
}

/* Table cell components */
.td-no{
  font-family:'JetBrains Mono',monospace;
  font-size:11px;color:var(--c-tx4);
  text-align:center;width:36px;vertical-align:middle;
}
.td-photo{text-align:center;width:60px;vertical-align:middle}
.td-photo img{
  width:46px;height:56px;object-fit:cover;
  border-radius:9px;border:2px solid var(--c-bd);
}
.no-photo{
  width:46px;height:56px;border-radius:9px;
  background:linear-gradient(135deg,var(--c-blue-l),var(--c-blue-m));
  border:2px solid var(--c-blue-m);
  display:inline-flex;align-items:center;justify-content:center;
  font-size:1.3rem;
}
.nis-tag{
  display:inline-flex;align-items:center;
  background:var(--c-blue-l);color:var(--c-blue);
  border:1.5px solid var(--c-blue-m);border-radius:7px;
  padding:3px 8px;
  font-family:'JetBrains Mono',monospace;font-size:11px;font-weight:600;
}
.name-cell{font-weight:800;font-size:14px;color:var(--c-tx)}
.name-cell small{display:block;font-size:11px;color:var(--c-tx3);font-weight:500;margin-top:2px}
.jk-pill{
  display:inline-flex;align-items:center;gap:3px;
  padding:3px 10px;border-radius:50px;
  font-size:11px;font-weight:700;white-space:nowrap;
}
.jk-m{background:var(--c-blue-l);color:var(--c-blue);border:1px solid var(--c-blue-m)}
.jk-f{background:var(--c-rose-l);color:var(--c-rose2);border:1px solid var(--c-rose-m)}
.info-lines{font-size:12px;color:var(--c-tx2);line-height:1.8}
.info-lines b{font-weight:700;color:var(--c-tx)}
.code-chip{
  display:inline-block;background:var(--c-bg);
  border:1px solid var(--c-bd);border-radius:6px;
  padding:2px 8px;font-size:11px;font-weight:600;color:var(--c-tx3);
  font-family:'JetBrains Mono',monospace;
}
.tag-item{
  display:inline-block;font-size:11px;font-weight:700;
  padding:2px 8px;border-radius:6px;border:1px solid;
}
.tag-rose  {background:var(--c-rose-l);color:var(--c-rose2);border-color:var(--c-rose-m)}
.tag-amber {background:var(--c-amb-l);color:var(--c-amber);border-color:var(--c-amb-m)}
.tag-green {background:var(--c-grn-l);color:var(--c-green);border-color:var(--c-grn-m)}
.tag-blue  {background:var(--c-blue-l);color:var(--c-blue);border-color:var(--c-blue-m)}
.act-btns{display:flex;gap:5px}

/* Kelas link */
a.kelas-link{
  color:var(--c-teal);font-weight:700;text-decoration:none;
  padding:2px 6px;border-radius:6px;background:var(--c-teal-l);
  border:1px solid var(--c-teal-m);font-size:13px;
  transition:background .15s;
}
a.kelas-link:hover{background:var(--c-teal-m)}

/* Empty state */
.empty-state{
  text-align:center;padding:clamp(40px,8vw,80px) 20px;
}
.empty-icon{font-size:3.5rem;margin-bottom:12px;display:block}
.empty-title{font-size:17px;font-weight:800;color:var(--c-tx);margin-bottom:6px}
.empty-sub{font-size:14px;color:var(--c-tx3)}

/* ═══════════════════════════════════════════
   MOBILE CARDS
═══════════════════════════════════════════ */
.mob-list{
  display:none;
  flex-direction:column;gap:12px;
  padding:16px;
}
.mob-card{
  background:#fff;border:1.5px solid var(--c-bd);
  border-radius:var(--r-l);padding:15px;
  box-shadow:var(--sh-s);
  transition:box-shadow .2s,transform .2s;
}
.mob-card:hover{box-shadow:var(--sh-m);transform:translateY(-1px)}
.mob-card-top{display:flex;align-items:flex-start;gap:13px;margin-bottom:13px}
.mob-photo img{width:54px;height:66px;object-fit:cover;border-radius:9px;border:2px solid var(--c-bd)}
.mob-photo .no-photo{width:54px;height:66px;border-radius:9px;font-size:1.5rem}
.mob-info{flex:1;min-width:0}
.mob-name{font-size:16px;font-weight:800;color:var(--c-tx);line-height:1.3;margin-bottom:4px}
.mob-nis{margin-bottom:6px}
.mob-tags{display:flex;gap:5px;flex-wrap:wrap;margin-top:6px}
.mob-grid{
  display:grid;grid-template-columns:1fr 1fr;
  gap:8px 12px;
  background:var(--c-bg);
  border-radius:10px;padding:12px;
  margin-bottom:13px;
}
.mob-field-label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--c-tx4);margin-bottom:2px}
.mob-field-value{font-size:13px;font-weight:600;color:var(--c-tx2);line-height:1.4}
.mob-actions{display:flex;gap:8px;padding-top:13px;border-top:1px solid var(--c-bd)}
.mob-actions .sw-btn{flex:1}

/* Import result */
.import-result{
  background:var(--c-pur-l);border:1.5px solid var(--c-pur-m);
  border-radius:var(--r);padding:16px 20px;margin-bottom:16px;
}
.import-result h4{font-size:14px;font-weight:800;color:var(--c-pur);margin-bottom:8px}
.import-errors{margin-top:8px;max-height:120px;overflow-y:auto;font-size:12px;color:#5B21B6;line-height:1.8}

/* ═══════════════════════════════════════════
   DELETE MODAL
═══════════════════════════════════════════ */
.modal-backdrop{
  display:none;position:fixed;inset:0;z-index:9000;
  background:rgba(0,0,0,.6);backdrop-filter:blur(6px);
  align-items:center;justify-content:center;padding:16px;
}
.modal-backdrop.open{display:flex}
.modal-box{
  background:#fff;border-radius:var(--r-xl);
  padding:clamp(20px,4vw,32px);max-width:400px;width:100%;
  box-shadow:var(--sh-xl);
  animation:fadeUp .32s cubic-bezier(.22,1,.36,1);
}
.modal-icon{
  width:56px;height:56px;border-radius:16px;
  background:var(--c-rose-l);
  display:flex;align-items:center;justify-content:center;
  font-size:1.8rem;margin-bottom:16px;
}
.modal-title{font-size:19px;font-weight:800;color:var(--c-tx);margin-bottom:8px}
.modal-desc{font-size:14px;color:var(--c-tx3);line-height:1.7}
.modal-footer{display:flex;gap:10px;margin-top:24px}
.modal-footer .sw-btn{flex:1}

/* ═══════════════════════════════════════════
   RESPONSIVE BREAKPOINTS
═══════════════════════════════════════════ */
@media (max-width:900px){
  .ei-grid{grid-template-columns:1fr}
  .ei-col:first-child{border-right:none;border-bottom:1.5px solid var(--c-bd)}
  .fgrid{grid-template-columns:1fr 1fr}
}

@media (max-width:640px){
  /* Hero */
  .sw-hero{border-radius:var(--r-l)}
  .hero-inner{flex-direction:column;align-items:flex-start}
  .hero-right{width:100%;flex-direction:row;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px}
  .hero-stats{display:grid;grid-template-columns:repeat(3,1fr);width:100%;flex:none}
  .hstat{padding:10px 8px;min-width:0}
  .hstat-n{font-size:1.5rem}
  .hero-kelas-btn{font-size:12px;padding:8px 14px}
  /* Hide desktop table, show mobile cards */
  .tbl-scroll{display:none}
  .mob-list{display:flex}
  /* Form */
  .fgrid{grid-template-columns:1fr}
  .fw{grid-column:1}
  .form-actions{flex-direction:column}
  .btn-save-main,.btn-update-main{width:100%;justify-content:center}
  .foto-wrap{flex-direction:column}
  /* Cards */
  .sw-card{border-radius:var(--r-l)}
  .tbl-topbar{gap:8px}
  .search-wrap{max-width:100%;flex:1}
  /* Buttons shrink on mobile */
  .sw-btn{padding:8px 12px;font-size:12px}
  .btn-row{gap:6px}
}

@media (max-width:400px){
  .hero-stats{grid-template-columns:1fr 1fr}
  .hero-right{flex-direction:column;align-items:flex-start}
  .mob-grid{grid-template-columns:1fr}
  .modal-footer{flex-direction:column}
}

/* Scrollbar hide trick for small content */
@media (max-width:640px){
  .sw-card-head{flex-wrap:wrap;gap:8px}
  .sw-card-head .sw-btn{font-size:12px;padding:7px 11px}
}
</style>

<!-- ════════ HERO ════════ -->
<div class="sw-hero anim-0">
  <div class="hero-inner">
    <div class="hero-left">
      <div class="hero-badge">🎓 Manajemen Akademik</div>
      <h1 class="hero-title">Buku Induk <span>Siswa</span></h1>
      <p class="hero-desc">MA As-Syafi'iyah 02 &mdash; Kelola data siswa secara lengkap &amp; terpusat</p>
    </div>
    <div class="hero-right">
      <a href="siswa_kelas.php" class="hero-kelas-btn">🏫 Lihat Per Kelas</a>
      <div class="hero-stats">
        <div class="hstat">
          <div class="hstat-n"><?= $total_siswa ?></div>
          <div class="hstat-l">Total</div>
        </div>
        <div class="hstat">
          <div class="hstat-n"><?= $lk ?></div>
          <div class="hstat-l">♂ L</div>
        </div>
        <div class="hstat">
          <div class="hstat-n"><?= $pr ?></div>
          <div class="hstat-l">♀ P</div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ════════ ALERTS ════════ -->
<div class="sw-alerts">
<?php if(isset($_GET['success'])): ?>
  <div class="sw-alert a-ok anim-0">
    <span class="sw-alert-icon">✅</span>
    <div><?php
      if($_GET['success']=='add')    echo '<b>Berhasil ditambahkan!</b> Data siswa baru tersimpan.';
      elseif($_GET['success']=='update') echo '<b>Data berhasil diperbarui.</b>';
      elseif($_GET['success']=='delete') echo '<b>Data berhasil dihapus</b> dari sistem.';
    ?></div>
  </div>
<?php endif; ?>
<?php if($edit_data): ?>
  <div class="sw-alert a-edit anim-0">
    <span class="sw-alert-icon">✏️</span>
    <div>Mode Edit: <b><?= htmlspecialchars($edit_data['nama']) ?></b> &nbsp;&mdash;&nbsp; <a href="siswa.php">Batal Edit</a></div>
  </div>
<?php endif; ?>
</div>

<?php if($import_result): ?>
  <?php if(isset($import_result['error'])): ?>
    <div class="sw-alert a-del anim-0" style="margin-bottom:16px">
      <span class="sw-alert-icon">❌</span>
      <div><b>Gagal impor:</b> <?= htmlspecialchars($import_result['error']) ?></div>
    </div>
  <?php else: ?>
    <div class="import-result anim-0">
      <h4>📥 Hasil Impor CSV</h4>
      <div style="font-size:14px;font-weight:600">
        ✅ Berhasil: <b><?= $import_result['success'] ?></b> &nbsp;|&nbsp; ❌ Gagal: <b><?= $import_result['fail'] ?></b>
      </div>
      <?php if(!empty($import_result['errors'])): ?>
        <div class="import-errors"><b>Detail error:</b><br><?= implode('<br>',array_map('htmlspecialchars',$import_result['errors'])) ?></div>
      <?php endif; ?>
    </div>
  <?php endif; ?>
<?php endif; ?>

<!-- ════════ EKSPOR & IMPOR ════════ -->
<div class="sw-card anim-1">
  <div class="sw-card-head">
    <div class="sw-card-head-l">
      <div class="sw-card-icon ic-pur">📊</div>
      <div>
        <div class="sw-card-title">Ekspor &amp; Impor Data</div>
        <div class="sw-card-sub">Unduh atau unggah data massal via CSV / Excel</div>
      </div>
    </div>
  </div>
  <div class="ei-grid">
    <!-- Ekspor -->
    <div class="ei-col">
      <div class="ei-section-label">📤 Ekspor Data</div>
      <div class="btn-row">
        <a href="siswa.php?export=excel" class="sw-btn btn-green">📊 Excel (.xls)</a>
        <a href="siswa.php?export=csv"   class="sw-btn btn-blue">📄 CSV</a>
        <a href="siswa.php?export=template" class="sw-btn btn-pur">📋 Template</a>
      </div>
      <p class="note-text">Unduh data dalam format Excel atau CSV. Gunakan <b>Template</b> sebagai panduan format saat mengimpor.</p>
    </div>
    <!-- Impor -->
    <div class="ei-col">
      <div class="ei-section-label">📥 Impor Data (CSV)</div>
      <form method="POST" enctype="multipart/form-data" action="siswa.php" id="importForm">
        <input type="hidden" name="import_csv" value="1">
        <div class="sw-dropzone" id="dropzone">
          <span class="dz-icon" id="dzIco">📂</span>
          <div class="dz-text">Seret &amp; lepas, atau <span onclick="document.getElementById('csvFile').click()">pilih file CSV</span></div>
          <div class="dz-hint">Format .CSV · Maks 5MB</div>
          <input type="file" id="csvFile" name="csv_file" accept=".csv,.CSV" required>
          <div id="csvBadge" style="display:none"><div class="file-badge">📄 <span id="csvName"></span></div></div>
        </div>
        <p class="note-text" style="margin:10px 0">⚠️ NIS sama → data akan <b>diperbarui</b>, tidak diduplikat.</p>
        <button type="submit" class="sw-btn btn-primary btn-lg btn-w100" id="impBtn">
          <span id="impBtnTxt">📥 Mulai Impor</span>
        </button>
      </form>
    </div>
  </div>
</div>

<!-- ════════ FORM TAMBAH / EDIT ════════ -->
<div class="sw-card anim-2" id="formCard"
     style="<?= $edit_data ? 'border-color:#FDE68A;' : '' ?>">
  <div class="sw-card-head"
       style="<?= $edit_data ? 'background:linear-gradient(135deg,#FFFBEB,#FEF9C3);border-bottom-color:#FDE68A;' : '' ?>">
    <div class="sw-card-head-l">
      <div class="sw-card-icon <?= $edit_data ? 'ic-amber' : 'ic-blue' ?>"><?= $edit_data ? '✏️' : '➕' ?></div>
      <div>
        <div class="sw-card-title"><?= $edit_data ? 'Edit Data Siswa' : 'Tambah Siswa Baru' ?></div>
        <div class="sw-card-sub"><?= $edit_data ? 'Memperbarui: '.$edit_data['nama'] : 'Isi semua kolom bertanda bintang (*)' ?></div>
      </div>
    </div>
    <?php if($edit_data): ?>
      <a href="siswa.php" class="sw-btn btn-ghost">✕ Batal</a>
    <?php endif; ?>
  </div>
  <div class="sw-card-body">
  <form method="POST" enctype="multipart/form-data">
  <?php if($edit_data): ?><input type="hidden" name="id" value="<?= $edit_data['id'] ?>"><?php endif; ?>

  <!-- §1 Identitas -->
  <div class="form-section">
    <div class="section-header"><span>👤</span><span class="section-header-text">Data Identitas</span></div>
    <div class="fgrid">
      <div class="fg"><label class="flbl">NIS <span class="freq">*</span></label><input type="text" name="nis" class="fi" placeholder="Nomor Induk Siswa" value="<?= $edit_data?htmlspecialchars($edit_data['nis']):'' ?>" required></div>
      <div class="fg"><label class="flbl">NISN <span class="freq">*</span></label><input type="text" name="nisn" class="fi" placeholder="Nomor Induk Nasional" value="<?= $edit_data?htmlspecialchars($edit_data['nisn']):'' ?>" required></div>
      <div class="fg fw"><label class="flbl">Nama Lengkap <span class="freq">*</span></label><input type="text" name="nama" class="fi" placeholder="Nama lengkap siswa" value="<?= $edit_data?htmlspecialchars($edit_data['nama']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Jenis Kelamin <span class="freq">*</span></label><select name="jk" class="fsel" required><option value="">— Pilih —</option><option value="Laki-laki" <?= $edit_data&&$edit_data['jk']=='Laki-laki'?'selected':'' ?>>♂ Laki-laki</option><option value="Perempuan" <?= $edit_data&&$edit_data['jk']=='Perempuan'?'selected':'' ?>>♀ Perempuan</option></select></div>
      <div class="fg"><label class="flbl">Agama <span class="freq">*</span></label><select name="agama" class="fsel" required><option value="">— Pilih —</option><?php foreach(['Islam','Kristen','Katolik','Hindu','Buddha','Konghucu'] as $a): ?><option value="<?= $a ?>" <?= $edit_data&&$edit_data['agama']==$a?'selected':'' ?>><?= $a ?></option><?php endforeach; ?></select></div>
      <div class="fg"><label class="flbl">Tempat Lahir <span class="freq">*</span></label><input type="text" name="tempat_lahir" class="fi" placeholder="Kota/Kabupaten" value="<?= $edit_data?htmlspecialchars($edit_data['tempat_lahir']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Tanggal Lahir <span class="freq">*</span></label><input type="date" name="tanggal_lahir" class="fi" value="<?= $edit_data?htmlspecialchars($edit_data['tanggal_lahir']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Kelas <span class="freq">*</span></label><input type="text" name="kelas" class="fi" placeholder="Contoh: X IPA 1" value="<?= $edit_data?htmlspecialchars($edit_data['kelas']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Tahun Masuk <span class="freq">*</span></label><select name="tahun_masuk" class="fsel" required><option value="">— Pilih —</option><?php for($y=date('Y');$y>=date('Y')-10;$y--): ?><option value="<?= $y ?>" <?= $edit_data&&$edit_data['tahun_masuk']==$y?'selected':'' ?>><?= $y ?></option><?php endfor; ?></select></div>
      <div class="fg"><label class="flbl">Tanggal Daftar <span class="freq">*</span></label><input type="date" name="tanggal_daftar" class="fi" value="<?= $edit_data?htmlspecialchars($edit_data['tanggal_daftar']):date('Y-m-d') ?>" required></div>
    </div>
  </div>

  <!-- §2 Fisik -->
  <div class="form-section">
    <div class="section-header c-teal"><span>🏃</span><span class="section-header-text">Data Fisik &amp; Keluarga</span></div>
    <div class="fgrid">
      <div class="fg"><label class="flbl">Anak Ke- <span class="freq">*</span></label><input type="number" name="anak_ke" class="fi" placeholder="1" min="1" max="20" value="<?= $edit_data?htmlspecialchars($edit_data['anak_ke']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Jumlah Saudara <span class="freq">*</span></label><input type="number" name="jumlah_saudara" class="fi" placeholder="0" min="0" max="20" value="<?= $edit_data?htmlspecialchars($edit_data['jumlah_saudara']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Tinggi Badan (cm) <span class="fopt">Opsional</span></label><input type="number" name="tinggi_badan" class="fi" placeholder="165" min="50" max="250" value="<?= $edit_data?htmlspecialchars($edit_data['tinggi_badan']):'' ?>"></div>
      <div class="fg"><label class="flbl">Berat Badan (kg) <span class="fopt">Opsional</span></label><input type="number" name="berat_badan" class="fi" placeholder="55" min="10" max="200" value="<?= $edit_data?htmlspecialchars($edit_data['berat_badan']):'' ?>"></div>
      <div class="fg"><label class="flbl">Golongan Darah <span class="fopt">Opsional</span></label><select name="golongan_darah" class="fsel"><option value="">— Pilih —</option><?php foreach(['A','B','AB','O','A+','A-','B+','B-','AB+','AB-','O+','O-'] as $gd): ?><option value="<?= $gd ?>" <?= $edit_data&&$edit_data['golongan_darah']==$gd?'selected':'' ?>><?= $gd ?></option><?php endforeach; ?></select></div>
    </div>
  </div>

  <!-- §3 Alamat -->
  <div class="form-section">
    <div class="section-header c-rose"><span>🏠</span><span class="section-header-text">Data Alamat</span></div>
    <div class="fgrid">
      <div class="fg fw"><label class="flbl">Alamat Lengkap <span class="freq">*</span></label><textarea name="alamat" class="fta" placeholder="Jalan, Gang, No. Rumah" required><?= $edit_data?htmlspecialchars($edit_data['alamat']):'' ?></textarea></div>
      <div class="fg"><label class="flbl">RT <span class="freq">*</span></label><input type="text" name="rt" class="fi" placeholder="001" maxlength="3" value="<?= $edit_data?htmlspecialchars($edit_data['rt']):'' ?>" required></div>
      <div class="fg"><label class="flbl">RW <span class="freq">*</span></label><input type="text" name="rw" class="fi" placeholder="005" maxlength="3" value="<?= $edit_data?htmlspecialchars($edit_data['rw']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Kelurahan/Desa <span class="freq">*</span></label><input type="text" name="kelurahan" class="fi" placeholder="Kelurahan/Desa" value="<?= $edit_data?htmlspecialchars($edit_data['kelurahan']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Kecamatan <span class="freq">*</span></label><input type="text" name="kecamatan" class="fi" placeholder="Kecamatan" value="<?= $edit_data?htmlspecialchars($edit_data['kecamatan']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Kota/Kabupaten <span class="freq">*</span></label><input type="text" name="kota" class="fi" placeholder="Kota/Kabupaten" value="<?= $edit_data?htmlspecialchars($edit_data['kota']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Provinsi <span class="freq">*</span></label><input type="text" name="provinsi" class="fi" placeholder="Provinsi" value="<?= $edit_data?htmlspecialchars($edit_data['provinsi']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Kode Pos <span class="freq">*</span></label><input type="text" name="kode_pos" class="fi" placeholder="12345" maxlength="5" value="<?= $edit_data?htmlspecialchars($edit_data['kode_pos']):'' ?>" required></div>
    </div>
  </div>

  <!-- §4 Kontak -->
  <div class="form-section">
    <div class="section-header c-amber"><span>📱</span><span class="section-header-text">Kontak</span></div>
    <div class="fgrid">
      <div class="fg"><label class="flbl">No. HP Siswa <span class="freq">*</span></label><input type="tel" name="no_telp" class="fi" placeholder="08xx xxxx xxxx" value="<?= $edit_data?htmlspecialchars($edit_data['no_telp']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Email <span class="fopt">Opsional</span></label><input type="email" name="email" class="fi" placeholder="siswa@email.com" value="<?= $edit_data?htmlspecialchars($edit_data['email']):'' ?>"></div>
    </div>
  </div>

  <!-- §5 Orang Tua -->
  <div class="form-section">
    <div class="section-header c-pur"><span>👨‍👩‍👧</span><span class="section-header-text">Data Orang Tua / Wali</span></div>
    <div class="fgrid">
      <div class="fg"><label class="flbl">Nama Ayah <span class="freq">*</span></label><input type="text" name="nama_ayah" class="fi" placeholder="Nama ayah" value="<?= $edit_data?htmlspecialchars($edit_data['nama_ayah']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Nama Ibu <span class="freq">*</span></label><input type="text" name="nama_ibu" class="fi" placeholder="Nama ibu" value="<?= $edit_data?htmlspecialchars($edit_data['nama_ibu']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Pekerjaan Ayah <span class="freq">*</span></label><select name="pekerjaan_ayah" class="fsel" required><option value="">— Pilih —</option><?php foreach($pekerjaan_list as $p): ?><option value="<?= $p ?>" <?= $edit_data&&$edit_data['pekerjaan_ayah']==$p?'selected':'' ?>><?= $p ?></option><?php endforeach; ?></select></div>
      <div class="fg"><label class="flbl">Pekerjaan Ibu <span class="freq">*</span></label><select name="pekerjaan_ibu" class="fsel" required><option value="">— Pilih —</option><?php foreach($pekerjaan_list as $p): ?><option value="<?= $p ?>" <?= $edit_data&&$edit_data['pekerjaan_ibu']==$p?'selected':'' ?>><?= $p ?></option><?php endforeach; ?></select></div>
      <div class="fg"><label class="flbl">Pendidikan Ayah <span class="freq">*</span></label><select name="pendidikan_ayah" class="fsel" required><option value="">— Pilih —</option><?php foreach($pendidikan_list as $p): ?><option value="<?= $p ?>" <?= $edit_data&&$edit_data['pendidikan_ayah']==$p?'selected':'' ?>><?= $p ?></option><?php endforeach; ?></select></div>
      <div class="fg"><label class="flbl">Pendidikan Ibu <span class="freq">*</span></label><select name="pendidikan_ibu" class="fsel" required><option value="">— Pilih —</option><?php foreach($pendidikan_list as $p): ?><option value="<?= $p ?>" <?= $edit_data&&$edit_data['pendidikan_ibu']==$p?'selected':'' ?>><?= $p ?></option><?php endforeach; ?></select></div>
      <div class="fg"><label class="flbl">No. HP Ortu/Wali <span class="freq">*</span></label><input type="tel" name="no_telp_ortu" class="fi" placeholder="08xx xxxx xxxx" value="<?= $edit_data?htmlspecialchars($edit_data['no_telp_ortu']):'' ?>" required></div>
      <div class="fg"><label class="flbl">Nama Wali <span class="fopt">Opsional</span></label><input type="text" name="nama_wali" class="fi" placeholder="Jika ada wali" value="<?= $edit_data?htmlspecialchars($edit_data['nama_wali']):'' ?>"></div>
      <div class="fg"><label class="flbl">Hubungan Wali <span class="fopt">Opsional</span></label><select name="hubungan_wali" class="fsel"><option value="">— Pilih —</option><?php foreach(['Kakek','Nenek','Paman','Bibi','Kakak Kandung','Kakak Tiri','Saudara','Wali Asuh','Lainnya'] as $hw): ?><option value="<?= $hw ?>" <?= $edit_data&&$edit_data['hubungan_wali']==$hw?'selected':'' ?>><?= $hw ?></option><?php endforeach; ?></select></div>
    </div>
  </div>

  <!-- §6 Foto -->
  <div class="form-section">
    <div class="section-header c-teal"><span>📷</span><span class="section-header-text">Pas Foto Siswa</span></div>
    <?php if($edit_data): ?><input type="hidden" name="old_foto" value="<?= htmlspecialchars($edit_data['foto']??'') ?>"><?php endif; ?>
    <div class="foto-wrap">
      <div class="foto-frame" id="fotoBox">
        <?php if($edit_data&&!empty($edit_data['foto'])&&file_exists($edit_data['foto'])): ?>
          <img src="<?= htmlspecialchars($edit_data['foto']) ?>" id="fpreview" alt="Foto">
        <?php else: ?>
          <div class="foto-ph" id="fotoPh">
            <span class="foto-ph-icon">👤</span>
            <span>Foto</span>
          </div>
          <img src="" id="fpreview" style="display:none">
        <?php endif; ?>
      </div>
      <div class="foto-side">
        <input type="file" id="fotoInput" name="foto" accept="image/jpg,image/jpeg,image/png,image/webp">
        <label for="fotoInput" class="sw-btn btn-blue" style="cursor:pointer;display:inline-flex">📁 Pilih Foto</label>
        <div class="foto-note">✅ JPG / PNG / WEBP<br>✅ Maks 2MB &nbsp;·&nbsp; Rasio 3×4</div>
      </div>
    </div>
  </div>

  <!-- §7 Kesehatan -->
  <div class="form-section">
    <div class="section-header c-rose"><span>🏥</span><span class="section-header-text">Riwayat Kesehatan</span></div>
    <div class="fgrid">
      <div class="fg fw"><label class="flbl">Riwayat Penyakit <span class="fopt">Opsional</span></label><textarea name="riwayat_penyakit" class="fta" placeholder="Kosongkan jika tidak ada."><?= $edit_data?htmlspecialchars($edit_data['riwayat_penyakit']):'' ?></textarea></div>
      <div class="fg fw"><label class="flbl">Alergi <span class="fopt">Opsional</span></label><textarea name="alergi" class="fta" style="min-height:72px" placeholder="Kosongkan jika tidak ada."><?= $edit_data?htmlspecialchars($edit_data['alergi']):'' ?></textarea></div>
    </div>
  </div>

  <!-- §8 Prestasi -->
  <div class="form-section">
    <div class="section-header c-green"><span>🏆</span><span class="section-header-text">Prestasi &amp; Catatan</span></div>
    <div class="fgrid">
      <div class="fg fw"><label class="flbl">Prestasi <span class="fopt">Opsional</span></label><textarea name="prestasi" class="fta" placeholder="Contoh: Juara 1 OSN 2024."><?= $edit_data?htmlspecialchars($edit_data['prestasi']):'' ?></textarea></div>
      <div class="fg fw"><label class="flbl">Catatan Khusus <span class="fopt">Opsional</span></label><textarea name="catatan_khusus" class="fta" placeholder="Catatan dari guru/wali kelas."><?= $edit_data?htmlspecialchars($edit_data['catatan_khusus']):'' ?></textarea></div>
    </div>
  </div>

  <div class="form-actions">
    <button type="submit" name="<?= $edit_data?'update':'simpan' ?>"
            class="<?= $edit_data?'btn-update-main':'btn-save-main' ?>">
      <?= $edit_data ? '💾 Perbarui Data' : '✅ Simpan Data Siswa' ?>
    </button>
    <?php if($edit_data): ?>
      <a href="siswa.php" class="sw-btn btn-ghost btn-lg">✕ Batal</a>
    <?php endif; ?>
  </div>

  </form>
  </div>
</div>

<!-- ════════ TABEL DATA SISWA ════════ -->
<div class="sw-card anim-3">
  <div class="sw-card-head">
    <div class="sw-card-head-l">
      <div class="sw-card-icon ic-blue">📋</div>
      <div>
        <div class="sw-card-title">Daftar Siswa</div>
        <div class="sw-card-sub"><?= $total_siswa ?> siswa terdaftar</div>
      </div>
    </div>
    <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
      <a href="siswa_kelas.php" class="sw-btn btn-teal">🏫 Per Kelas</a>
      <span class="count-pill"><?= $total_siswa ?> siswa</span>
    </div>
  </div>

  <!-- Topbar search -->
  <div class="tbl-topbar">
    <div class="search-wrap">
      <input type="text" class="search-input" id="si" placeholder="Cari nama, NIS, kelas…" oninput="doSearch()">
    </div>
    <a href="siswa_kelas.php" class="sw-btn btn-teal" style="flex-shrink:0">🏫 Per Kelas</a>
  </div>

  <!-- ── Desktop Table ── -->
  <div class="tbl-scroll">
    <?php if($total_siswa > 0): ?>
    <table class="sw-table" id="dtbl">
      <thead>
        <tr>
          <th>#</th><th>Foto</th><th>NIS/NISN</th><th>Nama</th><th>JK</th>
          <th>TTL</th><th>Kelas</th><th>T.Masuk</th><th>Kontak</th>
          <th>Orang Tua</th><th>Status</th><th>Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php $no=1; mysqli_data_seek($data,0); while($d=mysqli_fetch_array($data)): ?>
        <tr>
          <td class="td-no"><?= $no++ ?></td>
          <td class="td-photo">
            <?php if(!empty($d['foto'])&&file_exists($d['foto'])): ?>
              <img src="<?= htmlspecialchars($d['foto']) ?>" alt="">
            <?php else: ?><div class="no-photo">👤</div><?php endif; ?>
          </td>
          <td>
            <span class="nis-tag"><?= htmlspecialchars($d['nis']) ?></span>
            <?php if(!empty($d['nisn'])): ?>
              <div style="font-size:11px;color:var(--c-tx4);margin-top:3px;font-family:'JetBrains Mono',monospace"><?= htmlspecialchars($d['nisn']) ?></div>
            <?php endif; ?>
          </td>
          <td class="name-cell">
            <?= htmlspecialchars($d['nama']) ?>
            <small><?= htmlspecialchars($d['agama']) ?> · <?= htmlspecialchars($d['kota']) ?></small>
          </td>
          <td>
            <span class="jk-pill <?= $d['jk']=='Laki-laki'?'jk-m':'jk-f' ?>">
              <?= $d['jk']=='Laki-laki'?'♂':'♀' ?> <?= htmlspecialchars($d['jk']) ?>
            </span>
          </td>
          <td class="info-lines">
            <b><?= htmlspecialchars($d['tempat_lahir']) ?></b><br>
            <span style="font-family:'JetBrains Mono',monospace;font-size:11px;color:var(--c-tx3)"><?= date('d/m/Y',strtotime($d['tanggal_lahir'])) ?></span>
          </td>
          <td>
            <a href="siswa_kelas.php?kelas=<?= urlencode($d['kelas']) ?>" class="kelas-link">
              <?= htmlspecialchars($d['kelas']) ?>
            </a>
          </td>
          <td><span class="code-chip"><?= htmlspecialchars($d['tahun_masuk']) ?></span></td>
          <td class="info-lines">
            <?php if(!empty($d['no_telp'])): ?><div>📱 <?= htmlspecialchars($d['no_telp']) ?></div><?php endif; ?>
            <?php if(!empty($d['email'])): ?><div style="color:var(--c-tx3)">✉️ <?= htmlspecialchars($d['email']) ?></div><?php endif; ?>
            <?php if(!empty($d['no_telp_ortu'])): ?><div>☎️ <?= htmlspecialchars($d['no_telp_ortu']) ?></div><?php endif; ?>
          </td>
          <td class="info-lines">
            <div>Ayah: <b><?= htmlspecialchars($d['nama_ayah']) ?></b></div>
            <div style="font-size:11px;color:var(--c-tx3)"><?= htmlspecialchars($d['pekerjaan_ayah']) ?></div>
            <div style="margin-top:3px">Ibu: <b><?= htmlspecialchars($d['nama_ibu']) ?></b></div>
            <div style="font-size:11px;color:var(--c-tx3)"><?= htmlspecialchars($d['pekerjaan_ibu']) ?></div>
          </td>
          <td>
            <div style="display:flex;flex-direction:column;gap:3px">
              <?php if(!empty($d['riwayat_penyakit'])): ?><span class="tag-item tag-rose">🏥 Penyakit</span><?php endif; ?>
              <?php if(!empty($d['alergi'])): ?><span class="tag-item tag-amber">⚠️ Alergi</span><?php endif; ?>
              <?php if(!empty($d['prestasi'])): ?><span class="tag-item tag-green">🏆 Prestasi</span><?php endif; ?>
              <?php if(empty($d['riwayat_penyakit'])&&empty($d['alergi'])&&empty($d['prestasi'])): ?>
                <span style="color:var(--c-tx4);font-size:13px">—</span>
              <?php endif; ?>
            </div>
          </td>
          <td>
            <div class="act-btns">
              <a href="siswa.php?edit=<?= $d['id'] ?>" class="sw-btn btn-amber" style="padding:7px 11px;font-size:12px">✏️ Edit</a>
              <button class="sw-btn btn-danger" style="padding:7px 11px;font-size:12px"
                      onclick="konfirmHapus(<?= $d['id'] ?>,'<?= htmlspecialchars($d['nama'],ENT_QUOTES) ?>')">🗑️</button>
            </div>
          </td>
        </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
    <?php else: ?>
    <div class="empty-state">
      <span class="empty-icon">📚</span>
      <div class="empty-title">Belum ada data siswa</div>
      <div class="empty-sub">Gunakan form di atas untuk menambahkan siswa pertama</div>
    </div>
    <?php endif; ?>
  </div>

  <!-- ── Mobile Cards ── -->
  <div class="mob-list" id="mobList">
    <?php if($total_siswa > 0): mysqli_data_seek($data,0); while($d=mysqli_fetch_array($data)): ?>
    <div class="mob-card"
         data-search="<?= strtolower(htmlspecialchars($d['nama'].' '.$d['nis'].' '.$d['kelas'].' '.$d['nisn'])) ?>">
      <div class="mob-card-top">
        <div class="mob-photo">
          <?php if(!empty($d['foto'])&&file_exists($d['foto'])): ?>
            <img src="<?= htmlspecialchars($d['foto']) ?>" alt="">
          <?php else: ?>
            <div class="no-photo">👤</div>
          <?php endif; ?>
        </div>
        <div class="mob-info">
          <div class="mob-name"><?= htmlspecialchars($d['nama']) ?></div>
          <div class="mob-nis"><span class="nis-tag"><?= htmlspecialchars($d['nis']) ?></span></div>
          <div class="mob-tags">
            <span class="jk-pill <?= $d['jk']=='Laki-laki'?'jk-m':'jk-f' ?>"><?= $d['jk']=='Laki-laki'?'♂':'♀' ?> <?= htmlspecialchars($d['jk']) ?></span>
            <a href="siswa_kelas.php?kelas=<?= urlencode($d['kelas']) ?>" class="kelas-link">🏫 <?= htmlspecialchars($d['kelas']) ?></a>
            <?php if(!empty($d['riwayat_penyakit'])): ?><span class="tag-item tag-rose">🏥</span><?php endif; ?>
            <?php if(!empty($d['prestasi'])): ?><span class="tag-item tag-green">🏆</span><?php endif; ?>
          </div>
        </div>
      </div>
      <div class="mob-grid">
        <div>
          <div class="mob-field-label">TTL</div>
          <div class="mob-field-value"><?= htmlspecialchars($d['tempat_lahir']) ?>, <?= date('d/m/Y',strtotime($d['tanggal_lahir'])) ?></div>
        </div>
        <div>
          <div class="mob-field-label">Tahun Masuk</div>
          <div class="mob-field-value"><?= htmlspecialchars($d['tahun_masuk']) ?></div>
        </div>
        <div>
          <div class="mob-field-label">HP Siswa</div>
          <div class="mob-field-value"><?= !empty($d['no_telp'])?htmlspecialchars($d['no_telp']):'—' ?></div>
        </div>
        <div>
          <div class="mob-field-label">HP Ortu</div>
          <div class="mob-field-value"><?= !empty($d['no_telp_ortu'])?htmlspecialchars($d['no_telp_ortu']):'—' ?></div>
        </div>
        <div>
          <div class="mob-field-label">Ayah</div>
          <div class="mob-field-value"><?= htmlspecialchars($d['nama_ayah']) ?></div>
        </div>
        <div>
          <div class="mob-field-label">Ibu</div>
          <div class="mob-field-value"><?= htmlspecialchars($d['nama_ibu']) ?></div>
        </div>
        <div style="grid-column:1/-1">
          <div class="mob-field-label">Alamat</div>
          <div class="mob-field-value"><?= htmlspecialchars(mb_substr($d['alamat'],0,55)).(mb_strlen($d['alamat'])>55?'…':'') ?>, <?= htmlspecialchars($d['kota']) ?></div>
        </div>
      </div>
      <div class="mob-actions">
        <a href="siswa.php?edit=<?= $d['id'] ?>" class="sw-btn btn-amber">✏️ Edit</a>
        <button class="sw-btn btn-danger"
                onclick="konfirmHapus(<?= $d['id'] ?>,'<?= htmlspecialchars($d['nama'],ENT_QUOTES) ?>')">🗑️ Hapus</button>
      </div>
    </div>
    <?php endwhile; else: ?>
    <div class="empty-state" style="padding:40px 16px">
      <span class="empty-icon">📚</span>
      <div class="empty-title">Belum ada data siswa</div>
    </div>
    <?php endif; ?>
  </div>

</div><!-- /.sw-card table -->

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

<!-- ════════ MODAL HAPUS ════════ -->
<div class="modal-backdrop" id="delModal">
  <div class="modal-box">
    <div class="modal-icon">⚠️</div>
    <div class="modal-title">Konfirmasi Hapus</div>
    <div class="modal-desc" id="delMsg"></div>
    <div class="modal-footer">
      <button class="sw-btn btn-ghost btn-lg"
              onclick="document.getElementById('delModal').classList.remove('open')">✕ Batal</button>
      <button class="sw-btn btn-danger btn-lg" id="delConfirm">🗑️ Ya, Hapus</button>
    </div>
  </div>
</div>

<script>
/* ── Search ── */
function doSearch(){
  const q = document.getElementById('si').value.toLowerCase().trim();
  // Desktop rows
  document.querySelectorAll('#dtbl tbody tr').forEach(r => {
    r.style.display = r.textContent.toLowerCase().includes(q) ? '' : 'none';
  });
  // Mobile cards
  document.querySelectorAll('#mobList .mob-card').forEach(c => {
    const t = (c.dataset.search || '') + ' ' + c.textContent.toLowerCase();
    c.style.display = t.includes(q) ? '' : 'none';
  });
}

/* ── Delete Modal ── */
let delId = null;
function konfirmHapus(id, nama){
  delId = id;
  document.getElementById('delMsg').textContent =
    `Yakin ingin menghapus data siswa "${nama}"? Tindakan ini tidak dapat dibatalkan.`;
  document.getElementById('delModal').classList.add('open');
}
document.getElementById('delConfirm').addEventListener('click', () => {
  if(delId) location.href = 'siswa.php?hapus=' + delId;
});
document.getElementById('delModal').addEventListener('click', function(e){
  if(e.target === this) this.classList.remove('open');
});
document.addEventListener('keydown', e => {
  if(e.key === 'Escape') document.getElementById('delModal').classList.remove('open');
});

/* ── Foto Preview ── */
document.getElementById('fotoInput')?.addEventListener('change', function(){
  const f = this.files[0]; if(!f) return;
  const r = new FileReader();
  r.onload = e => {
    const p = document.getElementById('fpreview');
    const ph = document.getElementById('fotoPh');
    p.src = e.target.result; p.style.display = 'block';
    if(ph) ph.style.display = 'none';
  };
  r.readAsDataURL(f);
});

/* ── CSV Drag & Drop ── */
const csvFile   = document.getElementById('csvFile');
const csvBadge  = document.getElementById('csvBadge');
const csvNameEl = document.getElementById('csvName');
const dropzone  = document.getElementById('dropzone');

function setCsvFile(file){
  if(!file) return;
  const ext = file.name.split('.').pop().toLowerCase();
  if(ext !== 'csv'){ alert('⚠️ Hanya file .CSV yang diizinkan'); return; }
  if(file.size > 5*1024*1024){ alert('⚠️ Ukuran file maksimal 5MB'); return; }
  const dt = new DataTransfer(); dt.items.add(file); csvFile.files = dt.files;
  csvNameEl.textContent = file.name;
  csvBadge.style.display = 'block';
  document.getElementById('dzIco').textContent = '✅';
}
csvFile?.addEventListener('change', function(){ if(this.files[0]) setCsvFile(this.files[0]); });
if(dropzone){
  dropzone.addEventListener('click', e => {
    if(e.target.tagName !== 'SPAN') csvFile.click();
  });
  ['dragenter','dragover'].forEach(ev =>
    dropzone.addEventListener(ev, e => { e.preventDefault(); dropzone.classList.add('drag'); }));
  ['dragleave','drop'].forEach(ev =>
    dropzone.addEventListener(ev, () => dropzone.classList.remove('drag')));
  dropzone.addEventListener('drop', e => {
    e.preventDefault(); setCsvFile(e.dataTransfer.files[0]);
  });
}
document.getElementById('importForm')?.addEventListener('submit', () => {
  const t = document.getElementById('impBtnTxt');
  const b = document.getElementById('impBtn');
  if(t) t.textContent = '⏳ Mengimpor…';
  if(b){ b.disabled = true; b.style.opacity = '.65'; }
});

/* ── Auto-dismiss alerts ── */
document.querySelectorAll('.sw-alert').forEach(el => {
  setTimeout(() => {
    el.style.transition = 'opacity .4s,transform .4s';
    el.style.opacity = '0';
    el.style.transform = 'translateY(-8px)';
    setTimeout(() => el.remove(), 400);
  }, 5500);
});

/* ── Scroll to form on edit ── */
<?php if($edit_data): ?>
window.addEventListener('load', () => {
  document.getElementById('formCard')?.scrollIntoView({ behavior:'smooth', block:'start' });
});
<?php endif; ?>
</script>