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

date_default_timezone_set('Asia/Makassar');

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


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

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

$nomorSurat = '03 / 552 / Ds.M / '
    .$bulanRomawi[(int)date('n') - 1]
    .' / '
    .date('Y');


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

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

    if ($id > 0) {
        $stmt = $mysqli->prepare("
            DELETE FROM surat_pengantar_kayu
            WHERE id = ?
        ");

        if ($stmt) {
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $stmt->close();
        }
    }

    header('Location: surat_pengantar_kayu.php?msg=deleted');
    exit;
}


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

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

    if (
        $nomor_surat === '' ||
        $warga_id <= 0 ||
        $jenis_kayu === '' ||
        $tanggal_surat === ''
    ) {
        $errorText = 'Mohon lengkapi semua data yang wajib diisi.';
        $act = 'form';
    } elseif ($id > 0) {

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

        $qr_kode = '';

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

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

            $qrResult = $qrStmt->get_result();

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

            $qrStmt->close();
        }

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

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

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

        if ($stmt) {
            $stmt->bind_param(
                'sisssssssi',
                $nomor_surat,
                $warga_id,
                $jenis_kayu,
                $rincian_kayu,
                $lokasi_tujuan,
                $tanggal_surat,
                $waktu_ttd,
                $qr_kode,
                $qr_hash,
                $id
            );

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

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

            $stmt->close();
        }

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

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

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

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

        if ($stmt) {
            $stmt->bind_param(
                'sisssssss',
                $nomor_surat,
                $warga_id,
                $jenis_kayu,
                $rincian_kayu,
                $lokasi_tujuan,
                $tanggal_surat,
                $waktu_ttd,
                $qr_kode,
                $qr_hash
            );

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

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

            $stmt->close();
        }

        $errorText = 'Surat gagal disimpan. Silakan coba kembali.';
        $act = 'form';
    }
}


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

$edit = null;

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

    if ($editId > 0) {
        $stmt = $mysqli->prepare("
            SELECT *
            FROM surat_pengantar_kayu
            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();
        }
    }
}


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

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


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

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

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


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

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

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

    $time = strtotime($tanggal);

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

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

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


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

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

$msgText = [
    'saved'   => 'Surat pengantar kayu berhasil dibuat.',
    'updated' => 'Surat pengantar kayu berhasil diperbarui.',
    'deleted' => 'Surat pengantar kayu berhasil dihapus.'
][$msgKey] ?? '';


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

$isEdit = !empty($edit);

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

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

$jenisValue = $_POST['jenis_kayu']
    ?? $edit['jenis_kayu']
    ?? '';

$rincianValue = $_POST['rincian_kayu']
    ?? $edit['rincian_kayu']
    ?? '';

$lokasiValue = $_POST['lokasi_tujuan']
    ?? $edit['lokasi_tujuan']
    ?? '';

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

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

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

<link
    href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
    rel="stylesheet"
>

<link
    href="https://cdn.jsdelivr.net/npm/remixicon@4.6.0/fonts/remixicon.css"
    rel="stylesheet"
>

<style>
:root {
    --kayu-green-950: #002818;
    --kayu-green-900: #003d22;
    --kayu-green-800: #005530;
    --kayu-green-700: #047a3d;
    --kayu-green-600: #09a04f;
    --kayu-green-500: #15c46a;
    --kayu-green-400: #35e085;
    --kayu-green-100: #dcfaee;
    --kayu-green-50: #edfff5;

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

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

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

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

    70% {
        box-shadow: 0 0 0 12px rgba(9, 160, 79, 0);
    }

    100% {
        box-shadow: 0 0 0 0 rgba(9, 160, 79, 0);
    }
}

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

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

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

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

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

* {
    box-sizing: border-box;
}

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

.kayu-page {
    padding: 26px;
}


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    width: 22px;
    height: 2px;

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

    border-radius: 2px;
}

.kayu-header h2 {
    margin: 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

    backdrop-filter: blur(8px);
}

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

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


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

.kayu-panel {
    overflow: hidden;

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

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

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

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

    display: grid;
    place-items: center;

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

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

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

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

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

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

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


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

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

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

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

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

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


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

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

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

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

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

    backdrop-filter: blur(8px);
}

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

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

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

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

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

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


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

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

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

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

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

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

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

    transition: .2s ease;
}

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

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

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

    transform: translateY(-50%);
}

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

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

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

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


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

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

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

.kayu-table {
    width: 100%;

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

    font-size: 14px;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    display: grid;
    place-items: center;

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

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

    font-weight: 800;
}

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

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

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

.kayu-type {
    display: inline-flex;
    align-items: center;
    gap: 7px;

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

.kayu-type i {
    color: var(--kayu-green-600);
    font-size: 18px;
}

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

textarea.kayu-input {
    resize: vertical;
}

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

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

    margin-top: 4px;
}


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

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

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

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

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

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

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

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


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

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

    .kayu-header {
        padding: 20px;
    }

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

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

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

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

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

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

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


<div class="kayu-page">

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

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

        <div class="kayu-header">
            <div class="kayu-header-left">
                <p class="kayu-eyebrow">
                    <i class="ri-tree-fill"></i>
                    Layanan Surat Desa
                </p>

                <h2>
                    <i class="ri-tree-fill kayu-title-icon"></i>
                    Surat Pengantar Kayu
                </h2>

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

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

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

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

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

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


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


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

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

                        <p>
                            Data surat pengantar kayu yang sudah dibuat.
                        </p>
                    </div>
                </div>

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

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

                        <input
                            type="text"
                            id="searchSuratKayu"
                            placeholder="Cari nomor, nama, NIK, jenis kayu, atau tanggal..."
                        >
                    </div>
                </div>

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

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

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

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

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

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

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

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

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

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

                                        <td>
                                            <span class="kayu-type">
                                                <i class="ri-tree-fill"></i>

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

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

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

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

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

                                                <form
                                                    method="post"
                                                    action="surat_pengantar_kayu.php?a=delete"
                                                    class="kayu-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="kayu-btn kayu-btn-small kayu-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="kayu-header">
            <div class="kayu-header-left">
                <p class="kayu-eyebrow">
                    <i class="<?= $isEdit ? 'ri-edit-2-fill' : 'ri-add-box-fill' ?>"></i>

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

                <h2>
                    <i class="ri-file-edit-fill kayu-title-icon"></i>

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

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

                    <?= $isEdit
                        ? 'Perbarui data surat pengantar kayu.'
                        : 'Lengkapi form untuk membuat surat baru.' ?>
                </p>
            </div>

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


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


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

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

                        <p>
                            <?= $isEdit
                                ? 'Ubah data dengan teliti sebelum menyimpan.'
                                : 'Isi data warga, jenis kayu, dan tujuan pengiriman.' ?>
                        </p>
                    </div>
                </div>
            </div>

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

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

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

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

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

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

                        <select
                            name="warga_id"
                            id="wargaId"
                            class="kayu-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="kayu-field kayu-field-full">
                        <label for="jenisKayu">
                            Jenis Kayu
                            <span class="kayu-required">*</span>
                        </label>

                        <input
                            type="text"
                            class="kayu-input"
                            id="jenisKayu"
                            name="jenis_kayu"
                            value="<?= esc($jenisValue) ?>"
                            placeholder="Contoh: Kayu Jati Putih"
                            required
                        >
                    </div>

                    <div class="kayu-field kayu-field-full">
                        <label for="rincianKayu">
                            Rincian Kayu
                        </label>

                        <textarea
                            class="kayu-input"
                            id="rincianKayu"
                            name="rincian_kayu"
                            rows="4"
                            placeholder="Contoh:&#10;2 meter = 17 lembar&#10;3 meter = 10 lembar"
                        ><?= esc($rincianValue) ?></textarea>
                    </div>

                    <div class="kayu-field kayu-field-full">
                        <label for="lokasiTujuan">
                            Lokasi Tujuan
                        </label>

                        <textarea
                            class="kayu-input"
                            id="lokasiTujuan"
                            name="lokasi_tujuan"
                            rows="3"
                            placeholder="Contoh: Dusun Bonra, Desa Mapilli Barat"
                        ><?= esc($lokasiValue) ?></textarea>
                    </div>

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

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

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

    <?php endif; ?>

</div>


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

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

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

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


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

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