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

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

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

function inisial_hewan($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));
}


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

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

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

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

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

$nomorSuratOtomatis = sprintf(
    '524.2/%02d/DM/%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_pengantar_hewan.php?msg=notfound'
        );
        exit;
    }

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

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

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

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

    $stmt->close();

    header(
        'Location: surat_pengantar_hewan.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);
    $jenis_hewan     = trim($_POST['jenis_hewan'] ?? '');
    $jumlah_hewan    = (int)($_POST['jumlah_hewan'] ?? 0);
    $tujuan_alamat   = trim($_POST['tujuan_alamat'] ?? '');
    $tanggal_surat   = trim($_POST['tanggal_surat'] ?? '');
    $waktu_ttd       = date('Y-m-d H:i:s');

    if (
        $nomor_surat === '' ||
        $warga_id <= 0 ||
        $jenis_hewan === '' ||
        $jumlah_hewan <= 0 ||
        $tujuan_alamat === '' ||
        $tanggal_surat === ''
    ) {
        $errorText = 'Mohon lengkapi semua data yang wajib diisi.';
        $act = 'form';
    } elseif (!tanggal_valid_hewan($tanggal_surat)) {
        $errorText = 'Format tanggal surat tidak valid.';
        $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';
        } elseif ($id > 0) {

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

            $qr_kode = '';
            $dataDitemukan = false;

            $qrStmt = $mysqli->prepare("
                SELECT qr_kode
                FROM surat_pengantar_hewan
                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_pengantar_hewan.php?msg=notfound'
                );
                exit;
            }

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

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

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

            if ($stmt) {
                $stmt->bind_param(
                    'sisisssssi',
                    $nomor_surat,
                    $warga_id,
                    $jenis_hewan,
                    $jumlah_hewan,
                    $tujuan_alamat,
                    $tanggal_surat,
                    $waktu_ttd,
                    $qr_kode,
                    $qr_hash,
                    $id
                );

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

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

                $stmt->close();
            }

            $errorText = 'Surat pengantar hewan gagal diperbarui.';
            $act = 'form';
        } else {

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

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

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

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

            if ($stmt) {
                $stmt->bind_param(
                    'sisisssss',
                    $nomor_surat,
                    $warga_id,
                    $jenis_hewan,
                    $jumlah_hewan,
                    $tujuan_alamat,
                    $tanggal_surat,
                    $waktu_ttd,
                    $qr_kode,
                    $qr_hash
                );

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

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

                $stmt->close();
            }

            $errorText = 'Surat pengantar hewan 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_pengantar_hewan
            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_pengantar_hewan.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_pengantar_hewan 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
);

$jenisHewanValue = $_POST['jenis_hewan']
    ?? $edit['jenis_hewan']
    ?? '';

$jumlahHewanValue = (int)(
    $_POST['jumlah_hewan']
    ?? $edit['jumlah_hewan']
    ?? 1
);

$tujuanAlamatValue = $_POST['tujuan_alamat']
    ?? $edit['tujuan_alamat']
    ?? '';

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


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

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

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

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

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

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

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

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

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

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

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

* {
    box-sizing: border-box;
}

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

.sph-page {
    padding: 26px;
}


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    width: 22px;
    height: 2px;

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

    border-radius: 2px;
}

.sph-header h2 {
    margin: 0;

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

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

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

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

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

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

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

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

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

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

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


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

.sph-panel {
    overflow: hidden;

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

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

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

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

    display: grid;
    place-items: center;

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

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

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

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

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

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

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


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

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

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

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

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

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


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

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

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

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

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

    backdrop-filter: blur(8px);
}

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

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

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

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

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

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


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

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

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

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

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

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

    transform: translateY(-50%);
}

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

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

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

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

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

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

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


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

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

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

.sph-table {
    width: 100%;

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

    font-size: 14px;
}

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

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

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

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

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

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

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

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

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

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

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

    display: grid;
    place-items: center;

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

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

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

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

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

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

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

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

.sph-animal {
    display: flex;
    align-items: center;
    gap: 10px;
}

.sph-animal-icon {
    width: 38px;
    height: 38px;
    flex-shrink: 0;

    display: grid;
    place-items: center;

    color: #ffffff;
    background: linear-gradient(
        135deg,
        #9c7be8,
        var(--sph-purple-500)
    );

    border-radius: 12px;
    box-shadow: 0 7px 15px rgba(121, 86, 216, .20);
    font-size: 18px;
}

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

.sph-animal-count {
    margin-top: 2px;

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

.sph-destination {
    max-width: 260px;

    color: var(--sph-ink);
    font-size: 13px;
    font-weight: 600;
    line-height: 1.5;
}

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

    padding: 12px 14px;

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

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

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

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

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

    padding: 12px 14px;

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

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

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

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

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

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

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

    margin-top: 4px;
}


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

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

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

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

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

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

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

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


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

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

    .sph-header {
        padding: 20px;
    }

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

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

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

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

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

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

    .sph-actions {
        min-width: 245px;
    }

    .sph-destination {
        min-width: 220px;
    }
}
</style>


<div class="sph-page">

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

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

        <div class="sph-header">
            <div class="sph-header-left">
                <p class="sph-eyebrow">
                    <i class="ri-bear-smile-fill"></i>
                    Layanan Surat Desa
                </p>

                <h2>
                    <i class="ri-bear-smile-fill sph-title-icon"></i>
                    Surat Pengantar Hewan
                </h2>

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

                    Kelola surat pengantar hewan Desa Mambu
                </p>
            </div>

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

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

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

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


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

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


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

                    <div>
                        <h3>Daftar Surat Pengantar Hewan</h3>

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

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

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

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

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

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

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

                                        <td>
                                            <div class="sph-person">
                                                <div class="sph-avatar">
                                                    <?= esc(
                                                        inisial_hewan(
                                                            $r['nama_lengkap']
                                                        )
                                                    ) ?>
                                                </div>

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

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

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

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

                                        <td>
                                            <div class="sph-animal">
                                                <div class="sph-animal-icon">
                                                    <i class="ri-bear-smile-fill"></i>
                                                </div>

                                                <div>
                                                    <div class="sph-animal-name">
                                                        <?= esc(
                                                            $r['jenis_hewan']
                                                        ) ?>
                                                    </div>

                                                    <div class="sph-animal-count">
                                                        <?= (int)$r['jumlah_hewan'] ?>
                                                        ekor
                                                    </div>
                                                </div>
                                            </div>
                                        </td>

                                        <td>
                                            <div class="sph-destination">
                                                <i class="ri-map-pin-2-fill"></i>

                                                <?= nl2br(
                                                    esc(
                                                        $r['tujuan_alamat']
                                                    )
                                                ) ?>
                                            </div>
                                        </td>

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

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

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

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

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

                                                    <button
                                                        type="submit"
                                                        class="sph-btn sph-btn-small sph-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="sph-header">
            <div class="sph-header-left">
                <p class="sph-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-bear-smile-fill sph-title-icon"></i>

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

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

                    <?= $isEdit
                        ? 'Perbarui data pemilik, hewan, dan tujuan pengiriman.'
                        : 'Lengkapi data pemilik, hewan, dan tujuan pengiriman.' ?>
                </p>
            </div>

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


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


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

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

                        <p>
                            Pastikan jumlah dan tujuan pengiriman sudah benar.
                        </p>
                    </div>
                </div>
            </div>

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

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

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

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

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

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

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

                        <select
                            name="warga_id"
                            id="wargaId"
                            class="sph-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="sph-form-section">
                        <i class="ri-bear-smile-fill"></i>
                        Data Hewan
                    </div>

                    <div class="sph-field">
                        <label for="jenisHewan">
                            Jenis Hewan
                            <span class="sph-required">*</span>
                        </label>

                        <input
                            type="text"
                            class="sph-input"
                            id="jenisHewan"
                            name="jenis_hewan"
                            value="<?= esc($jenisHewanValue) ?>"
                            placeholder="Contoh: Sapi Jantan"
                            required
                        >
                    </div>

                    <div class="sph-field">
                        <label for="jumlahHewan">
                            Jumlah Hewan
                            <span class="sph-required">*</span>
                        </label>

                        <input
                            type="number"
                            class="sph-input"
                            id="jumlahHewan"
                            name="jumlah_hewan"
                            value="<?= $jumlahHewanValue > 0
                                ? (int)$jumlahHewanValue
                                : 1 ?>"
                            min="1"
                            step="1"
                            placeholder="Jumlah dalam ekor"
                            required
                        >
                    </div>


                    <div class="sph-form-section">
                        <i class="ri-map-pin-2-fill"></i>
                        Tujuan Pengiriman
                    </div>

                    <div class="sph-field sph-field-full">
                        <label for="tujuanAlamat">
                            Tujuan Alamat
                            <span class="sph-required">*</span>
                        </label>

                        <textarea
                            class="sph-input"
                            id="tujuanAlamat"
                            name="tujuan_alamat"
                            rows="4"
                            placeholder="Contoh: Pasar Hewan Wonomulyo, Kecamatan Wonomulyo, Kabupaten Polewali Mandar"
                            required
                        ><?= esc($tujuanAlamatValue) ?></textarea>
                    </div>

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

                        <span>
                            Data identitas pemilik hewan akan diambil dari
                            data penduduk berdasarkan warga yang dipilih.
                            Pastikan jenis hewan, jumlah hewan, dan alamat
                            tujuan telah sesuai sebelum surat dicetak.
                        </span>
                    </div>

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

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

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

    <?php endif; ?>

</div>


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

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

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

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


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

    if (jumlahHewan) {
        jumlahHewan.addEventListener('input', function () {
            if (Number(this.value) < 1) {
                this.value = 1;
            }
        });
    }


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

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