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

date_default_timezone_set('Asia/Makassar');

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

if (!function_exists('esc')) {
    function esc($value)
    {
        return htmlspecialchars(
            (string)$value,
            ENT_QUOTES,
            'UTF-8'
        );
    }
}

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

if ($act === 'edit') {
    $act = 'form';
}

if ($act === 'del') {
    $act = 'delete';
}

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


/* =========================================================
   KONFIGURASI
========================================================= */

$uploadDir = __DIR__.'/../uploads';
$uploadUrl = '../uploads';

if (empty($_SESSION['csrf_informasi'])) {
    try {
        $_SESSION['csrf_informasi'] = bin2hex(
            random_bytes(32)
        );
    } catch (Throwable $e) {
        $_SESSION['csrf_informasi'] = hash(
            'sha256',
            uniqid('', true).microtime(true)
        );
    }
}

$csrfToken = $_SESSION['csrf_informasi'];


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

function informasi_pesan_upload($kode)
{
    $pesan = [
        UPLOAD_ERR_INI_SIZE =>
            'Ukuran gambar melebihi batas server.',
        UPLOAD_ERR_FORM_SIZE =>
            'Ukuran gambar melebihi batas formulir.',
        UPLOAD_ERR_PARTIAL =>
            'Gambar hanya terunggah sebagian.',
        UPLOAD_ERR_NO_FILE =>
            'Tidak ada gambar yang dipilih.',
        UPLOAD_ERR_NO_TMP_DIR =>
            'Folder sementara upload tidak tersedia.',
        UPLOAD_ERR_CANT_WRITE =>
            'Server gagal menulis gambar.',
        UPLOAD_ERR_EXTENSION =>
            'Upload dihentikan oleh ekstensi server.'
    ];

    return $pesan[$kode]
        ?? 'Terjadi kesalahan saat mengunggah gambar.';
}

function informasi_pastikan_folder(
    $uploadDir,
    &$errorText
) {
    if (!is_dir($uploadDir)) {
        $berhasilDibuat = mkdir(
            $uploadDir,
            0755,
            true
        );

        if (
            !$berhasilDibuat &&
            !is_dir($uploadDir)
        ) {
            $errorText = 'Folder uploads tidak dapat dibuat.';
            return false;
        }
    }

    if (!is_writable($uploadDir)) {
        $errorText = 'Folder uploads tidak memiliki izin tulis.';
        return false;
    }

    return true;
}

function informasi_upload_gambar(
    $file,
    $uploadDir,
    &$errorText
) {
    if (
        empty($file) ||
        !isset($file['error']) ||
        $file['error'] === UPLOAD_ERR_NO_FILE
    ) {
        return null;
    }

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errorText = 'Upload gambar gagal: '
            .informasi_pesan_upload(
                $file['error']
            );

        return false;
    }

    if (
        empty($file['tmp_name']) ||
        !is_uploaded_file($file['tmp_name'])
    ) {
        $errorText = 'File gambar yang diunggah tidak valid.';
        return false;
    }

    $maksimalUkuran = 5 * 1024 * 1024;

    if ((int)$file['size'] > $maksimalUkuran) {
        $errorText = 'Ukuran gambar maksimal 5 MB.';
        return false;
    }

    $mimeType = '';

    if (class_exists('finfo')) {
        $finfo = new finfo(
            FILEINFO_MIME_TYPE
        );

        $mimeType = $finfo->file(
            $file['tmp_name']
        );
    } elseif (
        function_exists('mime_content_type')
    ) {
        $mimeType = mime_content_type(
            $file['tmp_name']
        );
    } else {
        $imageInfo = @getimagesize(
            $file['tmp_name']
        );

        $mimeType = $imageInfo['mime']
            ?? '';
    }

    $tipeDiizinkan = [
        'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/webp' => 'webp',
        'image/gif'  => 'gif'
    ];

    if (
        !isset($tipeDiizinkan[$mimeType]) ||
        @getimagesize($file['tmp_name']) === false
    ) {
        $errorText = 'Gambar harus berformat JPG, PNG, WEBP, atau GIF.';
        return false;
    }

    if (
        !informasi_pastikan_folder(
            $uploadDir,
            $errorText
        )
    ) {
        return false;
    }

    try {
        $kodeAcak = bin2hex(
            random_bytes(8)
        );
    } catch (Throwable $e) {
        $kodeAcak = str_replace(
            '.',
            '',
            uniqid('', true)
        );
    }

    $namaFile = 'info_'
        .date('YmdHis')
        .'_'
        .$kodeAcak
        .'.'
        .$tipeDiizinkan[$mimeType];

    $namaFile = preg_replace(
        '/[^a-zA-Z0-9._-]/',
        '',
        $namaFile
    );

    $lokasiTujuan = rtrim(
        $uploadDir,
        DIRECTORY_SEPARATOR
    )
    .DIRECTORY_SEPARATOR
    .$namaFile;

    if (
        !move_uploaded_file(
            $file['tmp_name'],
            $lokasiTujuan
        )
    ) {
        $errorText = 'Gambar gagal dipindahkan ke folder uploads.';
        return false;
    }

    return $namaFile;
}

function informasi_hapus_gambar(
    $uploadDir,
    $namaFile
) {
    $namaFile = basename(
        trim((string)$namaFile)
    );

    if ($namaFile === '') {
        return;
    }

    $lokasiFile = rtrim(
        $uploadDir,
        DIRECTORY_SEPARATOR
    )
    .DIRECTORY_SEPARATOR
    .$namaFile;

    if (
        is_file($lokasiFile) &&
        file_exists($lokasiFile)
    ) {
        @unlink($lokasiFile);
    }
}

function informasi_inisial($judul)
{
    $judul = trim((string)$judul);

    if ($judul === '') {
        return 'I';
    }

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

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

function informasi_ringkasan(
    $isi,
    $panjang = 130
) {
    $text = trim(
        preg_replace(
            '/\s+/',
            ' ',
            strip_tags((string)$isi)
        )
    );

    if ($text === '') {
        return 'Tidak ada isi informasi.';
    }

    if (function_exists('mb_strlen')) {
        if (
            mb_strlen(
                $text,
                'UTF-8'
            ) <= $panjang
        ) {
            return $text;
        }

        return mb_substr(
            $text,
            0,
            $panjang,
            'UTF-8'
        ).'...';
    }

    if (strlen($text) <= $panjang) {
        return $text;
    }

    return substr(
        $text,
        0,
        $panjang
    ).'...';
}


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

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

    if (
        !is_string($token) ||
        !hash_equals($csrfToken, $token)
    ) {
        header(
            'Location: informasi.php?msg=csrf'
        );
        exit;
    }

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

    $gambarLama = '';
    $dataDitemukan = false;

    $cekStmt = $mysqli->prepare("
        SELECT gambar
        FROM informasi_desa
        WHERE id = ?
        LIMIT 1
    ");

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

        $cekStmt->execute();
        $cekStmt->store_result();

        if ($cekStmt->num_rows > 0) {
            $cekStmt->bind_result(
                $gambarLama
            );

            $cekStmt->fetch();
            $dataDitemukan = true;
        }

        $cekStmt->close();
    }

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

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

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

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

    $berhasil = $stmt->execute();

    $terhapus = $berhasil &&
        $stmt->affected_rows > 0;

    $stmt->close();

    if ($terhapus) {
        informasi_hapus_gambar(
            $uploadDir,
            $gambarLama
        );
    }

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


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

$errorText = '';

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

    $token = $_POST['csrf_token'] ?? '';

    $judul = trim(
        (string)($_POST['judul'] ?? '')
    );

    $isi = trim(
        (string)($_POST['isi'] ?? '')
    );

    $hapusGambar = isset(
        $_POST['hapus_gambar']
    ) &&
        $_POST['hapus_gambar'] === '1';

    if (
        !is_string($token) ||
        !hash_equals($csrfToken, $token)
    ) {
        $errorText = 'Token keamanan tidak valid. Muat ulang halaman.';
        $act = 'form';
    } elseif ($judul === '') {
        $errorText = 'Judul informasi wajib diisi.';
        $act = 'form';
    } elseif ($isi === '') {
        $errorText = 'Isi informasi wajib diisi.';
        $act = 'form';
    } elseif (
        function_exists('mb_strlen') &&
        mb_strlen($judul, 'UTF-8') > 255
    ) {
        $errorText = 'Judul informasi maksimal 255 karakter.';
        $act = 'form';
    } elseif (
        !function_exists('mb_strlen') &&
        strlen($judul) > 255
    ) {
        $errorText = 'Judul informasi maksimal 255 karakter.';
        $act = 'form';
    } else {
        $gambarLama = '';
        $dataDitemukan = $id === 0;

        if ($id > 0) {
            $cekStmt = $mysqli->prepare("
                SELECT gambar
                FROM informasi_desa
                WHERE id = ?
                LIMIT 1
            ");

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

                $cekStmt->execute();
                $cekStmt->store_result();

                if ($cekStmt->num_rows > 0) {
                    $cekStmt->bind_result(
                        $gambarLama
                    );

                    $cekStmt->fetch();
                    $dataDitemukan = true;
                }

                $cekStmt->close();
            }
        }

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

        $gambarBaru = informasi_upload_gambar(
            $_FILES['gambar'] ?? [],
            $uploadDir,
            $errorText
        );

        if ($gambarBaru === false) {
            $act = 'form';
        } else {
            $gambarFinal = (string)$gambarLama;
            $gambarUntukDihapus = '';

            if ($hapusGambar) {
                $gambarFinal = '';

                if ($gambarLama !== '') {
                    $gambarUntukDihapus =
                        $gambarLama;
                }
            }

            if (
                is_string($gambarBaru) &&
                $gambarBaru !== ''
            ) {
                $gambarFinal = $gambarBaru;

                if ($gambarLama !== '') {
                    $gambarUntukDihapus =
                        $gambarLama;
                }
            }

            if ($id > 0) {

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

                $stmt = $mysqli->prepare("
                    UPDATE informasi_desa
                    SET
                        judul = ?,
                        isi = ?,
                        gambar = ?
                    WHERE id = ?
                ");

                if ($stmt) {
                    $stmt->bind_param(
                        'sssi',
                        $judul,
                        $isi,
                        $gambarFinal,
                        $id
                    );

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

                        if (
                            $gambarUntukDihapus !== '' &&
                            $gambarUntukDihapus !==
                            $gambarFinal
                        ) {
                            informasi_hapus_gambar(
                                $uploadDir,
                                $gambarUntukDihapus
                            );
                        }

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

                    $errorText = 'Informasi gagal diperbarui: '
                        .$stmt->error;

                    $stmt->close();
                } else {
                    $errorText = 'Query pembaruan gagal disiapkan: '
                        .$mysqli->error;
                }

                if (
                    is_string($gambarBaru) &&
                    $gambarBaru !== ''
                ) {
                    informasi_hapus_gambar(
                        $uploadDir,
                        $gambarBaru
                    );
                }

                $act = 'form';
            } else {

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

                $stmt = $mysqli->prepare("
                    INSERT INTO informasi_desa
                    (
                        judul,
                        isi,
                        gambar
                    )
                    VALUES (?, ?, ?)
                ");

                if ($stmt) {
                    $stmt->bind_param(
                        'sss',
                        $judul,
                        $isi,
                        $gambarFinal
                    );

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

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

                    $errorText = 'Informasi gagal disimpan: '
                        .$stmt->error;

                    $stmt->close();
                } else {
                    $errorText = 'Query penyimpanan gagal disiapkan: '
                        .$mysqli->error;
                }

                if (
                    is_string($gambarBaru) &&
                    $gambarBaru !== ''
                ) {
                    informasi_hapus_gambar(
                        $uploadDir,
                        $gambarBaru
                    );
                }

                $act = 'form';
            }
        }
    }
}


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

$edit = null;

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

    if ($editId > 0) {
        $stmt = $mysqli->prepare("
            SELECT
                id,
                judul,
                isi,
                gambar
            FROM informasi_desa
            WHERE id = ?
            LIMIT 1
        ");

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

            $stmt->execute();
            $stmt->store_result();

            if ($stmt->num_rows > 0) {
                $editResultId = 0;
                $editJudul = '';
                $editIsi = '';
                $editGambar = '';

                $stmt->bind_result(
                    $editResultId,
                    $editJudul,
                    $editIsi,
                    $editGambar
                );

                $stmt->fetch();

                $edit = [
                    'id' => $editResultId,
                    'judul' => $editJudul,
                    'isi' => $editIsi,
                    'gambar' => $editGambar
                ];
            }

            $stmt->close();
        }

        if (!$edit && $errorText === '') {
            header(
                'Location: informasi.php?msg=notfound'
            );
            exit;
        }
    }
}


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

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


/* =========================================================
   PENCARIAN DAN DAFTAR DATA
========================================================= */

$q = trim(
    (string)($_GET['q'] ?? '')
);

if ($q !== '') {
    $safeQ = $mysqli->real_escape_string(
        $q
    );

    $list = $mysqli->query("
        SELECT
            id,
            judul,
            isi,
            gambar
        FROM informasi_desa
        WHERE
            judul LIKE '%{$safeQ}%'
            OR isi LIKE '%{$safeQ}%'
        ORDER BY id DESC
    ");
} else {
    $list = $mysqli->query("
        SELECT
            id,
            judul,
            isi,
            gambar
        FROM informasi_desa
        ORDER BY id DESC
    ");
}

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


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

$isEdit = !empty($edit);

$judulValue = $_POST['judul']
    ?? $edit['judul']
    ?? '';

$isiValue = $_POST['isi']
    ?? $edit['isi']
    ?? '';

$gambarValue = $edit['gambar']
    ?? '';


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

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

$msgText = [
    'saved' =>
        'Informasi desa berhasil ditambahkan.',
    'updated' =>
        'Informasi desa berhasil diperbarui.',
    'deleted' =>
        'Informasi desa berhasil dihapus.',
    'notfound' =>
        'Data informasi desa tidak ditemukan.',
    'csrf' =>
        'Token keamanan tidak valid. Silakan ulangi proses.',
    'error' =>
        'Terjadi kesalahan saat memproses informasi desa.'
][$msgKey] ?? '';

$msgError = in_array(
    $msgKey,
    ['notfound', 'csrf', '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 {
    --info-green-950: #002818;
    --info-green-900: #003d22;
    --info-green-800: #005530;
    --info-green-700: #047a3d;
    --info-green-600: #09a04f;
    --info-green-500: #15c46a;
    --info-green-400: #35e085;
    --info-green-100: #dcfaee;
    --info-green-50: #edfff5;

    --info-blue: #2080e8;
    --info-yellow: #f5b400;
    --info-orange: #f26b1d;
    --info-purple: #7956d8;
    --info-red: #dc3545;

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

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

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

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

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

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

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

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

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

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

* {
    box-sizing: border-box;
}

body {
    color: var(--info-ink);
    background-color: var(--info-page);
    background-image:
        radial-gradient(
            ellipse at 80% 0%,
            rgba(21, 196, 106, .06),
            transparent 50%
        ),
        radial-gradient(
            ellipse at 20% 100%,
            rgba(9, 160, 79, .04),
            transparent 50%
        );
    font-family:
        'Inter',
        'Segoe UI',
        system-ui,
        sans-serif;
}

.info-page {
    padding: 26px;
}


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

.info-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(--info-green-950),
        var(--info-green-800),
        var(--info-green-900)
    );

    background-size: 200% 100%;

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

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

    animation:
        info-gradient 8s ease infinite;
}

.info-header::before,
.info-header::after {
    content: "";
    position: absolute;

    border-radius: 50%;
    pointer-events: none;
}

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

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

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

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

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

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

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

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

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

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

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

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

    width: 22px;
    height: 2px;

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

    border-radius: 2px;
}

.info-header h2 {
    margin: 0;

    color: #ffffff;

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

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

    color: var(--info-green-400);
    font-size: 27px;
    vertical-align: middle;

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

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

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

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

    animation:
        info-pulse 2s ease infinite;
}

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

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

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


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

.info-panel {
    overflow: hidden;

    background: var(--info-surface);

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

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

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

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

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

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

    display: grid;
    place-items: center;

    color: #ffffff;

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

    border-radius: 13px;

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

    font-size: 20px;
}

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

    color: var(--info-ink);

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

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

    color: var(--info-muted);

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

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


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

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

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

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

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

    border-radius: 14px;

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

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

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


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

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

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

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

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

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

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

    backdrop-filter: blur(8px);
}

.info-btn-view {
    color: #ffffff;

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

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

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

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

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

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

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

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

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

    font-size: 12px;
}


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

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

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

.info-search {
    position: relative;

    min-width: 260px;
    flex: 1;
}

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

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

    transform: translateY(-50%);
}

.info-search input {
    width: 100%;
    min-height: 44px;
    padding: 12px 14px 12px 42px;

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

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

.info-search input:focus {
    background: #ffffff;
    border-color: var(--info-green-500);

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

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

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

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

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

    border-radius: 999px;

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


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

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

    background: #ffffff;

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

    border-radius: 16px;
}

.info-table {
    width: 100%;

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

    font-size: 14px;
}

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

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

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

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

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

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

    border-bottom:
        1px solid #edf7f1;

    vertical-align: middle;
}

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

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

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

.info-number {
    width: 36px;
    height: 36px;

    display: inline-grid;
    place-items: center;

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

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

    border-radius: 11px;

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

.info-title-wrap {
    min-width: 290px;

    display: flex;
    align-items: flex-start;
    gap: 11px;
}

.info-avatar {
    width: 42px;
    height: 42px;
    flex-shrink: 0;

    display: grid;
    place-items: center;

    color: #ffffff;

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

    border-radius: 14px;

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

    font-weight: 800;
}

.info-title {
    color: var(--info-ink);

    font-weight: 800;
    line-height: 1.45;
}

.info-summary {
    max-width: 460px;
    margin-top: 4px;

    color: var(--info-muted);

    font-size: 11px;
    line-height: 1.55;
}

.info-image {
    width: 125px;
    height: 82px;

    display: block;

    object-fit: cover;

    background: #eef8f2;

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

    border-radius: 14px;

    box-shadow:
        0 7px 18px rgba(0, 0, 0, .12);

    cursor: pointer;

    transition:
        transform .2s ease,
        box-shadow .2s ease;
}

.info-image:hover {
    transform: scale(1.04);

    box-shadow:
        0 12px 25px rgba(0, 0, 0, .18);
}

.info-image-empty {
    width: 125px;
    height: 82px;

    display: grid;
    place-items: center;

    color: var(--info-green-700);
    background: var(--info-green-50);

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

    border-radius: 14px;

    font-size: 28px;
}

.info-actions {
    min-width: 235px;

    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 7px;
}

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

.info-empty {
    padding: 38px !important;

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

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

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

    color: var(--info-green-600);
    font-size: 36px;
}


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

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

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

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

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

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

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

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

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

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

.info-input:focus {
    background: #ffffff;
    border-color: var(--info-green-500);

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

textarea.info-input {
    min-height: 230px;

    resize: vertical;
    line-height: 1.7;
}

.info-section {
    grid-column: 1 / -1;

    padding: 12px 14px;

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

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

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

    border-radius: 13px;

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

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

.info-upload-box {
    padding: 17px;

    background: #f8fffb;

    border:
        1px dashed var(--info-green-500);

    border-radius: 14px;
}

.info-help {
    margin: 5px 0 0;

    color: var(--info-muted);

    font-size: 11px;
    font-weight: 600;
    line-height: 1.55;
}

.info-preview {
    width: 100%;
    max-width: 460px;
    height: 270px;

    display: block;
    margin-top: 14px;

    object-fit: cover;

    background: #ffffff;

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

    border-radius: 15px;

    box-shadow:
        0 9px 22px rgba(0, 0, 0, .12);
}

.info-preview-placeholder {
    width: 100%;
    max-width: 460px;
    height: 270px;

    margin-top: 14px;

    display: grid;
    place-items: center;

    color: var(--info-green-700);
    background: var(--info-green-50);

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

    border-radius: 15px;

    font-size: 54px;
}

.info-checkbox {
    margin-top: 11px;

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

    color: var(--info-red);

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

.info-checkbox input {
    width: 16px;
    height: 16px;
}

.info-note {
    grid-column: 1 / -1;

    padding: 12px 14px;

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

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

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

    border-radius: 13px;

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

.info-note i {
    margin-top: 1px;

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

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

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


/* =========================================================
   MODAL GAMBAR
========================================================= */

.info-modal {
    position: fixed;
    z-index: 99999;
    inset: 0;

    padding: 24px;

    display: none;
    align-items: center;
    justify-content: center;

    background: rgba(0, 20, 12, .84);

    backdrop-filter: blur(8px);
}

.info-modal.active {
    display: flex;
}

.info-modal-content {
    position: relative;

    width: min(100%, 980px);
    max-height: 90vh;

    padding: 14px;

    background: #ffffff;

    border-radius: 18px;

    box-shadow:
        0 25px 70px rgba(0, 0, 0, .42);
}

.info-modal-content img {
    width: 100%;
    max-height: calc(90vh - 28px);

    display: block;

    object-fit: contain;

    border-radius: 12px;
}

.info-modal-close {
    position: absolute;
    top: -13px;
    right: -13px;

    width: 40px;
    height: 40px;

    display: grid;
    place-items: center;

    color: #ffffff;
    background: var(--info-orange);

    border: 3px solid #ffffff;
    border-radius: 50%;

    cursor: pointer;

    font-size: 21px;

    box-shadow:
        0 8px 20px rgba(0, 0, 0, .25);
}


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

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

    .info-header {
        padding: 20px;
    }

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

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

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

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

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

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

    .info-actions {
        min-width: 220px;
    }

    .info-preview,
    .info-preview-placeholder {
        height: 220px;
    }
}
</style>


<div class="info-page">

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

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

        <div class="info-header">
            <div class="info-header-left">
                <p class="info-eyebrow">
                    <i class="ri-home-heart-fill"></i>
                    Profil dan Informasi Desa
                </p>

                <h2>
                    <i class="ri-community-fill info-title-icon"></i>
                    Informasi Desa
                </h2>

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

                    Kelola informasi, profil, dan publikasi mengenai desa
                </p>
            </div>

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

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

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

                <a
                    class="info-btn info-btn-light"
                    href="informasi.php?a=form"
                >
                    <i class="ri-add-circle-fill"></i>
                    Tambah Informasi
                </a>
            </div>
        </div>


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

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


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

                    <div>
                        <h3>Daftar Informasi Desa</h3>

                        <p>
                            Informasi yang telah tersimpan pada sistem desa.
                        </p>
                    </div>
                </div>

                <div class="info-stat">
                    <i class="ri-file-info-fill"></i>
                    <?= (int)$totalInformasi ?> Informasi
                </div>
            </div>

            <div class="info-panel-body">
                <div class="info-toolbar">
                    <form
                        method="get"
                        action="informasi.php"
                        class="info-search"
                    >
                        <i class="ri-search-line"></i>

                        <input
                            type="text"
                            name="q"
                            value="<?= esc($q) ?>"
                            placeholder="Cari judul atau isi informasi..."
                            autocomplete="off"
                        >
                    </form>

                    <?php if ($q !== ''): ?>
                        <a
                            href="informasi.php"
                            class="info-btn info-btn-ghost"
                        >
                            <i class="ri-refresh-line"></i>
                            Reset
                        </a>
                    <?php endif; ?>
                </div>

                <div class="info-table-wrap">
                    <table class="info-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Informasi</th>
                                <th>Gambar</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if ($totalInformasi === 0): ?>
                                <tr>
                                    <td
                                        colspan="4"
                                        class="info-empty"
                                    >
                                        <i class="ri-information-off-fill"></i>

                                        <?= $q !== ''
                                            ? 'Informasi yang dicari tidak ditemukan.'
                                            : 'Belum ada informasi desa. Klik tombol Tambah Informasi untuk menambahkan data baru.' ?>
                                    </td>
                                </tr>
                            <?php endif; ?>

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

                                <?php while ($row = $list->fetch_assoc()): ?>
                                    <?php
                                    $namaGambar = basename(
                                        trim(
                                            (string)(
                                                $row['gambar']
                                                ?? ''
                                            )
                                        )
                                    );

                                    $urlGambar = $namaGambar !== ''
                                        ? $uploadUrl.'/'.$namaGambar
                                        : '';
                                    ?>

                                    <tr class="info-data-row">
                                        <td>
                                            <span class="info-number">
                                                <?= $no++ ?>
                                            </span>
                                        </td>

                                        <td>
                                            <div class="info-title-wrap">
                                                <div class="info-avatar">
                                                    <?= esc(
                                                        informasi_inisial(
                                                            $row['judul']
                                                        )
                                                    ) ?>
                                                </div>

                                                <div>
                                                    <div class="info-title">
                                                        <?= esc(
                                                            $row['judul']
                                                        ) ?>
                                                    </div>

                                                    <div class="info-summary">
                                                        <?= esc(
                                                            informasi_ringkasan(
                                                                $row['isi']
                                                            )
                                                        ) ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>

                                        <td>
                                            <?php if ($urlGambar !== ''): ?>
                                                <img
                                                    src="<?= esc($urlGambar) ?>"
                                                    alt="<?= esc(
                                                        $row['judul']
                                                    ) ?>"
                                                    class="info-image info-open-image"
                                                    data-src="<?= esc(
                                                        $urlGambar
                                                    ) ?>"
                                                    data-title="<?= esc(
                                                        $row['judul']
                                                    ) ?>"
                                                    loading="lazy"
                                                >
                                            <?php else: ?>
                                                <div class="info-image-empty">
                                                    <i class="ri-image-line"></i>
                                                </div>
                                            <?php endif; ?>
                                        </td>

                                        <td>
                                            <div class="info-actions">
                                                <?php if ($urlGambar !== ''): ?>
                                                    <button
                                                        type="button"
                                                        class="info-btn info-btn-small info-btn-view info-view-button"
                                                        data-src="<?= esc(
                                                            $urlGambar
                                                        ) ?>"
                                                        data-title="<?= esc(
                                                            $row['judul']
                                                        ) ?>"
                                                    >
                                                        <i class="ri-eye-fill"></i>
                                                        Lihat
                                                    </button>
                                                <?php endif; ?>

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

                                                <form
                                                    method="post"
                                                    action="informasi.php?a=delete"
                                                    class="info-delete-form"
                                                    onsubmit="return confirm('Yakin ingin menghapus informasi ini? Gambar terkait juga akan dihapus dan data tidak dapat dikembalikan.');"
                                                >
                                                    <input
                                                        type="hidden"
                                                        name="csrf_token"
                                                        value="<?= esc(
                                                            $csrfToken
                                                        ) ?>"
                                                    >

                                                    <input
                                                        type="hidden"
                                                        name="id"
                                                        value="<?= (int)$row['id'] ?>"
                                                    >

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

                    <?= $isEdit
                        ? 'Edit Informasi Desa'
                        : 'Tambah Informasi Desa' ?>
                </p>

                <h2>
                    <i class="ri-community-fill info-title-icon"></i>

                    <?= $isEdit
                        ? 'Edit Informasi Desa'
                        : 'Tambah Informasi Desa' ?>
                </h2>

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

                    <?= $isEdit
                        ? 'Perbarui judul, isi, dan gambar informasi.'
                        : 'Tambahkan profil atau informasi mengenai desa.' ?>
                </p>
            </div>

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


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


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

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

                        <p>
                            Judul dan isi informasi wajib diisi.
                        </p>
                    </div>
                </div>
            </div>

            <div class="info-panel-body">
                <form
                    method="post"
                    action="informasi.php?a=save"
                    enctype="multipart/form-data"
                    class="info-form"
                    id="informasiForm"
                >
                    <input
                        type="hidden"
                        name="csrf_token"
                        value="<?= esc($csrfToken) ?>"
                    >

                    <input
                        type="hidden"
                        name="id"
                        value="<?= (int)($edit['id'] ?? 0) ?>"
                    >


                    <div class="info-section">
                        <i class="ri-file-text-fill"></i>
                        Isi Informasi
                    </div>

                    <div class="info-field info-field-full">
                        <label for="judul">
                            Judul Informasi
                            <span class="info-required">*</span>
                        </label>

                        <input
                            type="text"
                            class="info-input"
                            id="judul"
                            name="judul"
                            value="<?= esc($judulValue) ?>"
                            placeholder="Contoh: Sejarah Desa Mambu"
                            maxlength="255"
                            required
                        >
                    </div>

                    <div class="info-field info-field-full">
                        <label for="isi">
                            Isi Informasi
                            <span class="info-required">*</span>
                        </label>

                        <textarea
                            class="info-input"
                            id="isi"
                            name="isi"
                            rows="12"
                            placeholder="Masukkan isi informasi desa secara lengkap..."
                            required
                        ><?= esc($isiValue) ?></textarea>
                    </div>


                    <div class="info-section">
                        <i class="ri-image-add-fill"></i>
                        Gambar Informasi
                    </div>

                    <div class="info-field info-field-full">
                        <div class="info-upload-box">
                            <label for="gambar">
                                <?= $isEdit
                                    ? 'Ganti Gambar'
                                    : 'Pilih Gambar' ?>
                            </label>

                            <input
                                type="file"
                                class="info-input"
                                id="gambar"
                                name="gambar"
                                accept=".jpg,.jpeg,.png,.webp,.gif,image/jpeg,image/png,image/webp,image/gif"
                            >

                            <p class="info-help">
                                Format JPG, PNG, WEBP, atau GIF.
                                Ukuran maksimal 5 MB.
                                <?= $isEdit
                                    ? 'Kosongkan jika tidak ingin mengganti gambar lama.'
                                    : 'Gambar bersifat opsional.' ?>
                            </p>

                            <?php if ($gambarValue !== ''): ?>
                                <img
                                    id="gambarPreview"
                                    class="info-preview"
                                    src="<?= esc(
                                        $uploadUrl
                                        .'/'
                                        .basename($gambarValue)
                                    ) ?>"
                                    alt="Preview gambar"
                                >

                                <div
                                    id="gambarPlaceholder"
                                    class="info-preview-placeholder"
                                    style="display:none"
                                >
                                    <i class="ri-image-line"></i>
                                </div>

                                <label class="info-checkbox">
                                    <input
                                        type="checkbox"
                                        name="hapus_gambar"
                                        value="1"
                                        id="hapusGambar"
                                    >

                                    Hapus gambar lama
                                </label>
                            <?php else: ?>
                                <div
                                    id="gambarPlaceholder"
                                    class="info-preview-placeholder"
                                >
                                    <i class="ri-image-line"></i>
                                </div>

                                <img
                                    id="gambarPreview"
                                    class="info-preview"
                                    alt="Preview gambar"
                                    style="display:none"
                                >
                            <?php endif; ?>
                        </div>
                    </div>


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

                        <span>
                            Saat gambar baru diunggah dalam proses edit,
                            gambar lama akan dihapus otomatis setelah data
                            berhasil diperbarui. Menghapus informasi juga
                            akan menghapus file gambar terkait dari server.
                        </span>
                    </div>

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

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

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

    <?php endif; ?>

</div>


<div
    class="info-modal"
    id="infoImageModal"
>
    <div class="info-modal-content">
        <button
            type="button"
            class="info-modal-close"
            id="closeInfoModal"
            aria-label="Tutup"
        >
            <i class="ri-close-line"></i>
        </button>

        <img
            id="infoModalImage"
            src=""
            alt=""
        >
    </div>
</div>


<script>
(() => {
    const clockElement = document.getElementById(
        'infoLiveClock'
    );

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


    const searchInput = document.querySelector(
        '.info-search input'
    );

    let searchTimer = null;

    if (searchInput) {
        searchInput.addEventListener(
            'input',
            function () {
                clearTimeout(searchTimer);

                searchTimer = setTimeout(() => {
                    this.form.submit();
                }, 650);
            }
        );
    }


    const gambarInput = document.getElementById(
        'gambar'
    );

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

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

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

    if (gambarInput && gambarPreview) {
        gambarInput.addEventListener(
            'change',
            function () {
                const file = this.files &&
                    this.files.length > 0
                    ? this.files[0]
                    : null;

                if (!file) {
                    return;
                }

                const allowedTypes = [
                    'image/jpeg',
                    'image/png',
                    'image/webp',
                    'image/gif'
                ];

                if (!allowedTypes.includes(file.type)) {
                    alert(
                        'Gambar harus berformat JPG, PNG, WEBP, atau GIF.'
                    );

                    this.value = '';
                    return;
                }

                if (file.size > 5 * 1024 * 1024) {
                    alert(
                        'Ukuran gambar maksimal 5 MB.'
                    );

                    this.value = '';
                    return;
                }

                const reader = new FileReader();

                reader.onload = function (event) {
                    gambarPreview.src =
                        event.target.result;

                    gambarPreview.style.display =
                        'block';

                    gambarPreview.style.opacity =
                        '1';

                    if (gambarPlaceholder) {
                        gambarPlaceholder.style.display =
                            'none';
                    }

                    if (hapusGambar) {
                        hapusGambar.checked = false;
                    }
                };

                reader.readAsDataURL(file);
            }
        );
    }

    if (hapusGambar && gambarPreview) {
        hapusGambar.addEventListener(
            'change',
            function () {
                gambarPreview.style.opacity =
                    this.checked ? '.3' : '1';
            }
        );
    }


    const modal = document.getElementById(
        'infoImageModal'
    );

    const modalImage = document.getElementById(
        'infoModalImage'
    );

    const closeModalButton = document.getElementById(
        'closeInfoModal'
    );

    const bukaModal = (src, title) => {
        if (!modal || !modalImage) {
            return;
        }

        modalImage.src = src;
        modalImage.alt = title || 'Gambar informasi';

        modal.classList.add('active');

        document.body.style.overflow = 'hidden';
    };

    const tutupModal = () => {
        if (!modal) {
            return;
        }

        modal.classList.remove('active');

        if (modalImage) {
            modalImage.src = '';
        }

        document.body.style.overflow = '';
    };

    document
        .querySelectorAll(
            '.info-open-image, .info-view-button'
        )
        .forEach((element) => {
            element.addEventListener(
                'click',
                function () {
                    bukaModal(
                        this.dataset.src || '',
                        this.dataset.title || ''
                    );
                }
            );
        });

    if (closeModalButton) {
        closeModalButton.addEventListener(
            'click',
            tutupModal
        );
    }

    if (modal) {
        modal.addEventListener(
            'click',
            function (event) {
                if (event.target === modal) {
                    tutupModal();
                }
            }
        );
    }

    document.addEventListener(
        'keydown',
        function (event) {
            if (event.key === 'Escape') {
                tutupModal();
            }
        }
    );
})();
</script>

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