<?php
require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';

date_default_timezone_set('Asia/Makassar');

$act = $_GET['a'] ?? 'list';

if (!in_array($act, ['list', 'form', 'save', 'delete'], true)) {
    $act = 'list';
}


/* ===============================
   FUNGSI TANGGAL
================================ */

function tanggal_indo_belum_menikah($tanggal)
{
    if (!$tanggal) {
        return '-';
    }

    $waktu = strtotime($tanggal);

    if (!$waktu) {
        return '-';
    }

    $bulan = [
        1  => 'Januari',
        2  => 'Februari',
        3  => 'Maret',
        4  => 'April',
        5  => 'Mei',
        6  => 'Juni',
        7  => 'Juli',
        8  => 'Agustus',
        9  => 'September',
        10 => 'Oktober',
        11 => 'November',
        12 => 'Desember'
    ];

    return date('j', $waktu)
        .' '
        .$bulan[(int)date('n', $waktu)]
        .' '
        .date('Y', $waktu);
}


/* ===============================
   NOMOR SURAT OTOMATIS
================================ */

$bulanRomawi = [
    'I', 'II', 'III', 'IV', 'V', 'VI',
    'VII', 'VIII', 'IX', 'X', 'XI', 'XII'
];

$lastResult = $mysqli->query("
    SELECT id
    FROM surat_belum_menikah
    ORDER BY id DESC
    LIMIT 1
");

$last = $lastResult ? $lastResult->fetch_assoc() : null;
$urut = $last ? ((int)$last['id'] + 1) : 1;

$nomorSuratOtomatis = sprintf(
    '145/%03d/DM/%s/%s',
    $urut,
    $bulanRomawi[(int)date('n') - 1],
    date('Y')
);


/* ===============================
   HAPUS
================================ */

if ($act === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);

    if ($id <= 0) {
        header('Location: surat_belum_menikah.php?msg=notfound');
        exit;
    }

    $stmt = $mysqli->prepare("
        DELETE FROM surat_belum_menikah
        WHERE id = ?
    ");

    if (!$stmt) {
        header('Location: surat_belum_menikah.php?msg=error');
        exit;
    }

    $stmt->bind_param('i', $id);

    $berhasil = $stmt->execute();
    $terhapus = $berhasil && $stmt->affected_rows > 0;

    $stmt->close();

    header(
        'Location: surat_belum_menikah.php?msg='
        .($terhapus ? 'deleted' : 'notfound')
    );
    exit;
}


/* ===============================
   SIMPAN / UPDATE
================================ */

$errorText = '';

if ($act === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id             = (int)($_POST['id'] ?? 0);
    $nomor_surat    = trim($_POST['nomor_surat'] ?? '');
    $warga_id       = (int)($_POST['warga_id'] ?? 0);
    $tanggal_surat  = trim($_POST['tanggal_surat'] ?? '');
    $waktu_ttd      = date('Y-m-d H:i:s');

    if (
        $nomor_surat === '' ||
        $warga_id <= 0 ||
        $tanggal_surat === ''
    ) {
        $errorText = 'Mohon lengkapi semua data yang wajib diisi.';
        $act = 'form';
    } elseif ($id > 0) {

        /* UPDATE */

        $qr_kode = '';

        $qrStmt = $mysqli->prepare("
            SELECT qr_kode
            FROM surat_belum_menikah
            WHERE id = ?
            LIMIT 1
        ");

        if ($qrStmt) {
            $qrStmt->bind_param('i', $id);
            $qrStmt->execute();

            $qrResult = $qrStmt->get_result();

            if ($qrResult && $qrRow = $qrResult->fetch_assoc()) {
                $qr_kode = trim($qrRow['qr_kode'] ?? '');
            }

            $qrStmt->close();
        }

        if ($qr_kode === '') {
            $qr_kode = 'SBM-'.time().'-'.random_int(100, 999);
        }

        $qr_hash = hash(
            'sha256',
            $qr_kode.$nomor_surat
        );

        $stmt = $mysqli->prepare("
            UPDATE surat_belum_menikah
            SET
                nomor_surat = ?,
                warga_id = ?,
                tanggal_surat = ?,
                waktu_ttd = ?,
                qr_kode = ?,
                qr_hash = ?
            WHERE id = ?
        ");

        if ($stmt) {
            $stmt->bind_param(
                'sissssi',
                $nomor_surat,
                $warga_id,
                $tanggal_surat,
                $waktu_ttd,
                $qr_kode,
                $qr_hash,
                $id
            );

            if ($stmt->execute()) {
                $stmt->close();

                header(
                    'Location: surat_belum_menikah.php?msg=updated'
                );
                exit;
            }

            $stmt->close();
        }

        $errorText = 'Surat belum menikah gagal diperbarui.';
        $act = 'form';
    } else {

        /* INSERT */

        $qr_kode = 'SBM-'.time().'-'.random_int(100, 999);

        $qr_hash = hash(
            'sha256',
            $qr_kode.$nomor_surat
        );

        $stmt = $mysqli->prepare("
            INSERT INTO surat_belum_menikah
            (
                nomor_surat,
                warga_id,
                tanggal_surat,
                waktu_ttd,
                qr_kode,
                qr_hash
            )
            VALUES (?, ?, ?, ?, ?, ?)
        ");

        if ($stmt) {
            $stmt->bind_param(
                'sissss',
                $nomor_surat,
                $warga_id,
                $tanggal_surat,
                $waktu_ttd,
                $qr_kode,
                $qr_hash
            );

            if ($stmt->execute()) {
                $stmt->close();

                header(
                    'Location: surat_belum_menikah.php?msg=saved'
                );
                exit;
            }

            $stmt->close();
        }

        $errorText = 'Surat belum menikah gagal disimpan.';
        $act = 'form';
    }
}


/* ===============================
   DATA EDIT
================================ */

$edit = null;

if ($act === 'form') {
    $editId = (int)(
        $_GET['id']
        ?? $_POST['id']
        ?? 0
    );

    if ($editId > 0) {
        $stmt = $mysqli->prepare("
            SELECT *
            FROM surat_belum_menikah
            WHERE id = ?
            LIMIT 1
        ");

        if ($stmt) {
            $stmt->bind_param('i', $editId);
            $stmt->execute();

            $result = $stmt->get_result();

            if ($result) {
                $edit = $result->fetch_assoc();
            }

            $stmt->close();
        }

        if (!$edit && $errorText === '') {
            header(
                'Location: surat_belum_menikah.php?msg=notfound'
            );
            exit;
        }
    }
}


/* ===============================
   DATA WARGA
================================ */

$warga = $mysqli->query("
    SELECT
        id,
        nama_lengkap,
        nik
    FROM infografis
    ORDER BY nama_lengkap ASC
");


/* ===============================
   DATA SURAT
================================ */

$list = $mysqli->query("
    SELECT
        s.*,
        i.nama_lengkap,
        i.nik
    FROM surat_belum_menikah s
    JOIN infografis i
        ON s.warga_id = i.id
    ORDER BY s.id DESC
");

$totalSurat = $list ? $list->num_rows : 0;


/* ===============================
   NILAI FORM
================================ */

$isEdit = !empty($edit);

$nomorValue = $_POST['nomor_surat']
    ?? $edit['nomor_surat']
    ?? $nomorSuratOtomatis;

$wargaValue = (int)(
    $_POST['warga_id']
    ?? $edit['warga_id']
    ?? 0
);

$tanggalSuratValue = $_POST['tanggal_surat']
    ?? $edit['tanggal_surat']
    ?? date('Y-m-d');


/* ===============================
   PESAN
================================ */

$msgKey = $_GET['msg'] ?? '';

$msgText = [
    'saved'    => 'Surat keterangan belum menikah berhasil dibuat.',
    'updated'  => 'Surat keterangan belum menikah berhasil diperbarui.',
    'deleted'  => 'Surat keterangan belum menikah berhasil dihapus.',
    'notfound' => 'Data surat belum menikah tidak ditemukan.',
    'error'    => 'Terjadi kesalahan saat memproses data.'
][$msgKey] ?? '';

$msgError = in_array(
    $msgKey,
    ['notfound', 'error'],
    true
);

include __DIR__.'/../includes/header.php';
?>

<link
    href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
    rel="stylesheet"
>

<link
    href="https://cdn.jsdelivr.net/npm/remixicon@4.6.0/fonts/remixicon.css"
    rel="stylesheet"
>

<style>
:root {
    --sbm-green-950: #002818;
    --sbm-green-900: #003d22;
    --sbm-green-800: #005530;
    --sbm-green-700: #047a3d;
    --sbm-green-600: #09a04f;
    --sbm-green-500: #15c46a;
    --sbm-green-400: #35e085;
    --sbm-green-100: #dcfaee;
    --sbm-green-50: #edfff5;
    --sbm-blue: #2080e8;
    --sbm-yellow: #f5b400;
    --sbm-orange: #f26b1d;
    --sbm-ink: #0f1c16;
    --sbm-muted: #5e6e67;
    --sbm-line: #daeae1;
    --sbm-page: #f3faf6;
    --sbm-shadow: 0 8px 28px rgba(10, 40, 25, .10);
    --sbm-radius: 16px;
}

@keyframes sbm-gradient {
    0% {
        background-position: 0% 50%;
    }

    50% {
        background-position: 100% 50%;
    }

    100% {
        background-position: 0% 50%;
    }
}

@keyframes sbm-pulse {
    0% {
        box-shadow: 0 0 0 0 rgba(53, 224, 133, .45);
    }

    70% {
        box-shadow: 0 0 0 12px rgba(53, 224, 133, 0);
    }

    100% {
        box-shadow: 0 0 0 0 rgba(53, 224, 133, 0);
    }
}

* {
    box-sizing: border-box;
}

body {
    color: var(--sbm-ink);
    background: var(--sbm-page);
    font-family: 'Inter', sans-serif;
}

.sbm-page {
    padding: 26px;
}

.sbm-header {
    position: relative;
    overflow: hidden;

    margin-bottom: 22px;
    padding: 26px 30px;

    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 16px;

    color: #fff;
    background: linear-gradient(
        135deg,
        var(--sbm-green-950),
        var(--sbm-green-800),
        var(--sbm-green-900)
    );
    background-size: 200% 100%;

    border-radius: var(--sbm-radius);
    box-shadow: 0 14px 40px rgba(0, 60, 30, .28);

    animation: sbm-gradient 8s ease infinite;
}

.sbm-header::after {
    content: "";
    position: absolute;
    width: 210px;
    height: 210px;
    top: -80px;
    right: -50px;

    background: radial-gradient(
        circle,
        rgba(53, 224, 133, .20),
        transparent 70%
    );

    border-radius: 50%;
}

.sbm-header-left,
.sbm-header-actions {
    position: relative;
    z-index: 1;
}

.sbm-eyebrow {
    margin: 0 0 8px;

    display: flex;
    align-items: center;
    gap: 7px;

    color: var(--sbm-green-400);
    font-size: 11px;
    font-weight: 800;
    letter-spacing: .1em;
    text-transform: uppercase;
}

.sbm-header h2 {
    margin: 0;

    font-size: clamp(20px, 3vw, 27px);
    font-weight: 800;
    letter-spacing: -.03em;
}

.sbm-header h2 i {
    margin-right: 8px;
    color: var(--sbm-green-400);
}

.sbm-description {
    margin: 10px 0 0;

    display: flex;
    align-items: center;
    gap: 8px;

    color: rgba(255, 255, 255, .74);
    font-size: 12px;
    font-weight: 600;
}

.sbm-dot {
    width: 8px;
    height: 8px;

    background: var(--sbm-green-400);
    border-radius: 50%;

    animation: sbm-pulse 2s infinite;
}

.sbm-header-actions {
    display: flex;
    align-items: center;
    gap: 9px;
}

.sbm-clock {
    padding: 10px 14px;

    display: flex;
    align-items: center;
    gap: 8px;

    background: rgba(255, 255, 255, .12);
    border: 1px solid rgba(255, 255, 255, .18);
    border-radius: 12px;

    font-size: 13px;
    font-weight: 700;
}

.sbm-panel {
    overflow: hidden;

    background: #fff;
    border: 1px solid var(--sbm-line);
    border-radius: var(--sbm-radius);
    box-shadow: var(--sbm-shadow);
}

.sbm-panel-head {
    padding: 18px 20px;

    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 14px;

    border-bottom: 1px solid var(--sbm-line);
}

.sbm-panel-title {
    display: flex;
    align-items: center;
    gap: 12px;
}

.sbm-panel-icon {
    width: 42px;
    height: 42px;

    display: grid;
    place-items: center;

    color: #fff;
    background: linear-gradient(
        135deg,
        var(--sbm-green-500),
        var(--sbm-green-800)
    );

    border-radius: 13px;
    font-size: 20px;
}

.sbm-panel-title h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 800;
}

.sbm-panel-title p {
    margin: 3px 0 0;
    color: var(--sbm-muted);
    font-size: 12px;
    font-weight: 600;
}

.sbm-panel-body {
    padding: 20px;
}

.sbm-alert {
    margin-bottom: 16px;
    padding: 13px 15px;

    display: flex;
    align-items: center;
    gap: 8px;

    color: var(--sbm-green-800);
    background: var(--sbm-green-50);
    border: 1px solid var(--sbm-green-100);
    border-radius: 13px;

    font-size: 13px;
    font-weight: 800;
}

.sbm-alert-error {
    color: #a13b00;
    background: #fff4eb;
    border-color: #ffd7ba;
}

.sbm-btn {
    padding: 10px 15px;

    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 7px;

    border: 0;
    border-radius: 11px;
    cursor: pointer;
    text-decoration: none;

    font-family: inherit;
    font-size: 13px;
    font-weight: 800;

    transition: transform .2s, filter .2s;
}

.sbm-btn:hover {
    transform: translateY(-2px);
    filter: brightness(.97);
}

.sbm-btn-light {
    color: #fff;
    background: rgba(255, 255, 255, .13);
    border: 1px solid rgba(255, 255, 255, .2);
}

.sbm-btn-primary {
    color: #fff;
    background: linear-gradient(
        135deg,
        var(--sbm-green-500),
        var(--sbm-green-800)
    );
}

.sbm-btn-print {
    color: #fff;
    background: linear-gradient(135deg, #60b4ff, var(--sbm-blue));
}

.sbm-btn-edit {
    color: var(--sbm-ink);
    background: linear-gradient(135deg, #ffd85b, var(--sbm-yellow));
}

.sbm-btn-delete {
    color: #fff;
    background: linear-gradient(135deg, #ff9950, var(--sbm-orange));
}

.sbm-btn-ghost {
    color: var(--sbm-green-800);
    background: var(--sbm-green-50);
    border: 1px solid var(--sbm-green-100);
}

.sbm-btn-small {
    padding: 8px 11px;
    font-size: 12px;
}

.sbm-stat {
    padding: 9px 13px;

    display: flex;
    align-items: center;
    gap: 7px;

    color: var(--sbm-green-800);
    background: var(--sbm-green-50);
    border: 1px solid var(--sbm-green-100);
    border-radius: 999px;

    font-size: 12px;
    font-weight: 800;
}

.sbm-toolbar {
    margin-bottom: 16px;
}

.sbm-search {
    position: relative;
}

.sbm-search i {
    position: absolute;
    top: 50%;
    left: 14px;

    color: var(--sbm-green-700);
    font-size: 18px;

    transform: translateY(-50%);
}

.sbm-search input {
    width: 100%;
    padding: 12px 14px 12px 42px;

    background: #f8fffb;
    border: 1px solid var(--sbm-line);
    border-radius: 13px;
    outline: 0;

    font-family: inherit;
    font-size: 14px;
    font-weight: 600;
}

.sbm-search input:focus {
    border-color: var(--sbm-green-500);
    box-shadow: 0 0 0 4px rgba(21, 196, 106, .12);
}

.sbm-table-wrap {
    overflow-x: auto;

    border: 1px solid var(--sbm-line);
    border-radius: 14px;
}

.sbm-table {
    width: 100%;

    border-collapse: separate;
    border-spacing: 0;

    font-size: 14px;
}

.sbm-table th {
    padding: 13px;

    color: var(--sbm-green-900);
    background: var(--sbm-green-50);
    border-bottom: 1px solid var(--sbm-line);

    font-size: 11px;
    font-weight: 800;
    letter-spacing: .04em;
    text-align: left;
    text-transform: uppercase;
    white-space: nowrap;
}

.sbm-table td {
    padding: 13px;

    border-bottom: 1px solid #edf7f1;
    vertical-align: middle;
}

.sbm-table tbody tr:hover {
    background: var(--sbm-green-50);
}

.sbm-table tbody tr:last-child td {
    border-bottom: 0;
}

.sbm-person {
    display: flex;
    align-items: center;
    gap: 10px;
}

.sbm-avatar {
    width: 40px;
    height: 40px;
    flex-shrink: 0;

    display: grid;
    place-items: center;

    color: #fff;
    background: linear-gradient(
        135deg,
        var(--sbm-green-500),
        var(--sbm-green-800)
    );

    border-radius: 13px;
    font-weight: 800;
}

.sbm-name {
    font-weight: 800;
}

.sbm-nik {
    margin-top: 2px;
    color: var(--sbm-muted);
    font-size: 11px;
}

.sbm-number {
    color: var(--sbm-green-900);
    font-weight: 800;
    white-space: nowrap;
}

.sbm-date-badge {
    padding: 7px 10px;

    display: inline-flex;
    align-items: center;
    gap: 6px;

    color: var(--sbm-blue);
    background: #eef8ff;
    border-radius: 999px;

    font-size: 12px;
    font-weight: 800;
    white-space: nowrap;
}

.sbm-actions {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 7px;
}

.sbm-delete-form {
    margin: 0;
}

.sbm-empty {
    padding: 35px !important;

    color: var(--sbm-muted);
    text-align: center;
}

.sbm-empty i {
    display: block;
    margin-bottom: 8px;

    color: var(--sbm-green-600);
    font-size: 34px;
}

.sbm-form {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
}

.sbm-field {
    display: flex;
    flex-direction: column;
    gap: 7px;
}

.sbm-field-full {
    grid-column: 1 / -1;
}

.sbm-field label {
    font-size: 13px;
    font-weight: 800;
}

.sbm-required {
    color: var(--sbm-orange);
}

.sbm-input {
    width: 100%;
    min-height: 44px;
    padding: 12px 13px;

    color: var(--sbm-ink);
    background: #f8fffb;
    border: 1px solid var(--sbm-line);
    border-radius: 12px;
    outline: 0;

    font-family: inherit;
    font-size: 14px;
    font-weight: 600;
}

.sbm-input:focus {
    background: #fff;
    border-color: var(--sbm-green-500);
    box-shadow: 0 0 0 4px rgba(21, 196, 106, .12);
}

.sbm-input[readonly] {
    color: var(--sbm-green-900);
    background: var(--sbm-green-50);
}

.sbm-form-actions {
    grid-column: 1 / -1;

    display: flex;
    flex-wrap: wrap;
    gap: 9px;
}

.sbm-field .select2-container {
    width: 100% !important;
}

.sbm-field .select2-container .select2-selection--single {
    height: 44px;

    background: #f8fffb;
    border: 1px solid var(--sbm-line);
    border-radius: 12px;
}

.sbm-field
.select2-container
.select2-selection--single
.select2-selection__rendered {
    padding-left: 13px;
    line-height: 42px;
    font-size: 14px;
    font-weight: 600;
}

.sbm-field
.select2-container
.select2-selection--single
.select2-selection__arrow {
    height: 42px;
}

@media (max-width: 768px) {
    .sbm-page {
        padding: 15px;
    }

    .sbm-header {
        padding: 20px;
    }

    .sbm-header-actions {
        width: 100%;
        flex-direction: column;
        align-items: stretch;
    }

    .sbm-clock,
    .sbm-btn-light {
        width: 100%;
        justify-content: center;
    }

    .sbm-form {
        grid-template-columns: 1fr;
    }

    .sbm-field-full,
    .sbm-form-actions {
        grid-column: 1;
    }

    .sbm-actions {
        min-width: 245px;
    }
}
</style>

<div class="sbm-page">

    <?php if ($act === 'list'): ?>

        <div class="sbm-header">
            <div class="sbm-header-left">
                <p class="sbm-eyebrow">
                    <i class="ri-user-heart-fill"></i>
                    Layanan Surat Desa
                </p>

                <h2>
                    <i class="ri-user-star-fill"></i>
                    Surat Keterangan Belum Menikah
                </h2>

                <p class="sbm-description">
                    <span class="sbm-dot"></span>
                    Kelola surat keterangan belum menikah atau jejaka
                </p>
            </div>

            <div class="sbm-header-actions">
                <span class="sbm-clock">
                    <i class="ri-time-fill"></i>
                    <span id="sbmClock">--.--.--</span>
                    WITA
                </span>

                <a
                    class="sbm-btn sbm-btn-light"
                    href="surat_belum_menikah.php?a=form"
                >
                    <i class="ri-add-circle-fill"></i>
                    Buat Surat
                </a>
            </div>
        </div>

        <?php if ($msgText): ?>
            <div class="sbm-alert <?= $msgError ? 'sbm-alert-error' : '' ?>">
                <i class="<?= $msgError
                    ? 'ri-error-warning-fill'
                    : 'ri-checkbox-circle-fill' ?>"></i>

                <?= esc($msgText) ?>
            </div>
        <?php endif; ?>

        <div class="sbm-panel">
            <div class="sbm-panel-head">
                <div class="sbm-panel-title">
                    <div class="sbm-panel-icon">
                        <i class="ri-folder-user-fill"></i>
                    </div>

                    <div>
                        <h3>Daftar Surat Belum Menikah</h3>
                        <p>Data surat yang telah dibuat dan siap dicetak.</p>
                    </div>
                </div>

                <div class="sbm-stat">
                    <i class="ri-file-list-3-fill"></i>
                    <?= (int)$totalSurat ?> Surat
                </div>
            </div>

            <div class="sbm-panel-body">
                <div class="sbm-toolbar">
                    <div class="sbm-search">
                        <i class="ri-search-line"></i>

                        <input
                            type="text"
                            id="searchSbm"
                            placeholder="Cari nama, NIK, nomor surat, atau tanggal..."
                        >
                    </div>
                </div>

                <div class="sbm-table-wrap">
                    <table class="sbm-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Nama Warga</th>
                                <th>Nomor Surat</th>
                                <th>Tanggal Surat</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if ($totalSurat === 0): ?>
                                <tr>
                                    <td colspan="5" class="sbm-empty">
                                        <i class="ri-inbox-2-fill"></i>
                                        Belum ada surat keterangan belum menikah.
                                    </td>
                                </tr>
                            <?php endif; ?>

                            <?php if ($list): ?>
                                <?php $no = 1; ?>

                                <?php while ($r = $list->fetch_assoc()): ?>
                                    <tr class="sbm-data-row">
                                        <td><?= $no++ ?></td>

                                        <td>
                                            <div class="sbm-person">
                                                <div class="sbm-avatar">
                                                    <?= esc(
                                                        strtoupper(
                                                            substr(
                                                                $r['nama_lengkap'],
                                                                0,
                                                                1
                                                            )
                                                        )
                                                    ) ?>
                                                </div>

                                                <div>
                                                    <div class="sbm-name">
                                                        <?= esc($r['nama_lengkap']) ?>
                                                    </div>

                                                    <div class="sbm-nik">
                                                        NIK:
                                                        <?= esc($r['nik']) ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>

                                        <td>
                                            <span class="sbm-number">
                                                <i class="ri-file-paper-2-fill"></i>
                                                <?= esc($r['nomor_surat']) ?>
                                            </span>
                                        </td>

                                        <td>
                                            <span class="sbm-date-badge">
                                                <i class="ri-calendar-check-fill"></i>

                                                <?= esc(
                                                    tanggal_indo_belum_menikah(
                                                        $r['tanggal_surat']
                                                    )
                                                ) ?>
                                            </span>
                                        </td>

                                        <td>
                                            <div class="sbm-actions">
                                                <a
                                                    class="sbm-btn sbm-btn-small sbm-btn-print"
                                                    target="_blank"
                                                    rel="noopener"
                                                    href="surat_belum_menikah_print.php?id=<?= (int)$r['id'] ?>"
                                                >
                                                    <i class="ri-printer-fill"></i>
                                                    Print
                                                </a>

                                                <a
                                                    class="sbm-btn sbm-btn-small sbm-btn-edit"
                                                    href="surat_belum_menikah.php?a=form&id=<?= (int)$r['id'] ?>"
                                                >
                                                    <i class="ri-edit-2-fill"></i>
                                                    Edit
                                                </a>

                                                <form
                                                    method="post"
                                                    action="surat_belum_menikah.php?a=delete"
                                                    class="sbm-delete-form"
                                                    onsubmit="return confirm('Yakin ingin menghapus surat ini? Data yang dihapus tidak dapat dikembalikan.');"
                                                >
                                                    <input
                                                        type="hidden"
                                                        name="id"
                                                        value="<?= (int)$r['id'] ?>"
                                                    >

                                                    <button
                                                        type="submit"
                                                        class="sbm-btn sbm-btn-small sbm-btn-delete"
                                                    >
                                                        <i class="ri-delete-bin-6-fill"></i>
                                                        Hapus
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    <?php else: ?>

        <div class="sbm-header">
            <div class="sbm-header-left">
                <p class="sbm-eyebrow">
                    <i class="<?= $isEdit
                        ? 'ri-edit-2-fill'
                        : 'ri-file-add-fill' ?>"></i>

                    <?= $isEdit
                        ? 'Edit Dokumen Surat'
                        : 'Buat Dokumen Surat' ?>
                </p>

                <h2>
                    <i class="ri-user-star-fill"></i>

                    <?= $isEdit
                        ? 'Edit Surat Belum Menikah'
                        : 'Buat Surat Belum Menikah' ?>
                </h2>

                <p class="sbm-description">
                    <span class="sbm-dot"></span>
                    Pilih warga dan tentukan tanggal penerbitan surat.
                </p>
            </div>

            <div class="sbm-header-actions">
                <a
                    class="sbm-btn sbm-btn-light"
                    href="surat_belum_menikah.php"
                >
                    <i class="ri-arrow-left-line"></i>
                    Kembali
                </a>
            </div>
        </div>

        <?php if ($errorText): ?>
            <div class="sbm-alert sbm-alert-error">
                <i class="ri-error-warning-fill"></i>
                <?= esc($errorText) ?>
            </div>
        <?php endif; ?>

        <div class="sbm-panel">
            <div class="sbm-panel-head">
                <div class="sbm-panel-title">
                    <div class="sbm-panel-icon">
                        <i class="<?= $isEdit
                            ? 'ri-edit-2-fill'
                            : 'ri-draft-fill' ?>"></i>
                    </div>

                    <div>
                        <h3>
                            <?= $isEdit
                                ? 'Edit Data Surat'
                                : 'Form Surat Belum Menikah' ?>
                        </h3>

                        <p>
                            Nomor surat dapat disesuaikan sebelum disimpan.
                        </p>
                    </div>
                </div>
            </div>

            <div class="sbm-panel-body">
                <form
                    method="post"
                    action="surat_belum_menikah.php?a=save"
                    class="sbm-form"
                >
                    <input
                        type="hidden"
                        name="id"
                        value="<?= (int)($edit['id'] ?? 0) ?>"
                    >

                    <div class="sbm-field">
                        <label for="nomorSurat">
                            Nomor Surat
                            <span class="sbm-required">*</span>
                        </label>

                        <input
                            class="sbm-input"
                            id="nomorSurat"
                            name="nomor_surat"
                            value="<?= esc($nomorValue) ?>"
                            required
                        >
                    </div>

                    <div class="sbm-field">
                        <label for="tanggalSurat">
                            Tanggal Surat
                            <span class="sbm-required">*</span>
                        </label>

                        <input
                            type="date"
                            class="sbm-input"
                            id="tanggalSurat"
                            name="tanggal_surat"
                            value="<?= esc($tanggalSuratValue) ?>"
                            required
                        >
                    </div>

                    <div class="sbm-field sbm-field-full">
                        <label for="wargaId">
                            Pilih Warga
                            <span class="sbm-required">*</span>
                        </label>

                        <select
                            name="warga_id"
                            id="wargaId"
                            class="sbm-input select2"
                            required
                        >
                            <option value="">
                                -- Pilih Warga --
                            </option>

                            <?php if ($warga): ?>
                                <?php while ($w = $warga->fetch_assoc()): ?>
                                    <option
                                        value="<?= (int)$w['id'] ?>"
                                        <?= $wargaValue === (int)$w['id']
                                            ? 'selected'
                                            : '' ?>
                                    >
                                        <?= esc($w['nama_lengkap']) ?>
                                        -
                                        <?= esc($w['nik']) ?>
                                    </option>
                                <?php endwhile; ?>
                            <?php endif; ?>
                        </select>
                    </div>

                    <div class="sbm-form-actions">
                        <button
                            type="submit"
                            class="sbm-btn sbm-btn-primary"
                        >
                            <i class="ri-save-3-fill"></i>

                            <?= $isEdit
                                ? 'Perbarui Surat'
                                : 'Simpan Surat' ?>
                        </button>

                        <a
                            class="sbm-btn sbm-btn-ghost"
                            href="surat_belum_menikah.php"
                        >
                            <i class="ri-close-circle-fill"></i>
                            Batal
                        </a>
                    </div>
                </form>
            </div>
        </div>

    <?php endif; ?>

</div>

<script>
(() => {
    const search = document.getElementById('searchSbm');

    if (search) {
        search.addEventListener('input', function () {
            const keyword = this.value.toLowerCase().trim();

            document
                .querySelectorAll('.sbm-data-row')
                .forEach((row) => {
                    row.style.display = row.innerText
                        .toLowerCase()
                        .includes(keyword)
                        ? ''
                        : 'none';
                });
        });
    }

    const clock = document.getElementById('sbmClock');

    const updateClock = () => {
        if (!clock) {
            return;
        }

        clock.textContent = new Intl.DateTimeFormat(
            'id-ID',
            {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false,
                timeZone: 'Asia/Makassar'
            }
        )
        .format(new Date())
        .replaceAll(':', '.');
    };

    updateClock();
    setInterval(updateClock, 1000);
})();
</script>

<?php include __DIR__.'/../includes/footer.php'; ?>