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

date_default_timezone_set('Asia/Makassar');

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


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

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

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

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

$nomorSuratOtomatis = sprintf(
    '%02d/%03d/Ds.M/%s/%s',
    $urut,
    $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_undangan.php?msg=notfound');
        exit;
    }

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

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

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

    $deleted = $stmt->affected_rows > 0;

    $stmt->close();

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


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

$errorText = '';

if ($act === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id             = (int)($_POST['id'] ?? 0);
    $nomor_surat    = trim($_POST['nomor_surat'] ?? '');
    $sifat          = trim($_POST['sifat'] ?? '');
    $lampiran       = trim($_POST['lampiran'] ?? '');
    $perihal        = trim($_POST['perihal'] ?? '');
    $tujuan         = trim($_POST['tujuan'] ?? '');
    $hari_tanggal   = trim($_POST['hari_tanggal'] ?? '');
    $pukul          = trim($_POST['pukul'] ?? '');
    $tempat         = trim($_POST['tempat'] ?? '');
    $isi            = trim($_POST['isi'] ?? '');
    $tanggal_surat  = trim($_POST['tanggal_surat'] ?? '');
    $waktu_ttd      = date('Y-m-d H:i:s');

    if (
        $nomor_surat === '' ||
        $sifat === '' ||
        $perihal === '' ||
        $tujuan === '' ||
        $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_undangan
            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 = 'SU-'.time().'-'.random_int(100, 999);
        }

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

        $stmt = $mysqli->prepare("
            UPDATE surat_undangan
            SET
                nomor_surat = ?,
                sifat = ?,
                lampiran = ?,
                perihal = ?,
                tujuan = ?,
                hari_tanggal = ?,
                pukul = ?,
                tempat = ?,
                isi = ?,
                tanggal_surat = ?,
                waktu_ttd = ?,
                qr_kode = ?,
                qr_hash = ?
            WHERE id = ?
        ");

        if ($stmt) {
            $stmt->bind_param(
                'sssssssssssssi',
                $nomor_surat,
                $sifat,
                $lampiran,
                $perihal,
                $tujuan,
                $hari_tanggal,
                $pukul,
                $tempat,
                $isi,
                $tanggal_surat,
                $waktu_ttd,
                $qr_kode,
                $qr_hash,
                $id
            );

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

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

            $stmt->close();
        }

        $errorText = 'Surat undangan gagal diperbarui. Silakan coba kembali.';
        $act = 'form';
    } else {

        /* ================= INSERT ================= */

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

        $stmt = $mysqli->prepare("
            INSERT INTO surat_undangan
            (
                nomor_surat,
                sifat,
                lampiran,
                perihal,
                tujuan,
                hari_tanggal,
                pukul,
                tempat,
                isi,
                tanggal_surat,
                waktu_ttd,
                qr_kode,
                qr_hash
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        if ($stmt) {
            $stmt->bind_param(
                'sssssssssssss',
                $nomor_surat,
                $sifat,
                $lampiran,
                $perihal,
                $tujuan,
                $hari_tanggal,
                $pukul,
                $tempat,
                $isi,
                $tanggal_surat,
                $waktu_ttd,
                $qr_kode,
                $qr_hash
            );

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

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

            $stmt->close();
        }

        $errorText = 'Surat undangan gagal disimpan. Silakan coba kembali.';
        $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_undangan
            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_undangan.php?msg=notfound');
            exit;
        }
    }
}


/* ================= NORMALISASI HALAMAN ================= */

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


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

$list = $mysqli->query("
    SELECT *
    FROM surat_undangan
    ORDER BY id DESC
");

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


/* ================= TANGGAL INDONESIA ================= */

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

function tanggal_indo_undangan($tanggal, $bulanIndonesia)
{
    if (!$tanggal) {
        return '-';
    }

    $time = strtotime($tanggal);

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

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

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


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

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

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

$msgType = in_array($msgKey, ['notfound', 'error'], true)
    ? 'error'
    : 'success';


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

$isEdit = !empty($edit);

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

$sifatValue = $_POST['sifat']
    ?? $edit['sifat']
    ?? 'Penting';

$lampiranValue = $_POST['lampiran']
    ?? $edit['lampiran']
    ?? '-';

$perihalValue = $_POST['perihal']
    ?? $edit['perihal']
    ?? '';

$tujuanValue = $_POST['tujuan']
    ?? $edit['tujuan']
    ?? '';

$hariTanggalValue = $_POST['hari_tanggal']
    ?? $edit['hari_tanggal']
    ?? '';

$pukulValue = $_POST['pukul']
    ?? $edit['pukul']
    ?? '';

$tempatValue = $_POST['tempat']
    ?? $edit['tempat']
    ?? '';

$isiValue = $_POST['isi']
    ?? $edit['isi']
    ?? '';

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

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 {
    --undangan-green-950: #002818;
    --undangan-green-900: #003d22;
    --undangan-green-800: #005530;
    --undangan-green-700: #047a3d;
    --undangan-green-600: #09a04f;
    --undangan-green-500: #15c46a;
    --undangan-green-400: #35e085;
    --undangan-green-100: #dcfaee;
    --undangan-green-50: #edfff5;

    --undangan-blue-500: #2080e8;
    --undangan-yellow-500: #f5b400;
    --undangan-orange-500: #f26b1d;
    --undangan-red-500: #d94343;

    --undangan-ink: #0f1c16;
    --undangan-muted: #5e6e67;
    --undangan-line: #daeae1;
    --undangan-surface: #ffffff;
    --undangan-page: #f3faf6;

    --undangan-shadow: 0 8px 28px rgba(10, 40, 25, .10);
    --undangan-radius: 16px;
}

@keyframes undangan-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 undangan-float-y {
    0%,
    100% {
        transform: translateY(0);
    }

    50% {
        transform: translateY(-8px);
    }
}

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

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

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

* {
    box-sizing: border-box;
}

body {
    color: var(--undangan-ink);
    background-color: var(--undangan-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;
}

.undangan-page {
    padding: 26px;
}


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

.undangan-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;

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

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

    animation: undangan-gradient-shift 8s ease infinite;
}

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

.undangan-header::before {
    width: 200px;
    height: 200px;
    top: -60px;
    right: -50px;

    background: radial-gradient(
        circle,
        rgba(21, 196, 106, .20),
        transparent 70%
    );

    animation: undangan-float-y 7s ease-in-out infinite;
}

.undangan-header::after {
    width: 120px;
    height: 120px;
    bottom: -30px;
    left: 30%;

    background: radial-gradient(
        circle,
        rgba(245, 180, 0, .12),
        transparent 70%
    );

    animation: undangan-float-y 5s ease-in-out infinite reverse;
}

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

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

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

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

.undangan-eyebrow::before {
    content: "";

    width: 22px;
    height: 2px;

    background: linear-gradient(
        90deg,
        var(--undangan-green-400),
        var(--undangan-green-500)
    );

    border-radius: 2px;
}

.undangan-header h2 {
    margin: 0;

    color: #ffffff;
    font-size: clamp(20px, 3vw, 26px);
    font-weight: 800;
    letter-spacing: -.03em;
    line-height: 1.2;
}

.undangan-title-icon {
    margin-right: 8px;

    color: var(--undangan-green-400);
    font-size: 25px;
    vertical-align: middle;

    filter: drop-shadow(
        0 0 8px rgba(53, 224, 133, .5)
    );
}

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

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

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

.undangan-live-dot {
    width: 8px;
    height: 8px;
    flex-shrink: 0;

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

    animation: undangan-pulse-ring 2s ease infinite;
}

.undangan-header-actions {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
}

.undangan-date {
    padding: 10px 16px;

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

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

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

    backdrop-filter: blur(8px);
}

.undangan-date i {
    color: var(--undangan-green-400);
    font-size: 18px;

    filter: drop-shadow(
        0 0 6px rgba(53, 224, 133, .4)
    );
}


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

.undangan-panel {
    overflow: hidden;

    background: var(--undangan-surface);
    border: 1px solid rgba(210, 232, 220, .85);
    border-radius: var(--undangan-radius);
    box-shadow: var(--undangan-shadow);
}

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

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

    background:
        radial-gradient(
            circle at top right,
            rgba(21, 196, 106, .08),
            transparent 34%
        ),
        #ffffff;

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

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

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

    display: grid;
    place-items: center;

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

    border-radius: 13px;
    box-shadow: 0 4px 12px rgba(9, 160, 79, .28);
    font-size: 20px;
}

.undangan-panel-title h3 {
    margin: 0;

    color: var(--undangan-ink);
    font-size: 16px;
    font-weight: 800;
}

.undangan-panel-title p {
    margin: 3px 0 0;

    color: var(--undangan-muted);
    font-size: 12px;
    font-weight: 600;
}

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


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

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

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

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

    box-shadow: var(--undangan-shadow);
    font-size: 14px;
    font-weight: 800;
}

.undangan-alert-error {
    color: #a73c00;
    background: #fff4eb;
    border-color: #ffd8bd;
}


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

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

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

    border: none;
    border-radius: 12px;
    cursor: pointer;
    text-decoration: none;

    font-family: inherit;
    font-size: 13px;
    font-weight: 800;
    line-height: 1;

    box-shadow: 0 8px 18px rgba(10, 40, 25, .12);

    transition:
        transform .2s ease,
        filter .2s ease,
        box-shadow .2s ease;
}

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

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

.undangan-btn-light {
    color: #ffffff;
    background: rgba(255, 255, 255, .12);
    border: 1px solid rgba(255, 255, 255, .18);

    backdrop-filter: blur(8px);
}

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

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

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

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

.undangan-btn-small {
    padding: 8px 11px;

    border-radius: 10px;
    box-shadow: none;
    font-size: 12px;
}


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

.undangan-toolbar {
    margin-bottom: 16px;

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

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

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

    color: var(--undangan-ink);
    background: #f8fffb;
    border: 1px solid var(--undangan-line);
    border-radius: 14px;
    outline: none;

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

    transition: .2s ease;
}

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

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

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

    transform: translateY(-50%);
}

.undangan-stat {
    padding: 10px 14px;

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

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

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


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

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

    background: #ffffff;
    border: 1px solid var(--undangan-line);
    border-radius: 16px;
}

.undangan-table {
    width: 100%;

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

    font-size: 14px;
}

.undangan-table th {
    padding: 14px 13px;

    color: var(--undangan-green-900);
    background: linear-gradient(
        180deg,
        var(--undangan-green-50),
        #f8fffb
    );

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

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

.undangan-table td {
    padding: 14px 13px;

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

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

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

.undangan-table tbody tr:last-child td {
    border-bottom: none;
}

.undangan-number {
    display: inline-flex;
    align-items: center;
    gap: 7px;

    color: var(--undangan-green-900);
    font-weight: 800;
    white-space: nowrap;
}

.undangan-number i {
    color: var(--undangan-green-600);
}

.undangan-subject {
    display: flex;
    align-items: center;
    gap: 10px;
}

.undangan-subject-icon {
    width: 40px;
    height: 40px;
    flex-shrink: 0;

    display: grid;
    place-items: center;

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

    border-radius: 14px;
    box-shadow: 0 8px 16px rgba(9, 160, 79, .20);
    font-size: 18px;
}

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

.undangan-subject-sub {
    margin-top: 3px;

    color: var(--undangan-muted);
    font-size: 12px;
}

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

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

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

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

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

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

.undangan-empty {
    padding: 34px !important;

    color: var(--undangan-muted);
    background: #fbfffd;

    font-weight: 600;
    text-align: center;
}

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

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


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

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

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

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

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

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

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

    color: var(--undangan-ink);
    background: #f8fffb;
    border: 1px solid var(--undangan-line);
    border-radius: 13px;
    outline: none;

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

    transition:
        border-color .2s ease,
        background .2s ease,
        box-shadow .2s ease;
}

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

textarea.undangan-input {
    resize: vertical;
    line-height: 1.6;
}

.undangan-help {
    margin: 0;

    color: var(--undangan-muted);
    font-size: 11px;
    font-weight: 600;
}

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

    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;

    margin-top: 4px;
}


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

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

    .undangan-header {
        padding: 20px;
    }

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

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

    .undangan-toolbar {
        align-items: stretch;
    }

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

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

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

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


<div class="undangan-page">

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

        <!-- ================= HALAMAN DAFTAR ================= -->

        <div class="undangan-header">
            <div class="undangan-header-left">
                <p class="undangan-eyebrow">
                    <i class="ri-mail-send-fill"></i>
                    Layanan Surat Desa
                </p>

                <h2>
                    <i class="ri-mail-open-fill undangan-title-icon"></i>
                    Surat Undangan
                </h2>

                <p class="undangan-description">
                    <span class="undangan-live-dot"></span>

                    Kelola surat undangan Desa Mambu —
                    <?= esc($tanggalHariIni) ?>
                </p>
            </div>

            <div class="undangan-header-actions">
                <span class="undangan-date">
                    <i class="ri-time-fill"></i>

                    <span id="undanganLiveClock">
                        --.--.--
                    </span>

                    <span style="color:rgba(255,255,255,.55)">
                        WITA
                    </span>
                </span>

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


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

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


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

                    <div>
                        <h3>Daftar Surat Undangan</h3>

                        <p>
                            Data surat undangan yang sudah dibuat dan siap dicetak.
                        </p>
                    </div>
                </div>

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

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

                        <input
                            type="text"
                            id="searchSuratUndangan"
                            placeholder="Cari nomor surat, perihal, tujuan, sifat, atau tanggal..."
                        >
                    </div>
                </div>

                <div class="undangan-table-wrap">
                    <table class="undangan-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Nomor Surat</th>
                                <th>Perihal</th>
                                <th>Tanggal Surat</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if ($totalSurat === 0): ?>
                                <tr>
                                    <td colspan="5" class="undangan-empty">
                                        <i class="ri-inbox-2-fill"></i>

                                        Belum ada surat undangan.
                                        Klik tombol
                                        <strong>Buat Surat</strong>
                                        untuk menambahkan data baru.
                                    </td>
                                </tr>
                            <?php endif; ?>

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

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

                                        <td>
                                            <span class="undangan-number">
                                                <i class="ri-file-paper-2-fill"></i>

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

                                        <td>
                                            <div class="undangan-subject">
                                                <div class="undangan-subject-icon">
                                                    <i class="ri-mail-fill"></i>
                                                </div>

                                                <div>
                                                    <div class="undangan-subject-main">
                                                        <?= esc($r['perihal']) ?>
                                                    </div>

                                                    <div class="undangan-subject-sub">
                                                        Sifat:
                                                        <?= esc($r['sifat'] ?: '-') ?>

                                                        &nbsp;•&nbsp;

                                                        Tujuan:
                                                        <?= esc(
                                                            mb_strimwidth(
                                                                preg_replace(
                                                                    '/\s+/',
                                                                    ' ',
                                                                    $r['tujuan'] ?? ''
                                                                ),
                                                                0,
                                                                45,
                                                                '...'
                                                            )
                                                        ) ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>

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

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

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

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

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

                                                    <button
                                                        type="submit"
                                                        class="undangan-btn undangan-btn-small undangan-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: ?>

        <!-- ================= HALAMAN FORM ================= -->

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

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

                <h2>
                    <i class="ri-mail-edit-fill undangan-title-icon"></i>

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

                <p class="undangan-description">
                    <span class="undangan-live-dot"></span>

                    <?= $isEdit
                        ? 'Perbarui data surat undangan yang sudah dibuat.'
                        : 'Lengkapi form untuk membuat surat undangan baru.' ?>
                </p>
            </div>

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


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


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

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

                        <p>
                            <?= $isEdit
                                ? 'Ubah data dengan teliti sebelum menyimpan.'
                                : 'Isi informasi undangan, tujuan, waktu, dan tempat.' ?>
                        </p>
                    </div>
                </div>
            </div>

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

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

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

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

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

                    <div class="undangan-field">
                        <label for="sifat">
                            Sifat
                            <span class="undangan-required">*</span>
                        </label>

                        <input
                            type="text"
                            class="undangan-input"
                            id="sifat"
                            name="sifat"
                            value="<?= esc($sifatValue) ?>"
                            placeholder="Contoh: Penting"
                            required
                        >
                    </div>

                    <div class="undangan-field">
                        <label for="lampiran">
                            Lampiran
                        </label>

                        <input
                            type="text"
                            class="undangan-input"
                            id="lampiran"
                            name="lampiran"
                            value="<?= esc($lampiranValue) ?>"
                            placeholder="Contoh: -"
                        >
                    </div>

                    <div class="undangan-field undangan-field-full">
                        <label for="perihal">
                            Perihal
                            <span class="undangan-required">*</span>
                        </label>

                        <input
                            type="text"
                            class="undangan-input"
                            id="perihal"
                            name="perihal"
                            value="<?= esc($perihalValue) ?>"
                            placeholder="Contoh: Undangan Rapat Musyawarah Desa"
                            required
                        >
                    </div>

                    <div class="undangan-field undangan-field-full">
                        <label for="tujuan">
                            Tujuan / Kepada
                            <span class="undangan-required">*</span>
                        </label>

                        <textarea
                            class="undangan-input"
                            id="tujuan"
                            name="tujuan"
                            rows="5"
                            placeholder="Contoh:&#10;Ketua BPD Desa Mambu&#10;Kepala Dusun se-Desa Mambu&#10;Tokoh Masyarakat"
                            required
                        ><?= esc($tujuanValue) ?></textarea>

                        <p class="undangan-help">
                            Tulis satu tujuan atau penerima dalam satu baris.
                        </p>
                    </div>

                    <div class="undangan-field">
                        <label for="hariTanggal">
                            Hari / Tanggal Pelaksanaan
                        </label>

                        <input
                            type="text"
                            class="undangan-input"
                            id="hariTanggal"
                            name="hari_tanggal"
                            value="<?= esc($hariTanggalValue) ?>"
                            placeholder="Contoh: Senin, 29 Juni 2026"
                        >
                    </div>

                    <div class="undangan-field">
                        <label for="pukul">
                            Pukul
                        </label>

                        <input
                            type="text"
                            class="undangan-input"
                            id="pukul"
                            name="pukul"
                            value="<?= esc($pukulValue) ?>"
                            placeholder="Contoh: 09.00 WITA"
                        >
                    </div>

                    <div class="undangan-field undangan-field-full">
                        <label for="tempat">
                            Tempat
                        </label>

                        <input
                            type="text"
                            class="undangan-input"
                            id="tempat"
                            name="tempat"
                            value="<?= esc($tempatValue) ?>"
                            placeholder="Contoh: Kantor Desa Mambu"
                        >
                    </div>

                    <div class="undangan-field undangan-field-full">
                        <label for="isi">
                            Isi Undangan
                        </label>

                        <textarea
                            class="undangan-input"
                            id="isi"
                            name="isi"
                            rows="6"
                            placeholder="Tuliskan isi atau penjelasan undangan..."
                        ><?= esc($isiValue) ?></textarea>
                    </div>

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

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

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

    <?php endif; ?>

</div>


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

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

            document
                .querySelectorAll('.undangan-data-row')
                .forEach((row) => {
                    const rowText = row.innerText.toLowerCase();

                    row.style.display = rowText.includes(keyword)
                        ? ''
                        : 'none';
                });
        });
    }


    const clockElement = document.getElementById(
        'undanganLiveClock'
    );

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

        clockElement.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'; ?>