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

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

// ══════════════════════════════════════════════════════
//  Handle update settings
// ══════════════════════════════════════════════════════
if(isset($_POST['update_sekolah'])){
    $fields = [
        'nama_sekolah'      => $_POST['nama_sekolah']      ?? '',
        'nama_yayasan'      => $_POST['nama_yayasan']      ?? '',
        'status_akreditasi' => $_POST['status_akreditasi'] ?? '',
        'no_akreditasi'     => $_POST['no_akreditasi']     ?? '',
        'jabatan_kepala'    => $_POST['jabatan_kepala']    ?? '',
        'alamat'            => $_POST['alamat']            ?? '',
        'telp'              => $_POST['telp']              ?? '',
        'email'             => $_POST['email']             ?? '',
        'website'           => $_POST['website']           ?? '',
        'kepala_sekolah'    => $_POST['kepala_sekolah']    ?? '',
        'nip_kepala'        => $_POST['nip_kepala']        ?? '',
        'kota_surat'        => $_POST['kota_surat']        ?? 'Kota Bekasi',
        'kode_surat'        => $_POST['kode_surat']        ?? '',
    ];

    $logo_path = getSetting('logo_sekolah', '');
    if(isset($_FILES['logo']) && $_FILES['logo']['error'] == 0){
        $upload_dir = 'uploads/logo/';
        if(!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
        $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
        if(in_array($ext, ['jpg','jpeg','png','webp'])){
            $filename = 'logo_sekolah.' . $ext;
            $target = $upload_dir . $filename;
            if(move_uploaded_file($_FILES['logo']['tmp_name'], $target)){
                if(!empty($logo_path) && file_exists($logo_path) && $logo_path !== 'assets/sekolah.png') unlink($logo_path);
                $logo_path = $target;
            }
        }
    }
    $fields['logo_sekolah'] = $logo_path;

    $ttd_path = getSetting('ttd_image', '');
    if(isset($_FILES['ttd_image']) && $_FILES['ttd_image']['error'] == 0){
        $upload_dir = 'uploads/ttd/';
        if(!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
        $ext = strtolower(pathinfo($_FILES['ttd_image']['name'], PATHINFO_EXTENSION));
        if(in_array($ext, ['jpg','jpeg','png','webp'])){
            $filename = 'ttd_kepala.' . $ext;
            $target   = $upload_dir . $filename;
            if(move_uploaded_file($_FILES['ttd_image']['tmp_name'], $target)){
                if(!empty($ttd_path) && file_exists($ttd_path)) unlink($ttd_path);
                $ttd_path = $target;
            }
        }
    }
    $fields['ttd_image'] = $ttd_path;

    $cap_path = getSetting('cap_sekolah', '');
    if(isset($_FILES['cap_sekolah']) && $_FILES['cap_sekolah']['error'] == 0){
        $upload_dir = 'uploads/cap/';
        if(!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
        $ext = strtolower(pathinfo($_FILES['cap_sekolah']['name'], PATHINFO_EXTENSION));
        if(in_array($ext, ['jpg','jpeg','png','webp'])){
            $filename = 'cap_sekolah.' . $ext;
            $target   = $upload_dir . $filename;
            if(move_uploaded_file($_FILES['cap_sekolah']['tmp_name'], $target)){
                if(!empty($cap_path) && file_exists($cap_path)) unlink($cap_path);
                $cap_path = $target;
            }
        }
    }
    $fields['cap_sekolah'] = $cap_path;

    $vals = [];
    foreach($fields as $k => $v){
        $ks = mysqli_real_escape_string($conn, $k);
        $vs = mysqli_real_escape_string($conn, $v);
        $vals[] = "('$ks','$vs')";
    }
    $q = "INSERT INTO settings (setting_key,setting_value) VALUES ".implode(',',$vals)."
          ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value)";
    if(mysqli_query($conn,$q)) $success="✅ Pengaturan sekolah & surat berhasil disimpan!";
    else $error='❌ Gagal menyimpan: '.mysqli_error($conn);
}

if(isset($_POST['update_akademik'])){
    $tahun_ajaran = mysqli_real_escape_string($conn,$_POST['tahun_ajaran']??'');
    $semester     = mysqli_real_escape_string($conn,$_POST['semester']??'');
    $q = "INSERT INTO settings (setting_key,setting_value) VALUES
          ('tahun_ajaran','$tahun_ajaran'),('semester','$semester')
          ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value)";
    if(mysqli_query($conn,$q)) $success="✅ Pengaturan akademik berhasil disimpan!";
    else $error='❌ Gagal menyimpan: '.mysqli_error($conn);
}

$settings=[];
$r=mysqli_query($conn,"SELECT setting_key, setting_value FROM settings");
if($r) while($row=mysqli_fetch_assoc($r)) $settings[$row['setting_key']]=$row['setting_value'];
function getSetting($key,$default=''){global $settings;return $settings[$key]??$default;}

/* ── Setup untuk navbar.php ── */
$page_title  = "Pengaturan Sistem — MA As-Syafi'iyah 02";
$active_menu = 'pengaturan';
$loader_text = 'Memuat Pengaturan';
include 'navbar.php';
?>

<div class="main">

    <!-- PAGE HEADER -->
    <div class="pg-hdr">
        <div class="pg-hdr-left">
            <div class="pg-hdr-ico">⚙️</div>
            <div>
                <h1 class="pg-hdr-title">Pengaturan Sistem</h1>
                <p class="pg-hdr-sub">Semua perubahan langsung terhubung ke Generator Surat &amp; Kop Surat</p>
            </div>
        </div>
        <a href="surat-generator.php" class="btn-ghost-hdr">📄 Buka Generator →</a>
    </div>

    <div class="wrap">

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

        <!-- ══ INFORMASI SEKOLAH ══ -->
        <form method="POST" action="pengaturan.php" enctype="multipart/form-data">
        <div class="pg-card fade-up">
            <div class="pg-sec-hdr">
                <div class="pg-sec-ico pg-ico-gold">🏫</div>
                <div class="pg-sec-text">
                    <div class="pg-sec-title">Informasi Sekolah &amp; Kepala</div>
                    <div class="pg-sec-sub">Data ini tampil otomatis di Kop Surat dan Tanda Tangan semua surat</div>
                </div>
                <div class="pg-sec-badge-wrap"><span class="pg-sync-badge">Terhubung ke Generator Surat</span></div>
            </div>

            <!-- KOP PREVIEW LIVE -->
            <div class="kop-preview-box" id="kopPreviewBox">
                <div class="kop-preview-inner" id="kopPreviewInner">
                    <div class="kop-prev-logo">
                        <?php $lg = getSetting('logo_sekolah',''); ?>
                        <?php if(!empty($lg) && file_exists($lg)): ?>
                            <img src="<?= htmlspecialchars($lg) ?>" id="kopLogoImg" alt="Logo">
                        <?php else: ?>
                            <span style="font-size:2.5rem" id="kopLogoFallback">🏛️</span>
                            <img src="" id="kopLogoImg" style="display:none" alt="Logo">
                        <?php endif; ?>
                    </div>
                    <div class="kop-prev-text">
                        <div class="kop-prev-yayasan" id="prevYayasan"><?= htmlspecialchars(getSetting('nama_yayasan',"Yayasan Perguruan Islam As-Syafi'iyah")) ?></div>
                        <div class="kop-prev-nama" id="prevNama"><?= htmlspecialchars(getSetting('nama_sekolah',"MADRASAH ALIYAH AS-SYAFI'IYAH 02")) ?></div>
                        <?php $akr = getSetting('status_akreditasi',''); ?>
                        <?php if($akr): ?><div class="kop-prev-akreditasi" id="prevAkreditasi"><?= htmlspecialchars($akr) ?></div><?php endif; ?>
                        <div class="kop-prev-detail" id="prevDetail">
                            <?php $noAkr = getSetting('no_akreditasi',''); ?>
                            <?php if($noAkr): ?>No. Akreditasi : <?= htmlspecialchars($noAkr) ?><br><?php endif; ?>
                            <?= htmlspecialchars(getSetting('alamat','')) ?>
                            <?php if(getSetting('telp','')): ?> &nbsp;Telp. <?= htmlspecialchars(getSetting('telp','')) ?><?php endif; ?>
                        </div>
                    </div>
                </div>
                <div class="kop-preview-hint">👆 Preview kop surat — berubah otomatis saat Anda mengetik</div>
            </div>

            <!-- LOGO -->
            <div class="logo-area">
                <div class="logo-preview">
                    <?php if(!empty($lg) && file_exists($lg)): ?>
                        <img src="<?= htmlspecialchars($lg) ?>" id="logoImg" alt="Logo">
                    <?php else: ?>
                        <span style="font-size:2.5rem;opacity:.3" id="logoFallback">🏛️</span>
                        <img src="" id="logoImg" style="display:none">
                    <?php endif; ?>
                </div>
                <div class="logo-info">
                    <div class="logo-title">Logo Sekolah</div>
                    <div class="logo-hint">Tampil di sudut kiri Kop Surat. Format: JPG, PNG, WEBP • Rekomendasi 512×512px</div>
                    <input type="file" name="logo" id="logoInput" accept="image/jpeg,image/png,image/webp" style="display:none">
                    <label for="logoInput" class="logo-btn">📤 Ganti Logo</label>
                    <div id="logoPreviewName" class="logo-preview-name" style="display:none"></div>
                    <?php if(!empty($lg) && file_exists($lg)): ?>
                    <div class="logo-path">📁 <?= htmlspecialchars($lg) ?></div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- IDENTITAS -->
            <div class="fg-section-lbl">🏛️ Identitas Yayasan &amp; Madrasah — tampil di Kop Surat</div>

            <div class="fg">
                <label class="flbl">Nama Yayasan <span class="badge-key">nama_yayasan</span></label>
                <input type="text" name="nama_yayasan" id="inputYayasan" class="finp"
                       placeholder="Yayasan Perguruan Islam As-Syafi'iyah"
                       value="<?= htmlspecialchars(getSetting('nama_yayasan',"Yayasan Perguruan Islam As-Syafi'iyah")) ?>"
                       oninput="updateKopPreview()">
                <span class="fhint">Tampil di baris pertama kop surat (italic)</span>
            </div>

            <div class="fg">
                <label class="flbl">Nama Sekolah / Madrasah <span class="badge-key">nama_sekolah</span></label>
                <input type="text" name="nama_sekolah" id="inputNama" class="finp"
                       placeholder="MADRASAH ALIYAH AS-SYAFI'IYAH 02"
                       value="<?= htmlspecialchars(getSetting('nama_sekolah',"MA As-Syafi'iyah 02")) ?>" required
                       oninput="updateKopPreview()">
                <span class="fhint">Tampil di: Kop surat (baris utama, besar), isi paragraf semua jenis surat</span>
            </div>

            <div class="fgr">
                <div class="fg">
                    <label class="flbl">Status Akreditasi <span class="badge-key">status_akreditasi</span></label>
                    <input type="text" name="status_akreditasi" id="inputAkreditasi" class="finp"
                           placeholder="STATUS TERAKREDITASI A"
                           value="<?= htmlspecialchars(getSetting('status_akreditasi','STATUS TERAKREDITASI A')) ?>"
                           oninput="updateKopPreview()">
                    <span class="fhint">Tampil di kop surat — kosongkan jika tidak perlu</span>
                </div>
                <div class="fg">
                    <label class="flbl">Nomor Akreditasi <span class="badge-key">no_akreditasi</span></label>
                    <input type="text" name="no_akreditasi" id="inputNoAkr" class="finp finp-mono"
                           placeholder="02.00/323/BAP-SM/XI/2013"
                           value="<?= htmlspecialchars(getSetting('no_akreditasi','')) ?>"
                           oninput="updateKopPreview()">
                    <span class="fhint">Tampil di detail kop surat</span>
                </div>
            </div>

            <div class="fg">
                <label class="flbl">Alamat Lengkap Sekolah <span class="badge-key">alamat</span></label>
                <textarea name="alamat" id="inputAlamat" class="fta" rows="2"
                          placeholder="Jl. Raya Jatiwaringin No.8, Pondok Gede, Kota Bekasi"
                          required oninput="updateKopPreview()"><?= htmlspecialchars(getSetting('alamat','')) ?></textarea>
                <span class="fhint">Tampil di: Kop surat, dan pembuka Surat Keterangan Siswa</span>
            </div>

            <div class="fgr">
                <div class="fg">
                    <label class="flbl">No. Telepon <span class="badge-key">telp</span></label>
                    <input type="text" name="telp" id="inputTelp" class="finp finp-mono"
                           placeholder="(021) 84993755"
                           value="<?= htmlspecialchars(getSetting('telp','')) ?>"
                           oninput="updateKopPreview()">
                </div>
                <div class="fg">
                    <label class="flbl">Email <span class="badge-key">email</span></label>
                    <input type="email" name="email" class="finp" placeholder="info@sekolah.sch.id"
                           value="<?= htmlspecialchars(getSetting('email','')) ?>">
                </div>
            </div>

            <div class="fg">
                <label class="flbl">Website <span class="badge-key">website</span></label>
                <input type="text" name="website" class="finp" placeholder="www.sekolah.sch.id"
                       value="<?= htmlspecialchars(getSetting('website','')) ?>">
            </div>

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

            <!-- DATA KEPALA -->
            <div class="fg-section-lbl">🖊️ Data Kepala Sekolah — tampil di semua Tanda Tangan Surat</div>

            <div class="fgr">
                <div class="fg">
                    <label class="flbl">Nama Kepala Sekolah <span class="badge-key">kepala_sekolah</span></label>
                    <input type="text" name="kepala_sekolah" class="finp" placeholder="Muhammad Kasim, M.Pd"
                           value="<?= htmlspecialchars(getSetting('kepala_sekolah','')) ?>">
                    <span class="fhint">Tampil di TTD semua surat resmi</span>
                </div>
                <div class="fg">
                    <label class="flbl">NIP Kepala <span class="badge-key">nip_kepala</span></label>
                    <input type="text" name="nip_kepala" class="finp finp-mono" placeholder="198001012005011001 (opsional)"
                           value="<?= htmlspecialchars(getSetting('nip_kepala','')) ?>">
                    <span class="fhint">Muncul di bawah nama TTD jika diisi</span>
                </div>
            </div>

            <div class="fg">
                <label class="flbl">Jabatan Kepala <span class="badge-key">jabatan_kepala</span></label>
                <input type="text" name="jabatan_kepala" class="finp"
                       placeholder="Kepala Madrasah"
                       value="<?= htmlspecialchars(getSetting('jabatan_kepala','Kepala Madrasah')) ?>">
                <span class="fhint">Tampil di atas nama TTD — contoh: <code>Kepala Madrasah</code></span>
            </div>

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

            <!-- TTD & CAP -->
            <div class="fg-section-lbl">🖋️ Tanda Tangan &amp; Cap Basah — tampil di semua surat cetak / PDF</div>

            <div class="ttd-cap-grid">
                <!-- TTD -->
                <div class="ttd-upload-box">
                    <?php $ttd = getSetting('ttd_image',''); ?>
                    <div class="ttd-preview-wrap">
                        <?php if(!empty($ttd) && file_exists($ttd)): ?>
                            <img src="<?= htmlspecialchars($ttd) ?>" id="ttdPreviewImg" alt="TTD">
                        <?php else: ?>
                            <div class="ttd-preview-empty" id="ttdEmpty">
                                <span>✍️</span><span>Belum ada TTD</span>
                            </div>
                            <img src="" id="ttdPreviewImg" style="display:none" alt="TTD">
                        <?php endif; ?>
                    </div>
                    <div class="ttd-upload-info">
                        <div class="ttd-upload-title">Tanda Tangan Kepala</div>
                        <div class="ttd-upload-hint">
                            Foto / scan TTD di atas <strong>kertas putih</strong>.<br>
                            Format PNG transparan lebih direkomendasikan.
                        </div>
                        <?php if(!empty($ttd) && file_exists($ttd)): ?>
                            <div class="ttd-badge-ok" id="ttdStatus">✅ TTD tersimpan</div>
                        <?php else: ?>
                            <div class="ttd-badge-empty" id="ttdStatus">⚠️ Belum diunggah</div>
                        <?php endif; ?>
                        <div id="ttdFileName" class="ttd-file-name" style="display:none"></div>
                    </div>
                    <input type="file" name="ttd_image" id="ttdInput" accept="image/jpeg,image/png,image/webp" style="display:none">
                    <label for="ttdInput" class="logo-btn" style="width:100%;justify-content:center">✍️ Unggah TTD</label>
                </div>

                <!-- CAP -->
                <div class="ttd-upload-box">
                    <?php $cap = getSetting('cap_sekolah',''); ?>
                    <div class="ttd-preview-wrap">
                        <?php if(!empty($cap) && file_exists($cap)): ?>
                            <img src="<?= htmlspecialchars($cap) ?>" id="capPreviewImg" alt="Cap">
                        <?php else: ?>
                            <div class="ttd-preview-empty" id="capEmpty">
                                <span>🔏</span><span>Belum ada Cap</span>
                            </div>
                            <img src="" id="capPreviewImg" style="display:none" alt="Cap">
                        <?php endif; ?>
                    </div>
                    <div class="ttd-upload-info">
                        <div class="ttd-upload-title">Cap / Stempel Sekolah</div>
                        <div class="ttd-upload-hint">
                            Foto / scan cap sekolah, idealnya latar <strong>transparan</strong> (PNG).<br>
                            Akan muncul overlapping di area TTD surat.
                        </div>
                        <?php if(!empty($cap) && file_exists($cap)): ?>
                            <div class="ttd-badge-ok" id="capStatus">✅ Cap tersimpan</div>
                        <?php else: ?>
                            <div class="ttd-badge-empty" id="capStatus">⚠️ Belum diunggah</div>
                        <?php endif; ?>
                        <div id="capFileName" class="ttd-file-name" style="display:none"></div>
                    </div>
                    <input type="file" name="cap_sekolah" id="capInput" accept="image/jpeg,image/png,image/webp" style="display:none">
                    <label for="capInput" class="logo-btn" style="width:100%;justify-content:center">🔏 Unggah Cap</label>
                </div>
            </div>

            <div class="pg-tips">
                💡 <strong>Tips:</strong> Gunakan format <strong>PNG dengan latar transparan</strong> agar TTD dan Cap terlihat bersih di atas surat tanpa kotak putih.
                Scan dengan kualitas minimal 300 DPI untuk hasil cetak yang tajam.
            </div>

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

            <!-- FORMAT SURAT -->
            <div class="fg-section-lbl">📄 Konfigurasi Format Surat</div>

            <div class="fgr">
                <div class="fg">
                    <label class="flbl">Kota / Lokasi Surat <span class="badge-key">kota_surat</span></label>
                    <input type="text" name="kota_surat" class="finp" placeholder="Kota Bekasi"
                           value="<?= htmlspecialchars(getSetting('kota_surat','Kota Bekasi')) ?>">
                    <span class="fhint">Tampil di: <code>Kota Bekasi, 26 Januari 2026</code></span>
                </div>
                <div class="fg">
                    <label class="flbl">Kode Singkat Sekolah <span class="badge-key">kode_surat</span></label>
                    <input type="text" name="kode_surat" class="finp finp-mono" placeholder="MA.As-02"
                           value="<?= htmlspecialchars(getSetting('kode_surat','MA.As-02')) ?>">
                    <span class="fhint">Dipakai di nomor surat: <code>001/MA.As-02/Ext.B/I/2026</code></span>
                </div>
            </div>

            <div class="save-row">
                <button type="submit" name="update_sekolah" class="btn-save">💾 Simpan Pengaturan Sekolah &amp; Surat</button>
                <span class="save-note">Perubahan langsung aktif di Generator Surat</span>
            </div>
        </div>
        </form>

        <!-- ══ PENGATURAN AKADEMIK ══ -->
        <form method="POST" action="pengaturan.php">
        <div class="pg-card fade-up" style="animation-delay:.08s">
            <div class="pg-sec-hdr">
                <div class="pg-sec-ico pg-ico-jade">📚</div>
                <div class="pg-sec-text">
                    <div class="pg-sec-title">Pengaturan Akademik</div>
                    <div class="pg-sec-sub">Tahun ajaran dan semester aktif</div>
                </div>
                <div class="pg-sec-badge-wrap"><span class="pg-sync-badge">Terhubung ke Surat Keterangan</span></div>
            </div>

            <div class="fgr">
                <div class="fg">
                    <label class="flbl">Tahun Ajaran <span class="badge-key">tahun_ajaran</span></label>
                    <input type="text" name="tahun_ajaran" class="finp finp-mono" placeholder="2025/2026"
                           value="<?= htmlspecialchars(getSetting('tahun_ajaran',date('Y').'/'.(date('Y')+1))) ?>" required>
                    <span class="fhint">Format: <code>2025/2026</code></span>
                </div>
                <div class="fg">
                    <label class="flbl">Semester <span class="badge-key">semester</span></label>
                    <select name="semester" class="fsel">
                        <option value="Ganjil" <?= getSetting('semester')=='Ganjil'?'selected':'' ?>>Ganjil</option>
                        <option value="Genap"  <?= getSetting('semester')=='Genap' ?'selected':'' ?>>Genap</option>
                    </select>
                </div>
            </div>

            <div class="save-row">
                <button type="submit" name="update_akademik" class="btn-save">💾 Simpan Pengaturan Akademik</button>
            </div>
        </div>
        </form>

        <!-- ══ STATUS SINKRONISASI ══ -->
        <div class="pg-card fade-up" style="animation-delay:.13s">
            <div class="pg-sec-hdr">
                <div class="pg-sec-ico pg-ico-sky">🔗</div>
                <div class="pg-sec-text">
                    <div class="pg-sec-title">Status Sinkronisasi</div>
                    <div class="pg-sec-sub">Cek apakah semua data sudah terhubung ke Generator Surat</div>
                </div>
            </div>

            <?php
            $checks = [
                ['nama_sekolah',      'Nama Sekolah',        'Kop surat & isi paragraf semua surat',   true],
                ['nama_yayasan',      'Nama Yayasan',        'Baris pertama kop surat (italic)',        false],
                ['status_akreditasi', 'Status Akreditasi',   'Kop surat — baris STATUS TERAKREDITASI', false],
                ['no_akreditasi',     'No. Akreditasi',      'Kop surat — detail akreditasi',          false],
                ['alamat',            'Alamat Sekolah',      'Kop surat & Surat Keterangan Siswa',     true],
                ['kepala_sekolah',    'Nama Kepala',         'Tanda tangan semua surat',               true],
                ['jabatan_kepala',    'Jabatan Kepala',      'Label di atas nama TTD',                 false],
                ['kode_surat',        'Kode Surat',          'Format nomor surat otomatis',            true],
                ['kota_surat',        'Kota Surat',          'Baris tanggal di TTD',                   true],
                ['logo_sekolah',      'Logo Sekolah',        'Pojok kiri kop surat',                   false],
                ['telp',              'No. Telepon',         'Kop surat',                              false],
                ['tahun_ajaran',      'Tahun Ajaran',        'Surat Keterangan Siswa',                 true],
                ['nip_kepala',        'NIP Kepala',          'Bawah nama TTD (opsional)',              false],
                ['ttd_image',         'Tanda Tangan',        'Area TTD semua surat (opsional)',         false],
                ['cap_sekolah',       'Cap Sekolah',         'Stempel basah di area TTD (opsional)',    false],
            ];
            ?>
            <div class="sync-grid">
                <?php foreach($checks as $c): ?>
                <?php $v = getSetting($c[0],''); $ok = !empty($v); $req = $c[3]; ?>
                <div class="sync-item <?= $ok ? 'sync-ok' : ($req ? 'sync-err' : 'sync-warn') ?>">
                    <span class="sync-ico"><?= $ok ? '✅' : ($req ? '❌' : '⚠️') ?></span>
                    <div class="sync-item-body">
                        <div class="sync-item-title">
                            <?= htmlspecialchars($c[1]) ?>
                            <?php if($req): ?><span class="sync-req">*wajib</span><?php endif; ?>
                        </div>
                        <div class="sync-item-sub"><?= htmlspecialchars($c[2]) ?></div>
                    </div>
                    <div class="sync-val">
                        <?= $ok ? htmlspecialchars(mb_strimwidth($v,0,20,'…')) : 'Belum diisi' ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <?php
            $requiredChecks = array_filter($checks, fn($c) => $c[3]);
            $allOk = !array_filter($requiredChecks, fn($c) => empty(getSetting($c[0],'')));
            ?>
            <div class="sync-summary <?= $allOk ? 'sync-summary-ok' : 'sync-summary-warn' ?>">
                <span style="font-size:1.25rem"><?= $allOk ? '🎉' : '💡' ?></span>
                <span class="sync-summary-text">
                    <?= $allOk ? 'Semua field wajib terisi — Generator Surat siap digunakan!' : 'Field bertanda * wajib diisi agar Generator Surat berfungsi optimal.' ?>
                </span>
                <?php if(!$allOk): ?>
                <a href="#" onclick="window.scrollTo({top:0,behavior:'smooth'})" class="sync-summary-link">↑ Lengkapi sekarang</a>
                <?php endif; ?>
            </div>
        </div>

        <!-- ══ INFO SISTEM ══ -->
        <div class="pg-card fade-up" style="animation-delay:.18s">
            <div class="pg-sec-hdr">
                <div class="pg-sec-ico pg-ico-slate">💻</div>
                <div class="pg-sec-text"><div class="pg-sec-title">Informasi Sistem</div></div>
            </div>
            <div class="sys-grid">
                <div class="sys-item">
                    <div class="sys-lbl">PHP Version</div>
                    <div class="sys-val"><?= phpversion() ?></div>
                </div>
                <div class="sys-item">
                    <div class="sys-lbl">Database</div>
                    <div class="sys-val">MySQL</div>
                </div>
                <div class="sys-item">
                    <div class="sys-lbl">App Version</div>
                    <div class="sys-val">v2.1.0</div>
                </div>
            </div>
        </div>

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

<!-- PAGE-SPECIFIC STYLES -->
<style>
/* ════════════════════════════════════
   PAGE HEADER
════════════════════════════════════ */
.pg-hdr {
    background:var(--ob); border-bottom:1px solid rgba(201,168,76,.12);
    padding:1.5rem 2.5rem;
    display:flex; align-items:center; justify-content:space-between;
    flex-wrap:wrap; gap:1rem;
}
.pg-hdr-left { display:flex; align-items:center; gap:1rem; }
.pg-hdr-ico {
    width:48px; height:48px; border-radius:14px; flex-shrink:0;
    background:rgba(201,168,76,.15); border:1.5px solid rgba(201,168,76,.3);
    display:flex; align-items:center; justify-content:center; font-size:1.4rem;
}
.pg-hdr-title { font-family:'DM Serif Display',serif; font-size:1.3rem; color:var(--g-fg); line-height:1.2; }
.pg-hdr-sub   { font-size:.78rem; color:rgba(255,255,255,.4); margin-top:.2rem; }
.btn-ghost-hdr {
    display:inline-flex; align-items:center; gap:.4rem;
    padding:.55rem 1.25rem; border-radius:10px;
    border:1.5px solid rgba(201,168,76,.3); background:rgba(201,168,76,.08);
    font-family:'Outfit',sans-serif; font-size:.8rem; font-weight:700;
    color:var(--g-l); text-decoration:none; transition:all .2s; white-space:nowrap;
}
.btn-ghost-hdr:hover { background:rgba(201,168,76,.16); border-color:rgba(201,168,76,.5); }

/* ════════════════════════════════════
   ALERTS
════════════════════════════════════ */
.pg-alert {
    display:flex; align-items:center; gap:.75rem;
    padding:.875rem 1.125rem; border-radius:12px;
    margin-bottom:1.25rem; font-size:.825rem; font-weight:600;
    border-left:4px solid;
}
.pg-alert-ok  { background:#F0FDF4; color:#166534; border-color:#4ADE80; }
.pg-alert-err { background:#FEF2F2; color:#991B1B; border-color:#FCA5A5; }
.pg-alert-x { cursor:pointer; background:none; border:none; font-size:1rem; color:inherit; margin-left:auto; opacity:.5; }
.pg-alert-x:hover { opacity:1; }

/* ════════════════════════════════════
   CARD
════════════════════════════════════ */
.pg-card {
    background:var(--sf); border-radius:20px; border:1px solid var(--bd);
    padding:2rem; margin-bottom:1.75rem;
    box-shadow:0 2px 12px var(--sh);
}

/* ════════════════════════════════════
   SECTION HEADER
════════════════════════════════════ */
.pg-sec-hdr {
    display:flex; align-items:center; gap:.875rem;
    margin-bottom:1.75rem; padding-bottom:1rem;
    border-bottom:1.5px solid var(--bd); flex-wrap:wrap;
}
.pg-sec-ico {
    width:42px; height:42px; border-radius:12px; flex-shrink:0;
    display:flex; align-items:center; justify-content:center; font-size:1.25rem;
}
.pg-ico-gold  { background:linear-gradient(135deg,#FFFBEB,#FEF3C7); border:1.5px solid #FDE68A; }
.pg-ico-jade  { background:linear-gradient(135deg,#ECFDF5,#D1FAE5); border:1.5px solid #6EE7B7; }
.pg-ico-sky   { background:linear-gradient(135deg,#EFF6FF,#DBEAFE); border:1.5px solid #BFDBFE; }
.pg-ico-slate { background:linear-gradient(135deg,#F8FAFC,#F1F5F9); border:1.5px solid #E2E8F0; }
.pg-sec-text  { flex:1; min-width:0; }
.pg-sec-title { font-family:'DM Serif Display',serif; font-size:1.1rem; color:var(--tx); }
.pg-sec-sub   { font-size:.75rem; color:var(--txl); margin-top:.1rem; }
.pg-sec-badge-wrap { margin-left:auto; }
.pg-sync-badge {
    display:inline-flex; align-items:center; gap:.4rem;
    padding:.3rem .875rem; border-radius:50px;
    font-size:.68rem; font-weight:700;
    background:#ECFDF5; color:#065F46; border:1.5px solid #6EE7B7;
    white-space:nowrap;
}
.pg-sync-badge::before { content:'🔗'; font-size:.75rem; }

/* ════════════════════════════════════
   KOP PREVIEW
════════════════════════════════════ */
.kop-preview-box {
    background:#fff; border:1.5px solid var(--bd); border-radius:14px;
    padding:1.25rem; margin-bottom:1.5rem; overflow:hidden;
}
.kop-preview-inner {
    display:flex; align-items:center; gap:1rem;
    border-bottom:3px double #1a3a8f; padding-bottom:.875rem; margin-bottom:.5rem;
}
.kop-prev-logo { width:70px; height:70px; flex-shrink:0; display:flex; align-items:center; justify-content:center; }
.kop-prev-logo img { width:100%; height:100%; object-fit:contain; }
.kop-prev-text { flex:1; text-align:center; min-width:0; }
.kop-prev-yayasan { font-size:.72rem; color:#1a3a8f; font-weight:600; font-style:italic; margin-bottom:.15rem; }
.kop-prev-nama { font-size:1.2rem; font-weight:900; color:#1a3a8f; letter-spacing:.02em; text-transform:uppercase; line-height:1.1; margin-bottom:.2rem; }
.kop-prev-akreditasi { font-size:.7rem; font-weight:800; color:#1a3a8f; letter-spacing:.06em; text-transform:uppercase; margin-bottom:.25rem; }
.kop-prev-detail { font-size:.6rem; color:#1a3a8f; line-height:1.5; }
.kop-preview-hint { font-size:.65rem; color:var(--txl); text-align:center; padding:.5rem; background:#F8FAFC; border-radius:8px; }

/* ════════════════════════════════════
   LOGO AREA
════════════════════════════════════ */
.logo-area {
    display:flex; gap:1.5rem; align-items:flex-start;
    padding:1.25rem; background:var(--bg); border-radius:14px;
    border:1.5px dashed var(--bd); margin-bottom:1.25rem;
}
.logo-preview {
    width:100px; height:100px; border-radius:14px; border:1.5px solid var(--bd);
    overflow:hidden; background:#fff; display:flex; align-items:center;
    justify-content:center; flex-shrink:0;
}
.logo-preview img { width:100%; height:100%; object-fit:contain; }
.logo-info { flex:1; min-width:0; }
.logo-title { font-weight:700; font-size:.875rem; margin-bottom:.3rem; color:var(--tx); }
.logo-hint  { font-size:.75rem; color:var(--txl); margin-bottom:.75rem; }
.logo-btn {
    display:inline-flex; align-items:center; gap:.4rem;
    padding:.6rem 1.125rem; background:var(--sf); border:1.5px solid var(--bd);
    border-radius:10px; font-size:.78rem; font-weight:700; cursor:pointer;
    color:var(--tx); font-family:'Outfit',sans-serif; transition:all .2s;
}
.logo-btn:hover { border-color:var(--g); color:var(--g-d); background:var(--g-fg); }
.logo-preview-name { font-size:.72rem; color:var(--g-d); margin-top:.5rem; }
.logo-path { font-size:.68rem; color:var(--txl); margin-top:.375rem; }

/* ════════════════════════════════════
   FORM
════════════════════════════════════ */
.fg-section-lbl {
    font-size:.7rem; font-weight:800; text-transform:uppercase;
    letter-spacing:.1em; color:var(--txl); margin-bottom:.875rem;
}
.fg  { display:flex; flex-direction:column; gap:.4rem; margin-bottom:1.125rem; }
.fgr { display:grid; grid-template-columns:1fr 1fr; gap:1rem; }
.flbl {
    font-size:.68rem; font-weight:800; text-transform:uppercase;
    letter-spacing:.08em; color:var(--txm); display:flex; align-items:center; gap:.4rem; flex-wrap:wrap;
}
.badge-key {
    font-family:'DM Mono',monospace; font-size:.6rem; background:#F1F5F9;
    color:#64748B; padding:.1rem .45rem; border-radius:4px; border:1px solid #E2E8F0;
    text-transform:none; letter-spacing:.02em;
}
.finp,.fsel,.fta {
    width:100%; padding:.8rem .9rem; background:var(--bg); border:1.5px solid var(--bd);
    border-radius:12px; font-family:'Outfit',sans-serif;
    font-size:max(.875rem, 16px);
    font-weight:600; color:var(--tx); transition:all .2s; outline:none;
    -webkit-appearance:none;
}
.finp:focus,.fsel:focus,.fta:focus {
    border-color:var(--g); background:white; box-shadow:0 0 0 3px rgba(201,168,76,.1);
}
.fta { resize:vertical; min-height:76px; line-height:1.5; }
.finp-mono { font-family:'DM Mono',monospace; font-size:.8rem; letter-spacing:.03em; }
.fhint { font-size:.68rem; color:var(--txl); margin-top:.3rem; line-height:1.4; }
.fhint code { background:#F1F5F9; padding:.1rem .35rem; border-radius:4px; font-family:'DM Mono',monospace; font-size:.65rem; color:#475569; }
.pg-divider { border:none; border-top:1px dashed var(--bd); margin:1.25rem 0; }

/* ════════════════════════════════════
   TTD & CAP
════════════════════════════════════ */
.ttd-cap-grid { display:grid; grid-template-columns:1fr 1fr; gap:1.25rem; margin-bottom:1.25rem; }
.ttd-upload-box {
    background:var(--bg); border:1.5px dashed var(--bd); border-radius:14px;
    padding:1.25rem; display:flex; flex-direction:column;
    align-items:center; gap:.875rem; transition:border-color .2s;
}
.ttd-upload-box:hover { border-color:var(--g); }
.ttd-preview-wrap {
    width:160px; height:90px; border-radius:10px; border:1.5px solid var(--bd);
    background:#fff; display:flex; align-items:center; justify-content:center;
    overflow:hidden; position:relative;
}
.ttd-preview-wrap img { max-width:100%; max-height:100%; object-fit:contain; }
.ttd-preview-empty { display:flex; flex-direction:column; align-items:center; gap:.375rem; color:var(--txl); font-size:.72rem; }
.ttd-preview-empty span { font-size:2rem; opacity:.3; }
.ttd-upload-info { text-align:center; width:100%; }
.ttd-upload-title { font-size:.8rem; font-weight:700; color:var(--tx); margin-bottom:.25rem; }
.ttd-upload-hint { font-size:.65rem; color:var(--txl); line-height:1.4; margin-bottom:.625rem; }
.ttd-badge-ok    { display:inline-flex; align-items:center; gap:.3rem; padding:.2rem .625rem; border-radius:50px; font-size:.62rem; font-weight:700; background:#ECFDF5; color:#065F46; border:1px solid #6EE7B7; }
.ttd-badge-empty { display:inline-flex; align-items:center; gap:.3rem; padding:.2rem .625rem; border-radius:50px; font-size:.62rem; font-weight:700; background:#FFF7ED; color:#92400E; border:1px solid #FED7AA; }
.ttd-file-name   { font-size:.62rem; color:var(--g-d); margin-top:.375rem; }
.pg-tips {
    padding:.75rem 1rem; background:#FFFBEB; border:1.5px solid #FDE68A;
    border-radius:10px; font-size:.72rem; color:#92400E;
    margin-bottom:1rem; line-height:1.55;
}

/* ════════════════════════════════════
   SAVE ROW
════════════════════════════════════ */
.save-row {
    display:flex; align-items:center; justify-content:space-between;
    flex-wrap:wrap; gap:.75rem; margin-top:1.25rem;
}
.btn-save {
    display:inline-flex; align-items:center; gap:.5rem;
    padding:.825rem 2rem;
    background:linear-gradient(135deg, var(--g-d), var(--g));
    color:white; border:none; border-radius:12px;
    font-size:.85rem; font-weight:700; cursor:pointer;
    font-family:'Outfit',sans-serif; transition:all .25s;
    box-shadow:0 4px 14px rgba(201,168,76,.3);
}
.btn-save:hover { transform:translateY(-2px); box-shadow:0 8px 24px rgba(201,168,76,.4); }
.save-note { font-size:.72rem; color:var(--txl); }

/* ════════════════════════════════════
   SYNC GRID
════════════════════════════════════ */
.sync-grid { display:grid; grid-template-columns:1fr 1fr; gap:.625rem; }
.sync-item {
    display:flex; align-items:center; gap:.625rem;
    padding:.75rem 1rem; border-radius:10px; border:1px solid;
}
.sync-ok   { background:#F0FDF4; border-color:#BBF7D0; }
.sync-err  { background:#FEF2F2; border-color:#FCA5A5; }
.sync-warn { background:#FFF7ED; border-color:#FED7AA; }
.sync-ico  { font-size:1.1rem; flex-shrink:0; }
.sync-item-body { flex:1; min-width:0; }
.sync-item-title { font-size:.75rem; font-weight:700; }
.sync-ok   .sync-item-title { color:#166534; }
.sync-err  .sync-item-title { color:#991B1B; }
.sync-warn .sync-item-title { color:#92400E; }
.sync-req  { color:#DC2626; font-size:.6rem; font-weight:700; margin-left:.25rem; }
.sync-item-sub { font-size:.65rem; margin-top:1px; }
.sync-ok   .sync-item-sub { color:#4ADE80; }
.sync-warn .sync-item-sub,.sync-err .sync-item-sub { color:#F97316; }
.sync-val  {
    font-family:'DM Mono',monospace; font-size:.6rem;
    max-width:80px; overflow:hidden; text-overflow:ellipsis;
    white-space:nowrap; text-align:right; flex-shrink:0;
}
.sync-ok   .sync-val { color:#166534; }
.sync-warn .sync-val,.sync-err .sync-val { color:#92400E; }

.sync-summary {
    margin-top:1.25rem; padding:1rem 1.25rem; border-radius:12px;
    border:1.5px solid; display:flex; align-items:center; gap:.625rem; flex-wrap:wrap;
}
.sync-summary-ok   { background:#F0FDF4; border-color:#4ADE80; }
.sync-summary-warn { background:#FFFBEB; border-color:#FDE68A; }
.sync-summary-text { font-size:.8rem; font-weight:600; flex:1; min-width:0; }
.sync-summary-ok   .sync-summary-text { color:#166534; }
.sync-summary-warn .sync-summary-text { color:#92400E; }
.sync-summary-link { font-size:.75rem; font-weight:700; color:#B45309; text-decoration:none; white-space:nowrap; }

/* ════════════════════════════════════
   SYSTEM INFO
════════════════════════════════════ */
.sys-grid { display:grid; grid-template-columns:repeat(3,1fr); gap:1.25rem; }
.sys-item { padding:1.125rem; background:var(--bg); border-radius:12px; border:1px solid var(--bd); }
.sys-lbl  { font-size:.65rem; font-weight:800; letter-spacing:.1em; text-transform:uppercase; color:var(--txl); margin-bottom:.4rem; }
.sys-val  { font-family:'DM Mono',monospace; font-size:1rem; font-weight:700; color:var(--tx); }

/* ════════════════════════════════════
   RESPONSIVE
════════════════════════════════════ */
@media(max-width:1024px) {
    .pg-hdr { padding:1.25rem 1.5rem; }
    .pg-card { padding:1.5rem; }
    .wrap { padding:1.5rem; }
}
@media(max-width:900px) {
    .fgr { grid-template-columns:1fr; }
    .sys-grid { grid-template-columns:1fr 1fr; }
}
@media(max-width:768px) {
    .pg-hdr { padding:1rem; }
    .pg-hdr-title { font-size:1.1rem; }
    .pg-hdr-ico { width:42px; height:42px; font-size:1.1rem; }
    .pg-card { padding:1.125rem; border-radius:16px; margin-bottom:1.25rem; }
    .pg-sec-badge-wrap { margin-left:0; width:100%; margin-top:.25rem; }
    .kop-preview-inner { flex-direction:column; text-align:center; }
    .kop-prev-logo { width:56px; height:56px; }
    .kop-prev-nama { font-size:.95rem; }
    .logo-area { flex-direction:column; align-items:center; text-align:center; }
    .logo-info { width:100%; }
    .ttd-cap-grid { grid-template-columns:1fr; }
    .sync-grid { grid-template-columns:1fr; }
    .save-row { flex-direction:column; align-items:stretch; }
    .btn-save { width:100%; justify-content:center; padding:.875rem; }
    .sys-grid { grid-template-columns:1fr; }
    .btn-ghost-hdr { font-size:.75rem; padding:.45rem .875rem; }
}
@media(max-width:480px) {
    .pg-hdr { padding:.875rem; }
    .pg-hdr-title { font-size:1rem; }
    .pg-hdr-sub { display:none; }
    .btn-ghost-hdr { display:none; }
    .pg-card { padding:1rem; border-radius:14px; }
    .kop-prev-nama { font-size:.85rem; }
    .ttd-preview-wrap { width:140px; height:80px; }
}
@supports(padding:max(0px)) {
    .pg-hdr { padding-left:max(1rem, env(safe-area-inset-left)); padding-right:max(1rem, env(safe-area-inset-right)); }
    .wrap   { padding-left:max(1.25rem, env(safe-area-inset-left)); padding-right:max(1.25rem, env(safe-area-inset-right)); }
}
</style>

<!-- JAVASCRIPT -->
<script>
// ── Live Kop Preview ──────────────────────────────────────────────
function updateKopPreview(){
    const yayasan = document.getElementById('inputYayasan')?.value    || '';
    const nama    = document.getElementById('inputNama')?.value       || '';
    const akr     = document.getElementById('inputAkreditasi')?.value || '';
    const noAkr   = document.getElementById('inputNoAkr')?.value      || '';
    const alamat  = document.getElementById('inputAlamat')?.value     || '';
    const telp    = document.getElementById('inputTelp')?.value       || '';

    const elYayasan = document.getElementById('prevYayasan');
    const elNama    = document.getElementById('prevNama');
    const elAkr     = document.getElementById('prevAkreditasi');
    const elDetail  = document.getElementById('prevDetail');

    if(elYayasan) elYayasan.textContent = yayasan;
    if(elNama)    elNama.textContent    = nama;

    if(elAkr){
        if(akr){ elAkr.style.display=''; elAkr.textContent = akr; }
        else   { elAkr.style.display='none'; }
    } else if(akr){
        const div = document.createElement('div');
        div.className='kop-prev-akreditasi'; div.id='prevAkreditasi';
        div.textContent = akr;
        elNama.insertAdjacentElement('afterend', div);
    }

    if(elDetail){
        let detail = '';
        if(noAkr) detail += 'No. Akreditasi : ' + noAkr + '\n';
        detail += alamat;
        if(telp) detail += '  Telp. ' + telp;
        elDetail.innerHTML = detail.replace(/\n/g,'<br>');
    }
}

// ── TTD preview ──────────────────────────────────────────────────
document.getElementById('ttdInput').addEventListener('change', function(e){
    const file = e.target.files[0]; if(!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
        const img   = document.getElementById('ttdPreviewImg');
        const empty = document.getElementById('ttdEmpty');
        img.src = ev.target.result; img.style.display = 'block';
        if(empty) empty.style.display = 'none';
        document.getElementById('ttdStatus').className   = 'ttd-badge-ok';
        document.getElementById('ttdStatus').textContent = '✅ Siap diunggah';
    };
    reader.readAsDataURL(file);
    const fn = document.getElementById('ttdFileName');
    fn.textContent = '📎 ' + file.name; fn.style.display = 'block';
});

// ── Cap preview ──────────────────────────────────────────────────
document.getElementById('capInput').addEventListener('change', function(e){
    const file = e.target.files[0]; if(!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
        const img   = document.getElementById('capPreviewImg');
        const empty = document.getElementById('capEmpty');
        img.src = ev.target.result; img.style.display = 'block';
        if(empty) empty.style.display = 'none';
        document.getElementById('capStatus').className   = 'ttd-badge-ok';
        document.getElementById('capStatus').textContent = '✅ Siap diunggah';
    };
    reader.readAsDataURL(file);
    const fn = document.getElementById('capFileName');
    fn.textContent = '📎 ' + file.name; fn.style.display = 'block';
});

// ── Logo preview & kop sync ──────────────────────────────────────
document.getElementById('logoInput').addEventListener('change', function(e){
    const file = e.target.files[0]; if(!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
        ['logoImg','kopLogoImg'].forEach(id => {
            const img = document.getElementById(id);
            if(img){ img.src = ev.target.result; img.style.display='block'; }
        });
        const f1 = document.getElementById('logoFallback');
        const f2 = document.getElementById('kopLogoFallback');
        if(f1) f1.style.display='none';
        if(f2) f2.style.display='none';
    };
    reader.readAsDataURL(file);
    const preview = document.getElementById('logoPreviewName');
    preview.textContent = '✅ ' + file.name;
    preview.style.display = 'block';
});

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