<?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_indo_belum_bekerja($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);
}


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

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

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

$last = $lastResult
    ? $lastResult->fetch_assoc()
    : null;

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

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


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

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

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

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

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

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

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

    $stmt->close();

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


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

$errorText = '';

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

    if (
        $nomor_surat === '' ||
        $warga_id <= 0 ||
        $tanggal_surat === ''
    ) {
        $errorText = 'Mohon lengkapi semua data yang wajib diisi.';
        $act = 'form';
    } elseif (
        !preg_match(
            '/^\d{4}-\d{2}-\d{2}$/',
            $tanggal_surat
        )
    ) {
        $errorText = 'Format tanggal surat tidak valid.';
        $act = 'form';
    } elseif ($id > 0) {

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

        $qr_kode = '';
        $dataDitemukan = false;

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

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

            $qrResult = $qrStmt->get_result();

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

            $qrStmt->close();
        }

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

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

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

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

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

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

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

            $stmt->close();
        }

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

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

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

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

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

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

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

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

            $stmt->close();
        }

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


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

$edit = null;

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

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

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

            $result = $stmt->get_result();

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

            $stmt->close();
        }

        if (!$edit && $errorText === '') {
            header(
                'Location: surat_belum_bekerja.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_belum_bekerja s
    JOIN infografis i
        ON s.warga_id = i.id
    ORDER BY s.id DESC
");

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


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

$isEdit = !empty($edit);

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

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

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


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

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

$msgText = [
    'saved' => 'Surat keterangan belum bekerja berhasil dibuat.',
    'updated' => 'Surat keterangan belum bekerja berhasil diperbarui.',
    'deleted' => 'Surat keterangan belum bekerja berhasil dihapus.',
    'notfound' => 'Data surat keterangan belum bekerja 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 {
    --sbb-green-950: #002818;
    --sbb-green-900: #003d22;
    --sbb-green-800: #005530;
    --sbb-green-700: #047a3d;
    --sbb-green-600: #09a04f;
    --sbb-green-500: #15c46a;
    --sbb-green-400: #35e085;
    --sbb-green-100: #dcfaee;
    --sbb-green-50: #edfff5;

    --sbb-blue-500: #2080e8;
    --sbb-yellow-500: #f5b400;
    --sbb-orange-500: #f26b1d;

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

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

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

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

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

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

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

* {
    box-sizing: border-box;
}

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

.sbb-page {
    padding: 26px;
}


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

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

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

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

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

.sbb-header::before {
    width: 210px;
    height: 210px;
    top: -75px;
    right: -55px;

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

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

.sbb-header::after {
    width: 125px;
    height: 125px;
    bottom: -35px;
    left: 30%;

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

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

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

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

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

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

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

    width: 22px;
    height: 2px;

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

    border-radius: 2px;
}

.sbb-header h2 {
    margin: 0;

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

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

    color: var(--sbb-green-400);
    font-size: 26px;
    vertical-align: middle;

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

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

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

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

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

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

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

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


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

.sbb-panel {
    overflow: hidden;

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

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

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

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

    display: grid;
    place-items: center;

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

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

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

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

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

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

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


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

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

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

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

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

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


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

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

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

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

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

    backdrop-filter: blur(8px);
}

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

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

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

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

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

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


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

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

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

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

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

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

    transform: translateY(-50%);
}

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

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

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

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

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

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

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


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

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

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

.sbb-table {
    width: 100%;

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

    font-size: 14px;
}

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

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

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

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

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

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

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

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

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

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

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

    display: grid;
    place-items: center;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

    padding: 12px 14px;

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

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

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

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

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

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

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

    margin-top: 4px;
}


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

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

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

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

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

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

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

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


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

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

    .sbb-header {
        padding: 20px;
    }

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

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

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

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

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

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

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


<div class="sbb-page">

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

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

        <div class="sbb-header">
            <div class="sbb-header-left">
                <p class="sbb-eyebrow">
                    <i class="ri-briefcase-4-fill"></i>
                    Layanan Surat Desa
                </p>

                <h2>
                    <i class="ri-user-search-fill sbb-title-icon"></i>
                    Surat Keterangan Belum Bekerja
                </h2>

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

                    Kelola surat keterangan belum bekerja Desa Mambu
                </p>
            </div>

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

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

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

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


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

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


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

                    <div>
                        <h3>Daftar Surat Belum Bekerja</h3>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                <h2>
                    <i class="ri-user-search-fill sbb-title-icon"></i>

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

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

                    <?= $isEdit
                        ? 'Perbarui data surat keterangan belum bekerja.'
                        : 'Pilih warga dan tentukan tanggal penerbitan surat.' ?>
                </p>
            </div>

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


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


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

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

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

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

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

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

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

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

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

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

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

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

                        <span>
                            Data identitas warga pada surat akan diambil
                            dari data penduduk berdasarkan warga yang dipilih.
                            Pastikan data penduduk sudah benar sebelum surat
                            dicetak.
                        </span>
                    </div>

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

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

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

    <?php endif; ?>

</div>


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

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

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

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


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

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