<?php require_once 'layout/header.php';
require_once 'config/icons.php';

if (!isRole('superadmin','admin')) {
    echo '<div class="card" style="text-align:center;padding:40px"><p style="color:var(--red)">Akses ditolak.</p></div>';
    require_once 'layout/footer.php'; exit;
}

if ($_SERVER['REQUEST_METHOD']==='POST') {

    $tahunLamaPdo = $pdo->prepare("SELECT nilai FROM pengaturan WHERE kunci='tahun_ajaran' LIMIT 1");
    $tahunLamaPdo->execute();
    $tahunLama = (string)($tahunLamaPdo->fetchColumn() ?? '');

    foreach ($_POST as $k => $v) {
        if ($k === '_token') continue;
        $cek = $pdo->prepare("SELECT id FROM pengaturan WHERE kunci=?");
        $cek->execute([$k]);
        if ($cek->fetch()) {
            $pdo->prepare("UPDATE pengaturan SET nilai=? WHERE kunci=?")->execute([trim($v), $k]);
        } else {
            $label = ucwords(str_replace('_',' ', $k));
            $pdo->prepare("INSERT INTO pengaturan (kunci,nilai,keterangan) VALUES (?,?,?)")->execute([$k, trim($v), $label]);
        }
    }

    $upsertFile = function(string $kunci, string $nilai, string $ket) use ($pdo) {
        $cek = $pdo->prepare("SELECT id FROM pengaturan WHERE kunci=?");
        $cek->execute([$kunci]);
        if ($cek->fetch()) {
            $pdo->prepare("UPDATE pengaturan SET nilai=? WHERE kunci=?")->execute([$nilai, $kunci]);
        } else {
            $pdo->prepare("INSERT INTO pengaturan (kunci,nilai,keterangan) VALUES (?,?,?)")->execute([$kunci, $nilai, $ket]);
        }
    };

    $rootDir = str_replace('\\','/', dirname(__DIR__));

    // Logo sekolah
    if (!empty($_FILES['logo_sekolah']['name']) && $_FILES['logo_sekolah']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['logo_sekolah']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg','jpeg','png','webp','svg']) && $_FILES['logo_sekolah']['size'] <= 2*1024*1024) {
            $dir = $rootDir.'/uploads/logo/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $nama = 'logo_sekolah.'.$ext;
            if (move_uploaded_file($_FILES['logo_sekolah']['tmp_name'], $dir.$nama))
                $upsertFile('logo_sekolah', $nama, 'Logo sekolah');
        }
    }
    // Foto kepsek
    if (!empty($_FILES['foto_kepsek']['name']) && $_FILES['foto_kepsek']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['foto_kepsek']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg','jpeg','png','webp']) && $_FILES['foto_kepsek']['size'] <= 2*1024*1024) {
            $dir = $rootDir.'/uploads/logo/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $nama = 'foto_kepsek.'.$ext;
            if (move_uploaded_file($_FILES['foto_kepsek']['tmp_name'], $dir.$nama))
                $upsertFile('foto_kepsek', $nama, 'Foto kepala sekolah/madrasah');
        }
    }
    // Cap basah sekolah
    if (!empty($_FILES['cap_sekolah']['name']) && $_FILES['cap_sekolah']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['cap_sekolah']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg','jpeg','png','webp']) && $_FILES['cap_sekolah']['size'] <= 2*1024*1024) {
            $dir = $rootDir.'/uploads/logo/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $nama = 'cap_sekolah.'.$ext;
            if (move_uploaded_file($_FILES['cap_sekolah']['tmp_name'], $dir.$nama))
                $upsertFile('cap_sekolah', $nama, 'Cap/stempel basah sekolah');
        }
    }
    // Tanda tangan kepsek
    if (!empty($_FILES['ttd_kepsek']['name']) && $_FILES['ttd_kepsek']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['ttd_kepsek']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg','jpeg','png','webp']) && $_FILES['ttd_kepsek']['size'] <= 2*1024*1024) {
            $dir = $rootDir.'/uploads/logo/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $nama = 'ttd_kepsek.'.$ext;
            if (move_uploaded_file($_FILES['ttd_kepsek']['tmp_name'], $dir.$nama))
                $upsertFile('ttd_kepsek', $nama, 'Tanda tangan kepala sekolah/madrasah');
        }
    }

    $tahunBaru = trim($_POST['tahun_ajaran'] ?? '');
    $jmlKelas = 0; $jmlSiswa = 0; $pesanSinkron = '';
    if ($tahunBaru && $tahunBaru !== $tahunLama) {
        try { $stmtK = $pdo->prepare("UPDATE kelas SET tahun_ajaran=? WHERE status='aktif'"); $stmtK->execute([$tahunBaru]); $jmlKelas = $stmtK->rowCount(); } catch (Exception $e) {}
        try { $stmtS = $pdo->prepare("UPDATE siswa SET tahun_ajaran=? WHERE status='aktif'"); $stmtS->execute([$tahunBaru]); $jmlSiswa = $stmtS->rowCount(); } catch (Exception $e) {}
        if ($jmlKelas > 0 || $jmlSiswa > 0) $pesanSinkron = " — {$jmlKelas} kelas & {$jmlSiswa} siswa diperbarui";
    }

    $_SESSION['toast'] = 'Pengaturan berhasil disimpan' . $pesanSinkron;
    $_SESSION['sinkron_info'] = ['tahun_lama'=>$tahunLama,'tahun_baru'=>$tahunBaru,'jml_kelas'=>$jmlKelas,'jml_siswa'=>$jmlSiswa,'berubah'=>($tahunBaru !== $tahunLama && $tahunBaru !== '')];
    redirect('index.php?page=pengaturan');
}

// Auto-insert default keys
$defaultKeys = [
    'nama_sekolah'   => ['nilai'=>'', 'ket'=>'Nama lengkap sekolah/madrasah'],
    'nama_yayasan'   => ['nilai'=>'', 'ket'=>'Nama yayasan/naungan (opsional)'],
    'alamat_sekolah' => ['nilai'=>'', 'ket'=>'Alamat lengkap sekolah'],
    'nama_kepsek'    => ['nilai'=>'', 'ket'=>'Nama kepala sekolah/madrasah'],
    'nip_kepsek'     => ['nilai'=>'', 'ket'=>'NIP kepala sekolah/madrasah'],
    'telp_sekolah'   => ['nilai'=>'', 'ket'=>'Nomor telepon sekolah'],
    'email_sekolah'  => ['nilai'=>'', 'ket'=>'Email resmi sekolah'],
    'website'        => ['nilai'=>'', 'ket'=>'Website sekolah (opsional)'],
    'npsn'           => ['nilai'=>'', 'ket'=>'NPSN sekolah (opsional)'],
    'akreditasi'     => ['nilai'=>'', 'ket'=>'Status akreditasi, misal: A'],
    'no_akreditasi'  => ['nilai'=>'', 'ket'=>'Nomor SK akreditasi'],
    'tahun_ajaran'   => ['nilai'=>date('Y').'/'.(date('Y')+1), 'ket'=>'Tahun ajaran aktif'],
    'nominal_spp'    => ['nilai'=>'200000', 'ket'=>'Nominal SPP default (Rp)'],
    'nama_bendahara' => ['nilai'=>'', 'ket'=>'Nama bendahara/petugas SPP'],
    'nip_bendahara'  => ['nilai'=>'', 'ket'=>'NIP bendahara/petugas SPP'],
];
foreach ($defaultKeys as $k => $d) {
    $cek = $pdo->prepare("SELECT id FROM pengaturan WHERE kunci=?"); $cek->execute([$k]);
    if (!$cek->fetch())
        $pdo->prepare("INSERT INTO pengaturan (kunci,nilai,keterangan) VALUES (?,?,?)")->execute([$k, $d['nilai'], $d['ket']]);
}

$rows  = $pdo->query("SELECT * FROM pengaturan ORDER BY id")->fetchAll();
$toast = $_SESSION['toast'] ?? ''; unset($_SESSION['toast']);
$sinkronInfo = $_SESSION['sinkron_info'] ?? null; unset($_SESSION['sinkron_info']);

$settingMap = [];
foreach ($rows as $r) $settingMap[$r['kunci']] = $r['nilai'];

$rootDir    = str_replace('\\','/', dirname(__DIR__));
$logoFile   = $settingMap['logo_sekolah'] ?? null;
$kepsekFile = $settingMap['foto_kepsek']  ?? null;
$capFile    = $settingMap['cap_sekolah']  ?? null;
$ttdFile    = $settingMap['ttd_kepsek']   ?? null;
$hasLogo    = $logoFile   && file_exists($rootDir.'/uploads/logo/'.$logoFile);
$hasKepsek  = $kepsekFile && file_exists($rootDir.'/uploads/logo/'.$kepsekFile);
$hasCap     = $capFile    && file_exists($rootDir.'/uploads/logo/'.$capFile);
$hasTtd     = $ttdFile    && file_exists($rootDir.'/uploads/logo/'.$ttdFile);
$logoUrl    = $hasLogo   ? 'uploads/logo/'.$logoFile   : null;
$kepsekUrl  = $hasKepsek ? 'uploads/logo/'.$kepsekFile : null;
$capUrl     = $hasCap    ? 'uploads/logo/'.$capFile    : null;
$ttdUrl     = $hasTtd    ? 'uploads/logo/'.$ttdFile    : null;

$tahunAjaranSaatIni = $settingMap['tahun_ajaran'] ?? '';
$jumlahKelasAktif = 0; $jumlahSiswaAktif = 0; $jumlahKelasNotSync = 0; $jumlahSiswaNotSync = 0;
try {
    $jumlahKelasAktif = (int)$pdo->query("SELECT COUNT(*) FROM kelas WHERE status='aktif'")->fetchColumn();
    $jumlahSiswaAktif = (int)$pdo->query("SELECT COUNT(*) FROM siswa WHERE status='aktif'")->fetchColumn();
    $stNS = $pdo->prepare("SELECT COUNT(*) FROM kelas WHERE status='aktif' AND tahun_ajaran != ?"); $stNS->execute([$tahunAjaranSaatIni]); $jumlahKelasNotSync = (int)$stNS->fetchColumn();
    $stNSS = $pdo->prepare("SELECT COUNT(*) FROM siswa WHERE status='aktif' AND tahun_ajaran != ?"); $stNSS->execute([$tahunAjaranSaatIni]); $jumlahSiswaNotSync = (int)$stNSS->fetchColumn();
} catch (Exception $e) {}

$fieldMeta = [
    'nama_sekolah'   => ['label'=>'Nama Sekolah / Madrasah','ph'=>'Contoh: MA AS-SYAFIYAH 02','color'=>'#4F6EF7','bg'=>'#EEF1FF','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>'],
    'nama_yayasan'   => ['label'=>'Nama Yayasan / Naungan (Kop)','ph'=>'Contoh: Yayasan Perguruan Islam As-Syafiyah','color'=>'#0EA5E9','bg'=>'#E0F2FE','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>'],
    'alamat_sekolah' => ['label'=>'Alamat Sekolah','ph'=>'Jl. Raya No.1 Kota 12345','color'=>'#14B8A6','bg'=>'#CCFBF1','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>'],
    'telp_sekolah'   => ['label'=>'Nomor Telepon','ph'=>'(021) 12345678','color'=>'#22C55E','bg'=>'#DCFCE7','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.69 12 19.79 19.79 0 0 1 1.61 3.38 2 2 0 0 1 3.6 1h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L7.91 8.6a16 16 0 0 0 5.55 5.55l.96-.96a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92z"/></svg>'],
    'email_sekolah'  => ['label'=>'Email Sekolah','ph'=>'info@sekolah.sch.id','color'=>'#F59E0B','bg'=>'#FEF3C7','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>'],
    'website'        => ['label'=>'Website Sekolah (opsional)','ph'=>'www.sekolah.sch.id','color'=>'#6366F1','bg'=>'#EEF2FF','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>'],
    'npsn'           => ['label'=>'NPSN (opsional)','ph'=>'12345678','color'=>'#8B5CF6','bg'=>'#EDE9FE','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>'],
    'akreditasi'     => ['label'=>'Status Akreditasi (untuk kop)','ph'=>'A','color'=>'#EC4899','bg'=>'#FCE7F3','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>'],
    'no_akreditasi'  => ['label'=>'Nomor SK Akreditasi (untuk kop)','ph'=>'763/BAN-SM/SK/2019','color'=>'#D97706','bg'=>'#FEF3C7','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>'],
    'tahun_ajaran'   => ['label'=>'Tahun Ajaran Aktif','ph'=>'2024/2025','color'=>'#8B5CF6','bg'=>'#EDE9FE','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>'],
    'nominal_spp'    => ['label'=>'Nominal SPP Default (Rp)','ph'=>'200000','color'=>'#EF4444','bg'=>'#FEE2E2','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>'],
];
$kepsekMeta = [
    'nama_kepsek' => ['label'=>'Nama Kepala Sekolah/Madrasah','ph'=>'Drs. Ahmad Fauzi, M.Pd.','color'=>'#EC4899','bg'=>'#FCE7F3','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>'],
    'nip_kepsek'  => ['label'=>'NIP','ph'=>'19700101 199903 1 001','color'=>'#0EA5E9','bg'=>'#E0F2FE','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>'],
];
$bendaharaMeta = [
    'nama_bendahara' => ['label'=>'Nama Bendahara / Petugas SPP','ph'=>'Siti Aminah, S.Pd.','color'=>'#10B981','bg'=>'#D1FAE5','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>'],
    'nip_bendahara'  => ['label'=>'NIP Bendahara','ph'=>'19850505 201001 2 002','color'=>'#0EA5E9','bg'=>'#E0F2FE','icon'=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>'],
];
?>
<?php if($toast): ?><script>window.onload=()=>showToast('<?= addslashes($toast) ?>')</script><?php endif ?>

<style>
.pg-section{border-radius:var(--r);background:var(--surface);border:1px solid var(--border);margin-bottom:18px;overflow:hidden;transition:border-color .2s}
.pg-section:hover{border-color:var(--border2)}
.pg-section-head{padding:16px 20px 14px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px}
.pg-section-ico{width:40px;height:40px;border-radius:11px;flex-shrink:0;display:flex;align-items:center;justify-content:center}
.pg-section-ico svg{width:20px;height:20px}
.pg-section-title{font-size:14px;font-weight:700;color:var(--text)}
.pg-section-sub{font-size:11.5px;color:var(--text3);margin-top:1px}
.pg-section-body{padding:18px 20px}
.field-icon-row{display:flex;align-items:center;gap:12px;margin-bottom:15px}
.field-ico-box{width:38px;height:38px;border-radius:10px;flex-shrink:0;display:flex;align-items:center;justify-content:center}
.field-ico-box svg{width:17px;height:17px}
.field-content{flex:1;min-width:0}
.field-content label{font-size:11px;font-weight:700;color:var(--text3);text-transform:uppercase;letter-spacing:.7px;margin-bottom:5px;display:block}
.field-content input,.field-content textarea{width:100%;padding:9px 13px;border:1.5px solid var(--border2);border-radius:var(--r-xs);font-size:13.5px;font-family:'DM Sans',sans-serif;background:var(--bg3);color:var(--text);outline:none;transition:border-color .18s,background .18s}
.field-content input:focus,.field-content textarea:focus{border-color:var(--accent-c,var(--indigo));background:var(--bg2);box-shadow:0 0 0 3px var(--accent-s,rgba(79,110,247,.1))}
.tahun-field-wrap{position:relative}
.tahun-sync-badge{position:absolute;right:10px;top:50%;transform:translateY(-50%);background:#EDE9FE;color:#7C3AED;font-size:10px;font-weight:700;padding:2px 8px;border-radius:99px;pointer-events:none}
#input_tahun_ajaran{padding-right:90px}
.sinkron-result-banner{border-radius:12px;padding:14px 18px;display:flex;align-items:flex-start;gap:12px;margin-bottom:18px;animation:bannerIn .3s ease both}
@keyframes bannerIn{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}
.sinkron-preview-box{background:linear-gradient(135deg,#F5F3FF,#EDE9FE);border:1.5px solid #C4B5FD;border-radius:12px;padding:14px 16px;margin-top:8px;display:none}
.sinkron-preview-box.show{display:block}
.sinkron-arrow-row{display:flex;align-items:center;gap:10px;justify-content:center;padding:8px 0 12px;flex-wrap:wrap}
.sinkron-chip{border-radius:8px;padding:5px 16px;font-weight:700;font-size:13px}
.upload-zone{border:2px dashed var(--border2);border-radius:var(--r-sm);cursor:pointer;transition:all .2s;overflow:hidden}
.upload-zone:hover{border-color:var(--indigo);background:var(--surface2)}
.upload-preview{padding:16px 12px;text-align:center;min-height:110px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px}
.upload-preview img{width:64px;height:64px;object-fit:contain;border-radius:8px;margin-bottom:4px}
.upload-hint{font-size:12.5px;color:var(--text2);font-weight:600}
.upload-sub{font-size:10.5px;color:var(--text3)}
.upload-name{font-size:10.5px;color:var(--text2);font-weight:600;margin-top:2px}
/* Cap & TTD specific */
.upload-zone.cap-zone .upload-preview img { background: transparent; border: none; mix-blend-mode: multiply; }
.upload-zone.ttd-zone .upload-preview img { background: transparent; border: none; }
.img-trans-bg {
  background: repeating-conic-gradient(#e0e0e0 0% 25%, white 0% 50%) 0 0 / 12px 12px;
  border-radius: 8px; padding: 4px; display:inline-block;
}
.preview-school-card{background:linear-gradient(135deg,#1E2D4E 0%,#2E4478 100%);border-radius:14px;padding:22px;color:#fff;text-align:center;margin-bottom:14px;position:relative;overflow:hidden}
.preview-school-card::before{content:'';position:absolute;top:-30px;right:-30px;width:100px;height:100px;border-radius:50%;background:rgba(79,110,247,.25);pointer-events:none}
.tip-item{display:flex;align-items:flex-start;gap:8px;padding:8px 0;border-bottom:1px solid rgba(79,110,247,.1);font-size:12px;color:var(--text2);line-height:1.5}
.tip-item:last-child{border-bottom:none}
.tip-ico{width:24px;height:24px;border-radius:6px;flex-shrink:0;display:flex;align-items:center;justify-content:center}
.tip-ico svg{width:13px;height:13px}
.kop-preview-box{background:#fff;border:1.5px solid var(--border);border-radius:12px;padding:14px;margin-top:12px;font-family:serif}
.kop-preview-garis1{border-top:4px solid #1a1a1a;margin-top:6px}
.kop-preview-garis2{border-top:1.5px solid #1a1a1a;margin-top:2px}
/* Preview TTD section */
.ttd-preview-wrap {
  display:flex;align-items:flex-end;gap:12px;
  background:#F8FAFC;border:1.5px dashed var(--border2);border-radius:12px;
  padding:14px 16px;margin-top:12px;
}
.ttd-preview-col { text-align:center;flex:1; }
.ttd-preview-img { height:56px;max-width:120px;object-fit:contain; }
.ttd-preview-garis { border-top:1.5px solid #555;padding-top:5px;margin-top:6px;font-size:11px;font-weight:600;color:#333; }
</style>

<!-- Page Header -->
<div class="page-header">
  <div>
    <div class="page-header-title" style="display:flex;align-items:center;gap:10px">
      <span style="width:36px;height:36px;border-radius:10px;background:linear-gradient(135deg,#4F6EF7,#818CF8);display:inline-flex;align-items:center;justify-content:center;color:#fff;flex-shrink:0;box-shadow:0 4px 14px rgba(79,110,247,.3)">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
      </span>
      Pengaturan Sistem
    </div>
    <div class="page-header-sub">Konfigurasi identitas &amp; informasi sekolah</div>
  </div>
</div>

<?php if($sinkronInfo && $sinkronInfo['berubah']): ?>
<div class="sinkron-result-banner" style="background:linear-gradient(135deg,#ECFDF5,#D1FAE5);border:1.5px solid #6EE7B7">
  <div style="font-size:28px;flex-shrink:0">🔄</div>
  <div style="flex:1">
    <div style="font-weight:700;font-size:14px;color:#065F46;margin-bottom:6px">Tahun Ajaran Berhasil Disinkronkan</div>
    <div style="display:flex;align-items:center;gap:10px;margin-bottom:8px;flex-wrap:wrap">
      <span style="background:#FEE2E2;color:#DC2626;border-radius:7px;padding:3px 12px;font-weight:700;font-size:13px"><?= e($sinkronInfo['tahun_lama'] ?: '—') ?></span>
      <span style="font-size:18px;color:#059669;font-weight:900">→</span>
      <span style="background:#D1FAE5;color:#065F46;border-radius:7px;padding:3px 12px;font-weight:700;font-size:13px"><?= e($sinkronInfo['tahun_baru']) ?></span>
    </div>
    <div style="display:flex;gap:16px;flex-wrap:wrap">
      <span style="background:#D1FAE5;border-radius:6px;padding:2px 8px;font-weight:700;font-size:12px;color:#065F46">🏫 <?= $sinkronInfo['jml_kelas'] ?> kelas diperbarui</span>
      <span style="background:#D1FAE5;border-radius:6px;padding:2px 8px;font-weight:700;font-size:12px;color:#065F46">👥 <?= $sinkronInfo['jml_siswa'] ?> siswa diperbarui</span>
    </div>
  </div>
</div>
<?php endif ?>

<?php if(!$sinkronInfo && ($jumlahKelasNotSync > 0 || $jumlahSiswaNotSync > 0)): ?>
<div style="background:linear-gradient(135deg,#FEF3C7,#FDE68A);border:1.5px solid #FCD34D;border-radius:12px;padding:14px 18px;margin-bottom:18px;display:flex;align-items:center;gap:12px;flex-wrap:wrap">
  <span style="font-size:22px">⚠️</span>
  <div style="flex:1">
    <div style="font-weight:700;font-size:13.5px;color:#92400E;margin-bottom:2px">Ada data belum sinkron dengan tahun ajaran aktif</div>
    <div style="font-size:12.5px;color:#B45309">
      <?php if($jumlahKelasNotSync>0): ?>🏫 <strong><?= $jumlahKelasNotSync ?> kelas</strong> <?php endif ?>
      <?php if($jumlahSiswaNotSync>0): ?>👥 <strong><?= $jumlahSiswaNotSync ?> siswa</strong> <?php endif ?>
      masih menggunakan tahun ajaran lain.
    </div>
  </div>
</div>
<?php endif ?>

<form method="POST" enctype="multipart/form-data" id="formPengaturan">
<div style="display:grid;grid-template-columns:1fr 340px;gap:20px;max-width:980px;align-items:start">

<!-- ══ KOLOM KIRI ══ -->
<div>

  <!-- ══ LOGO & FOTO (2 kolom) ══ -->
  <div class="pg-section">
    <div class="pg-section-head">
      <div class="pg-section-ico" style="background:linear-gradient(135deg,#DBEAFE,#BFDBFE)">
        <svg viewBox="0 0 24 24" fill="none" stroke="#2563EB" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
      </div>
      <div><div class="pg-section-title">Logo &amp; Foto Identitas</div><div class="pg-section-sub">Upload logo sekolah dan foto kepala sekolah</div></div>
    </div>
    <div class="pg-section-body">
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:18px">
        <!-- Logo Sekolah -->
        <div>
          <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px">
            <div style="width:28px;height:28px;border-radius:7px;background:#DBEAFE;display:flex;align-items:center;justify-content:center"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#2563EB" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg></div>
            <label style="margin:0;font-size:11.5px;font-weight:700;color:var(--text2)">Logo Sekolah</label>
          </div>
          <div class="upload-zone" onclick="document.getElementById('inputLogoSekolah').click()">
            <div class="upload-preview" id="prevLogoSekolah">
              <?php if($hasLogo): ?><img src="<?= e($logoUrl) ?>?v=<?= time() ?>" alt="Logo"><div class="upload-name"><?= e($logoFile) ?></div>
              <?php else: ?><div style="color:#3B82F6"><svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg></div><div class="upload-hint">Klik untuk upload</div><div class="upload-sub">PNG, JPG, SVG — maks 2MB</div><?php endif ?>
            </div>
            <input type="file" id="inputLogoSekolah" name="logo_sekolah" accept="image/*" style="display:none" onchange="previewUpload(this,'prevLogoSekolah',false,'previewLogoDisplay')">
          </div>
          <?php if($hasLogo): ?><div style="margin-top:6px"><span class="badge badge-success" style="font-size:10.5px">✅ Terpasang</span></div><?php endif ?>
        </div>
        <!-- Foto Kepsek -->
        <div>
          <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px">
            <div style="width:28px;height:28px;border-radius:7px;background:#FCE7F3;display:flex;align-items:center;justify-content:center"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#EC4899" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg></div>
            <label style="margin:0;font-size:11.5px;font-weight:700;color:var(--text2)">Foto Kepala Sekolah</label>
          </div>
          <div class="upload-zone" onclick="document.getElementById('inputKepsek').click()">
            <div class="upload-preview" id="prevKepsek">
              <?php if($hasKepsek): ?><img src="<?= e($kepsekUrl) ?>?v=<?= time() ?>" alt="Kepsek" style="border-radius:50%;object-fit:cover"><div class="upload-name"><?= e($kepsekFile) ?></div>
              <?php else: ?><div style="color:#EC4899"><svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg></div><div class="upload-hint">Klik untuk upload</div><div class="upload-sub">PNG, JPG — maks 2MB</div><?php endif ?>
            </div>
            <input type="file" id="inputKepsek" name="foto_kepsek" accept="image/*" style="display:none" onchange="previewUpload(this,'prevKepsek',true,'previewKepsekDisplay')">
          </div>
          <?php if($hasKepsek): ?><div style="margin-top:6px"><span class="badge badge-success" style="font-size:10.5px">✅ Terpasang</span></div><?php endif ?>
        </div>
      </div>
    </div>
  </div>

  <!-- ══ CAP BASAH & TANDA TANGAN ══ -->
  <div class="pg-section" style="border-color:#BBF7D0">
    <div class="pg-section-head" style="background:linear-gradient(135deg,#ECFDF5,#D1FAE5)">
      <div class="pg-section-ico" style="background:linear-gradient(135deg,#D1FAE5,#A7F3D0)">
        <svg viewBox="0 0 24 24" fill="none" stroke="#059669" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><polyline points="9 12 11 14 15 10"/></svg>
      </div>
      <div style="flex:1">
        <div class="pg-section-title">Cap Basah &amp; Tanda Tangan</div>
        <div class="pg-section-sub">Akan otomatis tampil di laporan &amp; kwitansi yang dicetak</div>
      </div>
      <span style="background:#059669;color:#fff;border-radius:99px;padding:3px 12px;font-size:11px;font-weight:700;flex-shrink:0">📄 Laporan &amp; Kwitansi</span>
    </div>
    <div class="pg-section-body">
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:18px">

        <!-- Cap Basah -->
        <div>
          <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px">
            <div style="width:28px;height:28px;border-radius:7px;background:#D1FAE5;display:flex;align-items:center;justify-content:center">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#059669" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
            </div>
            <div>
              <div style="font-size:12px;font-weight:700;color:var(--text2)">Cap / Stempel Basah</div>
              <div style="font-size:10.5px;color:var(--text3)">Gunakan background transparan (PNG)</div>
            </div>
          </div>
          <div class="upload-zone cap-zone" onclick="document.getElementById('inputCapSekolah').click()">
            <div class="upload-preview" id="prevCapSekolah">
              <?php if($hasCap): ?>
              <div class="img-trans-bg"><img src="<?= e($capUrl) ?>?v=<?= time() ?>" style="width:64px;height:64px;object-fit:contain;display:block"></div>
              <div class="upload-name"><?= e($capFile) ?></div>
              <?php else: ?>
              <div style="font-size:36px;margin-bottom:4px">🔴</div>
              <div class="upload-hint">Klik untuk upload cap</div>
              <div class="upload-sub">PNG transparan — maks 2MB</div>
              <?php endif ?>
            </div>
            <input type="file" id="inputCapSekolah" name="cap_sekolah" accept="image/*" style="display:none" onchange="previewUploadTransp(this,'prevCapSekolah','previewCapDisplay')">
          </div>
          <?php if($hasCap): ?>
          <div style="margin-top:6px;display:flex;align-items:center;gap:6px">
            <span class="badge badge-success" style="font-size:10.5px">✅ Terpasang</span>
          </div>
          <?php else: ?>
          <div style="margin-top:6px;font-size:10.5px;color:var(--text3)">💡 Belum ada cap — laporan tampil tanpa cap</div>
          <?php endif ?>
        </div>

        <!-- Tanda Tangan Kepsek -->
        <div>
          <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px">
            <div style="width:28px;height:28px;border-radius:7px;background:#EDE9FE;display:flex;align-items:center;justify-content:center">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#7C3AED" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 17l4-4 4 4 9-9"/><path d="M14 8l2-2 2 2"/></svg>
            </div>
            <div>
              <div style="font-size:12px;font-weight:700;color:var(--text2)">Tanda Tangan Kepala Sekolah</div>
              <div style="font-size:10.5px;color:var(--text3)">Scan TTD di kertas putih / PNG transparan</div>
            </div>
          </div>
          <div class="upload-zone ttd-zone" onclick="document.getElementById('inputTtdKepsek').click()">
            <div class="upload-preview" id="prevTtdKepsek">
              <?php if($hasTtd): ?>
              <div class="img-trans-bg"><img src="<?= e($ttdUrl) ?>?v=<?= time() ?>" style="width:64px;height:64px;object-fit:contain;display:block"></div>
              <div class="upload-name"><?= e($ttdFile) ?></div>
              <?php else: ?>
              <div style="font-size:36px;margin-bottom:4px">✍️</div>
              <div class="upload-hint">Klik untuk upload TTD</div>
              <div class="upload-sub">PNG/JPG — maks 2MB</div>
              <?php endif ?>
            </div>
            <input type="file" id="inputTtdKepsek" name="ttd_kepsek" accept="image/*" style="display:none" onchange="previewUploadTransp(this,'prevTtdKepsek','previewTtdDisplay')">
          </div>
          <?php if($hasTtd): ?>
          <div style="margin-top:6px;display:flex;align-items:center;gap:6px">
            <span class="badge badge-success" style="font-size:10.5px">✅ Terpasang</span>
          </div>
          <?php else: ?>
          <div style="margin-top:6px;font-size:10.5px;color:var(--text3)">💡 Belum ada TTD — laporan tampil tanda tangan manual</div>
          <?php endif ?>
        </div>
      </div>

      <!-- Preview TTD section -->
      <div class="ttd-preview-wrap" id="ttdPreviewSection">
        <div class="ttd-preview-col">
          <div style="font-size:10.5px;color:var(--text3);margin-bottom:6px">Mengetahui,</div>
          <div style="font-size:11px;font-weight:600;color:#333;margin-bottom:8px">Kepala Sekolah/Madrasah</div>
          <div id="previewTtdDisplay" style="height:52px;display:flex;align-items:center;justify-content:center;margin-bottom:4px">
            <?php if($hasTtd): ?>
            <div class="img-trans-bg"><img src="<?= e($ttdUrl) ?>?v=<?= time() ?>" class="ttd-preview-img" style="height:48px"></div>
            <?php else: ?>
            <div style="height:48px;width:100%;border-bottom:1.5px solid #aaa;opacity:.3"></div>
            <?php endif ?>
          </div>
          <?php if($hasCap): ?><div style="position:relative;height:1px"><img src="<?= e($capUrl) ?>?v=<?= time() ?>" id="previewCapDisplay" style="position:absolute;left:50%;transform:translateX(-50%);width:52px;height:52px;object-fit:contain;opacity:.55;top:-26px"></div><?php endif ?>
          <div class="ttd-preview-garis">
            <div style="font-size:11.5px;font-weight:700;color:#111"><?= e($settingMap['nama_kepsek']??'Nama Kepala Sekolah') ?></div>
            <div style="font-size:10px;color:#555;margin-top:2px;font-family:monospace">NIP. <?= e($settingMap['nip_kepsek']??'—') ?></div>
          </div>
        </div>
        <div style="flex:1;font-size:11px;color:var(--text3);padding-left:12px;border-left:1px solid var(--border)">
          <div style="font-weight:700;color:var(--text2);margin-bottom:6px;font-size:12px">💡 Info Penggunaan</div>
          <ul style="padding-left:14px;line-height:1.8">
            <li>Cap &amp; TTD tampil otomatis di <strong>Laporan</strong> dan <strong>Kwitansi</strong></li>
            <li>Gunakan PNG <strong>background transparan</strong> agar terlihat profesional</li>
            <li>Scan TTD di kertas putih, crop rapi sebelum upload</li>
            <li>Ukuran ideal: minimal <strong>200×100px</strong>, format PNG</li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <!-- Kepala Sekolah -->
  <div class="pg-section">
    <div class="pg-section-head">
      <div class="pg-section-ico" style="background:linear-gradient(135deg,#FCE7F3,#FBCFE8)"><svg viewBox="0 0 24 24" fill="none" stroke="#EC4899" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg></div>
      <div><div class="pg-section-title">Kepala Sekolah / Madrasah</div><div class="pg-section-sub">Nama lengkap dan NIP kepala sekolah</div></div>
    </div>
    <div class="pg-section-body">
      <?php foreach($kepsekMeta as $k=>$m): ?>
      <div class="field-icon-row">
        <div class="field-ico-box" style="background:<?= $m['bg'] ?>;color:<?= $m['color'] ?>"><?= $m['icon'] ?></div>
        <div class="field-content" style="--accent-c:<?= $m['color'] ?>;--accent-s:<?= $m['color'] ?>22">
          <label><?= $m['label'] ?></label>
          <input type="text" name="<?= $k ?>" id="input_<?= $k ?>" value="<?= e($settingMap[$k] ?? '') ?>" placeholder="<?= e($m['ph']) ?>" <?= $k==='nip_kepsek'?'style="font-family:\'DM Mono\',monospace;letter-spacing:.3px"':'' ?>>
        </div>
      </div>
      <?php endforeach ?>
    </div>
  </div>

  <!-- Bendahara / Petugas SPP -->
  <div class="pg-section">
    <div class="pg-section-head">
      <div class="pg-section-ico" style="background:linear-gradient(135deg,#D1FAE5,#A7F3D0)">
        <svg viewBox="0 0 24 24" fill="none" stroke="#059669" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
      </div>
      <div><div class="pg-section-title">Bendahara / Petugas SPP</div><div class="pg-section-sub">Nama dan NIP yang muncul di kolom "Dibuat oleh" pada laporan</div></div>
    </div>
    <div class="pg-section-body">
      <?php foreach($bendaharaMeta as $k=>$m): ?>
      <div class="field-icon-row">
        <div class="field-ico-box" style="background:<?= $m['bg'] ?>;color:<?= $m['color'] ?>"><?= $m['icon'] ?></div>
        <div class="field-content" style="--accent-c:<?= $m['color'] ?>;--accent-s:<?= $m['color'] ?>22">
          <label><?= $m['label'] ?></label>
          <input type="text" name="<?= $k ?>" id="input_<?= $k ?>" value="<?= e($settingMap[$k] ?? '') ?>" placeholder="<?= e($m['ph']) ?>" <?= $k==='nip_bendahara'?'style="font-family:\'DM Mono\',monospace;letter-spacing:.3px"':'' ?>>
        </div>
      </div>
      <?php endforeach ?>
    </div>
  </div>

  <!-- Informasi Sekolah & Kop -->
  <div class="pg-section">
    <div class="pg-section-head">
      <div class="pg-section-ico" style="background:linear-gradient(135deg,#EEF1FF,#DBEAFE)"><svg viewBox="0 0 24 24" fill="none" stroke="#4F6EF7" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg></div>
      <div><div class="pg-section-title">Informasi Sekolah &amp; Kop Surat</div><div class="pg-section-sub">Nama, alamat, kontak, akreditasi untuk kop laporan</div></div>
    </div>
    <div class="pg-section-body">
      <?php
      $infoKeys = ['nama_sekolah','nama_yayasan','alamat_sekolah','telp_sekolah','email_sekolah','website','npsn','akreditasi','no_akreditasi'];
      foreach($infoKeys as $k):
        if(!isset($fieldMeta[$k])) continue; $m = $fieldMeta[$k];
      ?>
      <div class="field-icon-row">
        <div class="field-ico-box" style="background:<?= $m['bg'] ?>;color:<?= $m['color'] ?>"><?= $m['icon'] ?></div>
        <div class="field-content" style="--accent-c:<?= $m['color'] ?>;--accent-s:<?= $m['color'] ?>22">
          <label><?= $m['label'] ?></label>
          <input type="text" name="<?= $k ?>" id="input_<?= $k ?>" value="<?= e($settingMap[$k] ?? '') ?>" placeholder="<?= e($m['ph']) ?>">
        </div>
      </div>
      <?php endforeach ?>
      <!-- Preview kop mini -->
      <div style="margin-top:6px;background:#F8FAFC;border:1.5px dashed var(--border2);border-radius:10px;padding:12px">
        <div style="font-size:10px;font-weight:700;color:var(--text3);text-transform:uppercase;letter-spacing:.6px;margin-bottom:8px">Preview Kop Surat</div>
        <div class="kop-preview-box">
          <table style="width:100%;border-collapse:collapse">
            <tr>
              <td style="width:60px;text-align:center;vertical-align:middle;padding:0 8px 0 0">
                <?php if($hasLogo): ?><img src="<?= e($logoUrl) ?>?v=<?= time() ?>" style="width:55px;height:55px;object-fit:contain"><?php else: ?>
                <div style="width:55px;height:55px;border-radius:50%;border:2px solid #1a1a1a;display:flex;align-items:center;justify-content:center;margin:0 auto"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#1a1a1a" stroke-width="1.5"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg></div>
                <?php endif ?>
              </td>
              <td style="text-align:center;vertical-align:middle">
                <div id="kopPrevYayasan" style="font-size:8.5pt;font-weight:600;color:#1a1a1a;font-family:serif;<?= $settingMap['nama_yayasan']??''?'':'display:none' ?>"><?= e($settingMap['nama_yayasan']??'') ?></div>
                <div id="kopPrevNama" style="font-size:14pt;font-weight:900;color:#1a1a1a;font-family:serif;text-transform:uppercase;line-height:1.1"><?= e($settingMap['nama_sekolah']??'Nama Sekolah') ?></div>
                <div id="kopPrevAkred" style="font-size:8pt;font-weight:800;color:#1a1a1a;font-family:serif;<?= $settingMap['akreditasi']??''?'':'display:none' ?>">STATUS TERAKREDITASI <?= e($settingMap['akreditasi']??'') ?></div>
                <div id="kopPrevNoAkred" style="font-size:7.5pt;font-weight:600;color:#1a1a1a;<?= $settingMap['no_akreditasi']??''?'':'display:none' ?>">No. Akreditasi : <?= e($settingMap['no_akreditasi']??'') ?></div>
                <div id="kopPrevAlamat" style="font-size:7.5pt;font-weight:600;color:#1a1a1a"><?= e(($settingMap['alamat_sekolah']??'').($settingMap['telp_sekolah']??''?' Telp. '.($settingMap['telp_sekolah']??''):'')) ?></div>
              </td>
              <td style="width:60px"></td>
            </tr>
          </table>
          <div class="kop-preview-garis1"></div>
          <div class="kop-preview-garis2"></div>
        </div>
      </div>
    </div>
  </div>

  <!-- Akademik & Keuangan -->
  <div class="pg-section" style="border-color:#C4B5FD">
    <div class="pg-section-head" style="background:linear-gradient(135deg,#F5F3FF,#EDE9FE)">
      <div class="pg-section-ico" style="background:linear-gradient(135deg,#EDE9FE,#FEE2E2)"><svg viewBox="0 0 24 24" fill="none" stroke="#8B5CF6" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg></div>
      <div style="flex:1"><div class="pg-section-title">Akademik &amp; Keuangan</div><div class="pg-section-sub">Tahun ajaran aktif dan nominal SPP</div></div>
      <div style="display:flex;align-items:center;gap:6px;background:#7C3AED;color:#fff;border-radius:99px;padding:4px 12px;font-size:11px;font-weight:700;flex-shrink:0"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 .49-3.85"/></svg>Sinkron Otomatis</div>
    </div>
    <div class="pg-section-body">
      <?php $m=$fieldMeta['tahun_ajaran']; ?>
      <div class="field-icon-row" style="margin-bottom:8px">
        <div class="field-ico-box" style="background:<?= $m['bg'] ?>;color:<?= $m['color'] ?>"><?= $m['icon'] ?></div>
        <div class="field-content" style="--accent-c:<?= $m['color'] ?>;--accent-s:<?= $m['color'] ?>22">
          <label><?= $m['label'] ?> <span style="background:#7C3AED;color:#fff;border-radius:99px;padding:1px 7px;font-size:9px;font-weight:700;letter-spacing:.4px;margin-left:4px">🔄 SINKRON OTOMATIS</span></label>
          <div class="tahun-field-wrap">
            <input type="text" name="tahun_ajaran" id="input_tahun_ajaran" value="<?= e($settingMap['tahun_ajaran']??'') ?>" placeholder="<?= e($m['ph']) ?>" oninput="onTahunChange(this.value)" data-tahun-asal="<?= e($tahunAjaranSaatIni) ?>">
            <span class="tahun-sync-badge">🔄 Auto-sync</span>
          </div>
        </div>
      </div>
      <div id="sinkronPreviewBox" class="sinkron-preview-box">
        <div style="font-weight:700;font-size:13px;color:#5B21B6;margin-bottom:10px">🔄 Preview Sinkronisasi</div>
        <div class="sinkron-arrow-row">
          <div style="text-align:center"><div style="font-size:9.5px;font-weight:700;color:#9CA3AF;margin-bottom:4px;text-transform:uppercase">Tahun Lama</div><span class="sinkron-chip" style="background:#FEE2E2;color:#DC2626" id="sinkronDariLabel"><?= e($tahunAjaranSaatIni) ?></span></div>
          <div style="font-size:22px;color:#7C3AED;font-weight:900">→</div>
          <div style="text-align:center"><div style="font-size:9.5px;font-weight:700;color:#9CA3AF;margin-bottom:4px;text-transform:uppercase">Tahun Baru</div><span class="sinkron-chip" style="background:#D1FAE5;color:#065F46" id="sinkronKeLabel">—</span></div>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
          <div style="background:rgba(255,255,255,.7);border-radius:8px;padding:10px;text-align:center;border:1px solid #DDD6FE"><div style="font-size:20px;font-weight:800;color:#7C3AED"><?= $jumlahKelasAktif ?></div><div style="font-size:11px;color:#6B7280;font-weight:500">🏫 kelas aktif</div></div>
          <div style="background:rgba(255,255,255,.7);border-radius:8px;padding:10px;text-align:center;border:1px solid #DDD6FE"><div style="font-size:20px;font-weight:800;color:#7C3AED"><?= $jumlahSiswaAktif ?></div><div style="font-size:11px;color:#6B7280;font-weight:500">👥 siswa aktif</div></div>
        </div>
      </div>
      <?php $m=$fieldMeta['nominal_spp']; ?>
      <div class="field-icon-row" style="margin-top:14px">
        <div class="field-ico-box" style="background:<?= $m['bg'] ?>;color:<?= $m['color'] ?>"><?= $m['icon'] ?></div>
        <div class="field-content" style="--accent-c:<?= $m['color'] ?>;--accent-s:<?= $m['color'] ?>22">
          <label><?= $m['label'] ?></label>
          <input type="number" name="nominal_spp" id="input_nominal_spp" value="<?= e($settingMap['nominal_spp']??'') ?>" placeholder="200000" min="0" step="1000" style="font-family:'DM Mono',monospace">
        </div>
      </div>
    </div>
  </div>

  <div style="display:flex;gap:10px;align-items:center;padding:4px 0 20px">
    <button type="submit" class="btn btn-primary" style="display:inline-flex;align-items:center;gap:7px;padding:10px 22px;font-size:13.5px">
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
      Simpan Semua Pengaturan
    </button>
    <button type="button" class="btn btn-outline" onclick="location.reload()">Reset</button>
  </div>

</div><!-- end kolom kiri -->

<!-- ══ KOLOM KANAN ══ -->
<div>
  <div class="pg-section" style="position:sticky;top:76px">
    <div class="pg-section-head">
      <div class="pg-section-ico" style="background:linear-gradient(135deg,#DBEAFE,#E0E7FF)"><svg viewBox="0 0 24 24" fill="none" stroke="#2563EB" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></div>
      <div><div class="pg-section-title">Preview Identitas</div><div class="pg-section-sub">Tampilan real-time saat mengetik</div></div>
    </div>
    <div class="pg-section-body" style="padding-top:12px">
      <div class="preview-school-card">
        <div id="previewLogoDisplay" style="width:64px;height:64px;border-radius:16px;background:rgba(255,255,255,.15);display:flex;align-items:center;justify-content:center;margin:0 auto 12px;overflow:hidden;color:rgba(255,255,255,.7);position:relative;z-index:1">
          <?php if($hasLogo): ?><img src="<?= e($logoUrl) ?>?v=<?= time() ?>" style="width:100%;height:100%;object-fit:contain"><?php else: ?><svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg><?php endif ?>
        </div>
        <div style="font-size:14.5px;font-weight:700;line-height:1.3;position:relative;z-index:1" id="prevNamaSekolah"><?= e($settingMap['nama_sekolah']??'Nama Sekolah') ?></div>
        <div style="font-size:10.5px;opacity:.6;margin-top:4px;line-height:1.5;position:relative;z-index:1" id="prevAlamatSekolah"><?= e($settingMap['alamat_sekolah']??'Alamat Sekolah') ?></div>
      </div>

      <!-- Kepsek preview -->
      <div style="background:var(--bg3);border:1px solid var(--border);border-radius:12px;padding:14px;margin-bottom:12px">
        <div style="font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--text3);margin-bottom:10px">Kepala Sekolah / Madrasah</div>
        <div style="display:flex;align-items:center;gap:12px">
          <div id="previewKepsekDisplay" style="width:50px;height:50px;border-radius:50%;background:var(--indigo-light);overflow:hidden;flex-shrink:0;display:flex;align-items:center;justify-content:center;color:var(--indigo);border:2px solid var(--border2)">
            <?php if($hasKepsek): ?><img src="<?= e($kepsekUrl) ?>?v=<?= time() ?>" style="width:100%;height:100%;object-fit:cover"><?php else: ?><svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg><?php endif ?>
          </div>
          <div style="flex:1;min-width:0">
            <div style="font-size:13px;font-weight:600;color:var(--text)" id="prevNamaKepsek"><?= e($settingMap['nama_kepsek']??'–') ?></div>
            <div style="font-size:11px;color:var(--text3);margin-top:3px" id="prevNipKepsek"><?= $settingMap['nip_kepsek']?'NIP. '.e($settingMap['nip_kepsek']):'NIP belum diisi' ?></div>
          </div>
        </div>
      </div>

      <!-- Bendahara preview -->
      <div style="background:var(--bg3);border:1px solid var(--border);border-radius:12px;padding:14px;margin-bottom:12px">
        <div style="font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--text3);margin-bottom:10px">Bendahara / Petugas SPP</div>
        <div style="display:flex;align-items:center;gap:12px">
          <div style="width:50px;height:50px;border-radius:50%;background:#D1FAE5;overflow:hidden;flex-shrink:0;display:flex;align-items:center;justify-content:center;color:#059669;border:2px solid var(--border2)">
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
          </div>
          <div style="flex:1;min-width:0">
            <div style="font-size:13px;font-weight:600;color:var(--text)" id="prevNamaBendahara"><?= e($settingMap['nama_bendahara']??'–') ?></div>
            <div style="font-size:11px;color:var(--text3);margin-top:3px" id="prevNipBendahara"><?= $settingMap['nip_bendahara']?'NIP. '.e($settingMap['nip_bendahara']):'NIP belum diisi' ?></div>
          </div>
        </div>
      </div>

      <!-- Cap & TTD mini preview -->
      <div style="background:var(--bg3);border:1px solid var(--border);border-radius:12px;padding:12px;margin-bottom:12px">
        <div style="font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--text3);margin-bottom:8px">Cap &amp; Tanda Tangan</div>
        <div style="display:flex;gap:12px;align-items:flex-end">
          <div style="flex:1;text-align:center">
            <div id="sidebarTtdWrap" style="height:40px;display:flex;align-items:center;justify-content:center;margin-bottom:4px">
              <?php if($hasTtd): ?>
              <img src="<?= e($ttdUrl) ?>?v=<?= time() ?>" style="max-height:38px;max-width:80px;object-fit:contain">
              <?php else: ?>
              <div style="width:80px;height:2px;background:var(--border2);border-radius:99px;margin:0 auto"></div>
              <?php endif ?>
            </div>
            <div style="font-size:9.5px;color:var(--text3);border-top:1px solid var(--border2);padding-top:4px">Tanda Tangan</div>
          </div>
          <div style="width:1px;height:40px;background:var(--border)"></div>
          <div style="flex:1;text-align:center">
            <div id="sidebarCapWrap" style="height:40px;display:flex;align-items:center;justify-content:center;margin-bottom:4px">
              <?php if($hasCap): ?>
              <img src="<?= e($capUrl) ?>?v=<?= time() ?>" style="max-height:38px;max-width:60px;object-fit:contain;opacity:.75">
              <?php else: ?>
              <div style="font-size:22px;opacity:.3">🔴</div>
              <?php endif ?>
            </div>
            <div style="font-size:9.5px;color:var(--text3);border-top:1px solid var(--border2);padding-top:4px">Cap Sekolah</div>
          </div>
        </div>
        <?php if(!$hasTtd && !$hasCap): ?>
        <div style="font-size:10.5px;color:var(--text3);text-align:center;margin-top:6px">Belum ada cap &amp; TTD — upload di atas</div>
        <?php endif ?>
      </div>

      <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:12px">
        <div style="background:var(--bg3);border:1px solid var(--border);border-radius:9px;padding:10px"><div style="font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.6px;color:var(--text3);margin-bottom:4px">Telepon</div><div style="font-size:11.5px;color:var(--text);font-weight:500;font-family:'DM Mono',monospace" id="prevTelp"><?= e($settingMap['telp_sekolah']??'–') ?></div></div>
        <div style="background:var(--bg3);border:1px solid var(--border);border-radius:9px;padding:10px"><div style="font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.6px;color:var(--text3);margin-bottom:4px">Email</div><div style="font-size:11px;color:var(--text);font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis" id="prevEmail"><?= e($settingMap['email_sekolah']??'–') ?></div></div>
      </div>
      <div style="background:linear-gradient(135deg,var(--indigo-light),#EDE9FE);border:1px solid rgba(79,110,247,.15);border-radius:10px;padding:12px;display:flex;align-items:center;gap:10px" id="prevAkademikBox">
        <div style="width:36px;height:36px;border-radius:9px;background:rgba(79,110,247,.15);display:flex;align-items:center;justify-content:center;flex-shrink:0"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#4F6EF7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg></div>
        <div>
          <div style="font-size:10px;color:var(--indigo);font-weight:700;text-transform:uppercase;letter-spacing:.6px">Tahun Ajaran &amp; SPP</div>
          <div style="font-size:13px;font-weight:600;color:var(--text);margin-top:2px">
            <span id="prevTahunAjaran"><?= e($settingMap['tahun_ajaran']??'–') ?></span> &middot;
            <span style="font-family:'DM Mono',monospace" id="prevNominal">Rp <?= number_format((int)($settingMap['nominal_spp']??0),0,',','.') ?></span>
          </div>
          <div id="prevSinkronLabel" style="display:none;font-size:10.5px;color:#7C3AED;font-weight:600;margin-top:3px">🔄 Akan disinkronkan ke semua kelas &amp; siswa</div>
        </div>
      </div>
    </div>
  </div>

  <!-- Petunjuk -->
  <div class="pg-section" style="margin-top:16px">
    <div class="pg-section-head">
      <div class="pg-section-ico" style="background:linear-gradient(135deg,#FEF3C7,#FDE68A)"><svg viewBox="0 0 24 24" fill="none" stroke="#D97706" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg></div>
      <div><div class="pg-section-title">Petunjuk</div><div class="pg-section-sub">Tips penggunaan halaman ini</div></div>
    </div>
    <div class="pg-section-body" style="padding-top:4px">
      <div class="tip-item"><div class="tip-ico" style="background:#EDE9FE;color:#7C3AED"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 .49-3.85"/></svg></div><span><strong>Sinkron Otomatis:</strong> Mengubah Tahun Ajaran akan otomatis memperbarui semua kelas &amp; siswa aktif.</span></div>
      <div class="tip-item"><div class="tip-ico" style="background:#D1FAE5;color:#059669"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><polyline points="9 12 11 14 15 10"/></svg></div><span><strong>Cap &amp; TTD</strong> tampil otomatis di laporan cetak dan kwitansi. Gunakan PNG transparan untuk hasil terbaik.</span></div>
      <div class="tip-item"><div class="tip-ico" style="background:#FEE2E2;color:#EF4444"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg></div><span>Isi <strong>Nama Yayasan, Akreditasi, No. Akreditasi</strong> agar tampil di kop surat laporan.</span></div>
      <div class="tip-item"><div class="tip-ico" style="background:#DBEAFE;color:#2563EB"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg></div><span>Logo &amp; foto maks <strong>2MB</strong>. Format: JPG, PNG, WEBP, SVG.</span></div>
      <div class="tip-item"><div class="tip-ico" style="background:#DCFCE7;color:#16A34A"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="20 6 9 17 4 12"/></svg></div><span>Preview kop surat: klik <strong>"Preview Kop"</strong> di halaman Laporan.</span></div>
    </div>
  </div>
</div>

</div>
</form>

<script>
var _tahunAsal = document.getElementById('input_tahun_ajaran').dataset.tahunAsal || '';

function onTahunChange(val) {
  val = val.trim();
  var previewBox   = document.getElementById('sinkronPreviewBox');
  var keLabel      = document.getElementById('sinkronKeLabel');
  var dariLabel    = document.getElementById('sinkronDariLabel');
  var sinkronLabel = document.getElementById('prevSinkronLabel');
  var prevBox      = document.getElementById('prevAkademikBox');
  if (val && val !== _tahunAsal) {
    dariLabel.textContent = _tahunAsal || '—'; keLabel.textContent = val;
    previewBox.classList.add('show'); sinkronLabel.style.display='block';
    prevBox.style.borderColor='#C4B5FD';
  } else {
    previewBox.classList.remove('show'); sinkronLabel.style.display='none';
    prevBox.style.borderColor='';
  }
  document.getElementById('prevTahunAjaran').textContent = val || '–';
}

function previewUpload(input, previewId, circle, sidebarId) {
  if (!input.files || !input.files[0]) return;
  var file = input.files[0];
  var prev = document.getElementById(previewId);
  var reader = new FileReader();
  reader.onload = function(ev) {
    var r = circle ? 'border-radius:50%;object-fit:cover' : 'border-radius:10px;object-fit:contain';
    prev.innerHTML = '<img src="'+ev.target.result+'" style="width:70px;height:70px;'+r+';margin-bottom:5px"><div class="upload-name">'+file.name+'</div>';
    if (sidebarId) {
      var sb = document.getElementById(sidebarId); if(!sb) return;
      sb.innerHTML = '<img src="'+ev.target.result+'" style="width:100%;height:100%;object-fit:'+(circle?'cover':'contain')+'">';
    }
  };
  reader.readAsDataURL(file);
}

/* Preview untuk cap & TTD (tampilkan background kotak catur) */
function previewUploadTransp(input, previewId, sidebarId) {
  if (!input.files || !input.files[0]) return;
  var file = input.files[0];
  var prev = document.getElementById(previewId);
  var reader = new FileReader();
  reader.onload = function(ev) {
    prev.innerHTML = '<div class="img-trans-bg"><img src="'+ev.target.result+'" style="width:64px;height:64px;object-fit:contain;display:block"></div>'
                   + '<div class="upload-name">'+file.name+'</div>';
    /* Update sidebar preview */
    if (sidebarId) {
      var sb = document.getElementById(sidebarId); if(!sb) return;
      sb.innerHTML = '<img src="'+ev.target.result+'" style="max-height:38px;max-width:80px;object-fit:contain">';
    }
    /* Update ttd preview section */
    if (previewId === 'prevTtdKepsek') {
      var td = document.getElementById('previewTtdDisplay'); if(!td) return;
      td.innerHTML = '<div class="img-trans-bg"><img src="'+ev.target.result+'" class="ttd-preview-img" style="height:48px"></div>';
      /* Sidebar TTD wrap */
      var stw = document.getElementById('sidebarTtdWrap'); if(stw)
        stw.innerHTML = '<img src="'+ev.target.result+'" style="max-height:38px;max-width:80px;object-fit:contain">';
    }
    if (previewId === 'prevCapSekolah') {
      /* Sidebar cap wrap */
      var scw = document.getElementById('sidebarCapWrap'); if(scw)
        scw.innerHTML = '<img src="'+ev.target.result+'" style="max-height:38px;max-width:60px;object-fit:contain;opacity:.75">';
    }
  };
  reader.readAsDataURL(file);
}

function liveSync(inputId, targetId, fn) {
  var inp=document.getElementById(inputId); var tgt=document.getElementById(targetId);
  if(!inp||!tgt)return;
  inp.addEventListener('input',function(){ tgt.textContent=fn?fn(inp.value):(inp.value||'–'); });
}
liveSync('input_nama_sekolah',   'prevNamaSekolah',   null);
liveSync('input_alamat_sekolah', 'prevAlamatSekolah', null);
liveSync('input_telp_sekolah',   'prevTelp',          null);
liveSync('input_email_sekolah',  'prevEmail',         null);
liveSync('input_nominal_spp',    'prevNominal',       function(v){ return 'Rp '+( parseInt(v)||0).toLocaleString('id-ID'); });
liveSync('input_nama_kepsek',    'prevNamaKepsek',    null);
liveSync('input_nip_kepsek',     'prevNipKepsek',     function(v){ return v?'NIP. '+v:'NIP belum diisi'; });
liveSync('input_nama_bendahara', 'prevNamaBendahara', null);
liveSync('input_nip_bendahara',  'prevNipBendahara',  function(v){ return v?'NIP. '+v:'NIP belum diisi'; });

function liveSyncKop(inputId, kopTargetId, upperCase, showHide) {
  var inp = document.getElementById(inputId); var tgt = document.getElementById(kopTargetId);
  if(!inp||!tgt)return;
  inp.addEventListener('input',function(){
    var v = inp.value.trim();
    if(showHide){ tgt.style.display = v?'':'none'; }
    tgt.textContent = upperCase ? v.toUpperCase() : v;
  });
}
liveSyncKop('input_nama_sekolah',  'kopPrevNama',    true,  false);
liveSyncKop('input_nama_yayasan',  'kopPrevYayasan', false, true);
liveSyncKop('input_akreditasi',    'kopPrevAkred',   false, true);
liveSyncKop('input_no_akreditasi', 'kopPrevNoAkred', false, true);

function syncAlamatKop() {
  var a = (document.getElementById('input_alamat_sekolah')||{value:''}).value.trim();
  var t = (document.getElementById('input_telp_sekolah')||{value:''}).value.trim();
  var tgt = document.getElementById('kopPrevAlamat');
  if(tgt) tgt.textContent = a + (t?' Telp. '+t:'');
}
var iaEl = document.getElementById('input_alamat_sekolah');
var itEl = document.getElementById('input_telp_sekolah');
if(iaEl) iaEl.addEventListener('input', syncAlamatKop);
if(itEl) itEl.addEventListener('input', syncAlamatKop);

document.getElementById('input_akreditasi') && document.getElementById('input_akreditasi').addEventListener('input', function(){
  var v = this.value.trim(); var el = document.getElementById('kopPrevAkred');
  if(el){ el.style.display=v?'':'none'; el.textContent='STATUS TERAKREDITASI '+v; }
});
</script>

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