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

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

/* =========================
   DATA UMUM
========================= */

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

$bulan = [
    1=>'Januari','Februari','Maret','April','Mei','Juni',
    'Juli','Agustus','September','Oktober','November','Desember'
];

$tanggalHariIni = date('j') . ' ' . $bulan[(int)date('n')] . ' ' . date('Y');

function nomor_merantau_baru($mysqli, $bulanRomawi) {
    $last = $mysqli->query("
        SELECT id FROM surat_merantau 
        ORDER BY id DESC 
        LIMIT 1
    ")->fetch_assoc();

    $urut = $last ? ((int)$last['id'] + 1) : 1;

    return sprintf(
        "044/%03d/Ds.M/%s/%s",
        $urut,
        $bulanRomawi[(int)date('n')],
        date('Y')
    );
}

function tanggal_indo_merantau($tanggal, $bulan) {
    if (!$tanggal) return '-';

    $time = strtotime($tanggal);
    return date('j', $time).' '.$bulan[(int)date('n', $time)].' '.date('Y', $time);
}


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

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

    if ($id > 0) {
        $stmt = $mysqli->prepare("DELETE FROM surat_merantau WHERE id=?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
    }

    header("Location: surat_merantau.php?msg=deleted");
    exit;
}


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

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);
    $tujuan_merantau = trim($_POST['tujuan_merantau'] ?? '');
    $tanggal_surat   = trim($_POST['tanggal_surat'] ?? '');
    $waktu_ttd       = date('Y-m-d H:i:s');

    if ($nomor_surat === '') {
        $nomor_surat = nomor_merantau_baru($mysqli, $bulanRomawi);
    }

    if ($tanggal_surat === '') {
        $tanggal_surat = date('Y-m-d');
    }

    if ($id > 0) {
        $qr_kode = '';

        $stmt = $mysqli->prepare("SELECT qr_kode FROM surat_merantau WHERE id=? LIMIT 1");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res && $row = $res->fetch_assoc()) {
            $qr_kode = $row['qr_kode'];
        }

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

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

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

        $stmt->bind_param(
            "sisssssi",
            $nomor_surat,
            $warga_id,
            $tujuan_merantau,
            $tanggal_surat,
            $waktu_ttd,
            $qr_kode,
            $qr_hash,
            $id
        );

        $stmt->execute();

        header("Location: surat_merantau.php?msg=updated");
        exit;
    }

    $qr_kode = 'SKM-'.time().'-'.rand(100, 999);
    $qr_hash = hash('sha256', $qr_kode.$nomor_surat);

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

    $stmt->bind_param(
        "sisssss",
        $nomor_surat,
        $warga_id,
        $tujuan_merantau,
        $tanggal_surat,
        $waktu_ttd,
        $qr_kode,
        $qr_hash
    );

    $stmt->execute();

    header("Location: surat_merantau.php?msg=saved");
    exit;
}


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

$edit = null;

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

    if ($edit_id > 0) {
        $stmt = $mysqli->prepare("SELECT * FROM surat_merantau WHERE id=? LIMIT 1");
        $stmt->bind_param('i', $edit_id);
        $stmt->execute();
        $res = $stmt->get_result();

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


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

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


/* =========================
   LIST DATA
========================= */

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

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

$msgKey = $_GET['msg'] ?? '';
$msgText = [
    'saved'   => 'Surat keterangan merantau berhasil dibuat.',
    'updated' => 'Surat keterangan merantau berhasil diperbarui.',
    'deleted' => 'Surat keterangan merantau berhasil dihapus.'
][$msgKey] ?? '';

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

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=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 {
    --green-950: #002818;
    --green-900: #003d22;
    --green-800: #005530;
    --green-700: #047a3d;
    --green-600: #09a04f;
    --green-500: #15c46a;
    --green-400: #35e085;
    --green-100: #dcfaee;
    --green-50:  #edfff5;
    --blue-500:  #2080e8;
    --yellow-500:#f5b400;
    --purple-500:#9448d6;
    --teal-500:  #0ab3a0;
    --orange-500:#f26b1d;
    --ink:       #0f1c16;
    --muted:     #5e6e67;
    --line:      #daeae1;
    --surface:   #ffffff;
    --page:      #f3faf6;
    --shadow:    0 8px 28px rgba(10,40,25,.10);
    --shadow-hover: 0 18px 48px rgba(10,40,25,.18);
    --radius:    16px;
}

@keyframes pulse-ring {
    0%   { box-shadow: 0 0 0 0 rgba(9,160,79,.45); }
    70%  { box-shadow: 0 0 0 12px rgba(9,160,79,0); }
    100% { box-shadow: 0 0 0 0 rgba(9,160,79,0); }
}

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

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

* {
    box-sizing: border-box;
}

body {
    background: var(--page);
    background-image:
        radial-gradient(ellipse at 80% 0%, rgba(21,196,106,.06) 0%, transparent 50%),
        radial-gradient(ellipse at 20% 100%, rgba(9,160,79,.04) 0%, transparent 50%);
    font-family: 'Inter', 'Segoe UI', system-ui, sans-serif;
    color: var(--ink);
}

.merantau-page {
    padding: 26px;
}

/* ===== HEADER ===== */

.merantau-header {
    position: relative;
    overflow: hidden;
    padding: 26px 30px;
    margin-bottom: 22px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 16px;
    background: linear-gradient(135deg, var(--green-950), var(--green-800), var(--green-900));
    background-size: 200% 100%;
    animation: gradient-shift 8s ease infinite;
    border-radius: var(--radius);
    box-shadow: 0 14px 40px rgba(0,60,30,.28);
}

.merantau-header::before,
.merantau-header::after {
    content: "";
    position: absolute;
    border-radius: 50%;
    pointer-events: none;
}

.merantau-header::before {
    width: 200px;
    height: 200px;
    top: -60px;
    right: -50px;
    background: radial-gradient(circle, rgba(21,196,106,.20), transparent 70%);
    animation: float-y 7s ease-in-out infinite;
}

.merantau-header::after {
    width: 120px;
    height: 120px;
    bottom: -30px;
    left: 30%;
    background: radial-gradient(circle, rgba(245,180,0,.12), transparent 70%);
    animation: float-y 5s ease-in-out infinite reverse;
}

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

.merantau-eyebrow {
    margin: 0 0 8px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: var(--green-400);
    font-size: 11px;
    font-weight: 800;
    letter-spacing: .10em;
    text-transform: uppercase;
}

.merantau-eyebrow::before {
    content: '';
    width: 22px;
    height: 2px;
    background: linear-gradient(90deg, var(--green-400), var(--green-500));
    border-radius: 2px;
}

.merantau-header h2 {
    margin: 0;
    font-size: clamp(20px, 3vw, 26px);
    font-weight: 800;
    letter-spacing: -.03em;
    color: #fff;
    line-height: 1.2;
}

.merantau-desc {
    margin-top: 10px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: rgba(255,255,255,.75);
    font-size: 12px;
    font-weight: 600;
}

.live-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--green-400);
    flex-shrink: 0;
    animation: pulse-ring 2s ease infinite;
}

.merantau-date {
    display: inline-flex;
    align-items: center;
    gap: 9px;
    padding: 10px 16px;
    background: rgba(255,255,255,.12);
    border: 1px solid rgba(255,255,255,.18);
    border-radius: 12px;
    color: #fff;
    font-size: 13px;
    font-weight: 700;
    backdrop-filter: blur(8px);
    margin-right: 8px;
}

.merantau-date i {
    font-size: 18px;
    color: var(--green-400);
    filter: drop-shadow(0 0 6px rgba(53,224,133,.4));
}

/* ===== PANEL ===== */

.merantau-panel {
    background: var(--surface);
    border: 1px solid rgba(210,232,220,.85);
    border-radius: var(--radius);
    box-shadow: var(--shadow);
    overflow: hidden;
}

.merantau-panel-head {
    padding: 18px 20px;
    border-bottom: 1px solid var(--line);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 14px;
    flex-wrap: wrap;
    background:
        radial-gradient(circle at top right, rgba(21,196,106,.08), transparent 34%),
        #fff;
}

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

.merantau-panel-icon {
    width: 42px;
    height: 42px;
    display: grid;
    place-items: center;
    color: #fff;
    background: linear-gradient(135deg, var(--green-500), var(--green-800));
    border-radius: 13px;
    font-size: 20px;
    box-shadow: 0 4px 12px rgba(9,160,79,.28);
}

.merantau-panel-title h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 800;
    color: var(--ink);
}

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

.merantau-body {
    padding: 20px;
}

/* ===== ALERT ===== */

.merantau-page .alert {
    margin-bottom: 16px;
    padding: 13px 15px;
    border-radius: 14px;
    background: var(--green-50);
    color: var(--green-800);
    border: 1px solid var(--green-100);
    font-size: 14px;
    font-weight: 800;
    box-shadow: var(--shadow);
    display: flex;
    align-items: center;
    gap: 9px;
}

/* ===== BUTTON ===== */

.merantau-page .btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 7px;
    padding: 10px 15px;
    border-radius: 12px;
    border: none;
    cursor: pointer;
    text-decoration: none;
    font-size: 13px;
    font-weight: 800;
    line-height: 1;
    transition: transform .2s ease, box-shadow .2s ease, filter .2s ease;
    box-shadow: 0 8px 18px rgba(10,40,25,.12);
}

.merantau-page .btn:hover {
    transform: translateY(-2px);
    filter: brightness(.98);
}

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

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

.merantau-page .btn-edit {
    color: var(--ink);
    background: linear-gradient(135deg, #ffd234, var(--yellow-500));
}

.merantau-page .btn-delete {
    color: #fff;
    background: linear-gradient(135deg, #ff9a52, var(--orange-500));
}

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

.merantau-page .btn-light {
    color: #fff;
    background: rgba(255,255,255,.12);
    border: 1px solid rgba(255,255,255,.18);
    backdrop-filter: blur(8px);
}

.merantau-page .btn-small {
    font-size: 12px;
    padding: 8px 11px;
    border-radius: 10px;
    box-shadow: none;
}

/* ===== TOOLBAR ===== */

.toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
    flex-wrap: wrap;
}

.search-box {
    position: relative;
    min-width: 260px;
    flex: 1;
}

.search-box input {
    width: 100%;
    padding: 12px 14px 12px 42px;
    border-radius: 14px;
    border: 1px solid var(--line);
    background: #f8fffb;
    outline: none;
    transition: .2s;
    color: var(--ink);
    font-weight: 600;
}

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

.search-box i {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--green-700);
    font-size: 18px;
}

.stat-pill {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    padding: 10px 14px;
    border-radius: 999px;
    background: var(--green-50);
    color: var(--green-800);
    font-size: 13px;
    font-weight: 800;
    border: 1px solid var(--green-100);
}

/* ===== TABLE ===== */

.table-wrap {
    overflow-x: auto;
    border: 1px solid var(--line);
    border-radius: 16px;
    background: #fff;
}

.merantau-page .table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    font-size: 14px;
}

.merantau-page .table th {
    background: linear-gradient(180deg, var(--green-50), #f8fffb);
    padding: 14px 13px;
    text-align: left;
    color: var(--green-900);
    border-bottom: 1px solid var(--line);
    white-space: nowrap;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: .04em;
}

.merantau-page .table td {
    padding: 14px 13px;
    border-bottom: 1px solid #edf7f1;
    vertical-align: middle;
}

.merantau-page .table tr:last-child td {
    border-bottom: none;
}

.merantau-page .table tbody tr {
    transition: background .16s ease;
}

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

.user-cell {
    display: flex;
    align-items: center;
    gap: 10px;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 14px;
    display: grid;
    place-items: center;
    color: #fff;
    font-weight: 800;
    background: linear-gradient(135deg, var(--green-500), var(--green-800));
    box-shadow: 0 8px 16px rgba(9,160,79,.20);
}

.name-main {
    font-weight: 800;
    color: var(--ink);
}

.name-sub {
    margin-top: 2px;
    font-size: 12px;
    color: var(--muted);
}

.nomor-surat {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    font-weight: 800;
    color: var(--green-900);
}

.nomor-surat i {
    color: var(--green-600);
}

.tujuan-cell {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 11px;
    border-radius: 999px;
    background: var(--green-50);
    color: var(--green-800);
    font-weight: 800;
    border: 1px solid var(--green-100);
    font-size: 12px;
}

.tujuan-cell i {
    color: var(--green-700);
    font-size: 16px;
}

.badge-date {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 7px 10px;
    border-radius: 999px;
    background: #eef8ff;
    color: var(--blue-500);
    font-weight: 800;
    font-size: 12px;
}

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

.actions form {
    margin: 0;
}

.empty {
    text-align: center;
    padding: 34px !important;
    color: var(--muted);
    background: #fbfffd;
    font-weight: 600;
}

.empty i {
    display: block;
    margin-bottom: 8px;
    font-size: 34px;
    color: var(--green-600);
}

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

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

.form-section {
    grid-column: 1 / -1;
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 4px;
    padding: 12px 14px;
    border-radius: 14px;
    background: var(--green-50);
    color: var(--green-900);
    font-weight: 800;
    border: 1px solid var(--green-100);
}

.form-section i {
    width: 30px;
    height: 30px;
    border-radius: 10px;
    display: grid;
    place-items: center;
    color: #fff;
    background: linear-gradient(135deg, var(--green-500), var(--green-800));
}

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

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

.field label {
    color: var(--ink);
    font-size: 13px;
    font-weight: 800;
}

.merantau-page .input {
    width: 100%;
    padding: 12px 13px;
    border-radius: 13px;
    border: 1px solid var(--line);
    background: #f8fffb;
    outline: none;
    transition: .2s;
    color: var(--ink);
    font-family: inherit;
    font-weight: 600;
}

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

.form-actions {
    grid-column: 1 / -1;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin-top: 4px;
}

/* ===== RESPONSIVE ===== */

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

    .merantau-header {
        padding: 20px;
    }

    .merantau-header-actions {
        width: 100%;
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
    }

    .merantau-date,
    .btn-light,
    .btn-primary {
        width: 100%;
        justify-content: center;
    }

    .toolbar {
        align-items: stretch;
    }

    .search-box,
    .stat-pill {
        width: 100%;
    }

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

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


<div class="merantau-page">

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

        <div class="merantau-header">
            <div class="merantau-header-left">
                <p class="merantau-eyebrow">
                    <i class="ri-suitcase-3-fill"></i>
                    Layanan Surat Desa
                </p>

                <h2>
                    <i class="ri-road-map-fill" style="font-size:24px;vertical-align:middle;margin-right:8px;color:var(--green-400);filter:drop-shadow(0 0 8px rgba(53,224,133,.5))"></i>
                    Surat Keterangan Merantau
                </h2>

                <p class="merantau-desc">
                    <span class="live-dot"></span>
                    Kelola surat keterangan merantau warga Desa Mambu — <?= esc($tanggalHariIni) ?>
                </p>
            </div>

            <div class="merantau-header-actions">
                <span class="merantau-date">
                    <i class="ri-time-fill"></i>
                    <span id="liveClock">--:--:--</span>
                    <span style="color:rgba(255,255,255,.55)">WITA</span>
                </span>

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

        <?php if ($msgText): ?>
            <div class="alert">
                <i class="ri-checkbox-circle-fill"></i>
                <?= esc($msgText) ?>
            </div>
        <?php endif; ?>

        <div class="merantau-panel">
            <div class="merantau-panel-head">
                <div class="merantau-panel-title">
                    <div class="merantau-panel-icon">
                        <i class="ri-folder-user-fill"></i>
                    </div>
                    <div>
                        <h3>Daftar Surat Merantau</h3>
                        <p>Data surat merantau yang sudah dibuat dan siap dicetak.</p>
                    </div>
                </div>

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

            <div class="merantau-body">
                <div class="toolbar">
                    <div class="search-box">
                        <i class="ri-search-line"></i>
                        <input type="text" id="searchSurat" placeholder="Cari nama, NIK, nomor surat, tujuan, atau tanggal...">
                    </div>
                </div>

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

                        <tbody>
                            <?php if ($total_surat === 0): ?>
                                <tr>
                                    <td colspan="6" class="empty">
                                        <i class="ri-inbox-2-fill"></i>
                                        Belum ada surat merantau. Klik tombol <b>Buat Surat</b> untuk menambahkan data baru.
                                    </td>
                                </tr>
                            <?php endif; ?>

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

                                    <td>
                                        <div class="user-cell">
                                            <div class="avatar">
                                                <?= esc(strtoupper(substr($r['nama_lengkap'], 0, 1))) ?>
                                            </div>
                                            <div>
                                                <div class="name-main"><?= esc($r['nama_lengkap']) ?></div>
                                                <div class="name-sub">NIK: <?= esc($r['nik'] ?? '-') ?></div>
                                            </div>
                                        </div>
                                    </td>

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

                                    <td>
                                        <span class="tujuan-cell">
                                            <i class="ri-map-pin-2-fill"></i>
                                            <?= esc($r['tujuan_merantau']) ?>
                                        </span>
                                    </td>

                                    <td>
                                        <span class="badge-date">
                                            <i class="ri-calendar-check-fill"></i>
                                            <?= esc(tanggal_indo_merantau($r['tanggal_surat'], $bulan)) ?>
                                        </span>
                                    </td>

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

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

                                            <form method="post"
                                                  action="surat_merantau.php?a=delete"
                                                  onsubmit="return confirm('Yakin ingin menghapus surat merantau ini? Data yang dihapus tidak bisa dikembalikan.');">
                                                <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                                                <button type="submit" class="btn btn-small btn-delete">
                                                    <i class="ri-delete-bin-6-fill"></i>
                                                    Hapus
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>


    <?php else: ?>

        <?php
            $is_edit = !empty($edit);

            $nomor_value   = $edit['nomor_surat'] ?? nomor_merantau_baru($mysqli, $bulanRomawi);
            $tanggal_value = $edit['tanggal_surat'] ?? date('Y-m-d');
            $tujuan_value  = $edit['tujuan_merantau'] ?? '';
        ?>

        <div class="merantau-header">
            <div class="merantau-header-left">
                <p class="merantau-eyebrow">
                    <i class="<?= $is_edit ? 'ri-edit-2-fill' : 'ri-add-box-fill' ?>"></i>
                    <?= $is_edit ? 'Edit Dokumen Surat' : 'Buat Dokumen Surat' ?>
                </p>

                <h2>
                    <i class="ri-file-edit-fill" style="font-size:24px;vertical-align:middle;margin-right:8px;color:var(--green-400);filter:drop-shadow(0 0 8px rgba(53,224,133,.5))"></i>
                    <?= $is_edit ? 'Edit Surat Keterangan Merantau' : 'Buat Surat Keterangan Merantau' ?>
                </h2>

                <p class="merantau-desc">
                    <span class="live-dot"></span>
                    <?= $is_edit ? 'Perbarui data surat merantau yang sudah dibuat.' : 'Lengkapi data warga dan tujuan merantau.' ?>
                </p>
            </div>

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

        <?php if ($msgText): ?>
            <div class="alert">
                <i class="ri-checkbox-circle-fill"></i>
                <?= esc($msgText) ?>
            </div>
        <?php endif; ?>

        <div class="merantau-panel">
            <div class="merantau-panel-head">
                <div class="merantau-panel-title">
                    <div class="merantau-panel-icon">
                        <i class="ri-suitcase-3-fill"></i>
                    </div>
                    <div>
                        <h3>Form Surat Keterangan Merantau</h3>
                        <p><?= $is_edit ? 'Ubah data dengan teliti sebelum menyimpan.' : 'Nomor surat otomatis dibuat sesuai urutan data.' ?></p>
                    </div>
                </div>
            </div>

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

                    <div class="field">
                        <label>Nomor Surat</label>
                        <input class="input" name="nomor_surat" value="<?= esc($nomor_value) ?>" required>
                    </div>

                    <div class="field">
                        <label>Tanggal Surat</label>
                        <input class="input" type="date" name="tanggal_surat" value="<?= esc($tanggal_value) ?>" required>
                    </div>

                    <div class="form-section">
                        <i class="ri-user-location-fill"></i>
                        Data Warga
                    </div>

                    <div class="field full">
                        <label>Pilih Warga</label>
                        <select name="warga_id" class="input select2" required style="width:100%;">
                            <option value="">-- Pilih Warga --</option>

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

                    <div class="form-section">
                        <i class="ri-road-map-fill"></i>
                        Data Tujuan
                    </div>

                    <div class="field full">
                        <label>Tujuan Merantau</label>
                        <input class="input" name="tujuan_merantau" value="<?= esc($tujuan_value) ?>" placeholder="Contoh: Kalimantan" required>
                    </div>

                    <div class="form-actions">
                        <button class="btn btn-primary" type="submit">
                            <i class="ri-save-3-fill"></i>
                            <?= $is_edit ? 'Perbarui Surat' : 'Simpan Surat' ?>
                        </button>

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

    <?php endif; ?>

</div>


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

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

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

    const clockEl = document.getElementById('liveClock');

    const tick = () => {
        if (!clockEl) return;

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

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

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