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

$settingsResult = mysqli_query($conn, "SELECT setting_key, setting_value FROM settings");
$settings = [];
if($settingsResult) while($row = mysqli_fetch_assoc($settingsResult))
    $settings[$row['setting_key']] = $row['setting_value'];

function getSetting($key, $default='') { global $settings; return $settings[$key] ?? $default; }

$namaSekolah   = getSetting('nama_sekolah',   'MA As-Syafi\'iyah 02');
$alamatSekolah = getSetting('alamat',          'Jl. Raya Jatiwaringin No.8, Kec. Pondok Gede, Kota Bekasi');
$telp          = getSetting('telp',            '(021) 88888888');
$emailSekolah  = getSetting('email',           'info@sekolah.sch.id');
$website       = getSetting('website',         '');
$kepalaSekolah = getSetting('kepala_sekolah',  'Muhammad Kasim, M.Pd');
$nipKepala     = getSetting('nip_kepala',      '');
$logoSekolah   = getSetting('logo_sekolah',    'assets/sekolah.png');
$tahunAjaran   = getSetting('tahun_ajaran',    date('Y').'/'.((int)date('Y')+1));
$semester      = getSetting('semester',        'Ganjil');
$kotaSurat     = getSetting('kota_surat',      'Kota Bekasi');
$ttdImage     = getSetting('ttd_image',      '');
$capSekolah   = getSetting('cap_sekolah',    '');
$ttdPath  = (!empty($ttdImage)   && file_exists($ttdImage))   ? $ttdImage   : '';
$capPath  = (!empty($capSekolah) && file_exists($capSekolah)) ? $capSekolah : '';
$kodeSekolah   = getSetting('kode_surat', '');
if(empty($kodeSekolah)) $kodeSekolah = 'MA.As-02';
$logoPath = (!empty($logoSekolah) && file_exists($logoSekolah)) ? $logoSekolah : 'assets/sekolah.png';
$jabatanKepalaRaw = getSetting('jabatan_kepala', '');
if(!empty($jabatanKepalaRaw)){
    $jabatanKepala = $jabatanKepalaRaw;
} else {
    $jabatanKepala = 'Kepala Madrasah';
    if(stripos($namaSekolah, 'SMA') !== false || stripos($namaSekolah, 'SMK') !== false)
        $jabatanKepala = 'Kepala Sekolah';
    elseif(stripos($namaSekolah, 'MA') !== false || stripos($namaSekolah, 'Madrasah') !== false)
        $jabatanKepala = 'Kepala Madrasah';
}

$namaYayasan      = getSetting('nama_yayasan',      "Yayasan Perguruan Islam As-Syafi'iyah");
$statusAkreditasi = getSetting('status_akreditasi',  'STATUS TERAKREDITASI A');
$noAkreditasi     = getSetting('no_akreditasi',      '');

$guruResult = mysqli_query($conn, "SELECT id, nama, nip, mapel, jk FROM guru WHERE status='Aktif' ORDER BY nama");
$guruList = [];
if($guruResult) while($row = mysqli_fetch_assoc($guruResult)) $guruList[] = $row;

$siswaResult = mysqli_query($conn, "SELECT id, nis, nisn, nama, kelas, jk, tempat_lahir, tanggal_lahir, alamat, agama, tahun_masuk FROM siswa WHERE status_siswa='Aktif' ORDER BY nama");
$siswaList = [];
if($siswaResult) while($row = mysqli_fetch_assoc($siswaResult)) $siswaList[] = $row;

function getNomorSurat($conn, $kode){
    $bulan = date('m'); $tahun = date('Y');
    $bulanRom = ['I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'];
    $rom = $bulanRom[(int)$bulan - 1];
    $q = mysqli_query($conn, "SELECT COUNT(*)+1 as urut FROM surat WHERE MONTH(tanggal)=$bulan AND YEAR(tanggal)=$tahun AND jenis='Keluar'");
    $r = mysqli_fetch_assoc($q);
    $urut = str_pad($r['urut'] ?? 1, 3, '0', STR_PAD_LEFT);
    return "$urut/$kode/$rom/$tahun";
}

$nomorTugas          = getNomorSurat($conn, "ST/{$kodeSekolah}");
$nomorAktif          = getNomorSurat($conn, "{$kodeSekolah}/Ext./SK");
$nomorKelakuan       = getNomorSurat($conn, "SKB/{$kodeSekolah}");
$nomorPanggil        = getNomorSurat($conn, "{$kodeSekolah}/Ext.B");
$nomorSosialisasi    = getNomorSurat($conn, "{$kodeSekolah}/Ext.B");
$nomorPemberitahuan  = getNomorSurat($conn, "{$kodeSekolah}/Ext.B");
$nomorUndangan       = getNomorSurat($conn, "{$kodeSekolah}/Ext.B");
$nomorASAS           = getNomorSurat($conn, "{$kodeSekolah}/Ext.");
$nomorSkorsing       = getNomorSurat($conn, "{$kodeSekolah}/Ext.B");
$nomorPernyataan     = getNomorSurat($conn, "{$kodeSekolah}/Ext.B");
$nomorPermohonan     = getNomorSurat($conn, "{$kodeSekolah}/Ext.B");
$nomorRaport         = getNomorSurat($conn, "{$kodeSekolah}/Ext.B");

// ══════════════════════════════════════════════════════════════
// SIMPAN SURAT — ke tabel `surat` (arsip) DAN `surat_generator`
// ══════════════════════════════════════════════════════════════
$msg = ''; $msg_type = '';
if(isset($_POST['save_surat'])){
    $jenis_surat = $_POST['jenis_surat'] ?? '';
    $nomor       = mysqli_real_escape_string($conn, trim($_POST['nomor_surat']    ?? ''));
    $tanggal     = mysqli_real_escape_string($conn, trim($_POST['tanggal']        ?? date('Y-m-d')));
    $perihal     = mysqli_real_escape_string($conn, trim($_POST['perihal']        ?? ''));
    $keperluan   = mysqli_real_escape_string($conn, trim($_POST['keperluan_tugas']?? ''));
    $jabatan     = mysqli_real_escape_string($conn, trim($_POST['jabatan']        ?? ''));
    $nip         = mysqli_real_escape_string($conn, trim($_POST['nip']            ?? ''));
    $nama_lengkap= mysqli_real_escape_string($conn, trim($_POST['nama_lengkap']   ?? ''));
    $nisn        = mysqli_real_escape_string($conn, trim($_POST['nisn']           ?? ''));
    $uid         = isset($_SESSION['user_id']) ? intval($_SESSION['user_id']) : 1;

    // Auto-generate nomor untuk surat kelakuan baik
    if(empty($nomor) && $jenis_surat === 'kelakuan'){
        $bulan = date('m'); $tahun = date('Y');
        $bulanRom = ['I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'];
        $rom  = $bulanRom[(int)$bulan - 1];
        $q2   = mysqli_query($conn, "SELECT COUNT(*)+1 as urut FROM surat WHERE MONTH(tanggal)=$bulan AND YEAR(tanggal)=$tahun");
        $r2   = mysqli_fetch_assoc($q2);
        $urut = str_pad($r2['urut'] ?? 1, 3, '0', STR_PAD_LEFT);
        $kode = mysqli_real_escape_string($conn, "SKB/{$kodeSekolah}");
        $nomor = "$urut/$kode/$rom/$tahun";
    }

    $errors = [];
    if(empty($tanggal)) $errors[] = 'Tanggal';
    if(empty($perihal)) $errors[] = 'Perihal / Nama';

    if(!empty($errors)){
        $msg = "Data belum lengkap: ".implode(', ', $errors); $msg_type = 'err';
    } else {
        $dupCek = '';
        if(!empty($nomor)){
            $dupQ = mysqli_query($conn, "SELECT id FROM surat WHERE nomor_surat='$nomor' LIMIT 1");
            if(mysqli_num_rows($dupQ) > 0) $dupCek = " (duplikat nomor)";
        }

        // ── 1. Simpan ke tabel `surat` (arsip utama — tidak diubah) ──
        $q1 = "INSERT INTO surat (jenis, nomor_surat, tanggal, perihal, keterangan, status, prioritas, created_by)
               VALUES ('Keluar', '$nomor', '$tanggal', '$perihal', '$jenis_surat', 'Terkirim', 'Biasa', $uid)";
        if(mysqli_query($conn, $q1)){
            $newId = mysqli_insert_id($conn);

            // ── 2. Simpan ke tabel `surat_generator` (data detail) ──
            $cekTabel = mysqli_query($conn, "SHOW TABLES LIKE 'surat_generator'");
            if(mysqli_num_rows($cekTabel) > 0){
                $q2 = "INSERT INTO surat_generator
                           (jenis_surat, nomor_surat, tanggal_surat, perihal,
                            keperluan_tugas, jabatan, nip, nama_lengkap, nisn)
                       VALUES
                           ('$jenis_surat', '$nomor', '$tanggal', '$perihal',
                            '$keperluan', '$jabatan', '$nip', '$nama_lengkap', '$nisn')";
                mysqli_query($conn, $q2);
                // Jika gagal simpan ke surat_generator, tidak blok proses utama
            }

            $msg = "Surat berhasil disimpan! (ID #{$newId}){$dupCek}"; $msg_type = 'ok';
        } else {
            $msg = "Gagal simpan ke database: ".mysqli_error($conn); $msg_type = 'err';
        }
    }
}
?><!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<title>Generator Surat Resmi</title>
<link rel="icon" href="assets/sekolah.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,500;0,9..40,700;0,9..40,900;1,9..40,400&family=Playfair+Display:ital,wght@0,600;0,900;1,600&family=IBM+Plex+Mono:wght@400;600&display=swap" rel="stylesheet">
<style>
/* ════════════════════════════════════════════════════════════════════
   🎨 ULTRA MODERN VIBRANT DESIGN - Unique & Attractive
   ════════════════════════════════════════════════════════════════════ */

:root{
  --primary:#6366F1;--primary-l:#EEF2FF;--primary-m:#C7D2FE;--primary-d:#4F46E5;
  --secondary:#EC4899;--secondary-l:#FCE7F3;--secondary-m:#F9A8D4;--secondary-d:#DB2777;
  --accent:#14B8A6;--accent-l:#CCFBF1;--accent-m:#5EEAD4;--accent-d:#0D9488;
  --warning:#F59E0B;--warning-l:#FEF3C7;--warning-m:#FCD34D;--warning-d:#D97706;
  --success:#10B981;--success-l:#D1FAE5;--success-m:#6EE7B7;--success-d:#059669;
  --danger:#EF4444;--danger-l:#FEE2E2;--danger-m:#FCA5A5;--danger-d:#DC2626;
  --purple:#A855F7;--purple-l:#F3E8FF;--purple-m:#D8B4FE;--purple-d:#9333EA;
  --cyan:#06B6D4;--cyan-l:#CFFAFE;--cyan-m:#67E8F9;--cyan-d:#0891B2;
  --orange:#F97316;--orange-l:#FFEDD5;--orange-m:#FDBA74;--orange-d:#EA580C;
  --surface:#FFFFFF;
  --bg:linear-gradient(135deg,#F8FAFC 0%,#EEF2FF 50%,#FCE7F3 100%);
  --ink:#0F172A;--ink2:#334155;--ink3:#64748B;--ink4:#94A3B8;
  --border:#E2E8F0;--border2:#CBD5E1;
  --gradient-primary:linear-gradient(135deg,#6366F1,#8B5CF6);
  --gradient-secondary:linear-gradient(135deg,#EC4899,#F43F5E);
  --gradient-accent:linear-gradient(135deg,#14B8A6,#06B6D4);
  --gradient-warm:linear-gradient(135deg,#F59E0B,#F97316);
  --gradient-cool:linear-gradient(135deg,#06B6D4,#3B82F6);
  --gradient-sunset:linear-gradient(135deg,#F97316,#EC4899,#A855F7);
  --gradient-ocean:linear-gradient(135deg,#06B6D4,#14B8A6,#10B981);
  --gradient-fire:linear-gradient(135deg,#F59E0B,#EF4444,#EC4899);
  --sh-sm:0 2px 8px rgba(99,102,241,.08),0 1px 4px rgba(236,72,153,.06);
  --sh-md:0 6px 20px rgba(99,102,241,.12),0 3px 10px rgba(236,72,153,.08);
  --sh-lg:0 15px 50px rgba(99,102,241,.15),0 8px 25px rgba(236,72,153,.1);
  --sh-glow:0 0 40px rgba(99,102,241,.3),0 0 80px rgba(236,72,153,.2);
  --sh-neon:0 0 20px rgba(99,102,241,.5),0 0 40px rgba(236,72,153,.3);
  --r:16px;--r2:24px;--r3:32px;
}

*,*::before,*::after{margin:0;padding:0;box-sizing:border-box}
html{scroll-behavior:smooth}

body{
  font-family:'DM Sans',sans-serif;
  background:var(--bg);
  color:var(--ink);
  min-height:100vh;
  position:relative;
  overflow-x:hidden;
}

body::before{
  content:'';
  position:fixed;
  inset:0;
  background:
    radial-gradient(circle at 20% 50%,rgba(99,102,241,.12) 0%,transparent 50%),
    radial-gradient(circle at 80% 80%,rgba(236,72,153,.12) 0%,transparent 50%),
    radial-gradient(circle at 50% 20%,rgba(20,184,166,.08) 0%,transparent 50%);
  animation:gradientShift 15s ease-in-out infinite;
  pointer-events:none;
  z-index:0;
}

@keyframes gradientShift{
  0%,100%{opacity:.6;transform:scale(1) rotate(0deg)}
  50%{opacity:.8;transform:scale(1.1) rotate(5deg)}
}

body::after{
  content:'';
  position:fixed;
  inset:0;
  background-image:
    radial-gradient(circle,rgba(99,102,241,.4) 1px,transparent 1px),
    radial-gradient(circle,rgba(236,72,153,.3) 1px,transparent 1px);
  background-size:50px 50px,80px 80px;
  background-position:0 0,40px 40px;
  opacity:.15;
  animation:particles 20s linear infinite;
  pointer-events:none;
  z-index:0;
}

@keyframes particles{
  to{transform:translateY(-100px)}
}

/* ════════ TOPBAR ════════ */
.topbar{
  position:sticky;
  top:0;
  z-index:300;
  background:rgba(255,255,255,.85);
  backdrop-filter:blur(12px) saturate(180%);
  border-bottom:2px solid rgba(99,102,241,.2);
  box-shadow:var(--sh-md);
}

.topbar::before{
  content:'';
  position:absolute;
  top:0;left:0;right:0;
  height:4px;
  background:var(--gradient-sunset);
  opacity:.8;
}

.topbar-inner{
  max-width:1400px;
  margin:0 auto;
  padding:0 2rem;
  height:72px;
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:1.5rem;
}

.brand{
  display:flex;
  align-items:center;
  gap:1rem;
  animation:fadeIn .8s ease-out;
  flex-shrink:0;
}

.brand-logo{
  width:52px;
  height:52px;
  border-radius:16px;
  background:var(--gradient-primary);
  border:3px solid rgba(255,255,255,.8);
  box-shadow:var(--sh-glow),inset 0 2px 8px rgba(255,255,255,.4);
  display:flex;
  align-items:center;
  justify-content:center;
  position:relative;
  overflow:hidden;
  animation:logoFloat 3s ease-in-out infinite;
  flex-shrink:0;
}

@keyframes logoFloat{
  0%,100%{transform:translateY(0) rotate(-2deg)}
  50%{transform:translateY(-8px) rotate(2deg)}
}

.brand-logo::before{
  content:'';
  position:absolute;
  inset:-50%;
  background:conic-gradient(from 0deg,transparent,rgba(255,255,255,.5),transparent);
  animation:logoSpin 3s linear infinite;
}

@keyframes logoSpin{
  to{transform:rotate(360deg)}
}

.brand-logo img{
  width:100%;
  height:100%;
  object-fit:contain;
  position:relative;
  z-index:1;
}

.brand-name{
  font-size:1.25rem;
  font-weight:900;
  background:var(--gradient-sunset);
  -webkit-background-clip:text;
  -webkit-text-fill-color:transparent;
  background-clip:text;
  letter-spacing:-.02em;
}

.brand-sub{
  font-size:.8rem;
  color:var(--primary);
  font-weight:600;
  margin-top:2px;
}

.topnav{
  display:flex;
  align-items:center;
  gap:.75rem;
  overflow-x:auto;
  -webkit-overflow-scrolling:touch;
  scrollbar-width:none;
  flex-shrink:1;
  min-width:0;
}

.topnav::-webkit-scrollbar{display:none}

.tnl{
  display:inline-flex;
  align-items:center;
  gap:.5rem;
  padding:.7rem 1.5rem;
  border-radius:50px;
  font-size:.875rem;
  font-weight:700;
  text-decoration:none;
  transition:all .4s cubic-bezier(.34,1.56,.64,1);
  color:var(--ink3);
  border:2px solid transparent;
  position:relative;
  overflow:hidden;
  white-space:nowrap;
  flex-shrink:0;
}

.tnl::before{
  content:'';
  position:absolute;
  inset:0;
  background:var(--gradient-primary);
  opacity:0;
  transition:opacity .3s;
  border-radius:50px;
}

.tnl span{position:relative;z-index:1}

.tnl:hover{
  color:#fff;
  transform:translateY(-3px);
  box-shadow:var(--sh-neon);
}

.tnl:hover::before{opacity:1}

.tnl.active{
  background:var(--gradient-primary);
  color:#fff;
  border-color:rgba(255,255,255,.3);
  box-shadow:var(--sh-glow);
  transform:scale(1.05);
}

.tnl.back{border-color:var(--border)}

/* ════════ MAIN ════════ */
.main{
  position:relative;
  z-index:2;
  max-width:1400px;
  margin:0 auto;
  padding:3rem 2rem;
}

/* ════════ PAGE HEADER ════════ */
.page-hdr{
  margin-bottom:3.5rem;
  text-align:center;
  animation:fadeUp .8s ease-out;
  position:relative;
}

.page-hdr::before{
  content:'✨';
  position:absolute;
  left:10%;
  top:50%;
  font-size:3rem;
  filter:blur(2px);
  opacity:.4;
  animation:floatOrb1 6s ease-in-out infinite;
}

.page-hdr::after{
  content:'💫';
  position:absolute;
  right:10%;
  top:50%;
  font-size:3rem;
  filter:blur(2px);
  opacity:.4;
  animation:floatOrb2 6s ease-in-out infinite;
}

@keyframes floatOrb1{
  0%,100%{transform:translate(0,0) rotate(0deg) scale(1)}
  50%{transform:translate(-20px,-30px) rotate(180deg) scale(1.2)}
}

@keyframes floatOrb2{
  0%,100%{transform:translate(0,0) rotate(0deg) scale(1)}
  50%{transform:translate(20px,-30px) rotate(-180deg) scale(1.2)}
}

.page-eyebrow{
  display:inline-flex;
  align-items:center;
  gap:.75rem;
  background:rgba(255,255,255,.9);
  border:2px solid var(--primary-m);
  color:var(--primary-d);
  border-radius:50px;
  padding:.6rem 1.75rem;
  font-size:.85rem;
  font-weight:800;
  text-transform:uppercase;
  letter-spacing:.12em;
  margin-bottom:1.5rem;
  box-shadow:var(--sh-md);
  position:relative;
  overflow:hidden;
}

.page-eyebrow::before{
  content:'';
  position:absolute;
  inset:0;
  background:var(--gradient-primary);
  opacity:.1;
}

.page-eyebrow::after{
  content:'🎯';
  font-size:1.2rem;
  animation:pulse 2s infinite;
}

@keyframes pulse{
  0%,100%{transform:scale(1)}
  50%{transform:scale(1.15)}
}

.page-title{
  font-family:'Playfair Display',serif;
  font-size:4rem;
  font-weight:900;
  background:var(--gradient-sunset);
  -webkit-background-clip:text;
  -webkit-text-fill-color:transparent;
  background-clip:text;
  line-height:1.1;
  letter-spacing:-.03em;
  margin-bottom:1.25rem;
  animation:titleShine 5s ease-in-out infinite;
  background-size:200% 200%;
}

@keyframes titleShine{
  0%,100%{background-position:0% 50%}
  50%{background-position:100% 50%}
}

.page-title em{
  font-style:italic;
  display:inline-block;
  animation:titleBounce 2s ease-in-out infinite;
}

@keyframes titleBounce{
  0%,100%{transform:translateY(0)}
  50%{transform:translateY(-8px)}
}

.page-desc{
  font-size:1.15rem;
  color:var(--ink3);
  font-weight:500;
  max-width:700px;
  margin:0 auto;
  line-height:1.7;
}

/* ════════ TYPE SELECTOR ════════ */
.type-selector{
  display:flex;
  gap:.875rem;
  margin-bottom:3rem;
  overflow-x:auto;
  overflow-y:hidden;
  padding-bottom:1rem;
  scroll-behavior:smooth;
  -webkit-overflow-scrolling:touch;
  scroll-snap-type:x mandatory;
  scrollbar-width:thin;
  scrollbar-color:var(--primary-m) rgba(226,232,240,.4);
}

.type-selector::-webkit-scrollbar{height:6px}
.type-selector::-webkit-scrollbar-track{background:rgba(226,232,240,.4);border-radius:8px}
.type-selector::-webkit-scrollbar-thumb{background:var(--gradient-primary);border-radius:8px}

.type-card{
  background:rgba(255,255,255,.95);
  backdrop-filter:blur(8px);
  border:2px solid var(--border);
  border-radius:20px;
  padding:1rem .875rem;
  cursor:pointer;
  transition:all .5s cubic-bezier(.34,1.56,.64,1);
  position:relative;
  overflow:hidden;
  text-align:center;
  min-width:135px;
  max-width:135px;
  flex-shrink:0;
  scroll-snap-align:start;
  -webkit-tap-highlight-color:transparent;
}

.type-card::before{
  content:'';
  position:absolute;
  inset:0;
  background:var(--gradient-primary);
  opacity:0;
  transition:opacity .4s;
}

.type-card::after{
  content:'';
  position:absolute;
  bottom:-50%;
  left:-50%;
  width:200%;
  height:200%;
  background:conic-gradient(from 0deg,transparent,rgba(255,255,255,.3),transparent);
  opacity:0;
  transition:opacity .4s;
}

.type-card:hover{
  transform:translateY(-8px) scale(1.03) rotate(-1deg);
  box-shadow:var(--sh-lg);
  border-color:var(--primary-m);
}

.type-card:hover::before{opacity:.08}
.type-card:hover::after{opacity:1;animation:cardShine 2s linear infinite}

@keyframes cardShine{to{transform:rotate(360deg)}}

.type-card.active{
  background:var(--gradient-primary);
  border-color:var(--primary);
  box-shadow:var(--sh-glow);
  transform:scale(1.05) rotate(1deg);
}

.type-card.active *{color:#fff !important}

.type-card.active .tc-ico{
  transform:scale(1.2) rotate(8deg);
  filter:drop-shadow(0 6px 12px rgba(0,0,0,.25));
}

.tc-ico{
  font-size:2.25rem;
  margin-bottom:.625rem;
  display:block;
  transition:transform .5s cubic-bezier(.34,1.56,.64,1);
  filter:drop-shadow(0 3px 6px rgba(0,0,0,.1));
  position:relative;
  z-index:1;
  animation:iconBounce 2s ease-in-out infinite;
}

@keyframes iconBounce{
  0%,100%{transform:translateY(0)}
  50%{transform:translateY(-4px)}
}

.type-card:hover .tc-ico{animation:iconWiggle .5s ease-in-out}

@keyframes iconWiggle{
  0%,100%{transform:rotate(0deg)}
  25%{transform:rotate(-8deg)}
  75%{transform:rotate(8deg)}
}

.tc-num{
  position:absolute;
  top:8px;right:8px;
  font-family:'IBM Plex Mono',monospace;
  font-size:.6rem;font-weight:800;
  background:var(--gradient-warm);
  color:#fff;
  padding:.25rem .55rem;
  border-radius:50px;
  border:2px solid rgba(255,255,255,.9);
  box-shadow:0 2px 6px rgba(0,0,0,.15);
  z-index:2;
}

.tc-title{
  font-size:.8rem;font-weight:800;color:var(--ink);
  margin-bottom:.35rem;line-height:1.25;
  position:relative;z-index:1;
}

.tc-sub{
  font-size:.65rem;color:var(--ink3);font-weight:500;
  line-height:1.35;position:relative;z-index:1;
  display:-webkit-box;-webkit-line-clamp:2;
  -webkit-box-orient:vertical;overflow:hidden;
}

.tc-badge{
  display:inline-flex;align-items:center;gap:.3rem;
  margin-top:.625rem;padding:.3rem .75rem;
  border-radius:50px;font-size:.6rem;font-weight:800;
  text-transform:uppercase;letter-spacing:.05em;border:2px solid;
  position:relative;z-index:1;
}

.tc-badge.gold{background:var(--warning-l);color:var(--warning-d);border-color:var(--warning-m)}
.tc-badge.jade{background:var(--success-l);color:var(--success-d);border-color:var(--success-m)}
.tc-badge.sky{background:var(--cyan-l);color:var(--cyan-d);border-color:var(--cyan-m)}
.tc-badge.violet{background:var(--purple-l);color:var(--purple-d);border-color:var(--purple-m)}
.tc-badge.teal{background:var(--accent-l);color:var(--accent-d);border-color:var(--accent-m)}
.tc-badge.amber{background:var(--orange-l);color:var(--orange-d);border-color:var(--orange-m)}
.tc-badge.rose{background:var(--secondary-l);color:var(--secondary-d);border-color:var(--secondary-m)}
.tc-badge.indigo{background:var(--primary-l);color:var(--primary-d);border-color:var(--primary-m)}
.tc-badge.emerald{background:var(--success-l);color:var(--success-d);border-color:var(--success-m)}
.tc-badge.ruby{background:var(--danger-l);color:var(--danger-d);border-color:var(--danger-m)}


/* ════════ CONTENT LAYOUT ════════ */
.content-area{
  display:grid;
  grid-template-columns:450px 1fr;
  gap:2rem;
  align-items:start;
}

/* ════════ FORM PANEL ════════ */
.form-panel{
  background:rgba(255,255,255,.95);
  backdrop-filter:blur(12px);
  border:2px solid var(--border);
  border-radius:var(--r2);
  overflow:hidden;
  box-shadow:var(--sh-md);
  animation:fadeUp .6s ease-out .1s backwards;
}

.fp-head{
  padding:1.5rem 1.75rem;
  background:var(--gradient-primary);
  display:flex;align-items:center;gap:1rem;
  position:relative;overflow:hidden;
}

.fp-head::before{
  content:'';position:absolute;inset:0;
  background:linear-gradient(45deg,transparent,rgba(255,255,255,.2),transparent);
  transform:translateX(-100%);
  animation:headerShine 3s infinite;
}

@keyframes headerShine{to{transform:translateX(100%)}}

.fp-ico{
  width:48px;height:48px;
  background:rgba(255,255,255,.25);
  border:3px solid rgba(255,255,255,.5);
  border-radius:14px;
  display:flex;align-items:center;justify-content:center;
  font-size:1.5rem;flex-shrink:0;
}

.fp-title{font-size:1.05rem;font-weight:900;color:#fff}
.fp-sub{font-size:.8rem;color:rgba(255,255,255,.85);margin-top:3px}

.fp-body{padding:1.75rem}

.section-label{
  font-size:.75rem;font-weight:800;color:var(--primary);
  text-transform:uppercase;letter-spacing:.12em;
  margin:1.75rem 0 1rem;padding-bottom:.75rem;
  border-bottom:3px solid var(--primary-l);
  display:flex;align-items:center;gap:.5rem;
}

.fg{display:flex;flex-direction:column;gap:.5rem;margin-bottom:1.125rem}

.flbl{
  font-size:.85rem;font-weight:700;color:var(--ink2);
  display:flex;align-items:center;gap:.4rem;
}

.flbl .req{color:var(--danger);font-size:.75rem}

.fi,.fs,.fta{
  width:100%;
  padding:.95rem 1.125rem;
  background:rgba(248,250,252,.8);
  border:2px solid var(--border);
  border-radius:var(--r);
  font-size:.9rem;
  font-family:'DM Sans',sans-serif;
  font-weight:600;color:var(--ink);
  transition:all .3s;outline:none;
  touch-action:manipulation;
}

.fi:focus,.fs:focus,.fta:focus{
  background:#fff;
  border-color:transparent;
  box-shadow:0 0 0 3px var(--primary-m);
  transform:translateY(-2px);
}

.fta{resize:vertical;min-height:90px;line-height:1.6}

.fs{
  appearance:none;
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3E%3Cpath fill='%236366F1' d='M8 10L3 5h10z'/%3E%3C/svg%3E");
  background-repeat:no-repeat;
  background-position:right 1rem center;
  padding-right:3rem;cursor:pointer;
}

.fi-grid{display:grid;grid-template-columns:1fr 1fr;gap:.875rem}
.fi-mono{font-family:'IBM Plex Mono',monospace;font-size:.85rem}

.divider{
  border:none;height:3px;
  background:var(--gradient-cool);
  opacity:.15;border-radius:10px;margin:1.5rem 0;
}

.fp-foot{
  padding:1.25rem 1.75rem;
  background:linear-gradient(135deg,rgba(238,242,255,.6),rgba(252,231,243,.6));
  border-top:2px solid var(--border);
  display:flex;align-items:center;gap:1rem;flex-wrap:wrap;
}

.btn{
  display:inline-flex;align-items:center;gap:.5rem;
  padding:.85rem 1.75rem;border-radius:50px;
  font-size:.9rem;font-weight:800;font-family:'DM Sans',sans-serif;
  border:none;cursor:pointer;
  transition:all .4s cubic-bezier(.34,1.56,.64,1);
  text-decoration:none;white-space:nowrap;
  position:relative;overflow:hidden;
  -webkit-tap-highlight-color:transparent;
}

.btn::before{
  content:'';position:absolute;inset:0;
  background:linear-gradient(45deg,transparent,rgba(255,255,255,.3),transparent);
  transform:translateX(-100%);
}

.btn:hover{transform:translateY(-4px)}

.btn:hover::before{animation:btnShine .6s}
@keyframes btnShine{to{transform:translateX(100%)}}

.btn-primary{background:var(--gradient-primary);color:#fff;box-shadow:var(--sh-md)}
.btn-primary:hover{box-shadow:var(--sh-glow)}
.btn-gold{background:var(--gradient-warm);color:#fff;box-shadow:var(--sh-md)}
.btn-gold:hover{box-shadow:0 8px 25px rgba(245,158,11,.4)}
.btn-jade{background:var(--gradient-ocean);color:#fff;box-shadow:var(--sh-md)}
.btn-jade:hover{box-shadow:0 8px 25px rgba(16,185,129,.4)}
.btn-ghost{background:transparent;color:var(--ink3);border:2px solid var(--border2)}
.btn-ghost:hover{background:rgba(99,102,241,.08);color:var(--primary);border-color:var(--primary-m)}

/* ════════ PREVIEW PANEL ════════ */
.preview-panel{
  position:sticky;top:90px;
  animation:fadeUp .6s ease-out .2s backwards;
}

.pv-toolbar{
  display:flex;align-items:center;
  justify-content:space-between;
  margin-bottom:1.25rem;flex-wrap:wrap;gap:.875rem;
}

.pv-status{
  display:inline-flex;align-items:center;gap:.625rem;
  padding:.65rem 1.5rem;border-radius:50px;
  font-size:.85rem;font-weight:800;
  transition:all .3s;border:2px solid;
}

.pv-status.empty{background:rgba(248,250,252,.9);color:var(--ink4);border-color:var(--border2)}
.pv-status.partial{background:var(--gradient-warm);color:#fff;border-color:var(--warning-m);box-shadow:0 4px 12px rgba(245,158,11,.3)}
.pv-status.full{background:var(--gradient-ocean);color:#fff;border-color:var(--success-m);box-shadow:0 4px 12px rgba(16,185,129,.3)}

.pv-dot{
  width:10px;height:10px;border-radius:50%;
  background:currentColor;flex-shrink:0;animation:pulse 2s infinite;
}

.pv-actions{display:flex;gap:.75rem}

.pv-btn{
  display:inline-flex;align-items:center;gap:.5rem;
  padding:.7rem 1.5rem;border-radius:50px;
  font-size:.875rem;font-weight:800;
  font-family:'DM Sans',sans-serif;
  border:2px solid var(--border);
  background:rgba(255,255,255,.9);color:var(--ink3);
  cursor:pointer;transition:all .3s;
  -webkit-tap-highlight-color:transparent;
}

.pv-btn:hover{
  border-color:var(--primary);color:var(--primary);
  background:#fff;transform:translateY(-3px);box-shadow:var(--sh-md);
}

.pv-btn.print-btn{
  background:var(--gradient-fire);color:#fff;
  border-color:transparent;box-shadow:0 4px 14px rgba(245,158,11,.4);
}

.pv-btn.print-btn:hover{
  box-shadow:0 8px 25px rgba(245,158,11,.5);transform:translateY(-4px);
}

/* ════════ LETTER PREVIEW ════════ */
.letter-outer{
  background:#fff;border-radius:var(--r);
  border:2px solid var(--border);box-shadow:var(--sh-lg);
  transition:all .4s;opacity:.65;
  transform:translateY(10px) scale(.98);
  overflow:hidden;
  font-family:'Times New Roman',serif;
}

.letter-outer.alive{opacity:1;transform:translateY(0) scale(1)}

.kop{
  padding:1rem 1.5rem .75rem;
  border-bottom:4px double #0F172A;
  display:flex;align-items:center;gap:.875rem;background:#fff;
}

.kop-logo{width:100px;height:100px;flex-shrink:0}
.kop-logo img{width:100%;height:100%;object-fit:contain}

.kop-mid{flex:1;text-align:center}

.kop-nama{
  font-size:2rem;font-weight:900;
  font-family:'DM Sans',sans-serif;color:#0F172A;
  letter-spacing:.01em;line-height:1.25;text-transform:uppercase;
}

.kop-alamat{font-size:.80rem;color:#475569;margin-top:2px;line-height:1.4}
.kop-kontak{font-size:.70rem;color:#64748B;margin-top:1px}
.kop-right{width:60px;flex-shrink:0}

.kop-line{
  height:4px;background:var(--gradient-sunset);border-radius:10px;
}

.surat-judul-wrap{
  text-align:center;padding:.875rem 1.5rem .625rem;
  border-bottom:1px solid #E2E8F0;
}

.surat-judul-label{
  font-size:.52rem;letter-spacing:.18em;
  text-transform:uppercase;color:#94A3B8;
  margin-bottom:.2rem;font-family:'DM Sans',sans-serif;
}

.surat-judul{
  font-size:.99rem;font-weight:900;color:#0F172A;
  text-transform:uppercase;letter-spacing:.06em;
  text-decoration:underline;text-underline-offset:3px;
  font-family:'DM Sans',sans-serif;line-height:1.3;
}

.surat-nomor{font-size:.85rem;color:#475569;margin-top:.3rem;font-family:'Times New Roman',serif;letter-spacing:.01em}

.surat-bdy{
  padding:1rem 1.5rem 1.25rem;
  font-size:.72rem;line-height:1.75;color:#0F172A;
}

.surat-bdy p{margin-bottom:.5rem}
.surat-bdy .ph{color:#CBD5E1;font-style:italic}

.stamp-wrap{position:absolute;right:1.5rem;bottom:4.5rem;pointer-events:none}

.stamp-circle{
  width:85px;height:85px;
  border:4px solid var(--success);border-radius:50%;
  display:flex;flex-direction:column;align-items:center;justify-content:center;
  color:var(--success);text-align:center;
  transform:rotate(-12deg);opacity:0;
  transition:all .5s cubic-bezier(.34,1.56,.64,1);
  font-family:'DM Sans',sans-serif;
  background:linear-gradient(135deg,rgba(16,185,129,.1),rgba(6,182,212,.1));
  box-shadow:0 4px 12px rgba(16,185,129,.2);
}

.stamp-circle.show{opacity:.9;transform:rotate(-12deg) scale(1)}

.stamp-ico{font-size:1.75rem;line-height:1}
.stamp-txt{font-size:.48rem;font-weight:900;text-transform:uppercase;letter-spacing:.08em;line-height:1.3;margin-top:2px}

.surat-outer-pos{position:relative}

.data-table{width:100%;font-size:.68rem;margin:.5rem 0 .875rem;line-height:1.6}
.data-table td{vertical-align:top;padding:1px 0}
.data-table td:first-child{width:120px;color:#475569}
.data-table td:nth-child(2){width:16px;text-align:center}
.data-table td:last-child{font-weight:700;color:#0F172A}
.data-table td.ph{color:#CBD5E1;font-style:italic;font-weight:400}

/* ════════ ALERTS & TOASTS ════════ */
.alert-bar{
  display:flex;align-items:center;gap:1.125rem;
  padding:1.25rem 2rem;border-radius:var(--r);
  margin-bottom:2rem;font-size:.95rem;font-weight:700;
  animation:slideD .5s ease-out;border-left:6px solid;box-shadow:var(--sh-md);
}

.alert-bar.ok{background:var(--gradient-ocean);color:#fff;border-color:var(--success)}
.alert-bar.err{background:var(--gradient-secondary);color:#fff;border-color:var(--danger)}

.toast-notif{
  position:fixed;bottom:2rem;right:2rem;z-index:9999;
  padding:1.125rem 1.75rem;border-radius:50px;
  font-size:.95rem;font-weight:800;font-family:'DM Sans',sans-serif;
  box-shadow:var(--sh-lg);display:flex;align-items:center;gap:.875rem;
  animation:toastIn .4s cubic-bezier(.34,1.56,.64,1);
  transition:opacity .4s,transform .4s;max-width:400px;
  line-height:1.5;border:2px solid rgba(255,255,255,.3);
}

.toast-ok{background:var(--gradient-ocean);color:#fff}
.toast-err{background:var(--gradient-secondary);color:#fff}

/* ════════ ANIMATIONS ════════ */
@keyframes fadeIn{from{opacity:0}to{opacity:1}}
@keyframes fadeUp{from{opacity:0;transform:translateY(40px)}to{opacity:1;transform:translateY(0)}}
@keyframes slideD{from{opacity:0;transform:translateY(-25px)}to{opacity:1;transform:translateY(0)}}
@keyframes toastIn{from{opacity:0;transform:translateY(25px) scale(.9)}to{opacity:1;transform:translateY(0) scale(1)}}

/* ════════ UTILITY ════════ */
.form-section{display:none}
.form-section.active{display:block}

/* ════════════════════════════════════════════════════════════════════
   🖨️ PRINT
   ════════════════════════════════════════════════════════════════════ */
@media print{
  *{-webkit-print-color-adjust:exact!important;print-color-adjust:exact!important}
  body::before,body::after,.topbar,.page-hdr,.type-selector,.form-panel,.pv-toolbar,.stamp-wrap,.alert-bar{display:none!important}
  html,body{margin:0!important;padding:0!important;background:#fff!important;width:100%!important}
  .main{margin:0!important;padding:0!important;max-width:100%!important;position:static!important}
  .content-area{display:block!important;margin:0!important;padding:0!important}
  .preview-panel{position:static!important;width:100%!important;padding:0!important;margin:0!important}
  .surat-outer-pos{position:static!important;padding:0!important;margin:0!important}
  .letter-outer{width:100%!important;border:none!important;box-shadow:none!important;border-radius:0!important;opacity:1!important;transform:none!important;page-break-inside:avoid;background:#fff!important}
  .kop{padding:.75rem 1.5rem .625rem!important;border-bottom:4px double #000!important;display:flex!important;background:#fff!important}
  .kop-logo{width:85pt!important;height:85pt!important}
  .kop-nama{font-size:15pt!important;font-weight:900!important;color:#000!important;text-transform:uppercase!important}
  .kop-alamat{font-size:9pt!important;color:#333!important}
  .kop-kontak{font-size:8.5pt!important;color:#555!important}
  .kop-line{height:3px!important;background:#000!important}
  .surat-judul{font-size:11pt!important;font-weight:800!important;color:#000!important;text-decoration:underline!important}
  .surat-nomor{font-size:9pt!important;color:#333!important}
  .surat-bdy{padding:.875rem 1.5rem 1.25rem!important;font-size:10pt!important;line-height:1.8!important;color:#000!important}
  .surat-bdy p,.surat-bdy table,.surat-bdy td{color:#000!important}
  @page{size:A4 portrait;margin:1.5cm 2cm 2cm 2.5cm}
}

/* ════════════════════════════════════════════════════════════════════
   📱 RESPONSIVE
   ════════════════════════════════════════════════════════════════════ */
@media(max-width:1200px){.content-area{grid-template-columns:400px 1fr}}
@media(max-width:1050px){
  .content-area{grid-template-columns:1fr}
  .preview-panel{position:static}
  .type-card{min-width:125px;max-width:125px;padding:.875rem .75rem}
  .tc-ico{font-size:2rem}.tc-title{font-size:.75rem}.tc-sub{font-size:.6rem}
}
@media(max-width:900px){
  .main{padding:2.5rem 1.5rem}.page-title{font-size:3.25rem}
  .topbar-inner{height:auto;min-height:64px;flex-wrap:wrap;padding:.625rem 1.5rem;gap:.5rem}
  .topnav{order:3;width:100%;padding-bottom:.375rem;gap:.5rem}
  .tnl{padding:.55rem 1.125rem;font-size:.82rem}
  .type-selector{margin-bottom:2.25rem;gap:.625rem}
  .type-card{min-width:120px;max-width:120px;padding:.75rem .625rem;border-radius:16px}
  .tc-ico{font-size:1.875rem;margin-bottom:.5rem}.tc-title{font-size:.73rem}
  .tc-badge{padding:.25rem .6rem;font-size:.58rem;margin-top:.5rem}
  .tc-num{font-size:.55rem;top:6px;right:6px;padding:.2rem .4rem}
}
@media(max-width:768px){
  .main{padding:1.75rem 1rem}
  .topbar-inner{padding:.5rem 1rem;height:auto;min-height:56px;flex-wrap:wrap;gap:.375rem}
  .brand{gap:.625rem}
  .brand-logo{width:40px;height:40px;border-radius:12px;animation:none}
  .brand-logo::before{display:none}
  .brand-name{font-size:.95rem}.brand-sub{font-size:.7rem}
  .topnav{order:3;width:100%;gap:.375rem;padding-bottom:.25rem;flex-wrap:nowrap}
  .tnl{padding:.5rem .875rem;font-size:.78rem;flex-shrink:0}
  .tnl.active{transform:scale(1)}
  .page-hdr{margin-bottom:1.75rem}
  .page-hdr::before,.page-hdr::after{display:none}
  .page-eyebrow{font-size:.75rem;padding:.5rem 1.25rem;letter-spacing:.08em}
  .page-title{font-size:2.25rem}.page-desc{font-size:.95rem;padding:0 .25rem}
  .type-selector{gap:.5rem;margin-bottom:1.75rem;padding-bottom:.875rem}
  .type-card{min-width:115px;max-width:115px;padding:.7rem .6rem}
  .tc-ico{font-size:1.75rem;margin-bottom:.4rem}.tc-title{font-size:.7rem}.tc-sub{font-size:.58rem}
  .fp-head{padding:1.125rem 1.25rem;gap:.875rem}
  .fp-ico{width:42px;height:42px;border-radius:12px;font-size:1.25rem}
  .fp-title{font-size:.95rem}.fp-sub{font-size:.75rem;margin-top:2px}
  .fp-body{padding:1.25rem 1rem}
  .section-label{font-size:.7rem;margin:1.25rem 0 .75rem;padding-bottom:.625rem}
  .fg{margin-bottom:.875rem;gap:.4rem}.flbl{font-size:.82rem}
  .fi,.fs,.fta{padding:.8rem .875rem;font-size:max(.875rem, 16px);border-radius:14px}
  .fta{min-height:80px}.fi-grid{gap:.625rem}
  .fp-foot{padding:1rem 1.125rem;gap:.625rem}
  .btn{padding:.75rem 1.375rem;font-size:.85rem}
  .pv-toolbar{flex-direction:column;align-items:stretch;gap:.625rem}
  .pv-status{justify-content:center;text-align:center}
  .pv-actions{justify-content:stretch}
  .pv-btn{justify-content:center;width:100%;padding:.75rem 1rem;font-size:.85rem}
  .kop{padding:.75rem 1rem .625rem;gap:.625rem}
  .kop-logo{width:50px;height:50px}.kop-nama{font-size:.88rem}
  .kop-alamat{font-size:.58rem}.kop-kontak{font-size:.54rem}
  .surat-judul-wrap{padding:.75rem 1rem .5rem}
  .surat-judul{font-size:.82rem}.surat-nomor{font-size:.62rem}
  .surat-bdy{padding:.875rem 1rem 1rem;font-size:.7rem}
  .alert-bar{padding:1rem 1.25rem;font-size:.875rem;gap:.75rem;border-radius:14px}
}
@media(max-width:480px){
  .main{padding:1.25rem .75rem}
  .topbar-inner{padding:.45rem .75rem;gap:.3rem}
  .brand-sub{display:none}.brand-name{font-size:.9rem}
  .brand-logo{width:36px;height:36px;border-radius:10px}
  .tnl{padding:.45rem .75rem;font-size:.75rem}
  .page-title{font-size:1.875rem}
  .page-eyebrow{font-size:.7rem;padding:.45rem 1rem;gap:.5rem}
  .page-desc{font-size:.875rem}
  .type-card{min-width:105px;max-width:105px;padding:.625rem .5rem;border-radius:14px}
  .tc-ico{font-size:1.625rem}.tc-title{font-size:.67rem}
  .tc-sub{font-size:.55rem;-webkit-line-clamp:2}
  .tc-badge{padding:.2rem .5rem;font-size:.55rem;margin-top:.4rem;gap:.2rem}
  .tc-num{font-size:.52rem;top:5px;right:5px;padding:.15rem .35rem}
  .fi-grid{grid-template-columns:1fr}
  .fp-foot{flex-direction:column;gap:.5rem}
  .btn{width:100%;justify-content:center;padding:.8rem 1.25rem}
  .toast-notif{left:.75rem;right:.75rem;bottom:1rem;border-radius:16px;font-size:.875rem;padding:.875rem 1.125rem;max-width:none}
  .kop{padding:.625rem .875rem .5rem;gap:.5rem}
  .kop-logo{width:44px;height:44px}.kop-nama{font-size:.8rem}
  .surat-bdy{padding:.75rem .875rem .875rem;font-size:.67rem}
}
@media(max-width:360px){
  .main{padding:1rem .625rem}.page-title{font-size:1.625rem}
  .type-card{min-width:98px;max-width:98px;padding:.5rem .4rem}
  .tc-ico{font-size:1.5rem}.tc-title{font-size:.63rem}
  .tnl{padding:.4rem .625rem;font-size:.72rem}
}
.type-selector,.topnav{padding-bottom:.625rem}
@supports (-webkit-touch-callout: none){.fi,.fs,.fta{font-size:16px}}
@supports(padding-top: env(safe-area-inset-top)){
  .topbar{padding-top:env(safe-area-inset-top)}
  .main{padding-left:max(1rem, env(safe-area-inset-left));padding-right:max(1rem, env(safe-area-inset-right))}
  .toast-notif{bottom:calc(1.5rem + env(safe-area-inset-bottom))}
}
</style>
</head>
<body>
<header class="topbar">
  <div class="topbar-inner">
    <div class="brand">
      <div class="brand-logo"><img src="assets/sekolah.png" alt="Logo"></div>
      <div>
        <div class="brand-name">Generator Surat Resmi</div>
        <div class="brand-sub"><?= htmlspecialchars($namaSekolah) ?></div>
      </div>
    </div>
    <nav class="topnav">
      <a href="surat.php" class="tnl">Keluar</a>
      <a href="suratkeluar.php" class="tnl active">Dashboard Surat</a>
    </nav>
  </div>
</header>

<div class="main">
<div class="page-hdr">
  <div class="page-eyebrow">Dokumen Surat Resmi</div>
  <h1 class="page-title"> MA AS-SYAFI'IYAH 02 KOTA BEKASI <em>Surat Resmi</em></h1>
  <p class="page-desc">Buat surat resmi sekolah secara otomatis. Pilih jenis surat, isi data, dan surat siap cetak.</p>
</div>

<?php if($msg): ?>
<div class="alert-bar <?= $msg_type==='ok'?'ok':'err' ?>">
  <span><?= $msg_type==='ok'?'✅':'❌' ?></span><?= htmlspecialchars($msg) ?>
</div>
<?php endif; ?>

<div class="type-selector">
  <button class="type-card active" data-type="tugas" onclick="switchType('tugas',this)">
    <span class="tc-num">01</span><span class="tc-ico">📋</span>
    <div class="tc-title">Surat Tugas</div>
    <div class="tc-sub">Penugasan guru/staff untuk keperluan dinas atau kegiatan tertentu</div>
    <span class="tc-badge gold">Untuk Guru / Staff</span>
  </button>
  <button class="type-card" data-type="aktif" onclick="switchType('aktif',this)">
    <span class="tc-num">02</span><span class="tc-ico">🎓</span>
    <div class="tc-title">Surat Keterangan Siswa</div>
    <div class="tc-sub">Menerangkan bahwa siswa masih aktif terdaftar di sekolah ini</div>
    <span class="tc-badge jade">Untuk Siswa</span>
  </button>
  <button class="type-card" data-type="kelakuan" onclick="switchType('kelakuan',this)">
    <span class="tc-num">03</span><span class="tc-ico">⭐</span>
    <div class="tc-title">Surat Kelakuan Baik</div>
    <div class="tc-sub">Menerangkan siswa tidak pernah terlibat pelanggaran berat</div>
    <span class="tc-badge sky">Untuk Siswa</span>
  </button>
  <button class="type-card" data-type="panggilan" onclick="switchType('panggilan',this)">
    <span class="tc-num">04</span><span class="tc-ico">📨</span>
    <div class="tc-title">Surat Panggilan Ortu</div>
    <div class="tc-sub">Pemanggilan orang tua/wali murid terkait pelanggaran atau keperluan tertentu</div>
    <span class="tc-badge violet">Untuk Wali Murid</span>
  </button>
  <button class="type-card" data-type="sosialisasi" onclick="switchType('sosialisasi',this)">
    <span class="tc-num">05</span><span class="tc-ico">🏫</span>
    <div class="tc-title">Surat Sosialisasi PPDB</div>
    <div class="tc-sub">Permohonan izin presentasi PPDB ke sekolah lain (MTs/SMP)</div>
    <span class="tc-badge teal">Untuk Sekolah Lain</span>
  </button>
  <button class="type-card" data-type="pemberitahuan" onclick="switchType('pemberitahuan',this)">
    <span class="tc-num">06</span><span class="tc-ico">📢</span>
    <div class="tc-title">Surat Pemberitahuan</div>
    <div class="tc-sub">Pemberitahuan kegiatan sekolah kepada yayasan / pimpinan</div>
    <span class="tc-badge amber">Untuk Yayasan</span>
  </button>
  <button class="type-card" data-type="raport" onclick="switchType('raport',this)">
    <span class="tc-num">07</span><span class="tc-ico">📋</span>
    <div class="tc-title">Pengambilan Raport</div>
    <div class="tc-sub">Pemberitahuan jadwal pengambilan raport kepada orang tua / wali murid</div>
    <span class="tc-badge rose">Untuk Orang Tua</span>
  </button>
  <button class="type-card" data-type="undangan" onclick="switchType('undangan',this)">
    <span class="tc-num">08</span><span class="tc-ico">✉️</span>
    <div class="tc-title">Surat Undangan</div>
    <div class="tc-sub">Undangan kegiatan resmi kepada yayasan / tamu</div>
    <span class="tc-badge rose">Untuk Tamu / Yayasan</span>
  </button>
  <button class="type-card" data-type="asas" onclick="switchType('asas',this)">
    <span class="tc-num">09</span><span class="tc-ico">📝</span>
    <div class="tc-title">Pemberitahuan ASAS</div>
    <div class="tc-sub">Pemberitahuan Asesmen Sumatif Akhir Semester kepada orang tua siswa</div>
    <span class="tc-badge indigo">Untuk Orang Tua</span>
  </button>
  <button class="type-card" data-type="skorsing" onclick="switchType('skorsing',this)">
    <span class="tc-num">10</span><span class="tc-ico">⚠️</span>
    <div class="tc-title">Surat Peringatan Skorsing</div>
    <div class="tc-sub">Pemberitahuan sanksi skorsing siswa kepada orang tua / wali murid</div>
    <span class="tc-badge ruby">Untuk Orang Tua</span>
  </button>
  <button class="type-card" data-type="pernyataan" onclick="switchType('pernyataan',this)">
    <span class="tc-num">11</span><span class="tc-ico">📜</span>
    <div class="tc-title">Surat Pernyataan</div>
    <div class="tc-sub">Pernyataan Kepala Madrasah tentang kebijakan keringanan biaya siswa</div>
    <span class="tc-badge emerald">Keringanan Biaya</span>
  </button>
  <button class="type-card" data-type="permohonan" onclick="switchType('permohonan',this)">
    <span class="tc-num">12</span><span class="tc-ico">🏛️</span>
    <div class="tc-title">Permohonan Penggunaan Aula</div>
    <div class="tc-sub">Izin penggunaan aula / gedung YPIA atau instansi lain untuk kegiatan sekolah</div>
    <span class="tc-badge sky">Ke Yayasan / Instansi</span>
  </button>
</div>

<div class="content-area">
<div class="form-panel" id="formPanel">
  <!-- SURAT TUGAS -->
  <div class="form-section active" id="form-tugas">
    <div class="fp-head">
      <div class="fp-ico">📋</div>
      <div><div class="fp-title">Form Surat Tugas</div><div class="fp-sub">Format resmi MA As-Syafi'iyah 02</div></div>
    </div>
    <div class="fp-body">
      <div class="section-label">🔢 Identitas Surat</div>
      <div class="fg">
        <label class="flbl">Nomor Surat <span class="req">*</span></label>
        <input type="text" id="t_nomor" class="fi fi-mono" value="<?= $nomorTugas ?>" oninput="renderTugas()">
      </div>
      <div class="fg">
        <label class="flbl">Tanggal Surat <span class="req">*</span></label>
        <input type="date" id="t_tanggal" class="fi" value="<?= date('Y-m-d') ?>" oninput="renderTugas()">
      </div>
      <hr class="divider">
      <div class="section-label">👤 Yang Ditugaskan</div>
      <div class="fg">
        <label class="flbl">Pilih Guru / Staff</label>
        <select id="t_guru" class="fs" onchange="pilihGuru()">
          <option value="">— Pilih atau isi manual —</option>
          <?php foreach($guruList as $g): ?>
          <option value="<?= $g['id'] ?>" data-nama="<?= htmlspecialchars($g['nama']) ?>" data-nip="<?= htmlspecialchars($g['nip']) ?>" data-mapel="<?= htmlspecialchars($g['mapel']??'') ?>" data-jk="<?= $g['jk'] ?>">
            <?= htmlspecialchars($g['nama']) ?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="fg">
        <label class="flbl">Nama Lengkap <span class="req">*</span></label>
        <input type="text" id="t_nama" class="fi" placeholder="Nama beserta gelar" oninput="renderTugas()">
      </div>
      <div class="fi-grid">
        <div class="fg">
          <label class="flbl">Jabatan</label>
          <input type="text" id="t_jabatan" class="fi" placeholder="Guru / Staff TU / dll" oninput="renderTugas()">
        </div>
        <div class="fg">
          <label class="flbl">NIP (opsional)</label>
          <input type="text" id="t_nip" class="fi fi-mono" placeholder="NIP" oninput="renderTugas()">
        </div>
      </div>
      <hr class="divider">
      <div class="section-label">📌 Detail Penugasan</div>
      <div class="fg">
        <label class="flbl">Keperluan / Tugas <span class="req">*</span></label>
        <textarea id="t_keperluan" class="fta" placeholder="Cth: Penyerahan Undangan Sosialisasi PPDB" style="min-height:64px" oninput="renderTugas()"></textarea>
      </div>
      <div class="fg">
        <label class="flbl">Hari / Tanggal Pelaksanaan</label>
        <input type="text" id="t_haritgl" class="fi" placeholder="Senin, 26 Januari 2026" oninput="renderTugas()">
      </div>
      <div class="fg">
        <label class="flbl">Tempat (opsional)</label>
        <input type="text" id="t_tempat" class="fi" placeholder="Nama tempat / lokasi" oninput="renderTugas()">
      </div>
      <div class="fg">
        <label class="flbl">Keterangan Tambahan</label>
        <textarea id="t_ket" class="fta" style="min-height:48px" oninput="renderTugas()"></textarea>
      </div>
    </div>
    <div class="fp-foot">
      <button class="btn btn-gold" onclick="printSurat()">🖨️ Cetak</button>
      <button class="btn btn-jade" onclick="saveSurat('tugas')">💾 Simpan ke DB</button>
      <button class="btn btn-ghost" onclick="resetForm('tugas')">↺ Reset</button>
    </div>
  </div>
  <!-- SURAT KETERANGAN AKTIF -->
  <div class="form-section" id="form-aktif">
    <div class="fp-head">
      <div class="fp-ico">🎓</div>
      <div><div class="fp-title">Form Surat Keterangan Siswa</div><div class="fp-sub">Format resmi MA As-Syafi'iyah 02</div></div>
    </div>
    <div class="fp-body">
      <div class="section-label">🔢 Identitas Surat</div>
      <div class="fg">
        <label class="flbl">Nomor Surat <span class="req">*</span></label>
        <input type="text" id="a_nomor" class="fi fi-mono" value="<?= $nomorAktif ?>" oninput="renderAktif()">
      </div>
      <div class="fi-grid">
        <div class="fg">
          <label class="flbl">Tanggal Surat <span class="req">*</span></label>
          <input type="date" id="a_tanggal" class="fi" value="<?= date('Y-m-d') ?>" oninput="renderAktif()">
        </div>
        <div class="fg">
          <label class="flbl">Keperluan (opsional)</label>
          <input type="text" id="a_keperluan" class="fi" placeholder="Beasiswa / BPJS / dll" oninput="renderAktif()">
        </div>
      </div>
      <hr class="divider">
      <div class="section-label">👤 Data Siswa</div>
      <div class="fg">
        <label class="flbl">Pilih Siswa <span class="req">*</span></label>
        <select id="a_siswa" class="fs" onchange="pilihSiswa('a')">
          <option value="">— Pilih siswa atau isi manual —</option>
          <?php foreach($siswaList as $s): ?>
          <option value="<?= $s['id'] ?>"
            data-nama="<?= htmlspecialchars($s['nama']) ?>" data-nis="<?= htmlspecialchars($s['nis']) ?>"
            data-nisn="<?= htmlspecialchars($s['nisn']) ?>" data-kelas="<?= htmlspecialchars($s['kelas']) ?>"
            data-jk="<?= htmlspecialchars($s['jk']) ?>" data-ttl="<?= htmlspecialchars($s['tempat_lahir']) ?>"
            data-tgl="<?= htmlspecialchars($s['tanggal_lahir']) ?>" data-alamat="<?= htmlspecialchars($s['alamat']) ?>"
            data-agama="<?= htmlspecialchars($s['agama']) ?>" data-masuk="<?= htmlspecialchars($s['tahun_masuk']) ?>">
            <?= htmlspecialchars($s['nama']) ?> — <?= htmlspecialchars($s['kelas']) ?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="fg">
        <label class="flbl">Nama Lengkap <span class="req">*</span></label>
        <input type="text" id="a_nama" class="fi" placeholder="Nama siswa" oninput="renderAktif()">
      </div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">NIS</label><input type="text" id="a_nis" class="fi fi-mono" placeholder="NIS" oninput="renderAktif()"></div>
        <div class="fg"><label class="flbl">NISN</label><input type="text" id="a_nisn" class="fi fi-mono" placeholder="NISN" oninput="renderAktif()"></div>
        <div class="fg"><label class="flbl">Kelas</label><input type="text" id="a_kelas" class="fi" placeholder="X. 1 / XI A" oninput="renderAktif()"></div>
        <div class="fg">
          <label class="flbl">Jenis Kelamin</label>
          <select id="a_jk" class="fs" onchange="renderAktif()"><option>Laki-laki</option><option>Perempuan</option></select>
        </div>
        <div class="fg"><label class="flbl">Tempat Lahir</label><input type="text" id="a_ttl" class="fi" placeholder="Bekasi" oninput="renderAktif()"></div>
        <div class="fg"><label class="flbl">Tanggal Lahir</label><input type="date" id="a_tgl_lahir" class="fi" oninput="renderAktif()"></div>
      </div>
      <div class="fg">
        <label class="flbl">Agama</label>
        <select id="a_agama" class="fs" onchange="renderAktif()">
          <?php foreach(['Islam','Kristen','Katolik','Hindu','Buddha','Konghucu'] as $ag): ?>
          <option><?= $ag ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="fg">
        <label class="flbl">Alamat</label>
        <textarea id="a_alamat" class="fta" placeholder="Alamat lengkap siswa..." style="min-height:54px" oninput="renderAktif()"></textarea>
      </div>
    </div>
    <div class="fp-foot">
      <button class="btn btn-gold" onclick="printSurat()">🖨️ Cetak</button>
      <button class="btn btn-jade" onclick="saveSurat('aktif')">💾 Simpan ke DB</button>
      <button class="btn btn-ghost" onclick="resetForm('aktif')">↺ Reset</button>
    </div>
  </div>
  <!-- SURAT KELAKUAN BAIK -->
  <div class="form-section" id="form-kelakuan">
    <div class="fp-head">
      <div class="fp-ico">⭐</div>
      <div><div class="fp-title">Form Surat Kelakuan Baik</div><div class="fp-sub">Format resmi MA As-Syafi'iyah 02</div></div>
    </div>
    <div class="fp-body">
      <div class="section-label">🔢 Identitas Surat</div>
      <div class="fi-grid">
        <div class="fg">
          <label class="flbl">Tanggal Surat <span class="req">*</span></label>
          <input type="date" id="k_tanggal" class="fi" value="<?= date('Y-m-d') ?>" oninput="renderKelakuan()">
        </div>
        <div class="fg">
          <label class="flbl">Keperluan (opsional)</label>
          <input type="text" id="k_keperluan" class="fi" placeholder="Melamar kerja / beasiswa" oninput="renderKelakuan()">
        </div>
      </div>
      <hr class="divider">
      <div class="section-label">👤 Data Siswa</div>
      <div class="fg">
        <label class="flbl">Pilih Siswa <span class="req">*</span></label>
        <select id="k_siswa" class="fs" onchange="pilihSiswa('k')">
          <option value="">— Pilih siswa atau isi manual —</option>
          <?php foreach($siswaList as $s): ?>
          <option value="<?= $s['id'] ?>"
            data-nama="<?= htmlspecialchars($s['nama']) ?>" data-nis="<?= htmlspecialchars($s['nis']) ?>"
            data-nisn="<?= htmlspecialchars($s['nisn']) ?>" data-kelas="<?= htmlspecialchars($s['kelas']) ?>"
            data-jk="<?= htmlspecialchars($s['jk']) ?>" data-ttl="<?= htmlspecialchars($s['tempat_lahir']) ?>"
            data-tgl="<?= htmlspecialchars($s['tanggal_lahir']) ?>" data-agama="<?= htmlspecialchars($s['agama']) ?>"
            data-alamat="<?= htmlspecialchars($s['alamat']) ?>" data-masuk="<?= htmlspecialchars($s['tahun_masuk']) ?>">
            <?= htmlspecialchars($s['nama']) ?> — <?= htmlspecialchars($s['kelas']) ?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="fg"><label class="flbl">Nama Lengkap <span class="req">*</span></label><input type="text" id="k_nama" class="fi" placeholder="Nama siswa" oninput="renderKelakuan()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">NISN</label><input type="text" id="k_nisn" class="fi fi-mono" placeholder="NISN" oninput="renderKelakuan()"></div>
        <div class="fg"><label class="flbl">Kelas</label><input type="text" id="k_kelas" class="fi" placeholder="XII IPS 1" oninput="renderKelakuan()"></div>
      </div>
      <div class="fg"><label class="flbl">Sekolah Asal</label><input type="text" id="k_sekolah_asal" class="fi" value="<?= htmlspecialchars($namaSekolah) ?>" oninput="renderKelakuan()"></div>
      <div class="fg"><label class="flbl">Alamat Sekolah</label><input type="text" id="k_alamat_sekolah" class="fi" value="<?= htmlspecialchars($alamatSekolah) ?>" oninput="renderKelakuan()"></div>
    </div>
    <div class="fp-foot">
      <button class="btn btn-gold" onclick="printSurat()">🖨️ Cetak</button>
      <button class="btn btn-jade" onclick="saveSurat('kelakuan')">💾 Simpan ke DB</button>
      <button class="btn btn-ghost" onclick="resetForm('kelakuan')">↺ Reset</button>
    </div>
  </div>
  <!-- SURAT PANGGILAN ORANG TUA -->
  <div class="form-section" id="form-panggilan">
    <div class="fp-head">
      <div class="fp-ico">📨</div>
      <div><div class="fp-title">Form Surat Panggilan Orang Tua</div><div class="fp-sub">Format resmi MA As-Syafi'iyah 02</div></div>
    </div>
    <div class="fp-body">
      <div class="section-label">🔢 Identitas Surat</div>
      <div class="fg">
        <label class="flbl">Nomor Surat <span class="req">*</span></label>
        <input type="text" id="p_nomor" class="fi fi-mono" value="<?= $nomorPanggil ?>" oninput="renderPanggilan()">
      </div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Lampiran</label><input type="text" id="p_lamp" class="fi" placeholder="-" value="-" oninput="renderPanggilan()"></div>
        <div class="fg"><label class="flbl">Tanggal Surat <span class="req">*</span></label><input type="date" id="p_tanggal" class="fi" value="<?= date('Y-m-d') ?>" oninput="renderPanggilan()"></div>
      </div>
      <div class="fg"><label class="flbl">Perihal</label><input type="text" id="p_perihal" class="fi" value="Pemanggilan Orang Tua" oninput="renderPanggilan()"></div>
      <hr class="divider">
      <div class="section-label">👨‍👩‍👦 Data Siswa</div>
      <div class="fg">
        <label class="flbl">Pilih Siswa</label>
        <select id="p_siswa" class="fs" onchange="pilihSiswa('p')">
          <option value="">— Pilih siswa atau isi manual —</option>
          <?php foreach($siswaList as $s): ?>
          <option value="<?= $s['id'] ?>"
            data-nama="<?= htmlspecialchars($s['nama']) ?>" data-nis="<?= htmlspecialchars($s['nis']) ?>"
            data-nisn="<?= htmlspecialchars($s['nisn']) ?>" data-kelas="<?= htmlspecialchars($s['kelas']) ?>"
            data-jk="<?= htmlspecialchars($s['jk']) ?>" data-ttl="<?= htmlspecialchars($s['tempat_lahir']) ?>"
            data-tgl="<?= htmlspecialchars($s['tanggal_lahir']) ?>" data-agama="<?= htmlspecialchars($s['agama']) ?>"
            data-alamat="<?= htmlspecialchars($s['alamat']) ?>" data-masuk="<?= htmlspecialchars($s['tahun_masuk']) ?>">
            <?= htmlspecialchars($s['nama']) ?> — <?= htmlspecialchars($s['kelas']) ?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="fg"><label class="flbl">Nama Siswa <span class="req">*</span></label><input type="text" id="p_nama" class="fi" placeholder="Nama lengkap siswa" oninput="renderPanggilan()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Kelas</label><input type="text" id="p_kelas" class="fi" placeholder="X. 1 / XII IPS 2" oninput="renderPanggilan()"></div>
        <div class="fg"><label class="flbl">Jenis Kelamin</label><select id="p_jk" class="fs" onchange="renderPanggilan()"><option value="Laki-laki">Laki-laki</option><option value="Perempuan">Perempuan</option></select></div>
      </div>
      <hr class="divider">
      <div class="section-label">⚠️ Detail Pemanggilan</div>
      <div class="fg"><label class="flbl">Alasan Pemanggilan <span class="req">*</span></label><textarea id="p_alasan" class="fta" style="min-height:60px" oninput="renderPanggilan()">melakukan pelanggaran peraturan sekolah</textarea></div>
      <div class="fg"><label class="flbl">Hari / Tanggal Pertemuan <span class="req">*</span></label><input type="text" id="p_haritgl" class="fi" placeholder="Kamis, 21 Agustus 2025" oninput="renderPanggilan()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Jam</label><input type="text" id="p_jam" class="fi" placeholder="08.30" oninput="renderPanggilan()"></div>
        <div class="fg"><label class="flbl">Tempat Pertemuan</label><input type="text" id="p_tempat_pertemuan" class="fi" placeholder="<?= htmlspecialchars($namaSekolah) ?>" oninput="renderPanggilan()"></div>
      </div>
      <div class="fg"><label class="flbl">Catatan Tambahan <span style="font-weight:500;color:var(--ink4);text-transform:none;letter-spacing:0">(opsional)</span></label><textarea id="p_catatan" class="fta" style="min-height:54px" oninput="renderPanggilan()" placeholder="Kosongkan untuk menggunakan teks default (tidak diwakilkan)"></textarea></div>
    </div>
    <div class="fp-foot">
      <button class="btn btn-gold" onclick="printSurat()">🖨️ Cetak Surat</button>
      <button class="btn btn-jade" onclick="saveSurat('panggilan')">💾 Simpan ke DB</button>
      <button class="btn btn-ghost" onclick="resetForm('panggilan')">↺ Reset</button>
    </div>
  </div>
  <!-- SURAT SOSIALISASI PPDB -->
  <div class="form-section" id="form-sosialisasi">
    <div class="fp-head"><div class="fp-ico">🏫</div><div><div class="fp-title">Form Surat Permohonan Sosialisasi PPDB</div><div class="fp-sub">Surat izin presentasi ke MTs/SMP — Format resmi MA As-Syafi'iyah 02</div></div></div>
    <div class="fp-body">
      <div class="section-label">🔢 Identitas Surat</div>
      <div class="fg"><label class="flbl">Nomor Surat <span class="req">*</span></label><input type="text" id="s_nomor" class="fi fi-mono" value="<?= $nomorSosialisasi ?>" oninput="renderSosialisasi()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Lampiran</label><input type="text" id="s_lamp" class="fi" value="-" oninput="renderSosialisasi()"></div>
        <div class="fg"><label class="flbl">Tanggal Surat <span class="req">*</span></label><input type="date" id="s_tanggal" class="fi" value="<?= date('Y-m-d') ?>" oninput="renderSosialisasi()"></div>
      </div>
      <div class="fg"><label class="flbl">Perihal</label><input type="text" id="s_perihal" class="fi" value="Permohonan Sosialisasi PPDB" oninput="renderSosialisasi()"></div>
      <hr class="divider">
      <div class="section-label">🏫 Sekolah Tujuan</div>
      <div class="fg"><label class="flbl">Jabatan Penerima <span class="req">*</span></label><input type="text" id="s_jabatan_tujuan" class="fi" placeholder="Kepala Sekolah MTs Al Hidayah" oninput="renderSosialisasi()"></div>
      <div class="fg"><label class="flbl">Nama Sekolah Tujuan <span class="req">*</span></label><input type="text" id="s_sekolah_tujuan" class="fi" placeholder="MTs Al Hidayah" oninput="renderSosialisasi()"></div>
      <hr class="divider">
      <div class="section-label">📋 Detail Permohonan</div>
      <div class="fg"><label class="flbl">Tahun Pelajaran Lulusan</label><input type="text" id="s_tahun_pelajaran" class="fi" value="<?= htmlspecialchars($tahunAjaran) ?>" oninput="renderSosialisasi()"></div>
      <div class="fg"><label class="flbl">Keterangan Tambahan <span style="font-weight:500;color:var(--ink4);text-transform:none;letter-spacing:0">(opsional)</span></label><textarea id="s_ket" class="fta" style="min-height:54px" oninput="renderSosialisasi()"></textarea></div>
    </div>
    <div class="fp-foot">
      <button class="btn btn-gold" onclick="printSurat()">🖨️ Cetak Surat</button>
      <button class="btn btn-jade" onclick="saveSurat('sosialisasi')">💾 Simpan ke DB</button>
      <button class="btn btn-ghost" onclick="resetForm('sosialisasi')">↺ Reset</button>
    </div>
  </div>
  <!-- SURAT PEMBERITAHUAN KEGIATAN -->
  <div class="form-section" id="form-pemberitahuan">
    <div class="fp-head"><div class="fp-ico">📢</div><div><div class="fp-title">Form Surat Pemberitahuan Kegiatan</div><div class="fp-sub">Pemberitahuan ke yayasan / pimpinan — Format resmi MA As-Syafi'iyah 02</div></div></div>
    <div class="fp-body">
      <div class="section-label">🔢 Identitas Surat</div>
      <div class="fg"><label class="flbl">Nomor Surat <span class="req">*</span></label><input type="text" id="pb_nomor" class="fi fi-mono" value="<?= $nomorPemberitahuan ?>" oninput="renderPemberitahuan()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Lampiran</label><input type="text" id="pb_lamp" class="fi" value="-" oninput="renderPemberitahuan()"></div>
        <div class="fg"><label class="flbl">Tanggal Surat <span class="req">*</span></label><input type="date" id="pb_tanggal" class="fi" value="<?= date('Y-m-d') ?>" oninput="renderPemberitahuan()"></div>
      </div>
      <div class="fg"><label class="flbl">Perihal</label><input type="text" id="pb_perihal" class="fi" value="Pemberitahuan" oninput="renderPemberitahuan()"></div>
      <hr class="divider">
      <div class="section-label">🏛️ Penerima Surat</div>
      <div class="fg"><label class="flbl">Nama Penerima <span class="req">*</span></label><input type="text" id="pb_nama_penerima" class="fi" placeholder="Bapak KH. Ainul Yakin Abdullah Syafi'ie" oninput="renderPemberitahuan()"></div>
      <div class="fg"><label class="flbl">Jabatan Penerima</label><input type="text" id="pb_jabatan_penerima" class="fi" placeholder="Pimpinan YPIA KH. Abdullah Syafi'ie" oninput="renderPemberitahuan()"></div>
      <hr class="divider">
      <div class="section-label">📋 Detail Kegiatan</div>
      <div class="fg"><label class="flbl">Nama Kegiatan <span class="req">*</span></label><input type="text" id="pb_kegiatan" class="fi" placeholder="SuperCamp" oninput="renderPemberitahuan()"></div>
      <div class="fg"><label class="flbl">Hari / Tanggal Kegiatan <span class="req">*</span></label><input type="text" id="pb_haritgl" class="fi" placeholder="Senin-Selasa, 22-23 November 2025" oninput="renderPemberitahuan()"></div>
      <div class="fg"><label class="flbl">Tempat Kegiatan <span class="req">*</span></label><input type="text" id="pb_tempat" class="fi" placeholder="Resort Centhini Gunung Halimun Bogor" oninput="renderPemberitahuan()"></div>
      <div class="fg"><label class="flbl">Peserta Kegiatan</label><input type="text" id="pb_peserta" class="fi" value="Semua Siswa-siswi kelas 10, guru Wali kelas, dan staf" oninput="renderPemberitahuan()"></div>
      <div class="fg"><label class="flbl">Keterangan Tambahan <span style="font-weight:500;color:var(--ink4);text-transform:none;letter-spacing:0">(opsional)</span></label><textarea id="pb_ket" class="fta" style="min-height:54px" oninput="renderPemberitahuan()"></textarea></div>
    </div>
    <div class="fp-foot">
      <button class="btn btn-gold" onclick="printSurat()">🖨️ Cetak Surat</button>
      <button class="btn btn-jade" onclick="saveSurat('pemberitahuan')">💾 Simpan ke DB</button>
      <button class="btn btn-ghost" onclick="resetForm('pemberitahuan')">↺ Reset</button>
    </div>
  </div>
  <!-- SURAT PENGAMBILAN RAPORT -->
  <div class="form-section" id="form-raport">
    <div class="fp-head"><div class="fp-ico">📋</div><div><div class="fp-title">Form Surat Pengambilan Raport</div><div class="fp-sub">Pemberitahuan ke orang tua / wali murid — Format resmi MA As-Syafi'iyah 02</div></div></div>
    <div class="fp-body">
      <div class="section-label">🔢 Identitas Surat</div>
      <div class="fg"><label class="flbl">Nomor Surat <span class="req">*</span></label><input type="text" id="rp_nomor" class="fi fi-mono" value="<?= $nomorRaport ?>" oninput="renderRaport()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Lampiran</label><input type="text" id="rp_lamp" class="fi" value="-" oninput="renderRaport()"></div>
        <div class="fg"><label class="flbl">Tanggal Surat <span class="req">*</span></label><input type="date" id="rp_tanggal" class="fi" value="<?= date('Y-m-d') ?>" oninput="renderRaport()"></div>
      </div>
      <div class="fg"><label class="flbl">Perihal</label><input type="text" id="rp_perihal" class="fi" value="Pengambilan Raport Semester Ganjil" oninput="renderRaport()"></div>
      <hr class="divider">
      <div class="section-label">📅 Jadwal Pengambilan</div>
      <div class="fg"><label class="flbl">Hari / Tanggal <span class="req">*</span></label><input type="text" id="rp_haritgl" class="fi" placeholder="Jumat, 19 Desember 2025" oninput="renderRaport()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Waktu</label><input type="text" id="rp_waktu" class="fi" placeholder="08.00 – 11.00 WIB" oninput="renderRaport()"></div>
        <div class="fg"><label class="flbl">Tempat</label><input type="text" id="rp_tempat" class="fi" placeholder="Ruang Kelas X, XI, &amp; XII" oninput="renderRaport()"></div>
      </div>
      <hr class="divider">
      <div class="section-label">✅ Syarat Pengambilan Raport</div>
      <div class="fg"><label class="flbl">Syarat 1</label><input type="text" id="rp_syarat1" class="fi" value="Lunas SPP sampai dengan bulan Desember 2025" oninput="renderRaport()"></div>
      <div class="fg"><label class="flbl">Syarat 2</label><input type="text" id="rp_syarat2" class="fi" value="Lunas Uang LKS &amp; Daftar Ulang" oninput="renderRaport()"></div>
      <div class="fg"><label class="flbl">Syarat 3 <span style="font-weight:500;color:var(--ink4);text-transform:none;letter-spacing:0">(opsional)</span></label><input type="text" id="rp_syarat3" class="fi" value="Biaya Kalender Madrasah Rp. 30.000,-" oninput="renderRaport()"></div>
      <div class="fg"><label class="flbl">Syarat 4 <span style="font-weight:500;color:var(--ink4);text-transform:none;letter-spacing:0">(opsional)</span></label><input type="text" id="rp_syarat4" class="fi" placeholder="Tambahkan syarat lain jika ada" oninput="renderRaport()"></div>
      <div class="fg"><label class="flbl">Keterangan Tambahan <span style="font-weight:500;color:var(--ink4);text-transform:none;letter-spacing:0">(opsional)</span></label><textarea id="rp_ket" class="fta" style="min-height:48px" oninput="renderRaport()"></textarea></div>
    </div>
    <div class="fp-foot">
      <button class="btn btn-gold" onclick="printSurat()">🖨️ Cetak Surat</button>
      <button class="btn btn-jade" onclick="saveSurat('raport')">💾 Simpan ke DB</button>
      <button class="btn btn-ghost" onclick="resetForm('raport')">↺ Reset</button>
    </div>
  </div>
  <!-- SURAT UNDANGAN -->
  <div class="form-section" id="form-undangan">
    <div class="fp-head"><div class="fp-ico">✉️</div><div><div class="fp-title">Form Surat Undangan</div><div class="fp-sub">Undangan kegiatan resmi — Format MA As-Syafi'iyah 02</div></div></div>
    <div class="fp-body">
      <div class="section-label">🔢 Identitas Surat</div>
      <div class="fg"><label class="flbl">Nomor Surat <span class="req">*</span></label><input type="text" id="u_nomor" class="fi fi-mono" value="<?= $nomorUndangan ?>" oninput="renderUndangan()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Lampiran</label><input type="text" id="u_lamp" class="fi" value="-" oninput="renderUndangan()"></div>
        <div class="fg"><label class="flbl">Tanggal Surat <span class="req">*</span></label><input type="date" id="u_tanggal" class="fi" value="<?= date('Y-m-d') ?>" oninput="renderUndangan()"></div>
      </div>
      <div class="fg"><label class="flbl">Perihal</label><input type="text" id="u_perihal" class="fi" value="Undangan" oninput="renderUndangan()"></div>
      <hr class="divider">
      <div class="section-label">👤 Penerima Undangan</div>
      <div class="fg"><label class="flbl">Nama Penerima <span class="req">*</span></label><input type="text" id="u_nama_penerima" class="fi" placeholder="Bapak KH. Ainul Yakin Abdullah Syafi'ie" oninput="renderUndangan()"></div>
      <div class="fg"><label class="flbl">Jabatan Penerima</label><input type="text" id="u_jabatan_penerima" class="fi" placeholder="Pimpinan YPIA KH. Abdullah Syafi'ie" oninput="renderUndangan()"></div>
      <hr class="divider">
      <div class="section-label">📅 Detail Kegiatan</div>
      <div class="fg"><label class="flbl">Nama Kegiatan <span class="req">*</span></label><input type="text" id="u_kegiatan" class="fi" placeholder="Penilaian Kinerja Kepala Madrasah (PKKM)" oninput="renderUndangan()"></div>
      <div class="fg"><label class="flbl">Hari / Tanggal <span class="req">*</span></label><input type="text" id="u_haritgl" class="fi" placeholder="Sabtu, 13 Desember 2025" oninput="renderUndangan()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Waktu</label><input type="text" id="u_waktu" class="fi" placeholder="07.30 s/d selesai" oninput="renderUndangan()"></div>
        <div class="fg"><label class="flbl">Tempat</label><input type="text" id="u_tempat" class="fi" placeholder="<?= htmlspecialchars($namaSekolah) ?>" oninput="renderUndangan()"></div>
      </div>
      <div class="fg"><label class="flbl">Agenda</label><input type="text" id="u_agenda" class="fi" placeholder="Penilaian Kinerja Kepala Madrasah (PKKM) 2025" oninput="renderUndangan()"></div>
      <div class="fg"><label class="flbl">Keterangan Tambahan <span style="font-weight:500;color:var(--ink4);text-transform:none;letter-spacing:0">(opsional)</span></label><textarea id="u_ket" class="fta" style="min-height:48px" oninput="renderUndangan()"></textarea></div>
    </div>
    <div class="fp-foot">
      <button class="btn btn-gold" onclick="printSurat()">🖨️ Cetak Surat</button>
      <button class="btn btn-jade" onclick="saveSurat('undangan')">💾 Simpan ke DB</button>
      <button class="btn btn-ghost" onclick="resetForm('undangan')">↺ Reset</button>
    </div>
  </div>
  <!-- SURAT PEMBERITAHUAN ASAS -->
  <div class="form-section" id="form-asas">
    <div class="fp-head"><div class="fp-ico">📝</div><div><div class="fp-title">Form Pemberitahuan ASAS</div><div class="fp-sub">Asesmen Sumatif Akhir Semester — Format MA As-Syafi'iyah 02</div></div></div>
    <div class="fp-body">
      <div class="section-label">🔢 Identitas Surat</div>
      <div class="fg"><label class="flbl">Nomor Surat <span class="req">*</span></label><input type="text" id="as_nomor" class="fi fi-mono" value="<?= $nomorASAS ?>" oninput="renderASAS()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Perihal</label><input type="text" id="as_perihal" class="fi" value="Pemberitahuan ASAS" oninput="renderASAS()"></div>
        <div class="fg"><label class="flbl">Lampiran</label><input type="text" id="as_lamp" class="fi" value="-" oninput="renderASAS()"></div>
      </div>
      <div class="fg"><label class="flbl">Tanggal Surat <span class="req">*</span></label><input type="date" id="as_tanggal" class="fi" value="<?= date('Y-m-d') ?>" oninput="renderASAS()"></div>
      <hr class="divider">
      <div class="section-label">👨‍👩‍👧 Penerima</div>
      <div class="fg"><label class="flbl">Kelas Penerima</label><input type="text" id="as_kelas_penerima" class="fi" value="X, XI, &amp; XII" oninput="renderASAS()"><span style="font-size:.68rem;color:var(--ink4);margin-top:.25rem">Cth: X, XI, &amp; XII &nbsp;atau&nbsp; X</span></div>
      <hr class="divider">
      <div class="section-label">📅 Jadwal ASAS</div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Tanggal Mulai ASAS <span class="req">*</span></label><input type="date" id="as_tgl_mulai" class="fi" oninput="renderASAS()"></div>
        <div class="fg"><label class="flbl">Tanggal Selesai ASAS <span class="req">*</span></label><input type="date" id="as_tgl_selesai" class="fi" oninput="renderASAS()"></div>
      </div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Biaya ASAS (Rp)</label><input type="text" id="as_biaya" class="fi fi-mono" placeholder="275.000" oninput="renderASAS()"></div>
        <div class="fg"><label class="flbl">Batas Pembayaran</label><input type="date" id="as_tgl_bayar" class="fi" oninput="renderASAS()"></div>
      </div>
      <div class="fg"><label class="flbl">Tahun Pelajaran</label><input type="text" id="as_tahun_pelajaran" class="fi fi-mono" value="<?= htmlspecialchars($tahunAjaran) ?>" oninput="renderASAS()"></div>
      <hr class="divider">
      <div class="section-label">📋 Persyaratan ASAS</div>
      <div class="fg"><label class="flbl">Persyaratan 1</label><input type="text" id="as_syarat1" class="fi" value="Melunasi SPP sampai dengan bulan Desember <?= date('Y') ?>" oninput="renderASAS()"></div>
      <div class="fg"><label class="flbl">Persyaratan 2</label><input type="text" id="as_syarat2" class="fi" value="Melunasi Daftar Ulang bagi kelas XI dan XII" oninput="renderASAS()"></div>
      <div class="fg"><label class="flbl">Persyaratan 3</label><input type="text" id="as_syarat3" class="fi" value="Melunasi LKS." oninput="renderASAS()"></div>
      <div class="fg"><label class="flbl">Persyaratan 4 <span style="font-weight:500;color:var(--ink4);text-transform:none;letter-spacing:0">(opsional)</span></label><input type="text" id="as_syarat4" class="fi" placeholder="Tambahan jika ada..." oninput="renderASAS()"></div>
    </div>
    <div class="fp-foot">
      <button class="btn btn-gold" onclick="printSurat()">🖨️ Cetak Surat</button>
      <button class="btn btn-jade" onclick="saveSurat('asas')">💾 Simpan ke DB</button>
      <button class="btn btn-ghost" onclick="resetForm('asas')">↺ Reset</button>
    </div>
  </div>
  <!-- SURAT PERINGATAN SKORSING -->
  <div class="form-section" id="form-skorsing">
    <div class="fp-head"><div class="fp-ico">⚠️</div><div><div class="fp-title">Form Surat Peringatan / Skorsing</div><div class="fp-sub">Pemberitahuan sanksi skorsing kepada orang tua siswa — Format MA As-Syafi'iyah 02</div></div></div>
    <div class="fp-body">
      <div class="section-label">🔢 Identitas Surat</div>
      <div class="fg"><label class="flbl">Nomor Surat <span class="req">*</span></label><input type="text" id="sk_nomor" class="fi fi-mono" value="<?= $nomorSkorsing ?>" oninput="renderSkorsing()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Lampiran</label><input type="text" id="sk_lamp" class="fi" value="-" oninput="renderSkorsing()"></div>
        <div class="fg"><label class="flbl">Tanggal Surat <span class="req">*</span></label><input type="date" id="sk_tanggal" class="fi" value="<?= date('Y-m-d') ?>" oninput="renderSkorsing()"></div>
      </div>
      <div class="fg"><label class="flbl">Perihal</label><input type="text" id="sk_perihal" class="fi" value="Surat Peringatan" oninput="renderSkorsing()"></div>
      <hr class="divider">
      <div class="section-label">👨‍👩‍👦 Data Siswa</div>
      <div class="fg">
        <label class="flbl">Pilih Siswa <span class="req">*</span></label>
        <select id="sk_siswa" class="fs" onchange="pilihSiswa('sk')">
          <option value="">— Pilih siswa atau isi manual —</option>
          <?php foreach($siswaList as $s): ?>
          <option value="<?= $s['id'] ?>"
            data-nama="<?= htmlspecialchars($s['nama']) ?>" data-nis="<?= htmlspecialchars($s['nis']) ?>"
            data-nisn="<?= htmlspecialchars($s['nisn']) ?>" data-kelas="<?= htmlspecialchars($s['kelas']) ?>"
            data-jk="<?= htmlspecialchars($s['jk']) ?>" data-ttl="<?= htmlspecialchars($s['tempat_lahir']) ?>"
            data-tgl="<?= htmlspecialchars($s['tanggal_lahir']) ?>" data-agama="<?= htmlspecialchars($s['agama']) ?>"
            data-alamat="<?= htmlspecialchars($s['alamat']) ?>" data-masuk="<?= htmlspecialchars($s['tahun_masuk']) ?>">
            <?= htmlspecialchars($s['nama']) ?> — <?= htmlspecialchars($s['kelas']) ?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="fg"><label class="flbl">Nama Siswa <span class="req">*</span></label><input type="text" id="sk_nama" class="fi" placeholder="Nama lengkap siswa" oninput="renderSkorsing()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Kelas <span class="req">*</span></label><input type="text" id="sk_kelas" class="fi" placeholder="XI A" oninput="renderSkorsing()"></div>
        <div class="fg"><label class="flbl">NIS / NISN</label><input type="text" id="sk_nisn" class="fi fi-mono" placeholder="NIS/NISN" oninput="renderSkorsing()"></div>
      </div>
      <hr class="divider">
      <div class="section-label">🚫 Detail Sanksi Skorsing</div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Tanggal Mulai Skorsing <span class="req">*</span></label><input type="date" id="sk_tgl_mulai" class="fi" oninput="renderSkorsing()"></div>
        <div class="fg"><label class="flbl">Tanggal Selesai Skorsing <span class="req">*</span></label><input type="date" id="sk_tgl_selesai" class="fi" oninput="renderSkorsing()"></div>
      </div>
      <div class="fg"><label class="flbl">Jumlah Poin Pelanggaran</label><input type="number" id="sk_poin" class="fi fi-mono" placeholder="125" min="0" oninput="renderSkorsing()"></div>
      <div class="fg"><label class="flbl">Keterangan Pelanggaran <span class="req">*</span></label><textarea id="sk_pelanggaran" class="fta" style="min-height:60px" oninput="renderSkorsing()">melanggar Tata Tertib Peserta Didik Sistem Poin</textarea></div>
      <div class="fg"><label class="flbl">Pesan / Harapan Penutup <span style="font-weight:500;color:var(--ink4);text-transform:none;letter-spacing:0">(opsional)</span></label><textarea id="sk_pesan" class="fta" style="min-height:60px" placeholder="Kosongkan untuk menggunakan teks default" oninput="renderSkorsing()"></textarea></div>
    </div>
    <div class="fp-foot">
      <button class="btn btn-gold" onclick="printSurat()">🖨️ Cetak Surat</button>
      <button class="btn btn-jade" onclick="saveSurat('skorsing')">💾 Simpan ke DB</button>
      <button class="btn btn-ghost" onclick="resetForm('skorsing')">↺ Reset</button>
    </div>
  </div>
  <!-- SURAT PERNYATAAN KEPALA MADRASAH -->
  <div class="form-section" id="form-pernyataan">
    <div class="fp-head"><div class="fp-ico">📜</div><div><div class="fp-title">Form Surat Pernyataan Kepala Madrasah</div><div class="fp-sub">Keringanan biaya sekolah — Format resmi MA As-Syafi'iyah 02</div></div></div>
    <div class="fp-body">
      <div class="section-label">🔢 Identitas Surat</div>
      <div class="fg"><label class="flbl">Nomor Surat <span class="req">*</span></label><input type="text" id="py_nomor" class="fi fi-mono" value="<?= $nomorPernyataan ?>" oninput="renderPernyataan()"></div>
      <div class="fg"><label class="flbl">Tanggal Surat <span class="req">*</span></label><input type="date" id="py_tanggal" class="fi" value="<?= date('Y-m-d') ?>" oninput="renderPernyataan()"></div>
      <hr class="divider">
      <div class="section-label">🖊️ Identitas Penanda Tangan</div>
      <div class="fg"><label class="flbl">Nama Kepala</label><input type="text" id="py_nama_kepala" class="fi" value="<?= htmlspecialchars($kepalaSekolah) ?>" oninput="renderPernyataan()"></div>
      <div class="fg"><label class="flbl">Jabatan Kepala</label><input type="text" id="py_jabatan_kepala" class="fi" value="Kepala Madrasah Aliyah As-Syafi'iyah 02" oninput="renderPernyataan()"></div>
      <hr class="divider">
      <div class="section-label">👤 Data Siswa</div>
      <div class="fg">
        <label class="flbl">Pilih Siswa</label>
        <select id="py_siswa" class="fs" onchange="pilihSiswa('py')">
          <option value="">— Pilih siswa atau isi manual —</option>
          <?php foreach($siswaList as $s): ?>
          <option value="<?= $s['id'] ?>"
            data-nama="<?= htmlspecialchars($s['nama']) ?>" data-nis="<?= htmlspecialchars($s['nis']) ?>"
            data-nisn="<?= htmlspecialchars($s['nisn']) ?>" data-kelas="<?= htmlspecialchars($s['kelas']) ?>"
            data-jk="<?= htmlspecialchars($s['jk']) ?>" data-ttl="<?= htmlspecialchars($s['tempat_lahir']) ?>"
            data-tgl="<?= htmlspecialchars($s['tanggal_lahir']) ?>" data-agama="<?= htmlspecialchars($s['agama']) ?>"
            data-alamat="<?= htmlspecialchars($s['alamat']) ?>" data-masuk="<?= htmlspecialchars($s['tahun_masuk']) ?>">
            <?= htmlspecialchars($s['nama']) ?> — <?= htmlspecialchars($s['kelas']) ?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="fg"><label class="flbl">Nama Siswa <span class="req">*</span></label><input type="text" id="py_nama" class="fi" placeholder="Nama lengkap siswa" oninput="renderPernyataan()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">NISN</label><input type="text" id="py_nisn" class="fi fi-mono" placeholder="NISN" oninput="renderPernyataan()"></div>
        <div class="fg"><label class="flbl">Kelas</label><input type="text" id="py_kelas" class="fi" placeholder="X. 4" oninput="renderPernyataan()"></div>
      </div>
      <hr class="divider">
      <div class="section-label">📋 Kebijakan &amp; Ketentuan</div>
      <div class="fg"><label class="flbl">Jenis Kebijakan</label><input type="text" id="py_kebijakan" class="fi" value="keringanan biaya sekolah selama bersekolah di <?= htmlspecialchars($namaSekolah) ?>" oninput="renderPernyataan()"></div>
      <div class="fg"><label class="flbl">Ketentuan 1</label><input type="text" id="py_ket1" class="fi" value="Siswa wajib rajin mengikuti seluruh kegiatan belajar mengajar." oninput="renderPernyataan()"></div>
      <div class="fg"><label class="flbl">Ketentuan 2</label><input type="text" id="py_ket2" class="fi" value="Siswa tidak diperkenankan melakukan pelanggaran tata tertib atau tindakan kenakalan." oninput="renderPernyataan()"></div>
      <div class="fg"><label class="flbl">Ketentuan 3</label><input type="text" id="py_ket3" class="fi" value="Apabila orang tua/wali siswa di kemudian hari memiliki kemampuan, maka diperkenankan untuk membayar biaya sekolah sebagaimana mestinya." oninput="renderPernyataan()"></div>
      <div class="fg"><label class="flbl">Ketentuan 4</label><input type="text" id="py_ket4" class="fi" value="Jika ketentuan di atas dilanggar, maka surat pernyataan ini dinyatakan tidak berlaku, dan siswa wajib memenuhi kewajiban pembayaran biaya sekolah sesuai dengan ketentuan yang berlaku." oninput="renderPernyataan()"></div>
      <div class="fg"><label class="flbl">Ketentuan 5 <span style="font-weight:500;color:var(--ink4);text-transform:none;letter-spacing:0">(opsional)</span></label><input type="text" id="py_ket5" class="fi" placeholder="Tambahan ketentuan jika ada..." oninput="renderPernyataan()"></div>
      <hr class="divider">
      <div class="section-label">📬 Tembusan</div>
      <div class="fg"><label class="flbl">Tembusan 1</label><input type="text" id="py_tembusan1" class="fi" value="Bendahara" oninput="renderPernyataan()"></div>
      <div class="fg"><label class="flbl">Tembusan 2</label><input type="text" id="py_tembusan2" class="fi" value="Orang Tua/Wali Siswa" oninput="renderPernyataan()"></div>
      <div class="fg"><label class="flbl">Tembusan 3</label><input type="text" id="py_tembusan3" class="fi" value="Arsip" oninput="renderPernyataan()"></div>
    </div>
    <div class="fp-foot">
      <button class="btn btn-gold" onclick="printSurat()">🖨️ Cetak Surat</button>
      <button class="btn btn-jade" onclick="saveSurat('pernyataan')">💾 Simpan ke DB</button>
      <button class="btn btn-ghost" onclick="resetForm('pernyataan')">↺ Reset</button>
    </div>
  </div>
  <!-- SURAT PERMOHONAN PENGGUNAAN AULA -->
  <div class="form-section" id="form-permohonan">
    <div class="fp-head"><div class="fp-ico">🏛️</div><div><div class="fp-title">Form Permohonan Penggunaan Aula</div><div class="fp-sub">Izin tempat kegiatan ke yayasan — Format resmi MA As-Syafi'iyah 02</div></div></div>
    <div class="fp-body">
      <div class="section-label">🔢 Identitas Surat</div>
      <div class="fg"><label class="flbl">Nomor Surat <span class="req">*</span></label><input type="text" id="pm_nomor" class="fi fi-mono" value="<?= $nomorPermohonan ?>" oninput="renderPermohonan()"></div>
      <div class="fi-grid">
        <div class="fg"><label class="flbl">Lampiran</label><input type="text" id="pm_lamp" class="fi" value="-" oninput="renderPermohonan()"></div>
        <div class="fg"><label class="flbl">Tanggal Surat <span class="req">*</span></label><input type="date" id="pm_tanggal" class="fi" value="<?= date('Y-m-d') ?>" oninput="renderPermohonan()"></div>
      </div>
      <div class="fg"><label class="flbl">Perihal <span class="req">*</span></label><input type="text" id="pm_perihal" class="fi" placeholder="Permohonan Penggunaan Aula YPIA KH. Abdullah Syafi'ie" oninput="renderPermohonan()"></div>
      <hr class="divider">
      <div class="section-label">🏛️ Penerima / Pemilik Aula</div>
      <div class="fg"><label class="flbl">Nama Penerima <span class="req">*</span></label><input type="text" id="pm_nama_penerima" class="fi" placeholder="Bapak KH. Ainul Yakin Abdullah Syafi'ie" oninput="renderPermohonan()"></div>
      <div class="fg"><label class="flbl">Jabatan Penerima</label><input type="text" id="pm_jabatan_penerima" class="fi" placeholder="Pimpinan YPIA KH. Abdullah Syafi'ie" oninput="renderPermohonan()"></div>
      <hr class="divider">
      <div class="section-label">📋 Detail Permohonan</div>
      <div class="fg"><label class="flbl">Nama Kegiatan <span class="req">*</span></label><input type="text" id="pm_kegiatan" class="fi" placeholder="Maulid Nabi Muhammad SAW 1447 H / 2025 M" oninput="renderPermohonan()"></div>
      <div class="fg"><label class="flbl">Nama Aula / Gedung <span class="req">*</span></label><input type="text" id="pm_aula" class="fi" placeholder="Aula Utama YPIA KH. Abdullah Syafi'ie" oninput="renderPermohonan()"></div>
      <div class="fg"><label class="flbl">Hari / Tanggal Kegiatan <span class="req">*</span></label><input type="text" id="pm_haritgl" class="fi" placeholder="Selasa, 28 Oktober 2025" oninput="renderPermohonan()"></div>
      <div class="fg"><label class="flbl">Waktu</label><input type="text" id="pm_waktu" class="fi" placeholder="06.00 s.d. selesai" oninput="renderPermohonan()"></div>
      <div class="fg"><label class="flbl">Keterangan Tambahan <span style="font-weight:500;color:var(--ink4);text-transform:none;letter-spacing:0">(opsional)</span></label><textarea id="pm_ket" class="fta" style="min-height:54px" oninput="renderPermohonan()"></textarea></div>
    </div>
    <div class="fp-foot">
      <button class="btn btn-gold" onclick="printSurat()">🖨️ Cetak Surat</button>
      <button class="btn btn-jade" onclick="saveSurat('permohonan')">💾 Simpan ke DB</button>
      <button class="btn btn-ghost" onclick="resetForm('permohonan')">↺ Reset</button>
    </div>
  </div>
</div><!-- /form-panel -->

<div class="preview-panel" id="previewPanel">
  <div class="pv-toolbar">
    <div class="pv-status empty" id="pvStatus">
      <div class="pv-dot"></div>
      <span id="pvStatusTxt">Isi form untuk melihat preview surat</span>
    </div>
    <div class="pv-actions">
      <button class="pv-btn print-btn" onclick="printSurat()">🖨️ Cetak / Simpan PDF</button>
    </div>
  </div>
  <div class="surat-outer-pos">
    <div class="letter-outer" id="letterOuter">
      <div class="kop">
        <div class="kop-logo">
          <img src="<?= htmlspecialchars($logoPath) ?>" alt="Logo"
               onerror="this.style.display='none';this.parentElement.innerHTML='<span style=\'font-size:2.5rem\'>🏫</span>'">
        </div>
        <div class="kop-mid">
          <?php if(!empty($namaYayasan)): ?>
          <div style="font-size:.99rem;font-style:italic;font-weight:900;color:#1a3a8f;margin-bottom:1px;font-family:'DM Sans',sans-serif"><?= htmlspecialchars($namaYayasan) ?></div>
          <?php endif; ?>
          <div class="kop-nama"><?= htmlspecialchars($namaSekolah) ?></div>
          <?php if(!empty($statusAkreditasi)): ?>
          <div style="font-size:.58rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:#1a3a8f;margin-top:1px;font-family:'DM Sans',sans-serif"><?= htmlspecialchars($statusAkreditasi) ?></div>
          <?php endif; ?>
          <div class="kop-alamat">
            <?php if(!empty($noAkreditasi)): ?>
            <span>No. Akreditasi : <?= htmlspecialchars($noAkreditasi) ?></span><br>
            <?php endif; ?>
            <?= htmlspecialchars($alamatSekolah) ?>
          </div>
          <div class="kop-kontak">
            <?= $telp ? 'Telp: '.htmlspecialchars($telp) : '' ?>
            <?= ($telp && $emailSekolah) ? ' &nbsp;&bull;&nbsp; ' : '' ?>
            <?= $emailSekolah ? 'Email: '.htmlspecialchars($emailSekolah) : '' ?>
            <?= ($website && ($telp || $emailSekolah)) ? ' &nbsp;&bull;&nbsp; '.htmlspecialchars($website) : ($website ? htmlspecialchars($website) : '') ?>
          </div>
        </div>
        <div class="kop-right"></div>
      </div>
      <div class="kop-line"></div>
      <div class="surat-judul-wrap" id="pvJudulWrap">
        <div class="surat-judul-label">Surat Resmi</div>
        <div class="surat-judul" id="pvJudul">SURAT TUGAS</div>
        <div class="surat-nomor" id="pvNomor">Nomor : <span id="pvNomorVal" class="ph">—</span></div>
      </div>
      <div class="surat-bdy" id="pvBody">
        <p style="color:#CBD5E1;font-style:italic;text-align:center;padding:2rem 0">Isi form di sebelah kiri...</p>
      </div>
    </div>
    <div class="stamp-wrap">
      <div class="stamp-circle hide" id="pvStamp">
        <div class="stamp-ico">✅</div>
        <div class="stamp-txt">RESMI<br>SEKOLAH</div>
      </div>
    </div>
  </div>
</div>

</div><!-- /content-area -->
</div><!-- /main -->

<script>
const SEKOLAH = {
  nama:          <?= json_encode($namaSekolah) ?>,
  yayasan:       <?= json_encode($namaYayasan) ?>,
  akreditasi:    <?= json_encode($statusAkreditasi) ?>,
  noAkreditasi:  <?= json_encode($noAkreditasi) ?>,
  alamat:        <?= json_encode($alamatSekolah) ?>,
  telp:          <?= json_encode($telp) ?>,
  email:         <?= json_encode($emailSekolah) ?>,
  website:       <?= json_encode($website) ?>,
  kepala:        <?= json_encode($kepalaSekolah) ?>,
  nipKepala:     <?= json_encode($nipKepala) ?>,
  jabatanKepala: <?= json_encode($jabatanKepala) ?>,
  kota:          <?= json_encode($kotaSurat) ?>,
  kodeSekolah:   <?= json_encode($kodeSekolah) ?>,
  tahunAjaran:   <?= json_encode($tahunAjaran) ?>,
  semester:      <?= json_encode($semester) ?>,
  logo:          <?= json_encode($logoPath) ?>,
  ttd:           <?= json_encode($ttdPath) ?>,
  cap:           <?= json_encode($capPath) ?>
};
const BULAN = ['Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];

function buildTTD(tglFmt, jabatan, namaKepala, nipKepala, labelKiri='', extraCss=''){
  const tglHtml = tglFmt
    ? `${esc(SEKOLAH.kota)}, ${esc(tglFmt)}`
    : `<span class="ph">${esc(SEKOLAH.kota)}, — — —</span>`;
  const ttdHtml = SEKOLAH.ttd
    ? `<img src="${esc(SEKOLAH.ttd)}" alt="TTD" style="position:absolute;bottom:24px;left:50%;transform:translateX(-50%);width:170px;height:85px;object-fit:contain;opacity:.95;pointer-events:none">`
    : '';
  const capHtml = SEKOLAH.cap
    ? `<img src="${esc(SEKOLAH.cap)}" alt="Cap" style="position:absolute;bottom:10px;left:50%;transform:translateX(-58%) rotate(-10deg);width:130px;height:130px;object-fit:contain;opacity:.80;pointer-events:none">`
    : '';
  const nipHtml = nipKepala
    ? `<div style="font-size:.62rem;color:#64748B;margin-top:2px">NIP. ${esc(nipKepala)}</div>`
    : '';
  return `<div style="display:flex;justify-content:flex-end;font-size:.72rem;margin-top:.5rem${extraCss ? ';'+extraCss : ''}">
    ${labelKiri ? `<div style="flex:1;padding-top:1.5rem;font-size:.7rem;color:#334155">${labelKiri}</div>` : ''}
    <div style="text-align:center;min-width:185px;position:relative">
      <div style="margin-bottom:.25rem;color:#334155">${tglHtml}</div>
      <div style="font-weight:700;margin-bottom:.3rem;line-height:1.3">${esc(jabatan)}</div>
      <div style="height:72px;position:relative">${ttdHtml}${capHtml}</div>
      <div style="font-weight:700;color:#0F172A;padding-top:2px;display:inline-block;border-top:1.5px solid #0F172A;min-width:165px">
        ${esc(namaKepala) || 'Kepala Sekolah'}
      </div>
      ${nipHtml}
    </div>
  </div>`;
}

let currentType = 'tugas';

function esc(s){ return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
function fmtTgl(val){ if(!val) return null; const d=new Date(val+'T00:00:00'); return `${d.getDate()} ${BULAN[d.getMonth()]} ${d.getFullYear()}`; }
function ph(txt){ return `<span class="ph">${esc(txt||'—')}</span>`; }
function getV(id){ const el=document.getElementById(id); return el?el.value.trim():''; }
function setStatus(level,txt){
  const el=document.getElementById('pvStatus');
  el.className='pv-status '+level;
  document.getElementById('pvStatusTxt').textContent=txt;
}
function setStamp(show){ const s=document.getElementById('pvStamp'); s.className='stamp-circle '+(show?'show':'hide'); }

function switchType(type, btn){
  currentType=type;
  document.querySelectorAll('.type-card').forEach(c=>c.classList.remove('active'));
  btn.classList.add('active');
  document.querySelectorAll('.form-section').forEach(s=>s.classList.remove('active'));
  document.getElementById('form-'+type).classList.add('active');
  const titles={tugas:'SURAT TUGAS',aktif:'SURAT KETERANGAN SISWA AKTIF',kelakuan:'SURAT KETERANGAN BERKELAKUAN BAIK',panggilan:'SURAT PEMANGGILAN ORANG TUA / WALI MURID',sosialisasi:'SURAT PERMOHONAN SOSIALISASI PPDB',pemberitahuan:'SURAT PEMBERITAHUAN',raport:'SURAT PEMBERITAHUAN PENGAMBILAN RAPORT',undangan:'SURAT UNDANGAN',asas:'SURAT PEMBERITAHUAN ASAS',skorsing:'SURAT PERINGATAN / SKORSING',pernyataan:'SURAT PERNYATAAN KEPALA MADRASAH',permohonan:'SURAT PERMOHONAN'};
  document.getElementById('pvJudul').textContent=titles[type];
  document.getElementById('pvNomor').style.display = type !== 'kelakuan' ? '' : 'none';
  if(type==='tugas') renderTugas();
  else if(type==='aktif') renderAktif();
  else if(type==='kelakuan') renderKelakuan();
  else if(type==='panggilan') renderPanggilan();
  else if(type==='sosialisasi') renderSosialisasi();
  else if(type==='pemberitahuan') renderPemberitahuan();
  else if(type==='raport') renderRaport();
  else if(type==='undangan') renderUndangan();
  else if(type==='asas') renderASAS();
  else if(type==='skorsing') renderSkorsing();
  else if(type==='pernyataan') renderPernyataan();
  else renderPermohonan();
  if(window.innerWidth <= 1050){
    setTimeout(()=>{ document.getElementById('formPanel').scrollIntoView({behavior:'smooth',block:'start'}); }, 100);
  }
}

function pilihGuru(){
  const sel=document.getElementById('t_guru');
  const opt=sel.options[sel.selectedIndex];
  if(opt.value){
    document.getElementById('t_nama').value=opt.dataset.nama||'';
    document.getElementById('t_nip').value=opt.dataset.nip||'';
    document.getElementById('t_jabatan').value=opt.dataset.mapel||'';
  }
  renderTugas();
}

function pilihSiswa(prefix){
  const sel=document.getElementById(prefix+'_siswa');
  const opt=sel.options[sel.selectedIndex];
  if(!opt.value) return;
  const set=(id,v)=>{ const el=document.getElementById(prefix+'_'+id); if(el&&v!==undefined) el.value=v; };
  set('nama',opt.dataset.nama); set('nis',opt.dataset.nis); set('nisn',opt.dataset.nisn);
  set('kelas',opt.dataset.kelas); set('ttl',opt.dataset.ttl); set('tgl_lahir',opt.dataset.tgl);
  set('agama',opt.dataset.agama); set('masuk',opt.dataset.masuk);
  const jkEl=document.getElementById(prefix+'_jk');
  if(jkEl&&opt.dataset.jk) jkEl.value=opt.dataset.jk;
  const alEl=document.getElementById(prefix+'_alamat');
  if(alEl&&opt.dataset.alamat) alEl.value=opt.dataset.alamat;
  if(prefix==='a') renderAktif();
  else if(prefix==='k') renderKelakuan();
  else if(prefix==='p') renderPanggilan();
  else if(prefix==='sk') renderSkorsing();
  else if(prefix==='py') renderPernyataan();
  else renderPermohonan();
}

function renderRaport(){
  const nomor=getV('rp_nomor'),lamp=getV('rp_lamp')||'-',tanggal=getV('rp_tanggal'),perihal=getV('rp_perihal')||'Pengambilan Raport Semester Ganjil',haritgl=getV('rp_haritgl'),waktu=getV('rp_waktu'),tempat=getV('rp_tempat'),syarat1=getV('rp_syarat1'),syarat2=getV('rp_syarat2'),syarat3=getV('rp_syarat3'),syarat4=getV('rp_syarat4'),ketTambahan=getV('rp_ket'),tglFmt=fmtTgl(tanggal);
  const filled=[nomor,tanggal,haritgl].filter(v=>v).length;
  document.getElementById('pvJudul').textContent='SURAT PEMBERITAHUAN';document.getElementById('pvNomor').style.display='none';
  if(filled===0) setStatus('empty','Isi form untuk melihat preview surat');
  else if(filled<3) setStatus('partial',`✍️ ${filled}/3 field terisi...`);
  else{setStatus('full','✅ Surat lengkap — siap cetak!');setStamp(true);}
  if(filled<3) setStamp(false);
  document.getElementById('letterOuter').classList.toggle('alive',filled>0);
  const row=(label,val,lebar='130px')=>{const vHtml=val?`<strong>${esc(val)}</strong>`:`<span class="ph">—</span>`;return `<tr><td style="width:${lebar};padding:1px 0;color:#334155;vertical-align:top;white-space:nowrap">${label}</td><td style="width:14px;text-align:center;vertical-align:top;padding:1px 0">:</td><td style="vertical-align:top;padding:1px 0">${vHtml}</td></tr>`;};
  const syaratList=[syarat1,syarat2,syarat3,syarat4].filter(s=>s.trim());
  const syaratHTML=syaratList.length?syaratList.map((s,i)=>`<tr><td style="width:22px;padding:1px 0;vertical-align:top;color:#334155">${i+1}.</td><td style="padding:1px 0;vertical-align:top">${esc(s)}</td></tr>`).join(''):`<tr><td colspan="2" style="color:#CBD5E1;font-style:italic">Belum ada syarat...</td></tr>`;
  document.getElementById('pvBody').innerHTML=`
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1.25rem;line-height:1.85">${row('Nomor',nomor||null,'80px')}${row('Lamp.',lamp,'80px')}${row('Perihal',perihal||null,'80px')}</table>
    <p style="margin-bottom:.2rem;line-height:1.65">Kepada Yth.</p>
    <p style="margin-bottom:.2rem;font-weight:700">Bapak/Ibu Orang Tua Wali Murid</p>
    <p style="margin-bottom:.2rem;font-weight:700">${esc(SEKOLAH.nama)}</p>
    <p style="margin-bottom:1.25rem;line-height:1.75">di-<br>&nbsp;&nbsp;&nbsp;&nbsp;Tempat</p>
    <p style="margin-bottom:.875rem;font-style:italic"><em>Assalamualaikum Wr. Wb.</em></p>
    <p style="margin-bottom:.875rem;line-height:1.65">Semoga Allah SWT. Senantiasa memberikan taufik, hidayah &amp; inayah-Nya untuk kita semua, aamiin.</p>
    <p style="margin-bottom:1rem;line-height:1.75;text-align:justify">Selanjutnya, kami memberitahukan bahwa <strong>${esc(perihal)}</strong> bagi siswa kelas X, XI, &amp; XII akan dilaksanakan pada:</p>
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin:0 0 1rem 1rem;line-height:1.9">${row('Hari/Tanggal',haritgl||null,'130px')}${waktu?row('Waktu','Jam '+waktu,'130px'):''}${tempat?row('Tempat',tempat,'130px'):''}</table>
    ${syaratList.length?`<p style="margin-bottom:.5rem;line-height:1.65;font-weight:700">Syarat pengambilan raport:</p><table style="width:100%;border-collapse:collapse;font-size:.72rem;margin:0 0 1rem 0;line-height:1.85">${syaratHTML}</table>`:''}
    ${ketTambahan?`<p style="margin-bottom:.875rem;line-height:1.75;text-align:justify">${esc(ketTambahan)}</p>`:''}
    <p style="margin-bottom:1.5rem;line-height:1.65">Demikian pemberitahuan ini, atas perhatian dan kerjasamanya, kami ucapkan terima kasih.<br><em>wassalamualaikum Wr. Wb.</em></p>
    ${buildTTD(tglFmt,SEKOLAH.jabatanKepala,SEKOLAH.kepala,SEKOLAH.nipKepala)}`;
}

function renderASAS(){
  const nomor=getV('as_nomor'),perihal=getV('as_perihal')||'Pemberitahuan ASAS',lamp=getV('as_lamp')||'-',tanggal=getV('as_tanggal'),kelasPenerima=getV('as_kelas_penerima')||'X, XI, & XII',tglMulai=getV('as_tgl_mulai'),tglSelesai=getV('as_tgl_selesai'),biaya=getV('as_biaya'),tglBayar=getV('as_tgl_bayar'),tahunPelajaran=getV('as_tahun_pelajaran')||SEKOLAH.tahunAjaran,syarat1=getV('as_syarat1'),syarat2=getV('as_syarat2'),syarat3=getV('as_syarat3'),syarat4=getV('as_syarat4'),tglFmt=fmtTgl(tanggal),tglMulaiFmt=fmtTgl(tglMulai),tglSelesaiFmt=fmtTgl(tglSelesai),tglBayarFmt=fmtTgl(tglBayar);
  const filled=[nomor,tanggal,tglMulai,tglSelesai].filter(v=>v).length;
  document.getElementById('pvJudul').textContent='SURAT PEMBERITAHUAN';document.getElementById('pvNomor').style.display='none';
  if(filled===0) setStatus('empty','Isi form untuk melihat preview surat');
  else if(filled<4) setStatus('partial',`✍️ ${filled}/4 field terisi...`);
  else{setStatus('full','✅ Surat lengkap — siap cetak!');setStamp(true);}
  if(filled<4) setStamp(false);
  document.getElementById('letterOuter').classList.toggle('alive',filled>0);
  let rentang='';
  if(tglMulaiFmt&&tglSelesaiFmt) rentang=`${tglMulaiFmt} s.d ${tglSelesaiFmt}`;
  else if(tglMulaiFmt) rentang=`${tglMulaiFmt}`;
  let kalimatBiaya='';
  if(biaya||tglBayarFmt){
    if(biaya&&tglBayarFmt) kalimatBiaya=`, dengan biaya sebesar <strong>Rp. ${esc(biaya)},-</strong>. Pembayaran paling lambat tanggal <strong>${esc(tglBayarFmt)}</strong>.`;
    else if(biaya) kalimatBiaya=`, dengan biaya sebesar <strong>Rp. ${esc(biaya)},-</strong>.`;
    else kalimatBiaya=`. Pembayaran paling lambat tanggal <strong>${esc(tglBayarFmt)}</strong>.`;
  }
  const syaratList=[syarat1,syarat2,syarat3,syarat4].filter(s=>s.trim());
  const syaratHTML=syaratList.length?`<p style="margin-bottom:.375rem;line-height:1.65">Adapun persyaratan mengikuti ASAS adalah :</p><ol style="margin:0 0 1rem 1.5rem;font-size:.72rem;line-height:1.85">${syaratList.map(s=>`<li>${esc(s)}</li>`).join('')}</ol>`:'';
  document.getElementById('pvBody').innerHTML=`
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1.25rem;line-height:1.85">
      <tr><td style="width:80px;padding:1px 0;color:#334155;white-space:nowrap">Nomor</td><td style="width:14px;text-align:center;padding:1px 0">:</td><td style="padding:1px 0">${nomor?esc(nomor):`<span class="ph">—</span>`}</td></tr>
      <tr><td style="padding:1px 0;color:#334155">Perihal</td><td style="width:14px;text-align:center;padding:1px 0">:</td><td style="padding:1px 0;font-weight:700">${perihal?`<strong>${esc(perihal)}</strong>`:`<span class="ph">—</span>`}</td></tr>
      <tr><td style="padding:1px 0;color:#334155">Lamp.</td><td style="width:14px;text-align:center;padding:1px 0">:</td><td style="padding:1px 0">${esc(lamp)}</td></tr>
    </table>
    <p style="margin-bottom:.2rem;line-height:1.65">Kepada Yth.</p>
    <p style="margin-bottom:.2rem;font-weight:700">Bapak/Ibu Orang Tua kelas ${esc(kelasPenerima)}</p>
    <p style="margin-bottom:.2rem">${esc(SEKOLAH.nama)}</p>
    <p style="margin-bottom:1.25rem;line-height:1.75">di-<br>&nbsp;&nbsp;&nbsp;&nbsp;<u>&nbsp;Tempat&nbsp;</u></p>
    <p style="margin-bottom:.75rem;font-style:italic"><em>Assalamualaikum wr.wb.</em></p>
    <p style="margin-bottom:.875rem;line-height:1.65">Semoga Allah SWT. Senantiasa memberikan taufik, hidayah &amp; inayah-Nya untuk kita semua, aamiin.</p>
    <p style="margin-bottom:1rem;line-height:1.75;text-align:justify">Selanjutnya, kami informasikan bahwa sesuai kalender pendidikan ${esc(SEKOLAH.nama)}, insya Allah <strong>Asesmen Sumatif Akhir Semester Tahun Pelajaran ${esc(tahunPelajaran)}</strong> akan dilaksanakan pada tanggal <strong>${rentang||`<span class="ph">tgl mulai s.d tgl selesai</span>`}</strong>${kalimatBiaya}</p>
    ${syaratHTML}
    <p style="margin-bottom:1.5rem;line-height:1.65">Demikian pemberitahuan ini, atas perhatian dan kerjasamanya, kami mengucapkan terima kasih.<br><em>Wassalamualaikum wr.wb.</em></p>
    ${buildTTD(tglFmt,SEKOLAH.jabatanKepala,SEKOLAH.kepala,SEKOLAH.nipKepala)}`;
}

function renderUndangan(){
  const nomor=getV('u_nomor'),lamp=getV('u_lamp')||'-',tanggal=getV('u_tanggal'),perihal=getV('u_perihal')||'Undangan',namaPenerima=getV('u_nama_penerima'),jabatanPenerima=getV('u_jabatan_penerima'),kegiatan=getV('u_kegiatan'),haritgl=getV('u_haritgl'),waktu=getV('u_waktu'),tempat=getV('u_tempat')||SEKOLAH.nama,agenda=getV('u_agenda'),ketTambahan=getV('u_ket'),tglFmt=fmtTgl(tanggal);
  const filled=[nomor,tanggal,namaPenerima,kegiatan].filter(v=>v).length;
  document.getElementById('pvJudul').textContent='SURAT UNDANGAN';document.getElementById('pvNomor').style.display='none';
  if(filled===0) setStatus('empty','Isi form untuk melihat preview surat');
  else if(filled<4) setStatus('partial',`✍️ ${filled}/4 field terisi...`);
  else{setStatus('full','✅ Surat lengkap — siap cetak!');setStamp(true);}
  if(filled<4) setStamp(false);
  document.getElementById('letterOuter').classList.toggle('alive',filled>0);
  const row=(label,val,lebar='155px')=>{const vHtml=val?`<strong>${esc(val)}</strong>`:`<span class="ph">—</span>`;return `<tr><td style="width:${lebar};padding:1px 0;color:#334155;vertical-align:top;white-space:nowrap">${label}</td><td style="width:14px;text-align:center;vertical-align:top;padding:1px 0">:</td><td style="vertical-align:top;padding:1px 0">${vHtml}</td></tr>`;};
  document.getElementById('pvBody').innerHTML=`
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1.25rem;line-height:1.85">${row('Nomor',nomor||null,'80px')}${row('Lamp.',lamp,'80px')}${row('Perihal',perihal,'80px')}</table>
    <p style="margin-bottom:.2rem;line-height:1.65">Kepada Yth.</p>
    <p style="margin-bottom:.2rem;font-weight:700">${namaPenerima?esc(namaPenerima):`<span class="ph">Nama Penerima</span>`}</p>
    ${jabatanPenerima?`<p style="margin-bottom:.2rem">${esc(jabatanPenerima)}</p>`:''}
    <p style="margin-bottom:1.25rem;line-height:1.75">di<br>&nbsp;&nbsp;&nbsp;&nbsp;<u>&nbsp;Tempat&nbsp;</u></p>
    <p style="margin-bottom:.875rem;font-style:italic"><em>Assalamualaikum Wr. Wb.</em></p>
    <p style="margin-bottom:1rem;line-height:1.65">Semoga Allah SWT., senantiasa memberikan taufik, hidayah &amp; inayah-Nya untuk kita semua dalam menjalankan aktifitas sehari-hari, aamiin.</p>
    <p style="margin-bottom:1rem;line-height:1.75;text-align:justify">Dalam rangka pelaksanaan <strong>${kegiatan?esc(kegiatan):`<span class="ph">nama kegiatan</span>`}</strong> yang akan diselenggarakan di <strong>${esc(SEKOLAH.nama)}</strong>, kami bermaksud mengundang Bapak/Ibu untuk hadir dalam kegiatan tersebut.</p>
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin:0 0 1rem 0;line-height:1.9">${row('Hari / Tanggal',haritgl||null,'155px')}${waktu?row('Waktu',waktu,'155px'):''}${row('Tempat',tempat||SEKOLAH.nama,'155px')}${agenda?row('Agenda',agenda,'155px'):''}</table>
    ${ketTambahan?`<p style="margin-bottom:.875rem;line-height:1.75;text-align:justify">${esc(ketTambahan)}</p>`:''}
    <p style="margin-bottom:1.5rem;line-height:1.65">Demikian surat undangan ini kami sampaikan. Atas perhatian dan kehadirannya, kami ucapkan terima kasih.<br><em>Wassalamualaikum Wr. Wb.</em></p>
    ${buildTTD(tglFmt,SEKOLAH.jabatanKepala,SEKOLAH.kepala,SEKOLAH.nipKepala)}`;
}

function renderPemberitahuan(){
  const nomor=getV('pb_nomor'),lamp=getV('pb_lamp')||'-',tanggal=getV('pb_tanggal'),perihal=getV('pb_perihal')||'Pemberitahuan',namaPenerima=getV('pb_nama_penerima'),jabatanPenerima=getV('pb_jabatan_penerima'),kegiatan=getV('pb_kegiatan'),haritgl=getV('pb_haritgl'),tempat=getV('pb_tempat'),peserta=getV('pb_peserta'),ketTambahan=getV('pb_ket'),tglFmt=fmtTgl(tanggal);
  const filled=[nomor,tanggal,namaPenerima,kegiatan].filter(v=>v).length;
  document.getElementById('pvJudul').textContent='SURAT PEMBERITAHUAN';document.getElementById('pvNomor').style.display='none';
  if(filled===0) setStatus('empty','Isi form untuk melihat preview surat');
  else if(filled<4) setStatus('partial',`✍️ ${filled}/4 field terisi...`);
  else{setStatus('full','✅ Surat lengkap — siap cetak!');setStamp(true);}
  if(filled<4) setStamp(false);
  document.getElementById('letterOuter').classList.toggle('alive',filled>0);
  const row=(label,val,lebar='155px')=>{const vHtml=val?`<strong>${esc(val)}</strong>`:`<span class="ph">—</span>`;return `<tr><td style="width:${lebar};padding:1px 0;color:#334155;vertical-align:top;white-space:nowrap">${label}</td><td style="width:14px;text-align:center;vertical-align:top;padding:1px 0">:</td><td style="vertical-align:top;padding:1px 0;font-weight:${val?'600':'400'}">${vHtml}</td></tr>`;};
  const namaMadrasah=SEKOLAH.nama.includes('MA ')?SEKOLAH.nama.replace(/^MA\s+/,'Madrasah Aliyah '):SEKOLAH.nama;
  document.getElementById('pvBody').innerHTML=`
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1.25rem;line-height:1.85">${row('Nomor',nomor||null,'80px')}${row('Lamp.',lamp,'80px')}${row('Perihal',perihal?perihal:null,'80px')}</table>
    <p style="margin-bottom:.2rem;line-height:1.65">Kepada Yth.</p>
    <p style="margin-bottom:.2rem;font-weight:700">${namaPenerima?esc(namaPenerima):`<span class="ph">Nama Penerima</span>`}</p>
    ${jabatanPenerima?`<p style="margin-bottom:.2rem">${esc(jabatanPenerima)}</p>`:''}
    <p style="margin-bottom:1.25rem;line-height:1.75">di<br>&nbsp;&nbsp;&nbsp;&nbsp;<u>&nbsp;Tempat&nbsp;</u></p>
    <p style="margin-bottom:.875rem;font-style:italic"><em>Assalamualaikum Wr. Wb.</em></p>
    <p style="margin-bottom:.875rem;line-height:1.65">Semoga Allah SWT., senantiasa memberikan taufik, hidayah &amp; inayah-Nya untuk kita semua dalam menjalankan aktifitas sehari-hari, aamiin.</p>
    <p style="margin-bottom:1rem;line-height:1.75;text-align:justify">Selanjutnya, kami informasikan bahwa <strong>${esc(namaMadrasah)}</strong> akan melaksanakan <strong>${kegiatan?esc(kegiatan):`<span class="ph">nama kegiatan</span>`}</strong> di luar Madrasah. Insya Allah, kegiatan ini akan dilaksanakan pada:</p>
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin:0 0 1rem 1.5rem;line-height:1.9">${row('Hari/Tanggal',haritgl||null,'155px')}${row('Tempat',tempat||null,'155px')}</table>
    <p style="margin-bottom:.875rem;line-height:1.65">${peserta?`${esc(peserta)} akan mengikuti kegiatan ${kegiatan?esc(kegiatan):'tersebut'}.`:''}</p>
    ${ketTambahan?`<p style="margin-bottom:.875rem;line-height:1.75;text-align:justify">${esc(ketTambahan)}</p>`:''}
    <p style="margin-bottom:1.5rem;line-height:1.65">Demikian surat ini. Atas perhatian dan suport dari Pimpinan, kami ucapkan terimakasih.<br><em>Wassalamualaikum Wr. Wb.</em></p>
    ${buildTTD(tglFmt,SEKOLAH.jabatanKepala,SEKOLAH.kepala,SEKOLAH.nipKepala)}`;
}

function renderSosialisasi(){
  const nomor=getV('s_nomor'),lamp=getV('s_lamp')||'-',tanggal=getV('s_tanggal'),perihal=getV('s_perihal')||'Permohonan Sosialisasi PPDB',jabatanTujuan=getV('s_jabatan_tujuan'),sekolahTujuan=getV('s_sekolah_tujuan'),tahunPelajaran=getV('s_tahun_pelajaran')||SEKOLAH.tahunAjaran,ketTambahan=getV('s_ket'),tglFmt=fmtTgl(tanggal);
  const filled=[nomor,tanggal,sekolahTujuan].filter(v=>v).length;
  document.getElementById('pvJudul').textContent='SURAT PERMOHONAN SOSIALISASI PPDB';document.getElementById('pvNomor').style.display='none';
  if(filled===0) setStatus('empty','Isi form untuk melihat preview surat');
  else if(filled<3) setStatus('partial',`✍️ ${filled}/3 field terisi...`);
  else{setStatus('full','✅ Surat lengkap — siap cetak!');setStamp(true);}
  if(filled<3) setStamp(false);
  document.getElementById('letterOuter').classList.toggle('alive',filled>0);
  const row=(label,val,lebar='120px')=>{const vHtml=val?esc(val):`<span class="ph">—</span>`;return `<tr><td style="width:${lebar};padding:1px 0;color:#334155;vertical-align:top;white-space:nowrap">${label}</td><td style="width:14px;text-align:center;vertical-align:top;padding:1px 0">:</td><td style="vertical-align:top;padding:1px 0">${vHtml}</td></tr>`;};
  const namaPengirim=SEKOLAH.nama.includes('MA ')?SEKOLAH.nama.replace(/^MA\s+/,'Madrasah Aliyah '):SEKOLAH.nama;
  document.getElementById('pvBody').innerHTML=`
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1.25rem;line-height:1.85">${row('Nomor',nomor||null)}${row('Lamp.',lamp)}${row('Perihal',perihal||null)}</table>
    <p style="margin-bottom:.2rem;line-height:1.65">Kepada Yth.</p>
    <p style="margin-bottom:.2rem;font-weight:700">${jabatanTujuan?esc(jabatanTujuan):`<span class="ph">Kepala Sekolah MTs ...</span>`}</p>
    <p style="margin-bottom:1.25rem;line-height:1.75">di<br>&nbsp;&nbsp;&nbsp;&nbsp;<u>&nbsp;Tempat&nbsp;</u></p>
    <p style="margin-bottom:1rem;font-style:italic">Assalamualaikum wr.wb.</p>
    <p style="margin-bottom:1rem;line-height:1.65">Semoga Allah swt. Senantiasa memberikan taufik, hidayah &amp; inayah-Nya untuk kita semua, aamiin.</p>
    <p style="margin-bottom:1rem;line-height:1.75;text-align:justify">Sehubungan akan Lulusannya Peserta Didik Kelas IX Tahun Pelajaran <strong>${esc(tahunPelajaran)}</strong>, kami dari <strong>${esc(namaPengirim)} ${esc(SEKOLAH.kota)}</strong> bermaksud mengadakan presentasi di sekolah yang Bapak/Ibu Pimpin.</p>
    <p style="margin-bottom:1rem;line-height:1.75;text-align:justify">Maka kami memohon izin kepada Bapak/Ibu Kepala Sekolah untuk memberikan izin bagi kami untuk melakukan presentasi ${sekolahTujuan?`di <strong>${esc(sekolahTujuan)}</strong>`:'<span class="ph">di sekolah tujuan</span>'} dengan tujuan sebagai sarana informasi kepada siswa/siswi Kelas IX untuk melanjutkan studi ke jenjang pendidikan selanjutnya.</p>
    ${ketTambahan?`<p style="margin-bottom:1rem;line-height:1.75;text-align:justify">${esc(ketTambahan)}</p>`:''}
    <p style="margin-bottom:1.5rem;line-height:1.65">Demikian permohonan izin dari kami, atas perhatian dan kerjasamanya serta pemberian izin Bapak/Ibu Kepala Sekolah kami mengucapkan terima kasih.<br><em>Wassalamualaikum wr.wb.</em></p>
    ${buildTTD(tglFmt,`Kepala ${esc(SEKOLAH.nama)}`,SEKOLAH.kepala,SEKOLAH.nipKepala)}`;
}

function renderTugas(){
  const nomor=getV('t_nomor'),tanggal=getV('t_tanggal'),nama=getV('t_nama'),nip=getV('t_nip'),jabatan=getV('t_jabatan'),keperluan=getV('t_keperluan'),haritgl=getV('t_haritgl'),tempat=getV('t_tempat'),ket=getV('t_ket'),tglFmt=fmtTgl(tanggal);
  const filled=[nomor,tanggal,nama,keperluan].filter(v=>v).length;
  document.getElementById('pvNomor').style.display='';
  document.getElementById('pvNomor').innerHTML='Nomor&nbsp; : '+(nomor?`<span>${esc(nomor)}</span>`:ph('—'));
  if(filled===0) setStatus('empty','Isi form untuk melihat preview surat');
  else if(filled<4) setStatus('partial',`✍️ ${filled}/4 field terisi...`);
  else{setStatus('full','✅ Surat lengkap — siap cetak!');setStamp(true);}
  if(filled<4) setStamp(false);
  document.getElementById('letterOuter').classList.toggle('alive',filled>0);
  const row=(label,val,bold=false)=>{const vHtml=val?(bold?`<strong>${esc(val)}</strong>`:esc(val)):`<span class="ph">—</span>`;return `<tr><td style="width:90px;padding:1px 0;color:#334155;vertical-align:top">${label}</td><td style="width:14px;text-align:center;padding:1px 0">:</td><td style="padding:1px 0;font-weight:${val?'600':'400'}">${vHtml}</td></tr>`;};
  document.getElementById('pvBody').innerHTML=`
    <p style="margin-bottom:.875rem;line-height:1.65"><strong>Saya yang bertanda tangan di bawah ini :</strong></p>
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1rem;line-height:1.8">${row('Nama',SEKOLAH.kepala,true)}${row('Jabatan',SEKOLAH.jabatanKepala)}</table>
    <p style="margin-bottom:.875rem;line-height:1.65">Menugaskan kepada :</p>
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1rem;line-height:1.8">${row('Nama',nama,true)}${row('Jabatan',jabatan||'Guru')}${nip?row('NIP',nip):''}</table>
    <p style="margin-bottom:${haritgl?'.5rem':'1rem'};line-height:1.65">Untuk <strong>${keperluan?esc(keperluan):'<span style="color:#CBD5E1;font-style:italic">keperluan tugas...</span>'}</strong>${haritgl||tempat?' yang akan di laksanakan pada :':'.'}</p>
    ${(haritgl||tempat)?`<table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1rem;line-height:1.8">${haritgl?row('Hari / Tanggal',haritgl):''}${tempat?row('Tempat',tempat):''}</table>`:''}
    ${ket?`<p style="margin-bottom:.875rem">${esc(ket)}</p>`:''}
    <p style="margin-bottom:.75rem">Demikian surat tugas ini saya buat agar dapat digunakan seperlunya.</p>
    <p style="margin-bottom:1.5rem;font-style:italic">wassalamualaikum Wr. Wb.</p>
    ${buildTTD(tglFmt,SEKOLAH.jabatanKepala,SEKOLAH.kepala,SEKOLAH.nipKepala)}`;
}

function renderAktif(){
  const nomor=getV('a_nomor'),tanggal=getV('a_tanggal'),nama=getV('a_nama'),nis=getV('a_nis'),nisn=getV('a_nisn'),kelas=getV('a_kelas'),keperluan=getV('a_keperluan');
  const jkEl=document.getElementById('a_jk'),jk=jkEl?jkEl.value:'Laki-laki';
  const ttl=getV('a_ttl'),tglLahir=getV('a_tgl_lahir'),tanggalFmt=fmtTgl(tanggal),tglLahirFmt=fmtTgl(tglLahir);
  const romanMap={'X':'Sepuluh','XI':'Sebelas','XII':'Dua Belas'};
  let kelasDisplay=kelas||null;
  if(kelas){const m=kelas.trim().match(/^(X{1,3}I{0,2})/i);if(m){const romKey=m[1].toUpperCase();const label=romanMap[romKey];if(label&&!kelas.includes('('))kelasDisplay=`${esc(kelas)} (${label})`;else kelasDisplay=esc(kelas);}else kelasDisplay=esc(kelas);}
  const namaLengkap=SEKOLAH.nama.replace(/^MA\s+/,'Madrasah Aliyah ');
  const jabatanTTD='Kepala '+SEKOLAH.nama;
  const ttlDisplay=(ttl&&tglLahirFmt)?`${esc(ttl)}, ${esc(tglLahirFmt)}`:ttl?esc(ttl):tglLahirFmt?esc(tglLahirFmt):null;
  const filled=[nomor,tanggal,nama].filter(v=>v).length;
  document.getElementById('pvJudul').textContent='SURAT KETERANGAN SISWA AKTIF';
  document.getElementById('pvNomor').innerHTML='Nomor : '+(nomor?`<span>${esc(nomor)}</span>`:ph('—'));
  document.getElementById('pvNomor').style.display='';
  if(filled===0) setStatus('empty','Isi form untuk melihat preview surat');
  else if(filled<3) setStatus('partial',`✍️ ${filled}/3 field terisi...`);
  else{setStatus('full','✅ Surat lengkap — siap cetak!');setStamp(true);}
  if(filled<3) setStamp(false);
  document.getElementById('letterOuter').classList.toggle('alive',filled>0);
  const row=(label,val)=>{const vHtml=val?`<strong>${val}</strong>`:`<span class="ph">—</span>`;return `<tr><td style="width:185px;padding:2px 0;color:#334155;vertical-align:top">${label}</td><td style="width:14px;text-align:center;vertical-align:top;padding:2px 0">:</td><td style="vertical-align:top;padding:2px 0;font-weight:${val?'600':'400'}">${vHtml}</td></tr>`;};
  const keperluanSentence=keperluan?` untuk keperluan <strong>${esc(keperluan)}</strong>`:'';
  document.getElementById('pvBody').innerHTML=`
    <p style="margin-bottom:1rem;line-height:1.75;text-align:justify">Yang bertanda tangan di bawah ini ${esc(SEKOLAH.jabatanKepala)} <strong>${esc(namaLengkap)}</strong> beralamat di ${esc(SEKOLAH.alamat)} menerangkan dengan sebenarnya&nbsp;:</p>
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1.25rem;line-height:1.85">
      ${row('Nama',nama?esc(nama):null)}${row('NISN',nisn?esc(nisn):null)}${row('Jenis Kelamin',jk?esc(jk):null)}${row('Tempat/Tgl Lahir',ttlDisplay)}${row('Kelas',kelasDisplay)}
    </table>
    <p style="margin-bottom:.875rem;line-height:1.75;text-align:justify">Bahwa nama tersebut adalah benar murid <strong>${esc(namaLengkap)}</strong> masih aktif sebagai siswa <strong>${esc(namaLengkap)}</strong> hingga saat ini${keperluanSentence}.</p>
    <p style="margin-bottom:1.75rem;line-height:1.75">Demikian surat keterangan ini dibuat dengan sebenarnya untuk dipergunakan sebagaimana mestinya.</p>
    ${buildTTD(tanggalFmt,jabatanTTD,SEKOLAH.kepala,SEKOLAH.nipKepala)}`;
}

function renderKelakuan(){
  const tanggal=getV('k_tanggal'),nama=getV('k_nama'),nisn=getV('k_nisn'),kelas=getV('k_kelas'),keperluan=getV('k_keperluan');
  const sekolahAsal=getV('k_sekolah_asal')||SEKOLAH.nama,alamatSekolah=getV('k_alamat_sekolah')||SEKOLAH.alamat,tglFmt=fmtTgl(tanggal);
  const namaLengkap=sekolahAsal.replace(/^MA\s+/,'Madrasah Aliyah ');
  const jabatanTTD='Kepala Madrasah '+SEKOLAH.nama.replace(/^MA\s+(As-Syafi[^\s]*\s*\d*).*/, '$1').trim();
  const filled=[tanggal,nama].filter(v=>v).length;
  document.getElementById('pvJudul').textContent='SURAT KETERANGAN BERKELAKUAN BAIK';
  document.getElementById('pvNomor').style.display='none';
  if(filled===0) setStatus('empty','Isi form untuk melihat preview surat');
  else if(filled<2) setStatus('partial',`✍️ ${filled}/2 field terisi...`);
  else{setStatus('full','✅ Surat lengkap — siap cetak!');setStamp(true);}
  if(filled<2) setStamp(false);
  document.getElementById('letterOuter').classList.toggle('alive',filled>0);
  const row=(label,val,lebar='220px')=>{const vHtml=val?`<strong>${esc(val)}</strong>`:`<span class="ph">—</span>`;return `<tr><td style="width:${lebar};padding:2px 0;vertical-align:top;color:#334155;white-space:nowrap">${label}</td><td style="width:14px;text-align:center;vertical-align:top;padding:2px 0">:</td><td style="vertical-align:top;padding:2px 0;font-weight:${val?'600':'400'}">${vHtml}</td></tr>`;};
  const keperluanSentence=keperluan?`<p style="margin-bottom:1rem;line-height:1.75;text-align:justify">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Surat keterangan ini dibuat untuk keperluan <strong>${esc(keperluan)}</strong>.</p>`:'';
  document.getElementById('pvBody').innerHTML=`
    <p style="margin-bottom:1.25rem;line-height:1.75;text-align:justify">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Yang bertanda tangan di bawah ini ${esc(SEKOLAH.jabatanKepala)} <strong>${esc(namaLengkap)}</strong> menerangkan bahwa&nbsp;:</p>
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin:0 0 1.25rem .5rem;line-height:1.9">
      ${row('N a m a',nama||null)}${row('Sekolah Asal',namaLengkap)}${row('Alamat Sekolah',alamatSekolah)}${row('Nomor Induk/NISN',nisn||null)}
    </table>
    <p style="margin-bottom:1rem;line-height:1.75;text-align:justify">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Dengan ini menjelaskan bahwa siswa yang tersebut namanya diatas adalah salah satu siswa di <strong>${esc(namaLengkap)}</strong> dan <strong>tidak pernah terlibat dan atau melakukan pelanggaran berat</strong> seperti <em>Bullying, tawuran antar sekolah, merokok, LGBT, Seks Bebas, Pornography</em> dan <em>Narkoba</em> selama mengikuti pembelajaran pada satuan pendidikan yang kami pimpin.</p>
    ${keperluanSentence}
    <p style="margin-bottom:1.75rem;line-height:1.65">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Demikian Surat Keterangan ini dibuat, untuk dapat dipergunakan sebagaimana mestinya.</p>
    ${buildTTD(tglFmt,jabatanTTD,SEKOLAH.kepala,SEKOLAH.nipKepala)}`;
}

function renderPanggilan(){
  const nomor=getV('p_nomor'),lamp=getV('p_lamp')||'-',tanggal=getV('p_tanggal'),perihal=getV('p_perihal')||'Pemanggilan Orang Tua',nama=getV('p_nama'),kelas=getV('p_kelas'),alasan=getV('p_alasan')||'melakukan pelanggaran peraturan sekolah',haritgl=getV('p_haritgl'),jam=getV('p_jam'),tempatPertemuan=getV('p_tempat_pertemuan')||SEKOLAH.nama,catatan=getV('p_catatan'),tglFmt=fmtTgl(tanggal);
  const filled=[nomor,tanggal,nama].filter(v=>v).length;
  document.getElementById('pvJudul').textContent='SURAT PEMANGGILAN ORANG TUA / WALI MURID';
  document.getElementById('pvNomor').style.display='none';
  if(filled===0) setStatus('empty','Isi form untuk melihat preview surat');
  else if(filled<3) setStatus('partial',`✍️ ${filled}/3 field terisi...`);
  else{setStatus('full','✅ Surat lengkap — siap cetak!');setStamp(true);}
  if(filled<3) setStamp(false);
  document.getElementById('letterOuter').classList.toggle('alive',filled>0);
  const row=(label,val,lebar='120px')=>{const vHtml=val?esc(val):`<span class="ph">—</span>`;return `<tr><td style="width:${lebar};padding:1px 0;color:#334155;vertical-align:top;white-space:nowrap">${label}</td><td style="width:14px;text-align:center;vertical-align:top;padding:1px 0">:</td><td style="vertical-align:top;padding:1px 0">${vHtml}</td></tr>`;};
  document.getElementById('pvBody').innerHTML=`
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1.25rem;line-height:1.85">${row('Nomor',nomor||null)}${row('Lamp.',lamp)}${row('Perihal',perihal||null)}</table>
    <p style="margin-bottom:.2rem;line-height:1.65">Kepada Yth.</p>
    <p style="margin-bottom:.2rem;font-weight:700">Bapak / Ibu Wali Murid</p>
    <p style="margin-bottom:.2rem;font-weight:700">${nama?esc(nama):`<span class="ph">Nama Siswa</span>`}</p>
    <p style="margin-bottom:1.25rem;line-height:1.75">di<br>&nbsp;&nbsp;&nbsp;&nbsp;<u>&nbsp;Tempat&nbsp;</u></p>
    <p style="margin-bottom:1rem;font-style:italic">Assalamualaikum wr.wb.</p>
    <p style="margin-bottom:.875rem;line-height:1.75;text-align:justify">Bersama surat ini, kami pihak sekolah menyampaikan bahwa anak Bapak/Ibu ${nama?`<strong>${esc(nama)}</strong>`:`<span class="ph">nama siswa</span>`} ${alasan?esc(alasan):'...'}. Untuk itu, kami mengharapkan kedatangan Bapak/Ibu pada:</p>
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin:0 0 1rem 1.5rem;line-height:1.9">${row('Hari/Tanggal',haritgl||null)}${row('Jam',jam?esc(jam)+' WIB':null)}${row('Tempat',tempatPertemuan)}</table>
    <p style="margin-bottom:.875rem;line-height:1.75;text-align:justify">${catatan?esc(catatan):'Mengingat pentingnya hal tersebut, kehadiran Bapak/Ibu <strong>tidak diwakilkan</strong> oleh orang lain.'}</p>
    <p style="margin-bottom:1.5rem;line-height:1.65">Demikian pemberitahuan ini, Atas perhatian dan kehadiran Bapak/Ibu, Kami ucapkan terima kasih.<br><em>Wassalamualaikum wr.wb.</em></p>
    ${buildTTD(tglFmt,SEKOLAH.jabatanKepala,SEKOLAH.kepala,SEKOLAH.nipKepala)}`;
}

function renderPermohonan(){
  const nomor=getV('pm_nomor'),lamp=getV('pm_lamp')||'-',tanggal=getV('pm_tanggal'),perihal=getV('pm_perihal'),namaPenerima=getV('pm_nama_penerima'),jabatanPenerima=getV('pm_jabatan_penerima'),kegiatan=getV('pm_kegiatan'),aula=getV('pm_aula'),haritgl=getV('pm_haritgl'),waktu=getV('pm_waktu'),ketTambahan=getV('pm_ket'),tglFmt=fmtTgl(tanggal);
  const filled=[nomor,tanggal,namaPenerima,kegiatan,aula,haritgl].filter(v=>v).length;
  document.getElementById('pvJudul').textContent='SURAT PERMOHONAN';document.getElementById('pvNomor').style.display='none';
  if(filled===0) setStatus('empty','Isi form untuk melihat preview surat');
  else if(filled<6) setStatus('partial',`✍️ ${filled}/6 field terisi...`);
  else{setStatus('full','✅ Surat lengkap — siap cetak!');setStamp(true);}
  if(filled<6) setStamp(false);
  document.getElementById('letterOuter').classList.toggle('alive',filled>0);
  const row=(label,val,lebar='160px')=>{const vHtml=val?`<strong>${esc(val)}</strong>`:`<span class="ph">—</span>`;return `<tr><td style="width:${lebar};padding:1px 0;color:#334155;vertical-align:top;white-space:nowrap">${label}</td><td style="width:14px;text-align:center;vertical-align:top;padding:1px 0">:</td><td style="vertical-align:top;padding:1px 0">${vHtml}</td></tr>`;};
  document.getElementById('pvBody').innerHTML=`
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1.25rem;line-height:1.85">${row('Nomor',nomor||null,'80px')}${row('Lamp.',lamp,'80px')}${row('Perihal',perihal||null,'80px')}</table>
    <p style="margin-bottom:.2rem;line-height:1.65">Kepada Yth.</p>
    <p style="margin-bottom:.2rem;font-weight:700">${namaPenerima?esc(namaPenerima):`<span class="ph">Nama Penerima</span>`}</p>
    ${jabatanPenerima?`<p style="margin-bottom:.2rem">${esc(jabatanPenerima)}</p>`:''}
    <p style="margin-bottom:1.25rem;line-height:1.75">di<br>&nbsp;&nbsp;&nbsp;&nbsp;<u>&nbsp;Tempat&nbsp;</u></p>
    <p style="margin-bottom:.875rem;font-style:italic"><em>Assalamualaikum Wr. Wb.</em></p>
    <p style="margin-bottom:1rem;line-height:1.65">Semoga Allah SWT., senantiasa memberikan taufik, hidayah &amp; inayah-Nya untuk kita semua dalam menjalankan aktifitas sehari-hari, aamiin.</p>
    <p style="margin-bottom:1rem;line-height:1.75;text-align:justify">Dalam rangka memperingati / melaksanakan <strong>${kegiatan?esc(kegiatan):`<span class="ph">nama kegiatan</span>`}</strong>, kami dari <strong>${esc(SEKOLAH.nama)}</strong> bermaksud untuk memohon izin penggunaan <strong>${aula?esc(aula):`<span class="ph">nama aula / gedung</span>`}</strong> sebagai tempat pelaksanaan kegiatan tersebut.</p>
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin:0 0 1rem 1.5rem;line-height:1.9">${row('Hari/Tanggal',haritgl||null,'155px')}${waktu?row('Waktu',waktu,'155px'):''}</table>
    ${ketTambahan?`<p style="margin-bottom:1rem;line-height:1.75;text-align:justify">${esc(ketTambahan)}</p>`:''}
    <p style="margin-bottom:1.5rem;line-height:1.65">Demikian pemberitahuan dan permohonan ini, atas perhatian dan kehadiran Bapak, kami mengucapkan terima kasih.<br><em>Wassalamualaikum Wr. Wb.</em></p>
    ${buildTTD(tglFmt,SEKOLAH.jabatanKepala,SEKOLAH.kepala,SEKOLAH.nipKepala)}`;
}

function renderPernyataan(){
  const nomor=getV('py_nomor'),tanggal=getV('py_tanggal'),namaKepala=getV('py_nama_kepala')||SEKOLAH.kepala,jabatanKepala=getV('py_jabatan_kepala')||SEKOLAH.jabatanKepala,namaSiswa=getV('py_nama'),nisn=getV('py_nisn'),kelas=getV('py_kelas'),kebijakan=getV('py_kebijakan')||`keringanan biaya sekolah selama bersekolah di ${esc(SEKOLAH.nama)}`,ket1=getV('py_ket1'),ket2=getV('py_ket2'),ket3=getV('py_ket3'),ket4=getV('py_ket4'),ket5=getV('py_ket5'),tembusan1=getV('py_tembusan1'),tembusan2=getV('py_tembusan2'),tembusan3=getV('py_tembusan3'),tglFmt=fmtTgl(tanggal);
  const filled=[nomor,tanggal,namaSiswa].filter(v=>v).length;
  document.getElementById('pvJudul').textContent='SURAT PERNYATAAN';
  document.getElementById('pvNomor').style.display=nomor?'':'none';
  if(nomor) document.getElementById('pvNomor').innerHTML=`Nomor : <span>${esc(nomor)}</span>`;
  if(filled===0) setStatus('empty','Isi form untuk melihat preview surat');
  else if(filled<3) setStatus('partial',`✍️ ${filled}/3 field terisi...`);
  else{setStatus('full','✅ Surat pernyataan lengkap — siap cetak!');setStamp(true);}
  if(filled<3) setStamp(false);
  document.getElementById('letterOuter').classList.toggle('alive',filled>0);
  const row=(label,val,lebar='160px')=>{const vHtml=val?esc(val):`<span class="ph">—</span>`;return `<tr><td style="width:${lebar};padding:2px 0;color:#334155;vertical-align:top">${label}</td><td style="width:14px;text-align:center;vertical-align:top;padding:2px 0">:</td><td style="vertical-align:top;padding:2px 0;font-weight:${val?'600':'400'}">${vHtml}</td></tr>`;};
  const ketList=[ket1,ket2,ket3,ket4,ket5].filter(k=>k.trim());
  const ketHTML=ketList.length?`<ol style="margin:0 0 1rem 1.5rem;font-size:.72rem;line-height:1.9">${ketList.map(k=>`<li style="margin-bottom:2px">${esc(k)}</li>`).join('')}</ol>`:`<p class="ph" style="font-size:.72rem;margin-bottom:1rem">Belum ada ketentuan...</p>`;
  const tembusanList=[tembusan1,tembusan2,tembusan3].filter(t=>t.trim());
  const tembusanHTML=tembusanList.length?`<div style="font-size:.68rem;margin-top:1.25rem;line-height:1.85;border-top:1px dashed #CBD5E1;padding-top:.75rem"><div style="font-weight:700;color:#334155;margin-bottom:.25rem">Tembusan:</div><ol style="margin:0 0 0 1.25rem;padding:0">${tembusanList.map(t=>`<li>${esc(t)}</li>`).join('')}</ol></div>`:'';
  document.getElementById('pvBody').innerHTML=`
    <p style="margin-bottom:1rem;font-size:.72rem;line-height:1.65">Yang bertanda tangan di bawah ini:</p>
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1rem;line-height:1.85">${row('Nama',namaKepala||null)}${row('Jabatan',jabatanKepala||null)}</table>
    <p style="margin-bottom:1rem;font-size:.72rem;line-height:1.65">Dengan ini menyatakan bahwa:</p>
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1rem;line-height:1.85">${row('Nama Siswa',namaSiswa||null)}${row('NISN',nisn||null)}${row('Kelas',kelas||null)}</table>
    <p style="margin-bottom:.75rem;font-size:.72rem;line-height:1.75;text-align:justify">Diberikan kebijakan berupa <strong>${esc(kebijakan)}</strong>, dengan ketentuan sebagai berikut:</p>
    ${ketHTML}
    <p style="margin-bottom:1.5rem;font-size:.72rem;line-height:1.75;text-align:justify">Demikian surat pernyataan ini dibuat dengan sebenarnya untuk dipergunakan sebagaimana mestinya.</p>
    <div style="display:flex;justify-content:flex-end;font-size:.72rem">
      <div style="text-align:center;min-width:185px;position:relative">
        <div style="margin-bottom:.25rem;color:#334155">${tglFmt?`${esc(SEKOLAH.kota)}, ${esc(tglFmt)}`:`<span class="ph">${esc(SEKOLAH.kota)}, — — —</span>`}</div>
        <div style="font-weight:700;margin-bottom:.3rem;line-height:1.3">${esc(SEKOLAH.jabatanKepala)}</div>
        <div style="height:72px;position:relative">${SEKOLAH.ttd?`<img src="${esc(SEKOLAH.ttd)}" alt="TTD" style="position:absolute;bottom:28px;left:50%;transform:translateX(-50%);width:130px;height:65px;object-fit:contain;opacity:.92;pointer-events:none">`:''}${SEKOLAH.cap?`<img src="${esc(SEKOLAH.cap)}" alt="Cap" style="position:absolute;bottom:16px;left:50%;transform:translateX(-55%) rotate(-8deg);width:95px;height:95px;object-fit:contain;opacity:.75;pointer-events:none">`:''}
        </div>
        <div style="font-weight:700;color:#0F172A;padding-top:2px;display:inline-block;border-top:1.5px solid #0F172A;min-width:165px">${esc(namaKepala)||'Kepala Sekolah'}</div>
        ${SEKOLAH.nipKepala?`<div style="font-size:.62rem;color:#64748B;margin-top:2px">NIP. ${esc(SEKOLAH.nipKepala)}</div>`:''}
      </div>
    </div>
    ${tembusanHTML}`;
}

function renderSkorsing(){
  const nomor=getV('sk_nomor'),lamp=getV('sk_lamp')||'-',tanggal=getV('sk_tanggal'),perihal=getV('sk_perihal')||'Surat Peringatan',nama=getV('sk_nama'),kelas=getV('sk_kelas'),nisn=getV('sk_nisn'),tglMulai=getV('sk_tgl_mulai'),tglSelesai=getV('sk_tgl_selesai'),poin=getV('sk_poin'),pelanggaran=getV('sk_pelanggaran')||'melanggar Tata Tertib Peserta Didik Sistem Poin',pesan=getV('sk_pesan'),tglFmt=fmtTgl(tanggal),tglMulaiFmt=fmtTgl(tglMulai),tglSelesaiFmt=fmtTgl(tglSelesai);
  const filled=[nomor,tanggal,nama,kelas].filter(v=>v).length;
  document.getElementById('pvJudul').textContent='SURAT PERINGATAN';document.getElementById('pvNomor').style.display='none';
  if(filled===0) setStatus('empty','Isi form untuk melihat preview surat');
  else if(filled<4) setStatus('partial',`✍️ ${filled}/4 field terisi...`);
  else{setStatus('full','✅ Surat lengkap — siap cetak!');setStamp(true);}
  if(filled<4) setStamp(false);
  document.getElementById('letterOuter').classList.toggle('alive',filled>0);
  const row=(label,val,lebar='155px')=>{const vHtml=val?`<strong>${esc(val)}</strong>`:`<span class="ph">—</span>`;return `<tr><td style="width:${lebar};padding:2px 0;color:#334155;vertical-align:top;white-space:nowrap">${label}</td><td style="width:14px;text-align:center;vertical-align:top;padding:2px 0">:</td><td style="vertical-align:top;padding:2px 0;font-weight:${val?'600':'400'}">${vHtml}</td></tr>`;};
  let rentang='';
  if(tglMulaiFmt&&tglSelesaiFmt) rentang=`Tanggal ${tglMulaiFmt} – ${tglSelesaiFmt}`;
  else if(tglMulaiFmt) rentang=`Tanggal ${tglMulaiFmt}`;
  const poinInfo=poin?` dengan jumlah poin <strong>${esc(poin)}</strong>`:'';
  const pesanDefault='Demikian surat pemberitahuan ini kami buat, agar menjadi perhatian untuk Bapak/Ibu dalam rangka tetap memberikan dorongan/motivasi dan pengawasan kepada putra/putrinya yang akan menjalani Sanksi Skorsing, dan kedepan semoga tidak melanggar aturan lagi, menjadi Peserta Didik yang lebih baik dan berprestasi. Aamiiiin ….';
  const pesanFinal=pesan?esc(pesan):pesanDefault;
  document.getElementById('pvBody').innerHTML=`
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1.25rem;line-height:1.85">${row('Nomor',nomor||null,'80px')}${row('Lamp.',lamp,'80px')}${row('Perihal',perihal,'80px')}</table>
    <p style="margin-bottom:.2rem;line-height:1.65">Kepada</p>
    <p style="margin-bottom:.2rem">Yth. Orangtua Siswa dari <strong>${nama?esc(nama):`<span class="ph">Nama Siswa</span>`}</strong></p>
    <p style="margin-bottom:1.25rem">Di Tempat</p>
    <p style="margin-bottom:.875rem;font-style:italic"><em>Assalamu'alaikum Wr. Wb</em></p>
    <p style="margin-bottom:.875rem;line-height:1.75;text-align:justify">Diberitahukan dengan hormat kepada Bapak/Ibu Orang Tua Siswa dari:</p>
    <table style="width:100%;border-collapse:collapse;font-size:.72rem;margin-bottom:1rem;line-height:1.9">${row('Nama Siswa',nama||null,'155px')}${row('Kelas',kelas||null,'155px')}${nisn?row('NIS/NISN',nisn,'155px'):''}</table>
    <p style="margin-bottom:1rem;line-height:1.75;text-align:justify">Bahwa berdasarkan Surat Keputusan <strong>${esc(SEKOLAH.nama.toUpperCase())}</strong> tentang pemberian sanksi skorsing peserta didik. Siswa yang tersebut namanya di atas harus menjalani sanksi skorsing dari <strong>${rentang||`<span class="ph">tanggal mulai – tanggal selesai</span>`}</strong> karena telah terbukti ${esc(pelanggaran)}${poinInfo}.</p>
    <p style="margin-bottom:1.5rem;line-height:1.75;text-align:justify">${pesanFinal}</p>
    <p style="margin-bottom:1rem;font-style:italic"><em>Wassalamu'alaikum Wr. Wb.</em></p>
    ${buildTTD(tglFmt,SEKOLAH.jabatanKepala,SEKOLAH.kepala,SEKOLAH.nipKepala)}`;
}

function printSurat(){
  const lo=document.getElementById('letterOuter');
  if(!lo.classList.contains('alive')){ alert('⚠️ Isi data surat terlebih dahulu sebelum mencetak.'); return; }
  const prefix=currentType==='tugas'?'t':currentType==='aktif'?'a':currentType==='kelakuan'?'k':'p';
  const nomor=document.getElementById(prefix+'_nomor')?.value?.trim()||'Surat';
  const judulMap={tugas:'Surat Tugas',aktif:'Surat Keterangan Siswa',kelakuan:'Surat Kelakuan Baik',panggilan:'Surat Panggilan Orang Tua',sosialisasi:'Surat Sosialisasi PPDB',pemberitahuan:'Surat Pemberitahuan',raport:'Surat Pengambilan Raport',undangan:'Surat Undangan',asas:'Surat Pemberitahuan ASAS',skorsing:'Surat Peringatan Skorsing',pernyataan:'Surat Pernyataan',permohonan:'Surat Permohonan Aula'};
  document.title=`${judulMap[currentType]} - ${nomor}`;
  setTimeout(()=>{ window.focus(); window.print(); setTimeout(()=>{ document.title='Generator Surat Resmi'; },3000); },150);
}

// ══════════════════════════════════════════════════════════════
// FUNGSI SIMPAN — kirim ke suratkeluar.php (file ini sendiri)
// + tambahan field untuk surat_generator
// ══════════════════════════════════════════════════════════════
function saveSurat(type){
  const prefix=type==='tugas'?'t':type==='aktif'?'a':type==='kelakuan'?'k':type==='panggilan'?'p':type==='sosialisasi'?'s':type==='pemberitahuan'?'pb':type==='raport'?'rp':type==='undangan'?'u':type==='asas'?'as':type==='skorsing'?'sk':type==='pernyataan'?'py':'pm';
  const nomor=getV(prefix+'_nomor');
  const tgl=getV(prefix+'_tanggal');

  // Kumpulkan data khusus per jenis untuk surat_generator
  let perihal='', keperluan_tugas='', jabatan='', nip='', nama_lengkap='', nisn='';

  if(type==='tugas'){
    nama_lengkap=getV('t_nama'); keperluan_tugas=getV('t_keperluan');
    jabatan=getV('t_jabatan'); nip=getV('t_nip');
    if(!nama_lengkap){alert('⚠️ Nama yang ditugaskan wajib diisi.');return;}
    if(!keperluan_tugas){alert('⚠️ Keperluan/tugas wajib diisi.');return;}
    perihal=`Surat Tugas: ${nama_lengkap} - ${keperluan_tugas}`;
  } else if(type==='aktif'){
    nama_lengkap=getV('a_nama'); nisn=getV('a_nisn');
    jabatan=getV('a_kelas'); keperluan_tugas=getV('a_keperluan');
    if(!nama_lengkap){alert('⚠️ Nama siswa wajib diisi.');return;}
    perihal=keperluan_tugas?`Surat Keterangan Siswa: ${nama_lengkap} - ${keperluan_tugas}`:`Surat Keterangan Siswa: ${nama_lengkap}`;
  } else if(type==='kelakuan'){
    nama_lengkap=getV('k_nama'); nisn=getV('k_nisn');
    jabatan=getV('k_kelas'); keperluan_tugas=getV('k_keperluan');
    if(!nama_lengkap){alert('⚠️ Nama siswa wajib diisi.');return;}
    perihal=`Surat Kelakuan Baik: ${nama_lengkap}`;
  } else if(type==='panggilan'){
    nama_lengkap=getV('p_nama'); nisn=getV('p_nisn')||'';
    jabatan=getV('p_kelas'); keperluan_tugas=getV('p_alasan');
    const ph2=getV('p_perihal')||'Pemanggilan Orang Tua';
    if(!nama_lengkap){alert('⚠️ Nama siswa wajib diisi.');return;}
    perihal=`${ph2}: ${nama_lengkap}`;
  } else if(type==='sosialisasi'){
    nama_lengkap=getV('s_sekolah_tujuan'); jabatan=getV('s_jabatan_tujuan');
    keperluan_tugas=getV('s_perihal');
    if(!nama_lengkap){alert('⚠️ Nama sekolah tujuan wajib diisi.');return;}
    perihal=`Surat Sosialisasi PPDB: ${nama_lengkap}`;
  } else if(type==='pemberitahuan'){
    nama_lengkap=getV('pb_nama_penerima'); jabatan=getV('pb_jabatan_penerima');
    keperluan_tugas=getV('pb_kegiatan');
    if(!keperluan_tugas){alert('⚠️ Nama kegiatan wajib diisi.');return;}
    perihal=`Surat Pemberitahuan Kegiatan: ${keperluan_tugas}`;
  } else if(type==='raport'){
    keperluan_tugas=getV('rp_haritgl'); jabatan=getV('rp_tempat');
    perihal=`Surat Pemberitahuan Pengambilan Raport`;
  } else if(type==='undangan'){
    nama_lengkap=getV('u_nama_penerima'); jabatan=getV('u_jabatan_penerima');
    keperluan_tugas=getV('u_kegiatan');
    if(!keperluan_tugas){alert('⚠️ Nama kegiatan wajib diisi.');return;}
    perihal=`Surat Undangan: ${keperluan_tugas}`;
  } else if(type==='asas'){
    const ta=getV('as_tahun_pelajaran'); keperluan_tugas=getV('as_perihal');
    jabatan=getV('as_kelas_penerima');
    perihal=`Surat Pemberitahuan ASAS${ta?' TA '+ta:''}`;
  } else if(type==='skorsing'){
    nama_lengkap=getV('sk_nama'); nisn=getV('sk_nisn');
    jabatan=getV('sk_kelas'); keperluan_tugas=getV('sk_pelanggaran');
    if(!nama_lengkap){alert('⚠️ Nama siswa wajib diisi.');return;}
    perihal=`Surat Peringatan Skorsing: ${nama_lengkap}`;
  } else if(type==='pernyataan'){
    nama_lengkap=getV('py_nama'); nisn=getV('py_nisn');
    jabatan=getV('py_jabatan_kepala'); nip=getV('py_nama_kepala');
    keperluan_tugas=getV('py_kebijakan');
    if(!nama_lengkap){alert('⚠️ Nama siswa wajib diisi.');return;}
    perihal=`Surat Pernyataan Keringanan Biaya: ${nama_lengkap}`;
  } else {
    nama_lengkap=getV('pm_nama_penerima'); jabatan=getV('pm_jabatan_penerima');
    keperluan_tugas=getV('pm_kegiatan');
    if(!keperluan_tugas){alert('⚠️ Nama kegiatan wajib diisi.');return;}
    perihal=`Permohonan Penggunaan Aula: ${keperluan_tugas}`;
  }

  if(!tgl){alert('⚠️ Tanggal surat wajib diisi.');return;}

  const judulMap={tugas:'Surat Tugas',aktif:'Surat Keterangan Siswa',kelakuan:'Surat Kelakuan Baik',panggilan:'Surat Panggilan Orang Tua',sosialisasi:'Surat Sosialisasi PPDB',pemberitahuan:'Surat Pemberitahuan',raport:'Surat Pengambilan Raport',undangan:'Surat Undangan',asas:'Surat Pemberitahuan ASAS',skorsing:'Surat Peringatan Skorsing',pernyataan:'Surat Pernyataan',permohonan:'Surat Permohonan Aula'};
  const konfirm=confirm(`Simpan ${judulMap[type]} ke database?\n\nNomor  : ${nomor||'(otomatis)'}\nTanggal: ${tgl}\nPerihal: ${perihal.substring(0,60)}${perihal.length>60?'...':''}`);
  if(!konfirm) return;

  const fd=new FormData();
  fd.append('save_surat','1');
  fd.append('jenis_surat', type);
  fd.append('nomor_surat', nomor);
  fd.append('tanggal',     tgl);
  fd.append('perihal',     perihal);
  // Field tambahan untuk tabel surat_generator
  fd.append('keperluan_tugas', keperluan_tugas);
  fd.append('jabatan',         jabatan);
  fd.append('nip',             nip);
  fd.append('nama_lengkap',    nama_lengkap);
  fd.append('nisn',            nisn);

  const btn=event?.target, origText=btn?.innerHTML;
  if(btn){btn.innerHTML='⏳ Menyimpan...';btn.disabled=true;}

  // ✅ PERBAIKAN: fetch ke suratkeluar.php (file ini sendiri)
  fetch('suratkeluar.php',{method:'POST',body:fd})
    .then(res=>res.text())
    .then(html=>{
      const parser=new DOMParser(),doc=parser.parseFromString(html,'text/html');
      const ok=doc.querySelector('.alert-bar.ok'),err=doc.querySelector('.alert-bar.err');
      if(ok) showToast('✅ '+(ok.textContent?.trim()||'Surat berhasil disimpan!'),'ok');
      else if(err) showToast('❌ '+(err.textContent?.trim()||'Gagal menyimpan.'),'err');
      else showToast('✅ Surat berhasil disimpan ke database!','ok');
    })
    .catch(e=>showToast('❌ Koneksi gagal: '+e.message,'err'))
    .finally(()=>{if(btn){btn.innerHTML=origText;btn.disabled=false;}});
}

function showToast(msg,type){
  document.querySelectorAll('.toast-notif').forEach(t=>t.remove());
  const toast=document.createElement('div');
  toast.className='toast-notif toast-'+type;
  toast.innerHTML=msg;
  document.body.appendChild(toast);
  setTimeout(()=>{toast.style.opacity='0';toast.style.transform='translateY(20px)';setTimeout(()=>toast.remove(),400);},4000);
}

function resetForm(type){
  const section=document.getElementById('form-'+type);
  section.querySelectorAll('input:not([type=submit]),textarea').forEach(el=>{
    if(el.type==='date') el.value='<?= date('Y-m-d') ?>';
    else el.value='';
  });
  section.querySelectorAll('select').forEach(el=>el.selectedIndex=0);
  if(type==='skorsing'){
    const speri=document.getElementById('sk_perihal');if(speri) speri.value='Surat Peringatan';
    const slamp=document.getElementById('sk_lamp');if(slamp) slamp.value='-';
    const snom=document.getElementById('sk_nomor');if(snom) snom.value='<?= $nomorSkorsing ?>';
    const spel=document.getElementById('sk_pelanggaran');if(spel) spel.value='melanggar Tata Tertib Peserta Didik Sistem Poin';
  }
  if(type==='panggilan'){
    const pj=document.getElementById('p_perihal');if(pj) pj.value='Pemanggilan Orang Tua';
    const pa=document.getElementById('p_alasan');if(pa) pa.value='melakukan pelanggaran peraturan sekolah';
    const pjam=document.getElementById('p_jam');if(pjam) pjam.value='08.30 WIB';
    const plamp=document.getElementById('p_lamp');if(plamp) plamp.value='-';
    const ptp=document.getElementById('p_tempat_pertemuan');if(ptp) ptp.value=SEKOLAH.nama;
    const pn=document.getElementById('p_nomor');if(pn) pn.value='<?= $nomorPanggil ?>';
  }
  if(type==='tugas') renderTugas();
  else if(type==='aktif') renderAktif();
  else if(type==='kelakuan') renderKelakuan();
  else if(type==='panggilan') renderPanggilan();
  else if(type==='sosialisasi') renderSosialisasi();
  else if(type==='pemberitahuan') renderPemberitahuan();
  else if(type==='raport') renderRaport();
  else if(type==='undangan') renderUndangan();
  else if(type==='asas') renderASAS();
  else if(type==='skorsing') renderSkorsing();
  else if(type==='pernyataan') renderPernyataan();
  else renderPermohonan();
}

renderTugas();
</script>
</body>
</html>