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

date_default_timezone_set('Asia/Makassar');

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


/* =========================================================
   FUNGSI BANTU
========================================================= */

function tanggal_valid_gadai($tanggal)
{
    if ($tanggal === '') {
        return false;
    }

    $objekTanggal = DateTime::createFromFormat('Y-m-d', $tanggal);

    return $objekTanggal
        && $objekTanggal->format('Y-m-d') === $tanggal;
}

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

    $waktu = strtotime($tanggal);

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

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

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

    $waktu = strtotime($tanggal);

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

    return date('d-m-Y', $waktu);
}

function rupiah_gadai($nominal)
{
    $nominal = preg_replace('/[^0-9]/', '', (string)$nominal);

    if ($nominal === '') {
        return 'Rp 0';
    }

    return 'Rp '.number_format(
        (float)$nominal,
        0,
        ',',
        '.'
    );
}

function inisial_gadai($nama)
{
    $nama = trim((string)$nama);

    if ($nama === '') {
        return '?';
    }

    if (function_exists('mb_substr')) {
        return mb_strtoupper(
            mb_substr($nama, 0, 1, 'UTF-8'),
            'UTF-8'
        );
    }

    return strtoupper(substr($nama, 0, 1));
}


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

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

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

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

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

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

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

    $stmt->close();

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


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

$errorText = '';

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

    $pihakPertamaId = (int)(
        $_POST['pihak_pertama_id'] ?? 0
    );

    $pihakKeduaId = (int)(
        $_POST['pihak_kedua_id'] ?? 0
    );

    $luasLahan = trim(
        $_POST['luas_lahan'] ?? ''
    );

    $lokasiLahan = trim(
        $_POST['lokasi_lahan'] ?? ''
    );

    $batasUtara = trim(
        $_POST['batas_utara'] ?? ''
    );

    $batasSelatan = trim(
        $_POST['batas_selatan'] ?? ''
    );

    $batasBarat = trim(
        $_POST['batas_barat'] ?? ''
    );

    $batasTimur = trim(
        $_POST['batas_timur'] ?? ''
    );

    $jumlahUang = preg_replace(
        '/[^0-9]/',
        '',
        (string)($_POST['jumlah_uang'] ?? '')
    );

    $tanggalSurat = trim(
        $_POST['tanggal_surat'] ?? ''
    );


    /* ================= VALIDASI ================= */

    if (
        $pihakPertamaId <= 0 ||
        $pihakKeduaId <= 0 ||
        $luasLahan === '' ||
        $lokasiLahan === '' ||
        $jumlahUang === '' ||
        (float)$jumlahUang <= 0 ||
        !tanggal_valid_gadai($tanggalSurat)
    ) {
        $errorText = 'Mohon lengkapi semua data yang wajib diisi.';
        $act = 'form';
    } elseif ($pihakPertamaId === $pihakKeduaId) {
        $errorText = 'Pihak pertama dan pihak kedua tidak boleh merupakan warga yang sama.';
        $act = 'form';
    } elseif ($id > 0) {

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

        $stmt = $mysqli->prepare("
            UPDATE surat_gadai
            SET
                pihak_pertama_id = ?,
                pihak_kedua_id = ?,
                luas_lahan = ?,
                lokasi_lahan = ?,
                batas_utara = ?,
                batas_selatan = ?,
                batas_barat = ?,
                batas_timur = ?,
                jumlah_uang = ?,
                tanggal_surat = ?
            WHERE id = ?
        ");

        if ($stmt) {
            $stmt->bind_param(
                'iissssssssi',
                $pihakPertamaId,
                $pihakKeduaId,
                $luasLahan,
                $lokasiLahan,
                $batasUtara,
                $batasSelatan,
                $batasBarat,
                $batasTimur,
                $jumlahUang,
                $tanggalSurat,
                $id
            );

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

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

            $stmt->close();
        }

        $errorText = 'Surat keterangan gadai gagal diperbarui.';
        $act = 'form';
    } else {

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

        $stmt = $mysqli->prepare("
            INSERT INTO surat_gadai
            (
                pihak_pertama_id,
                pihak_kedua_id,
                luas_lahan,
                lokasi_lahan,
                batas_utara,
                batas_selatan,
                batas_barat,
                batas_timur,
                jumlah_uang,
                tanggal_surat
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        if ($stmt) {
            $stmt->bind_param(
                'iissssssss',
                $pihakPertamaId,
                $pihakKeduaId,
                $luasLahan,
                $lokasiLahan,
                $batasUtara,
                $batasSelatan,
                $batasBarat,
                $batasTimur,
                $jumlahUang,
                $tanggalSurat
            );

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

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

            $stmt->close();
        }

        $errorText = 'Surat keterangan gadai 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_gadai
            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_gadai.php?msg=notfound');
            exit;
        }
    }
}


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

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


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

$wargaData = [];

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

if ($wargaResult) {
    while ($row = $wargaResult->fetch_assoc()) {
        $wargaData[] = $row;
    }
}


/* =========================================================
   DAFTAR SURAT
========================================================= */

$list = $mysqli->query("
    SELECT
        g.*,
        p1.nama_lengkap AS pihak1,
        p1.nik AS nik_pihak1,
        p2.nama_lengkap AS pihak2,
        p2.nik AS nik_pihak2
    FROM surat_gadai g
    JOIN infografis p1
        ON g.pihak_pertama_id = p1.id
    JOIN infografis p2
        ON g.pihak_kedua_id = p2.id
    ORDER BY g.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'
];

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


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

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

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

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


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

$isEdit = !empty($edit);

$pihakPertamaValue = (int)(
    $_POST['pihak_pertama_id']
    ?? $edit['pihak_pertama_id']
    ?? 0
);

$pihakKeduaValue = (int)(
    $_POST['pihak_kedua_id']
    ?? $edit['pihak_kedua_id']
    ?? 0
);

$luasLahanValue = $_POST['luas_lahan']
    ?? $edit['luas_lahan']
    ?? '';

$lokasiLahanValue = $_POST['lokasi_lahan']
    ?? $edit['lokasi_lahan']
    ?? '';

$batasUtaraValue = $_POST['batas_utara']
    ?? $edit['batas_utara']
    ?? '';

$batasSelatanValue = $_POST['batas_selatan']
    ?? $edit['batas_selatan']
    ?? '';

$batasBaratValue = $_POST['batas_barat']
    ?? $edit['batas_barat']
    ?? '';

$batasTimurValue = $_POST['batas_timur']
    ?? $edit['batas_timur']
    ?? '';

$jumlahUangValue = preg_replace(
    '/[^0-9]/',
    '',
    (string)(
        $_POST['jumlah_uang']
        ?? $edit['jumlah_uang']
        ?? ''
    )
);

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

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

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

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

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

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

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

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

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

* {
    box-sizing: border-box;
}

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

.gadai-page {
    padding: 26px;
}


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

.gadai-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(--gadai-green-950),
        var(--gadai-green-800),
        var(--gadai-green-900)
    );
    background-size: 200% 100%;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    width: 22px;
    height: 2px;

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

    border-radius: 2px;
}

.gadai-header h2 {
    margin: 0;

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

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

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

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

.gadai-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;
}

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

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

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

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

.gadai-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);
}

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

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


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

.gadai-panel {
    overflow: hidden;

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

.gadai-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(--gadai-line);
}

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

.gadai-panel-icon {
    width: 42px;
    height: 42px;
    flex-shrink: 0;

    display: grid;
    place-items: center;

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

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

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

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

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

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

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


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

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

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

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

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

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


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

.gadai-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;
}

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

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

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

    backdrop-filter: blur(8px);
}

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

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

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

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

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

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


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

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

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

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

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

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

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

    transition: .2s ease;
}

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

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

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

    transform: translateY(-50%);
}

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

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

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

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


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

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

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

.gadai-table {
    width: 100%;

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

    font-size: 14px;
}

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

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

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

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

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

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

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

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

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

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

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

    display: grid;
    place-items: center;

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

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

.gadai-avatar-second {
    background: linear-gradient(
        135deg,
        #3b9ced,
        #1762b0
    );

    box-shadow: 0 8px 16px rgba(32, 128, 232, .20);
}

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

.gadai-person-nik {
    margin-top: 3px;

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

.gadai-object {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.gadai-object-title {
    display: inline-flex;
    align-items: center;
    gap: 7px;

    color: var(--gadai-green-900);
    font-weight: 800;
}

.gadai-object-title i {
    color: var(--gadai-green-600);
    font-size: 17px;
}

.gadai-object-location {
    max-width: 260px;

    color: var(--gadai-muted);
    font-size: 12px;
    line-height: 1.4;
}

.gadai-money-badge {
    padding: 7px 10px;

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

    color: var(--gadai-ink);
    background: #f8fffb;
    border: 1px solid var(--gadai-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;
}

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

.gadai-input[readonly] {
    color: var(--gadai-green-900);
    background: var(--gadai-green-50);
    cursor: not-allowed;
}

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

.gadai-help {
    margin: 0;

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

.gadai-section-title {
    grid-column: 1 / -1;

    margin-top: 2px;
    padding: 12px 14px;

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

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

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

.gadai-section-title i {
    color: var(--gadai-green-600);
    font-size: 18px;
}

.gadai-party-card {
    padding: 15px;

    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;

    background: #fbfffd;
    border: 1px solid var(--gadai-line);
    border-radius: 14px;
}

.gadai-party-card-title {
    grid-column: 1 / -1;

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

    color: var(--gadai-green-900);
    font-size: 13px;
    font-weight: 800;
}

.gadai-party-card-title i {
    color: var(--gadai-green-600);
    font-size: 18px;
}

.gadai-party-info {
    min-width: 0;
}

.gadai-party-info span {
    display: block;

    color: var(--gadai-muted);
    font-size: 10px;
    font-weight: 800;
    letter-spacing: .04em;
    text-transform: uppercase;
}

.gadai-party-info strong {
    display: block;
    overflow: hidden;

    margin-top: 4px;

    color: var(--gadai-ink);
    font-size: 12px;
    font-weight: 700;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.gadai-boundary-grid {
    grid-column: 1 / -1;

    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
}

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

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

    margin-top: 4px;
}


/* =========================================================
   SELECT2
========================================================= */

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

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

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

.gadai-field
.select2-container
.select2-selection--single
.select2-selection__rendered {
    padding-left: 13px;
    padding-right: 38px;

    color: var(--gadai-ink);
    font-size: 14px;
    font-weight: 600;
    line-height: 42px;
}

.gadai-field
.select2-container
.select2-selection--single
.select2-selection__arrow {
    height: 42px;
    right: 8px;
}

.gadai-field
.select2-container--default.select2-container--focus
.select2-selection--single,
.gadai-field
.select2-container--default.select2-container--open
.select2-selection--single {
    background: #ffffff;
    border-color: var(--gadai-green-500);
    box-shadow: 0 0 0 4px rgba(21, 196, 106, .13);
}


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

@media (max-width: 900px) {
    .gadai-table {
        min-width: 1080px;
    }
}

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

    .gadai-header {
        padding: 20px;
    }

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

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

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

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

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

    .gadai-field-full,
    .gadai-section-title,
    .gadai-boundary-grid,
    .gadai-form-actions {
        grid-column: 1;
    }

    .gadai-boundary-grid {
        grid-template-columns: 1fr;
    }

    .gadai-party-card {
        grid-template-columns: 1fr;
    }

    .gadai-party-card-title {
        grid-column: 1;
    }
}
</style>


<div class="gadai-page">

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

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

        <div class="gadai-header">
            <div class="gadai-header-left">
                <p class="gadai-eyebrow">
                    <i class="ri-hand-coin-fill"></i>
                    Layanan Surat Desa
                </p>

                <h2>
                    <i class="ri-file-shield-2-fill gadai-title-icon"></i>
                    Surat Keterangan Gadai
                </h2>

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

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

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

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

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

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


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

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


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

                    <div>
                        <h3>Daftar Surat Gadai</h3>

                        <p>
                            Data perjanjian gadai lahan yang sudah dibuat.
                        </p>
                    </div>
                </div>

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

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

                        <input
                            type="text"
                            id="searchSuratGadai"
                            placeholder="Cari nama, NIK, lokasi, luas, nominal, atau tanggal..."
                        >
                    </div>
                </div>

                <div class="gadai-table-wrap">
                    <table class="gadai-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Pihak Pertama</th>
                                <th>Pihak Kedua</th>
                                <th>Objek Gadai</th>
                                <th>Jumlah Uang</th>
                                <th>Tanggal</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>

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

                                        Belum ada surat keterangan gadai.
                                        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="gadai-data-row">
                                        <td>
                                            <?= $no++ ?>
                                        </td>

                                        <td>
                                            <div class="gadai-person">
                                                <div class="gadai-avatar">
                                                    <?= esc(
                                                        inisial_gadai(
                                                            $r['pihak1']
                                                        )
                                                    ) ?>
                                                </div>

                                                <div>
                                                    <div class="gadai-person-name">
                                                        <?= esc($r['pihak1']) ?>
                                                    </div>

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

                                        <td>
                                            <div class="gadai-person">
                                                <div class="gadai-avatar gadai-avatar-second">
                                                    <?= esc(
                                                        inisial_gadai(
                                                            $r['pihak2']
                                                        )
                                                    ) ?>
                                                </div>

                                                <div>
                                                    <div class="gadai-person-name">
                                                        <?= esc($r['pihak2']) ?>
                                                    </div>

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

                                        <td>
                                            <div class="gadai-object">
                                                <div class="gadai-object-title">
                                                    <i class="ri-landscape-fill"></i>

                                                    <?= esc(
                                                        $r['luas_lahan']
                                                        ?: '-'
                                                    ) ?>
                                                </div>

                                                <div class="gadai-object-location">
                                                    <?= esc(
                                                        $r['lokasi_lahan']
                                                        ?: '-'
                                                    ) ?>
                                                </div>
                                            </div>
                                        </td>

                                        <td>
                                            <span class="gadai-money-badge">
                                                <i class="ri-money-dollar-circle-fill"></i>

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

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

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

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

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

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

                                                    <button
                                                        type="submit"
                                                        class="gadai-btn gadai-btn-small gadai-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="gadai-header">
            <div class="gadai-header-left">
                <p class="gadai-eyebrow">
                    <i class="<?= $isEdit
                        ? 'ri-edit-2-fill'
                        : 'ri-file-add-fill' ?>"></i>

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

                <h2>
                    <i class="ri-hand-coin-fill gadai-title-icon"></i>

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

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

                    <?= $isEdit
                        ? 'Perbarui data perjanjian gadai yang sudah dibuat.'
                        : 'Lengkapi data kedua pihak dan objek lahan yang digadaikan.' ?>
                </p>
            </div>

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


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


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

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

                        <p>
                            <?= $isEdit
                                ? 'Periksa kembali setiap data sebelum diperbarui.'
                                : 'Pilih kedua pihak lalu lengkapi data objek gadai.' ?>
                        </p>
                    </div>
                </div>
            </div>

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


                    <!-- ================= PARA PIHAK ================= -->

                    <div class="gadai-section-title">
                        <i class="ri-group-fill"></i>
                        Data Para Pihak
                    </div>

                    <div class="gadai-field">
                        <label for="pihakPertama">
                            Pihak Pertama
                            <span class="gadai-required">*</span>
                        </label>

                        <select
                            class="gadai-input select2"
                            id="pihakPertama"
                            name="pihak_pertama_id"
                            required
                        >
                            <option
                                value=""
                                data-nama=""
                                data-nik=""
                                data-tanggal-lahir=""
                                data-pekerjaan=""
                                data-dusun=""
                            >
                                -- Pilih Pihak Pertama --
                            </option>

                            <?php foreach ($wargaData as $w): ?>
                                <option
                                    value="<?= (int)$w['id'] ?>"
                                    data-nama="<?= esc(
                                        $w['nama_lengkap'] ?? ''
                                    ) ?>"
                                    data-nik="<?= esc(
                                        $w['nik'] ?? ''
                                    ) ?>"
                                    data-tanggal-lahir="<?= esc(
                                        tanggal_singkat_gadai(
                                            $w['tanggal_lahir'] ?? ''
                                        )
                                    ) ?>"
                                    data-pekerjaan="<?= esc(
                                        $w['pekerjaan'] ?? ''
                                    ) ?>"
                                    data-dusun="<?= esc(
                                        $w['dusun'] ?? ''
                                    ) ?>"
                                    <?= $pihakPertamaValue === (int)$w['id']
                                        ? 'selected'
                                        : '' ?>
                                >
                                    <?= esc($w['nama_lengkap']) ?>
                                    |
                                    <?= esc($w['nik']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <p class="gadai-help">
                            Pihak yang menyerahkan atau menggadaikan lahan.
                        </p>
                    </div>

                    <div class="gadai-field">
                        <label for="pihakKedua">
                            Pihak Kedua
                            <span class="gadai-required">*</span>
                        </label>

                        <select
                            class="gadai-input select2"
                            id="pihakKedua"
                            name="pihak_kedua_id"
                            required
                        >
                            <option
                                value=""
                                data-nama=""
                                data-nik=""
                                data-tanggal-lahir=""
                                data-pekerjaan=""
                                data-dusun=""
                            >
                                -- Pilih Pihak Kedua --
                            </option>

                            <?php foreach ($wargaData as $w): ?>
                                <option
                                    value="<?= (int)$w['id'] ?>"
                                    data-nama="<?= esc(
                                        $w['nama_lengkap'] ?? ''
                                    ) ?>"
                                    data-nik="<?= esc(
                                        $w['nik'] ?? ''
                                    ) ?>"
                                    data-tanggal-lahir="<?= esc(
                                        tanggal_singkat_gadai(
                                            $w['tanggal_lahir'] ?? ''
                                        )
                                    ) ?>"
                                    data-pekerjaan="<?= esc(
                                        $w['pekerjaan'] ?? ''
                                    ) ?>"
                                    data-dusun="<?= esc(
                                        $w['dusun'] ?? ''
                                    ) ?>"
                                    <?= $pihakKeduaValue === (int)$w['id']
                                        ? 'selected'
                                        : '' ?>
                                >
                                    <?= esc($w['nama_lengkap']) ?>
                                    |
                                    <?= esc($w['nik']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <p class="gadai-help">
                            Pihak yang menerima gadai atau menyerahkan uang.
                        </p>
                    </div>


                    <!-- ================= RINGKASAN PIHAK ================= -->

                    <div class="gadai-party-card">
                        <div class="gadai-party-card-title">
                            <i class="ri-user-location-fill"></i>
                            Informasi Pihak Pertama
                        </div>

                        <div class="gadai-party-info">
                            <span>Nama</span>
                            <strong id="pihak1Nama">-</strong>
                        </div>

                        <div class="gadai-party-info">
                            <span>NIK</span>
                            <strong id="pihak1Nik">-</strong>
                        </div>

                        <div class="gadai-party-info">
                            <span>Tanggal Lahir</span>
                            <strong id="pihak1TanggalLahir">-</strong>
                        </div>

                        <div class="gadai-party-info">
                            <span>Pekerjaan</span>
                            <strong id="pihak1Pekerjaan">-</strong>
                        </div>

                        <div class="gadai-party-info">
                            <span>Dusun</span>
                            <strong id="pihak1Dusun">-</strong>
                        </div>
                    </div>

                    <div class="gadai-party-card">
                        <div class="gadai-party-card-title">
                            <i class="ri-user-received-fill"></i>
                            Informasi Pihak Kedua
                        </div>

                        <div class="gadai-party-info">
                            <span>Nama</span>
                            <strong id="pihak2Nama">-</strong>
                        </div>

                        <div class="gadai-party-info">
                            <span>NIK</span>
                            <strong id="pihak2Nik">-</strong>
                        </div>

                        <div class="gadai-party-info">
                            <span>Tanggal Lahir</span>
                            <strong id="pihak2TanggalLahir">-</strong>
                        </div>

                        <div class="gadai-party-info">
                            <span>Pekerjaan</span>
                            <strong id="pihak2Pekerjaan">-</strong>
                        </div>

                        <div class="gadai-party-info">
                            <span>Dusun</span>
                            <strong id="pihak2Dusun">-</strong>
                        </div>
                    </div>


                    <!-- ================= OBJEK GADAI ================= -->

                    <div class="gadai-section-title">
                        <i class="ri-landscape-fill"></i>
                        Data Lahan yang Digadaikan
                    </div>

                    <div class="gadai-field">
                        <label for="luasLahan">
                            Luas Lahan
                            <span class="gadai-required">*</span>
                        </label>

                        <input
                            type="text"
                            class="gadai-input"
                            id="luasLahan"
                            name="luas_lahan"
                            value="<?= esc($luasLahanValue) ?>"
                            placeholder="Contoh: 15 Are"
                            required
                        >
                    </div>

                    <div class="gadai-field">
                        <label for="lokasiLahan">
                            Lokasi Lahan
                            <span class="gadai-required">*</span>
                        </label>

                        <input
                            type="text"
                            class="gadai-input"
                            id="lokasiLahan"
                            name="lokasi_lahan"
                            value="<?= esc($lokasiLahanValue) ?>"
                            placeholder="Contoh: Pepalang, Desa Mambu, Kec. Luyo"
                            required
                        >
                    </div>


                    <!-- ================= BATAS LAHAN ================= -->

                    <div class="gadai-section-title">
                        <i class="ri-map-pin-range-fill"></i>
                        Batas-Batas Lahan
                    </div>

                    <div class="gadai-boundary-grid">
                        <div class="gadai-field">
                            <label for="batasUtara">
                                Batas Utara
                            </label>

                            <input
                                type="text"
                                class="gadai-input"
                                id="batasUtara"
                                name="batas_utara"
                                value="<?= esc($batasUtaraValue) ?>"
                                placeholder="Nama pemilik atau batas wilayah"
                            >
                        </div>

                        <div class="gadai-field">
                            <label for="batasSelatan">
                                Batas Selatan
                            </label>

                            <input
                                type="text"
                                class="gadai-input"
                                id="batasSelatan"
                                name="batas_selatan"
                                value="<?= esc($batasSelatanValue) ?>"
                                placeholder="Nama pemilik atau batas wilayah"
                            >
                        </div>

                        <div class="gadai-field">
                            <label for="batasBarat">
                                Batas Barat
                            </label>

                            <input
                                type="text"
                                class="gadai-input"
                                id="batasBarat"
                                name="batas_barat"
                                value="<?= esc($batasBaratValue) ?>"
                                placeholder="Nama pemilik atau batas wilayah"
                            >
                        </div>

                        <div class="gadai-field">
                            <label for="batasTimur">
                                Batas Timur
                            </label>

                            <input
                                type="text"
                                class="gadai-input"
                                id="batasTimur"
                                name="batas_timur"
                                value="<?= esc($batasTimurValue) ?>"
                                placeholder="Nama pemilik atau batas wilayah"
                            >
                        </div>
                    </div>


                    <!-- ================= NILAI DAN TANGGAL ================= -->

                    <div class="gadai-section-title">
                        <i class="ri-money-dollar-circle-fill"></i>
                        Nilai Gadai dan Tanggal Surat
                    </div>

                    <div class="gadai-field">
                        <label for="jumlahUang">
                            Jumlah Uang
                            <span class="gadai-required">*</span>
                        </label>

                        <input
                            type="number"
                            class="gadai-input"
                            id="jumlahUang"
                            name="jumlah_uang"
                            value="<?= esc($jumlahUangValue) ?>"
                            placeholder="Contoh: 36000000"
                            min="1"
                            step="1"
                            required
                        >

                        <p class="gadai-help" id="jumlahUangPreview">
                            Rp 0
                        </p>
                    </div>

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

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


                    <!-- ================= AKSI ================= -->

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

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

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

    <?php endif; ?>

</div>


<script>
(() => {
    /* =====================================================
       PENCARIAN TABEL
    ===================================================== */

    const searchInput = document.getElementById(
        'searchSuratGadai'
    );

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

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

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


    /* =====================================================
       JAM WITA
    ===================================================== */

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

    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())
        .replace(/:/g, '.');
    };

    updateClock();
    setInterval(updateClock, 1000);


    /* =====================================================
       INFORMASI PIHAK
    ===================================================== */

    const pihakPertama = document.getElementById(
        'pihakPertama'
    );

    const pihakKedua = document.getElementById(
        'pihakKedua'
    );

    const setText = (id, value) => {
        const element = document.getElementById(id);

        if (element) {
            element.textContent = value || '-';
        }
    };

    const isiInformasiPihak = (select, prefix) => {
        if (!select) {
            return;
        }

        const option = select.options[select.selectedIndex];
        const data = option ? option.dataset : {};

        setText(prefix + 'Nama', data.nama || '-');
        setText(prefix + 'Nik', data.nik || '-');

        setText(
            prefix + 'TanggalLahir',
            data.tanggalLahir || '-'
        );

        setText(
            prefix + 'Pekerjaan',
            data.pekerjaan || '-'
        );

        setText(
            prefix + 'Dusun',
            data.dusun || '-'
        );
    };

    const updatePihakPertama = () => {
        isiInformasiPihak(
            pihakPertama,
            'pihak1'
        );
    };

    const updatePihakKedua = () => {
        isiInformasiPihak(
            pihakKedua,
            'pihak2'
        );
    };

    if (pihakPertama) {
        pihakPertama.addEventListener(
            'change',
            updatePihakPertama
        );

        updatePihakPertama();
    }

    if (pihakKedua) {
        pihakKedua.addEventListener(
            'change',
            updatePihakKedua
        );

        updatePihakKedua();
    }

    if (window.jQuery) {
        if (pihakPertama) {
            window.jQuery(pihakPertama).on(
                'select2:select select2:clear',
                updatePihakPertama
            );
        }

        if (pihakKedua) {
            window.jQuery(pihakKedua).on(
                'select2:select select2:clear',
                updatePihakKedua
            );
        }
    }


    /* =====================================================
       FORMAT PREVIEW RUPIAH
    ===================================================== */

    const jumlahUangInput = document.getElementById(
        'jumlahUang'
    );

    const jumlahUangPreview = document.getElementById(
        'jumlahUangPreview'
    );

    const formatRupiah = (value) => {
        const angka = String(value || '')
            .replace(/[^0-9]/g, '');

        if (angka === '') {
            return 'Rp 0';
        }

        return 'Rp ' + new Intl.NumberFormat(
            'id-ID'
        ).format(Number(angka));
    };

    const updateRupiahPreview = () => {
        if (!jumlahUangInput || !jumlahUangPreview) {
            return;
        }

        jumlahUangPreview.textContent = formatRupiah(
            jumlahUangInput.value
        );
    };

    if (jumlahUangInput) {
        jumlahUangInput.addEventListener(
            'input',
            updateRupiahPreview
        );

        updateRupiahPreview();
    }


    /* =====================================================
       VALIDASI PIHAK BERBEDA
    ===================================================== */

    const validasiPihak = () => {
        if (!pihakPertama || !pihakKedua) {
            return;
        }

        if (
            pihakPertama.value !== '' &&
            pihakPertama.value === pihakKedua.value
        ) {
            pihakKedua.setCustomValidity(
                'Pihak pertama dan pihak kedua tidak boleh sama.'
            );
        } else {
            pihakKedua.setCustomValidity('');
        }
    };

    if (pihakPertama) {
        pihakPertama.addEventListener(
            'change',
            validasiPihak
        );
    }

    if (pihakKedua) {
        pihakKedua.addEventListener(
            'change',
            validasiPihak
        );
    }

    validasiPihak();
})();
</script>

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