<?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 kesanggupan_tanggal_valid($tanggal)
{
    if ($tanggal === '') {
        return false;
    }

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

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

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

    $waktu = strtotime($tanggal);

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

    $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'
    ];

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

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

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

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

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

function kesanggupan_nomor_otomatis($mysqli)
{
    $tahun = date('Y');
    $nomorUrut = 1;

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

    if ($result && $row = $result->fetch_assoc()) {
        $nomorUrut = (int)$row['id'] + 1;
    }

    do {
        $nomor = str_pad(
            (string)$nomorUrut,
            3,
            '0',
            STR_PAD_LEFT
        )
        .'/SPK/DS.M/'
        .$tahun;

        $sudahAda = false;

        $stmt = $mysqli->prepare("
            SELECT id
            FROM surat_pernyataan_kesanggupan
            WHERE nomor_surat = ?
            LIMIT 1
        ");

        if ($stmt) {
            $stmt->bind_param('s', $nomor);
            $stmt->execute();

            $cek = $stmt->get_result();

            $sudahAda = $cek &&
                $cek->num_rows > 0;

            $stmt->close();
        }

        if ($sudahAda) {
            $nomorUrut++;
        }
    } while ($sudahAda);

    return $nomor;
}

$nomorSuratOtomatis = kesanggupan_nomor_otomatis(
    $mysqli
);


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

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

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

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

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

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

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

    $stmt->close();

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


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

$errorText = '';

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

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

    $nomor_surat = trim(
        $_POST['nomor_surat'] ?? ''
    );

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

    $no_hp = trim(
        $_POST['no_hp'] ?? ''
    );

    if (
        $warga_id <= 0 ||
        $nomor_surat === '' ||
        $tanggal_surat === '' ||
        $no_hp === ''
    ) {
        $errorText = 'Mohon lengkapi semua data yang wajib diisi.';
        $act = 'form';
    } elseif (!kesanggupan_tanggal_valid($tanggal_surat)) {
        $errorText = 'Format tanggal surat tidak valid.';
        $act = 'form';
    } elseif (
        !preg_match(
            '/^[0-9+\-\s().]{8,20}$/',
            $no_hp
        )
    ) {
        $errorText = 'Nomor HP tidak valid. Gunakan 8 sampai 20 karakter angka.';
        $act = 'form';
    } else {

        /* Periksa data warga */

        $wargaDitemukan = false;

        $wargaStmt = $mysqli->prepare("
            SELECT id
            FROM infografis
            WHERE id = ?
            LIMIT 1
        ");

        if ($wargaStmt) {
            $wargaStmt->bind_param(
                'i',
                $warga_id
            );

            $wargaStmt->execute();

            $wargaResult = $wargaStmt->get_result();

            $wargaDitemukan = $wargaResult &&
                $wargaResult->num_rows > 0;

            $wargaStmt->close();
        }

        if (!$wargaDitemukan) {
            $errorText = 'Data warga yang dipilih tidak ditemukan.';
            $act = 'form';
        } else {

            /* Periksa nomor surat ganda */

            $nomorGanda = false;

            $cekNomorStmt = $mysqli->prepare("
                SELECT id
                FROM surat_pernyataan_kesanggupan
                WHERE nomor_surat = ?
                  AND id <> ?
                LIMIT 1
            ");

            if ($cekNomorStmt) {
                $cekNomorStmt->bind_param(
                    'si',
                    $nomor_surat,
                    $id
                );

                $cekNomorStmt->execute();

                $cekNomorResult = $cekNomorStmt->get_result();

                $nomorGanda = $cekNomorResult &&
                    $cekNomorResult->num_rows > 0;

                $cekNomorStmt->close();
            }

            if ($nomorGanda) {
                $errorText = 'Nomor surat sudah digunakan pada data lain.';
                $act = 'form';
            } elseif ($id > 0) {

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

                $dataDitemukan = false;

                $cekDataStmt = $mysqli->prepare("
                    SELECT id
                    FROM surat_pernyataan_kesanggupan
                    WHERE id = ?
                    LIMIT 1
                ");

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

                    $cekDataStmt->execute();

                    $cekDataResult = $cekDataStmt->get_result();

                    $dataDitemukan = $cekDataResult &&
                        $cekDataResult->num_rows > 0;

                    $cekDataStmt->close();
                }

                if (!$dataDitemukan) {
                    header(
                        'Location: surat_pernyataan_kesanggupan.php?msg=notfound'
                    );
                    exit;
                }

                $stmt = $mysqli->prepare("
                    UPDATE surat_pernyataan_kesanggupan
                    SET
                        warga_id = ?,
                        nomor_surat = ?,
                        tanggal_surat = ?,
                        no_hp = ?
                    WHERE id = ?
                ");

                if ($stmt) {
                    $stmt->bind_param(
                        'isssi',
                        $warga_id,
                        $nomor_surat,
                        $tanggal_surat,
                        $no_hp,
                        $id
                    );

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

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

                    $stmt->close();
                }

                $errorText = 'Surat pernyataan kesanggupan gagal diperbarui.';
                $act = 'form';
            } else {

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

                $stmt = $mysqli->prepare("
                    INSERT INTO surat_pernyataan_kesanggupan
                    (
                        warga_id,
                        nomor_surat,
                        tanggal_surat,
                        no_hp
                    )
                    VALUES (?, ?, ?, ?)
                ");

                if ($stmt) {
                    $stmt->bind_param(
                        'isss',
                        $warga_id,
                        $nomor_surat,
                        $tanggal_surat,
                        $no_hp
                    );

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

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

                    $stmt->close();
                }

                $errorText = 'Surat pernyataan kesanggupan 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_pernyataan_kesanggupan
            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_pernyataan_kesanggupan.php?msg=notfound'
            );
            exit;
        }
    }
}


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

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


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

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


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

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

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


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

$isEdit = !empty($edit);

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

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

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

$noHpValue = $_POST['no_hp']
    ?? $edit['no_hp']
    ?? '';


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

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

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

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

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

    --kesanggupan-blue-500: #2080e8;
    --kesanggupan-yellow-500: #f5b400;
    --kesanggupan-orange-500: #f26b1d;
    --kesanggupan-purple-500: #7956d8;

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

    --kesanggupan-shadow:
        0 8px 28px rgba(10, 40, 25, .10);

    --kesanggupan-radius: 16px;
}

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

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

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

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

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

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

@keyframes kesanggupan-float {
    0%,
    100% {
        transform: translateY(0);
    }

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

* {
    box-sizing: border-box;
}

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

.kesanggupan-page {
    padding: 26px;
}


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

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

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

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

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

    border-radius: var(--kesanggupan-radius);

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

    animation:
        kesanggupan-gradient 8s ease infinite;
}

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

.kesanggupan-header::before {
    width: 220px;
    height: 220px;
    top: -80px;
    right: -55px;

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

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

.kesanggupan-header::after {
    width: 130px;
    height: 130px;
    bottom: -40px;
    left: 30%;

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

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

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

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

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

    color: var(--kesanggupan-green-400);

    font-size: 11px;
    font-weight: 800;
    letter-spacing: .10em;
    text-transform: uppercase;
}

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

    width: 22px;
    height: 2px;

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

    border-radius: 2px;
}

.kesanggupan-header h2 {
    margin: 0;

    color: #ffffff;

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

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

    color: var(--kesanggupan-green-400);

    font-size: 27px;
    vertical-align: middle;

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

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

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

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

    animation:
        kesanggupan-pulse 2s ease infinite;
}

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

.kesanggupan-clock {
    padding: 10px 15px;

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

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

.kesanggupan-clock i {
    color: var(--kesanggupan-green-400);
    font-size: 18px;
}


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

.kesanggupan-panel {
    overflow: hidden;

    background: var(--kesanggupan-surface);

    border:
        1px solid rgba(210, 232, 220, .85);

    border-radius: var(--kesanggupan-radius);

    box-shadow: var(--kesanggupan-shadow);
}

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

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

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

    display: grid;
    place-items: center;

    color: #ffffff;

    background: linear-gradient(
        135deg,
        var(--kesanggupan-green-500),
        var(--kesanggupan-green-800)
    );

    border-radius: 13px;

    box-shadow:
        0 4px 12px rgba(9, 160, 79, .28);

    font-size: 20px;
}

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

    color: var(--kesanggupan-ink);

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

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

    color: var(--kesanggupan-muted);

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

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


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

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

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

    color: var(--kesanggupan-green-800);
    background: var(--kesanggupan-green-50);

    border:
        1px solid var(--kesanggupan-green-100);

    border-radius: 14px;

    box-shadow: var(--kesanggupan-shadow);

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

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


/* =========================================================
   TOMBOL
========================================================= */

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

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

.kesanggupan-btn-primary {
    color: #ffffff;

    background: linear-gradient(
        135deg,
        var(--kesanggupan-green-500),
        var(--kesanggupan-green-800)
    );
}

.kesanggupan-btn-light {
    color: #ffffff;
    background: rgba(255, 255, 255, .12);

    border:
        1px solid rgba(255, 255, 255, .18);

    backdrop-filter: blur(8px);
}

.kesanggupan-btn-print {
    color: #ffffff;

    background: linear-gradient(
        135deg,
        #60b4ff,
        var(--kesanggupan-blue-500)
    );
}

.kesanggupan-btn-edit {
    color: var(--kesanggupan-ink);

    background: linear-gradient(
        135deg,
        #ffd95c,
        var(--kesanggupan-yellow-500)
    );
}

.kesanggupan-btn-delete {
    color: #ffffff;

    background: linear-gradient(
        135deg,
        #ff9a52,
        var(--kesanggupan-orange-500)
    );
}

.kesanggupan-btn-ghost {
    color: var(--kesanggupan-green-800);
    background: var(--kesanggupan-green-50);

    border:
        1px solid var(--kesanggupan-green-100);
}

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

    border-radius: 10px;
    box-shadow: none;

    font-size: 12px;
}


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

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

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

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

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

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

    transform: translateY(-50%);
}

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

    color: var(--kesanggupan-ink);
    background: #f8fffb;

    border:
        1px solid var(--kesanggupan-line);

    border-radius: 14px;
    outline: none;

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

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

.kesanggupan-search input:focus {
    background: #ffffff;

    border-color:
        var(--kesanggupan-green-500);

    box-shadow:
        0 0 0 4px rgba(21, 196, 106, .13);
}

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

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

    color: var(--kesanggupan-green-800);
    background: var(--kesanggupan-green-50);

    border:
        1px solid var(--kesanggupan-green-100);

    border-radius: 999px;

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


/* =========================================================
   TABEL
========================================================= */

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

    background: #ffffff;

    border:
        1px solid var(--kesanggupan-line);

    border-radius: 16px;
}

.kesanggupan-table {
    width: 100%;

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

    font-size: 14px;
}

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

    color: var(--kesanggupan-green-900);

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

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

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

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

    border-bottom:
        1px solid #edf7f1;

    vertical-align: middle;
}

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

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

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

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

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

    display: grid;
    place-items: center;

    color: #ffffff;

    background: linear-gradient(
        135deg,
        var(--kesanggupan-green-500),
        var(--kesanggupan-green-800)
    );

    border-radius: 14px;

    box-shadow:
        0 8px 16px rgba(9, 160, 79, .20);

    font-weight: 800;
}

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

.kesanggupan-nik {
    margin-top: 2px;

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

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

    color: var(--kesanggupan-green-900);

    font-weight: 800;
    white-space: nowrap;
}

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

.kesanggupan-phone {
    padding: 7px 10px;

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

    color: var(--kesanggupan-purple-500);
    background: #f5f1ff;

    border-radius: 999px;

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

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

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

    color: var(--kesanggupan-blue-500);
    background: #eef8ff;

    border-radius: 999px;

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

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

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

.kesanggupan-empty {
    padding: 36px !important;

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

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

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

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


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

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

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

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

.kesanggupan-field label {
    color: var(--kesanggupan-ink);

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

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

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

    color: var(--kesanggupan-ink);
    background: #f8fffb;

    border:
        1px solid var(--kesanggupan-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;
}

.kesanggupan-input:focus {
    background: #ffffff;

    border-color:
        var(--kesanggupan-green-500);

    box-shadow:
        0 0 0 4px rgba(21, 196, 106, .13);
}

.kesanggupan-form-section {
    grid-column: 1 / -1;

    padding: 12px 14px;

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

    color: var(--kesanggupan-green-900);
    background: var(--kesanggupan-green-50);

    border:
        1px solid var(--kesanggupan-green-100);

    border-radius: 13px;

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

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

.kesanggupan-form-note {
    grid-column: 1 / -1;

    padding: 12px 14px;

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

    color: var(--kesanggupan-green-900);
    background: var(--kesanggupan-green-50);

    border:
        1px solid var(--kesanggupan-green-100);

    border-radius: 13px;

    font-size: 12px;
    font-weight: 600;
    line-height: 1.6;
}

.kesanggupan-form-note i {
    margin-top: 1px;

    color: var(--kesanggupan-green-600);
    font-size: 18px;
}

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

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

    margin-top: 4px;
}


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

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

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

    background: #f8fffb;

    border:
        1px solid var(--kesanggupan-line);

    border-radius: 13px;
}

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

    color: var(--kesanggupan-ink);

    font-size: 14px;
    font-weight: 600;
    line-height: 42px;
}

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

.kesanggupan-field
.select2-container--default.select2-container--focus
.select2-selection--single,
.kesanggupan-field
.select2-container--default.select2-container--open
.select2-selection--single {
    background: #ffffff;

    border-color:
        var(--kesanggupan-green-500);

    box-shadow:
        0 0 0 4px rgba(21, 196, 106, .13);
}


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

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

    .kesanggupan-header {
        padding: 20px;
    }

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

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

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

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

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

    .kesanggupan-field-full,
    .kesanggupan-form-section,
    .kesanggupan-form-note,
    .kesanggupan-form-actions {
        grid-column: 1;
    }

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


<div class="kesanggupan-page">

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

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

        <div class="kesanggupan-header">
            <div class="kesanggupan-header-left">
                <p class="kesanggupan-eyebrow">
                    <i class="ri-file-shield-2-fill"></i>
                    Layanan Surat Desa
                </p>

                <h2>
                    <i class="ri-draft-fill kesanggupan-title-icon"></i>
                    Surat Pernyataan Kesanggupan
                </h2>

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

                    Kelola surat pernyataan kesanggupan Desa Mambu
                </p>
            </div>

            <div class="kesanggupan-header-actions">
                <span class="kesanggupan-clock">
                    <i class="ri-time-fill"></i>

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

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

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


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

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


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

                    <div>
                        <h3>Daftar Surat Kesanggupan</h3>

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

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

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

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

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

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

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

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

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

                                        <td>
                                            <div class="kesanggupan-person">
                                                <div class="kesanggupan-avatar">
                                                    <?= esc(
                                                        kesanggupan_inisial(
                                                            $row['nama_lengkap']
                                                        )
                                                    ) ?>
                                                </div>

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

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

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

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

                                        <td>
                                            <span class="kesanggupan-phone">
                                                <i class="ri-phone-fill"></i>

                                                <?= esc(
                                                    $row['no_hp']
                                                ) ?>
                                            </span>
                                        </td>

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

                                                <?= esc(
                                                    kesanggupan_tanggal_indo(
                                                        $row['tanggal_surat']
                                                    )
                                                ) ?>
                                            </span>
                                        </td>

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

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

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

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

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

                <h2>
                    <i class="ri-draft-fill kesanggupan-title-icon"></i>

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

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

                    <?= $isEdit
                        ? 'Perbarui data warga dan nomor kontak.'
                        : 'Pilih warga dan masukkan nomor kontak yang aktif.' ?>
                </p>
            </div>

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


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


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

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

                        <p>
                            Lengkapi data surat dan nomor kontak warga.
                        </p>
                    </div>
                </div>
            </div>

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


                    <div class="kesanggupan-form-section">
                        <i class="ri-file-paper-2-fill"></i>
                        Data Surat
                    </div>

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

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

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

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


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

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

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

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

                    <div class="kesanggupan-field kesanggupan-field-full">
                        <label for="noHp">
                            Nomor HP
                            <span class="kesanggupan-required">*</span>
                        </label>

                        <input
                            type="tel"
                            class="kesanggupan-input"
                            id="noHp"
                            name="no_hp"
                            value="<?= esc($noHpValue) ?>"
                            placeholder="Contoh: 081234567890"
                            maxlength="20"
                            pattern="[0-9+\-\s().]{8,20}"
                            required
                        >
                    </div>

                    <div class="kesanggupan-form-note">
                        <i class="ri-information-fill"></i>

                        <span>
                            Pastikan nomor HP yang dimasukkan masih aktif.
                            Data identitas warga pada surat akan diambil
                            dari data penduduk berdasarkan warga yang dipilih.
                        </span>
                    </div>

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

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

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

    <?php endif; ?>

</div>


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

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

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

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


    const noHpInput = document.getElementById('noHp');

    if (noHpInput) {
        noHpInput.addEventListener('input', function () {
            this.value = this.value.replace(
                /[^0-9+\-\s().]/g,
                ''
            );
        });
    }


    const wargaSelect = document.getElementById('wargaId');

    if (
        wargaSelect &&
        window.jQuery &&
        window.jQuery.fn &&
        window.jQuery.fn.select2
    ) {
        const selectElement = window.jQuery(wargaSelect);

        if (
            !selectElement.hasClass(
                'select2-hidden-accessible'
            )
        ) {
            selectElement.select2({
                width: '100%',
                placeholder: '-- Pilih Warga --',
                allowClear: true
            });
        }
    }


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

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