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


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

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

if (!isset($_SESSION['csrf_galeri'])) {
    $_SESSION['csrf_galeri'] = bin2hex(
        random_bytes(32)
    );
}

$csrfToken = $_SESSION['csrf_galeri'];


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

function galeri_hapus_file($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 galeri_upload_gambar(
    $file,
    $uploadDir,
    &$errorText
) {
    if (
        !isset($file['error']) ||
        $file['error'] === UPLOAD_ERR_NO_FILE
    ) {
        return null;
    }

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $pesanUpload = [
            UPLOAD_ERR_INI_SIZE =>
                'Ukuran gambar melebihi batas server.',
            UPLOAD_ERR_FORM_SIZE =>
                'Ukuran gambar melebihi batas form.',
            UPLOAD_ERR_PARTIAL =>
                'Gambar hanya terunggah sebagian.',
            UPLOAD_ERR_NO_TMP_DIR =>
                'Folder sementara upload tidak tersedia.',
            UPLOAD_ERR_CANT_WRITE =>
                'Server gagal menulis file gambar.',
            UPLOAD_ERR_EXTENSION =>
                'Upload dihentikan oleh ekstensi server.'
        ];

        $errorText = $pesanUpload[$file['error']]
            ?? 'Upload gambar gagal.';

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

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

    if (!isset($tipeDiizinkan[$mimeType])) {
        $errorText = 'Format gambar harus JPG, PNG, WEBP, atau GIF.';
        return false;
    }

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

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

    $namaFileBaru = 'galeri_'
        .date('YmdHis')
        .'_'
        .$kodeAcak
        .'.'
        .$tipeDiizinkan[$mimeType];

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

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

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

    return $namaFileBaru;
}

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

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

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

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

function galeri_youtube_id($url)
{
    $url = trim((string)$url);

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

    if (preg_match('/^[a-zA-Z0-9_-]{11}$/', $url)) {
        return $url;
    }

    if (!preg_match('~^https?://~i', $url)) {
        $url = 'https://'.$url;
    }

    $bagian = parse_url($url);
    if (!is_array($bagian)) {
        return '';
    }

    $host = strtolower((string)($bagian['host'] ?? ''));
    $host = preg_replace('/^www\./', '', $host);
    $path = (string)($bagian['path'] ?? '');
    $videoId = '';

    if (in_array($host, ['youtu.be'], true)) {
        $videoId = trim(explode('/', trim($path, '/'))[0] ?? '');
    } elseif (in_array($host, [
        'youtube.com',
        'm.youtube.com',
        'music.youtube.com',
        'youtube-nocookie.com'
    ], true)) {
        if ($path === '/watch') {
            $query = [];
            parse_str((string)($bagian['query'] ?? ''), $query);
            $videoId = trim((string)($query['v'] ?? ''));
        } elseif (preg_match('~^/(?:embed|shorts|live)/([a-zA-Z0-9_-]{11})(?:/|$)~', $path, $match)) {
            $videoId = (string)$match[1];
        }
    }

    return preg_match('/^[a-zA-Z0-9_-]{11}$/', $videoId)
        ? $videoId
        : '';
}

function galeri_youtube_url($url)
{
    $videoId = galeri_youtube_id($url);
    return $videoId !== ''
        ? 'https://www.youtube.com/watch?v='.$videoId
        : '';
}

function galeri_youtube_thumbnail($url)
{
    $videoId = galeri_youtube_id($url);
    return $videoId !== ''
        ? 'https://i.ytimg.com/vi/'.$videoId.'/hqdefault.jpg'
        : '';
}

function galeri_youtube_embed($url)
{
    $videoId = galeri_youtube_id($url);
    return $videoId !== ''
        ? 'https://www.youtube-nocookie.com/embed/'.$videoId.'?rel=0'
        : '';
}


/* =========================================================
   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: galeri.php?msg=csrf'
        );
        exit;
    }

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

    $gambarLama = '';
    $dataDitemukan = false;

    $cekStmt = $mysqli->prepare("
        SELECT image
        FROM galeri
        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: galeri.php?msg=notfound'
        );
        exit;
    }

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

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

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

    $berhasil = $stmt->execute();

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

    $stmt->close();

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

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


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

$errorText = '';

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

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

    $mediaType = trim(
        (string)($_POST['media_type'] ?? 'image')
    );

    if (!in_array($mediaType, ['image', 'youtube'], true)) {
        $mediaType = 'image';
    }

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

    $youtubeUrl = galeri_youtube_url(
        $youtubeInput
    );

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

    if (
        !is_string($token) ||
        !hash_equals($csrfToken, $token)
    ) {
        $errorText = 'Token keamanan tidak valid. Muat ulang halaman.';
        $act = 'form';
    } elseif ($title === '') {
        $errorText = 'Judul galeri wajib diisi.';
        $act = 'form';
    } elseif (
        function_exists('mb_strlen') &&
        mb_strlen($title, 'UTF-8') > 200
    ) {
        $errorText = 'Judul galeri maksimal 200 karakter.';
        $act = 'form';
    } elseif (
        !function_exists('mb_strlen') &&
        strlen($title) > 200
    ) {
        $errorText = 'Judul galeri maksimal 200 karakter.';
        $act = 'form';
    } elseif (
        $mediaType === 'youtube' &&
        $youtubeInput === ''
    ) {
        $errorText = 'Link video YouTube wajib diisi.';
        $act = 'form';
    } elseif (
        $mediaType === 'youtube' &&
        $youtubeUrl === ''
    ) {
        $errorText = 'Link YouTube tidak valid. Gunakan link video YouTube, Shorts, atau youtu.be.';
        $act = 'form';
    } else {
        $gambarLama = '';
        $youtubeLama = '';
        $dataDitemukan = $id === 0;

        if ($id > 0) {
            $cekStmt = $mysqli->prepare("
                SELECT image, youtube_url
                FROM galeri
                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,
                        $youtubeLama
                    );

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

                $cekStmt->close();
            }
        }

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

        $gambarBaru = null;

        if ($mediaType === 'image') {
            $gambarBaru = galeri_upload_gambar(
                $_FILES['image'] ?? [],
                $uploadDir,
                $errorText
            );
        }

        if ($gambarBaru === false) {
            $act = 'form';
        } else {
            $gambarSimpan = $mediaType === 'image'
                ? ($gambarBaru ?? $gambarLama)
                : null;

            $youtubeSimpan = $mediaType === 'youtube'
                ? $youtubeUrl
                : null;

            if (
                $mediaType === 'image' &&
                trim((string)$gambarSimpan) === ''
            ) {
                $errorText = 'Pilih gambar atau ubah jenis media menjadi Video YouTube.';
                $act = 'form';
            } elseif ($id > 0) {

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

                $stmt = $mysqli->prepare("
                    UPDATE galeri
                    SET
                        title = ?,
                        image = ?,
                        youtube_url = ?
                    WHERE id = ?
                ");

                if ($stmt) {
                    $stmt->bind_param(
                        'sssi',
                        $title,
                        $gambarSimpan,
                        $youtubeSimpan,
                        $id
                    );

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

                        if (
                            trim((string)$gambarLama) !== '' &&
                            $gambarLama !== $gambarSimpan
                        ) {
                            galeri_hapus_file(
                                $uploadDir,
                                $gambarLama
                            );
                        }

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

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

                if ($gambarBaru !== null) {
                    galeri_hapus_file(
                        $uploadDir,
                        $gambarBaru
                    );
                }

                $act = 'form';
            } else {

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

                $stmt = $mysqli->prepare("
                    INSERT INTO galeri
                    (
                        title,
                        image,
                        youtube_url
                    )
                    VALUES (?, ?, ?)
                ");

                if ($stmt) {
                    $stmt->bind_param(
                        'sss',
                        $title,
                        $gambarSimpan,
                        $youtubeSimpan
                    );

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

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

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

                if ($gambarBaru !== null) {
                    galeri_hapus_file(
                        $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,
                title,
                image,
                youtube_url
            FROM galeri
            WHERE id = ?
            LIMIT 1
        ");

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

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

            if ($stmt->num_rows > 0) {
                $editIdResult = 0;
                $editTitle = '';
                $editImage = '';
                $editYoutubeUrl = '';

                $stmt->bind_result(
                    $editIdResult,
                    $editTitle,
                    $editImage,
                    $editYoutubeUrl
                );

                $stmt->fetch();

                $edit = [
                    'id' => $editIdResult,
                    'title' => $editTitle,
                    'image' => $editImage,
                    'youtube_url' => $editYoutubeUrl
                ];
            }

            $stmt->close();
        }

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


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

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


/* =========================================================
   DATA DAFTAR GALERI
========================================================= */

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

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

    $list = $mysqli->query("
        SELECT
            id,
            title,
            image,
            youtube_url
        FROM galeri
        WHERE title LIKE '%{$safeQ}%'
        ORDER BY id DESC
    ");
} else {
    $list = $mysqli->query("
        SELECT
            id,
            title,
            image,
            youtube_url
        FROM galeri
        ORDER BY id DESC
    ");
}

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

$totalFoto = 0;
$totalVideo = 0;
$statResult = $mysqli->query("
    SELECT
        SUM(CASE WHEN COALESCE(youtube_url, '') = '' THEN 1 ELSE 0 END) AS total_foto,
        SUM(CASE WHEN COALESCE(youtube_url, '') <> '' THEN 1 ELSE 0 END) AS total_video
    FROM galeri
");

if ($statResult && $statRow = $statResult->fetch_assoc()) {
    $totalFoto = (int)($statRow['total_foto'] ?? 0);
    $totalVideo = (int)($statRow['total_video'] ?? 0);
}


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

$isEdit = !empty($edit);

$titleValue = $_POST['title']
    ?? $edit['title']
    ?? '';

$imageValue = $edit['image']
    ?? '';

$youtubeValue = $_POST['youtube_url']
    ?? $edit['youtube_url']
    ?? '';

$mediaTypeValue = $_POST['media_type']
    ?? (trim((string)$youtubeValue) !== '' ? 'youtube' : 'image');

if (!in_array($mediaTypeValue, ['image', 'youtube'], true)) {
    $mediaTypeValue = 'image';
}


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

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

$msgText = [
    'saved' =>
        'Media galeri berhasil ditambahkan.',
    'updated' =>
        'Media galeri berhasil diperbarui.',
    'deleted' =>
        'Media galeri berhasil dihapus.',
    'notfound' =>
        'Data galeri tidak ditemukan.',
    'csrf' =>
        'Token keamanan tidak valid. Silakan ulangi proses.',
    'error' =>
        'Terjadi kesalahan saat memproses data galeri.'
][$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=Outfit: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 {
    --galeri-green-950: #002818;
    --galeri-green-900: #003d22;
    --galeri-green-800: #005530;
    --galeri-green-700: #047a3d;
    --galeri-green-600: #09a04f;
    --galeri-green-500: #15c46a;
    --galeri-green-400: #35e085;
    --galeri-green-100: #dcfaee;
    --galeri-green-50: #edfff5;

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

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

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

    --galeri-radius: 16px;
}

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

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

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

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

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

* {
    box-sizing: border-box;
}

body {
    color: var(--galeri-ink);
    background-color: var(--galeri-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:
        'Outfit',
        'Segoe UI',
        system-ui,
        sans-serif;
}

.galeri-page {
    padding: 26px;
}


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

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

    background-size: 200% 100%;

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

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

    animation:
        galeri-gradient 8s ease infinite;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    width: 22px;
    height: 2px;

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

    border-radius: 2px;
}

.galeri-header h2 {
    margin: 0;

    color: #ffffff;

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

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

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

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

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

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

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

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

    animation:
        galeri-pulse 2s ease infinite;
}

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

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

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


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

.galeri-panel {
    overflow: hidden;

    background: var(--galeri-surface);

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

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

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

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

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

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

    display: grid;
    place-items: center;

    color: #ffffff;

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

    border-radius: 13px;

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

    font-size: 20px;
}

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

    color: var(--galeri-ink);

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

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

    color: var(--galeri-muted);

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

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


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

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

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

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

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

    border-radius: 14px;

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

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

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


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

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

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

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

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

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

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

    backdrop-filter: blur(8px);
}

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

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

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

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

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

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

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

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

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

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

    font-size: 12px;
}


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

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

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

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

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

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

    transform: translateY(-50%);
}

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

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

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

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

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

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

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

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

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

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

    border-radius: 999px;

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


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

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

    background: #ffffff;

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

    border-radius: 16px;
}

.galeri-table {
    width: 100%;

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

    font-size: 14px;
}

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

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

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

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

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

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

    border-bottom:
        1px solid #edf7f1;

    vertical-align: middle;
}

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

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

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

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

    display: block;

    object-fit: cover;

    background: #edf7f1;

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

    border-radius: 14px;

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

    cursor: pointer;

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

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

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

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

    display: grid;
    place-items: center;

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

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

    border-radius: 14px;

    font-size: 27px;
}

.galeri-page [hidden] {
    display: none !important;
}

.galeri-video-cover {
    position: relative;
    width: 125px;
    height: 82px;
    overflow: hidden;
    border-radius: 14px;
    background: #102219;
}

.galeri-video-cover .galeri-image {
    width: 100%;
    height: 100%;
    border: 0;
    border-radius: inherit;
    box-shadow: none;
}

.galeri-video-play {
    position: absolute;
    inset: 0;
    display: grid;
    place-items: center;
    color: #fff;
    background: rgba(5, 30, 17, .28);
    pointer-events: none;
}

.galeri-video-play i {
    width: 38px;
    height: 38px;
    display: grid;
    place-items: center;
    border: 1px solid rgba(255, 255, 255, .68);
    border-radius: 50%;
    background: rgba(4, 122, 61, .88);
    font-size: 21px;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .2);
}

.galeri-media-label {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    margin-top: 5px;
    padding: 4px 7px;
    border-radius: 999px;
    color: var(--galeri-green-800);
    background: var(--galeri-green-50);
    border: 1px solid var(--galeri-green-100);
    font-size: 10px;
    font-weight: 800;
}

.galeri-title-wrap {
    min-width: 230px;

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

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

    display: grid;
    place-items: center;

    color: #ffffff;

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

    border-radius: 14px;

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

    font-weight: 800;
}

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

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

.galeri-file {
    max-width: 260px;
    margin-top: 3px;

    overflow: hidden;

    color: var(--galeri-muted);

    font-size: 11px;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.galeri-id {
    width: 36px;
    height: 36px;

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

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

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

    border-radius: 11px;

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

    padding: 12px 14px;

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

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

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

    border-radius: 13px;

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

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

.galeri-upload-box {
    padding: 18px;

    background: #f8fffb;

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

    border-radius: 15px;
}

.galeri-media-switch {
    grid-column: 1 / -1;
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 10px;
}

.galeri-media-option {
    position: relative;
    min-width: 0;
    cursor: pointer;
}

.galeri-media-option input {
    position: absolute;
    opacity: 0;
    pointer-events: none;
}

.galeri-media-option span {
    min-height: 66px;
    padding: 12px 14px;
    display: flex;
    align-items: center;
    gap: 11px;
    color: var(--galeri-muted);
    background: #fff;
    border: 1px solid var(--galeri-line);
    border-radius: 13px;
    font-size: 13px;
    font-weight: 800;
    transition: border-color .2s ease, background-color .2s ease, color .2s ease, transform .2s ease;
}

.galeri-media-option span i {
    width: 35px;
    height: 35px;
    flex: 0 0 35px;
    display: grid;
    place-items: center;
    border-radius: 10px;
    color: var(--galeri-green-700);
    background: var(--galeri-green-50);
    font-size: 19px;
}

.galeri-media-option input:checked + span {
    color: var(--galeri-green-900);
    background: var(--galeri-green-50);
    border-color: var(--galeri-green-500);
    box-shadow: inset 0 0 0 1px rgba(21, 196, 106, .18);
}

.galeri-media-option input:focus-visible + span {
    box-shadow: 0 0 0 4px rgba(21, 196, 106, .13);
}

.galeri-media-option:active span {
    transform: scale(.985);
}

.galeri-youtube-box {
    padding: 18px;
    background: #f8fffb;
    border: 1px solid var(--galeri-line);
    border-radius: 15px;
}

.galeri-youtube-preview {
    width: 100%;
    max-width: 560px;
    aspect-ratio: 16 / 9;
    margin-top: 14px;
    overflow: hidden;
    display: grid;
    place-items: center;
    color: var(--galeri-green-700);
    background: #edf7f1;
    border: 1px solid var(--galeri-line);
    border-radius: 15px;
}

.galeri-youtube-preview iframe {
    width: 100%;
    height: 100%;
    border: 0;
}

.galeri-youtube-placeholder {
    padding: 24px;
    text-align: center;
}

.galeri-youtube-placeholder i {
    display: block;
    margin-bottom: 8px;
    font-size: 42px;
}

.galeri-youtube-placeholder span {
    color: var(--galeri-muted);
    font-size: 12px;
    font-weight: 700;
}

.galeri-preview {
    width: 100%;
    max-width: 430px;
    height: 260px;

    display: block;

    margin-top: 14px;

    object-fit: cover;

    background: #ffffff;

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

    border-radius: 15px;

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

.galeri-preview-placeholder {
    width: 100%;
    max-width: 430px;
    height: 260px;

    margin-top: 14px;

    display: grid;
    place-items: center;

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

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

    border-radius: 15px;

    font-size: 54px;
}

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

    color: var(--galeri-muted);

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

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

    padding: 12px 14px;

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

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

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

    border-radius: 13px;

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

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

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

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

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


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

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

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

.galeri-modal-content {
    position: relative;

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

    padding: 14px;

    background: #ffffff;

    border-radius: 18px;

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

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

    display: block;

    object-fit: contain;

    border-radius: 12px;
}

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

    width: 40px;
    height: 40px;

    display: grid;
    place-items: center;

    color: #ffffff;
    background: var(--galeri-orange-500);

    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) {
    .galeri-page {
        padding: 16px;
    }

    .galeri-header {
        padding: 20px;
    }

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

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

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

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

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

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

    .galeri-actions {
        min-width: 190px;
    }

    .galeri-preview,
    .galeri-preview-placeholder {
        height: 220px;
    }

    .galeri-media-switch {
        grid-template-columns: 1fr;
    }
}
</style>


<div class="galeri-page">

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

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

        <div class="galeri-header">
            <div class="galeri-header-left">
                <p class="galeri-eyebrow">
                    <i class="ri-gallery-fill"></i>
                    Dokumentasi Desa
                </p>

                <h2>
                    <i class="ri-image-2-fill galeri-title-icon"></i>
                    Galeri Desa
                </h2>

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

                    Kelola foto dan video YouTube dokumentasi desa
                </p>
            </div>

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

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

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

                <a
                    class="galeri-btn galeri-btn-light"
                    href="galeri.php?a=form"
                >
                    <i class="ri-add-box-fill"></i>
                    Tambah Media
                </a>
            </div>
        </div>


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

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


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

                    <div>
                        <h3>Daftar Media Galeri</h3>

                        <p>
                            Foto dan video kegiatan yang telah dipublikasikan.
                        </p>
                    </div>
                </div>

                <div class="galeri-stat">
                    <i class="ri-gallery-fill"></i>
                    <?= $totalFoto ?> Foto · <?= $totalVideo ?> Video
                </div>
            </div>

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

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

                <div class="galeri-table-wrap">
                    <table class="galeri-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Judul</th>
                                <th>Media</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if ($totalGaleri === 0): ?>
                                <tr>
                                    <td
                                        colspan="4"
                                        class="galeri-empty"
                                    >
                                        <i class="ri-image-line"></i>

                                        <?= $q !== ''
                                            ? 'Media galeri yang dicari tidak ditemukan.'
                                            : 'Belum ada media galeri. Klik tombol Tambah Media untuk menambahkan foto atau video.' ?>
                                    </td>
                                </tr>
                            <?php endif; ?>

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

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

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

                                    $youtubeUrlRow = trim(
                                        (string)($row['youtube_url'] ?? '')
                                    );
                                    $youtubeIdRow = galeri_youtube_id(
                                        $youtubeUrlRow
                                    );
                                    $youtubeThumbRow = galeri_youtube_thumbnail(
                                        $youtubeUrlRow
                                    );
                                    $isYoutubeRow = $youtubeIdRow !== '';
                                    ?>

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

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

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

                                                    <div class="galeri-file">
                                                        <?= $isYoutubeRow
                                                            ? esc($youtubeUrlRow)
                                                            : ($namaGambar !== ''
                                                                ? esc($namaGambar)
                                                                : 'Media tidak tersedia') ?>
                                                    </div>

                                                    <span class="galeri-media-label">
                                                        <i class="<?= $isYoutubeRow ? 'ri-youtube-line' : 'ri-image-line' ?>"></i>
                                                        <?= $isYoutubeRow ? 'Video YouTube' : 'Foto' ?>
                                                    </span>
                                                </div>
                                            </div>
                                        </td>

                                        <td>
                                            <?php if ($isYoutubeRow): ?>
                                                <a
                                                    class="galeri-video-cover"
                                                    href="<?= esc($youtubeUrlRow) ?>"
                                                    target="_blank"
                                                    rel="noopener noreferrer"
                                                    title="Buka video YouTube"
                                                >
                                                    <img
                                                        src="<?= esc($youtubeThumbRow) ?>"
                                                        alt="Thumbnail <?= esc($row['title']) ?>"
                                                        class="galeri-image"
                                                        loading="lazy"
                                                    >
                                                    <span class="galeri-video-play"><i class="ri-play-fill"></i></span>
                                                </a>
                                            <?php elseif ($urlGambar !== ''): ?>
                                                <img
                                                    src="<?= esc($urlGambar) ?>"
                                                    alt="<?= esc(
                                                        $row['title']
                                                    ) ?>"
                                                    class="galeri-image"
                                                    loading="lazy"
                                                    onclick="bukaGaleriModal('<?= esc($urlGambar) ?>', '<?= esc($row['title']) ?>')"
                                                >
                                            <?php else: ?>
                                                <div class="galeri-image-empty">
                                                    <i class="ri-image-line"></i>
                                                </div>
                                            <?php endif; ?>
                                        </td>

                                        <td>
                                            <div class="galeri-actions">
                                                <?php if ($isYoutubeRow): ?>
                                                    <a
                                                        class="galeri-btn galeri-btn-small galeri-btn-view"
                                                        href="<?= esc($youtubeUrlRow) ?>"
                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                    >
                                                        <i class="ri-youtube-line"></i>
                                                        Putar
                                                    </a>
                                                <?php elseif ($urlGambar !== ''): ?>
                                                    <button
                                                        type="button"
                                                        class="galeri-btn galeri-btn-small galeri-btn-view"
                                                        onclick="bukaGaleriModal('<?= esc($urlGambar) ?>', '<?= esc($row['title']) ?>')"
                                                    >
                                                        <i class="ri-eye-fill"></i>
                                                        Lihat
                                                    </button>
                                                <?php endif; ?>

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

                                                <form
                                                    method="post"
                                                    action="galeri.php?a=delete"
                                                    class="galeri-delete-form"
                                                    onsubmit="return confirm('Yakin ingin menghapus media galeri ini? Data yang dihapus 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="galeri-btn galeri-btn-small galeri-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="galeri-header">
            <div class="galeri-header-left">
                <p class="galeri-eyebrow">
                    <i class="<?= $isEdit
                        ? 'ri-edit-2-fill'
                        : 'ri-image-add-fill' ?>"></i>

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

                <h2>
                    <i class="ri-image-2-fill galeri-title-icon"></i>

                    <?= $isEdit
                        ? 'Edit Media Galeri'
                        : 'Tambah Media Galeri' ?>
                </h2>

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

                    <?= $isEdit
                        ? 'Perbarui judul atau sumber media galeri.'
                        : 'Tambahkan foto unggahan atau video dari link YouTube.' ?>
                </p>
            </div>

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


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


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

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

                        <p>
                            Pilih satu sumber media: unggah foto atau masukkan link YouTube.
                        </p>
                    </div>
                </div>
            </div>

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

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


                    <div class="galeri-section">
                        <i class="ri-file-text-fill"></i>
                        Informasi Galeri
                    </div>

                    <div class="galeri-field galeri-field-full">
                        <label for="title">
                            Judul Galeri
                            <span class="galeri-required">*</span>
                        </label>

                        <input
                            type="text"
                            class="galeri-input"
                            id="title"
                            name="title"
                            value="<?= esc($titleValue) ?>"
                            placeholder="Contoh: Kegiatan Gotong Royong Desa"
                            maxlength="200"
                            required
                        >
                    </div>


                    <div class="galeri-section">
                        <i class="ri-gallery-fill"></i>
                        Sumber Media
                    </div>

                    <div class="galeri-media-switch" role="radiogroup" aria-label="Pilih jenis media galeri">
                        <label class="galeri-media-option">
                            <input
                                type="radio"
                                name="media_type"
                                value="image"
                                <?= $mediaTypeValue === 'image' ? 'checked' : '' ?>
                            >
                            <span><i class="ri-image-add-line"></i> Unggah Foto</span>
                        </label>

                        <label class="galeri-media-option">
                            <input
                                type="radio"
                                name="media_type"
                                value="youtube"
                                <?= $mediaTypeValue === 'youtube' ? 'checked' : '' ?>
                            >
                            <span><i class="ri-youtube-line"></i> Video YouTube</span>
                        </label>
                    </div>

                    <div
                        class="galeri-field galeri-field-full"
                        id="imageMediaPanel"
                        <?= $mediaTypeValue !== 'image' ? 'hidden' : '' ?>
                    >
                        <div class="galeri-upload-box">
                            <label for="image">
                                <?= $isEdit
                                    ? 'Ganti Gambar'
                                    : 'Pilih Gambar' ?>

                                <?php if (!$isEdit): ?>
                                    <span class="galeri-required">*</span>
                                <?php endif; ?>
                            </label>

                            <input
                                type="file"
                                class="galeri-input"
                                id="image"
                                name="image"
                                accept=".jpg,.jpeg,.png,.webp,.gif,image/jpeg,image/png,image/webp,image/gif"
                                <?= !$isEdit && $mediaTypeValue === 'image' ? 'required' : '' ?>
                            >

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

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

                                <div
                                    id="imagePlaceholder"
                                    class="galeri-preview-placeholder"
                                    style="display:none"
                                >
                                    <i class="ri-image-line"></i>
                                </div>
                            <?php else: ?>
                                <div
                                    id="imagePlaceholder"
                                    class="galeri-preview-placeholder"
                                >
                                    <i class="ri-image-line"></i>
                                </div>

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

                    <div
                        class="galeri-field galeri-field-full"
                        id="youtubeMediaPanel"
                        <?= $mediaTypeValue !== 'youtube' ? 'hidden' : '' ?>
                    >
                        <div class="galeri-youtube-box">
                            <label for="youtubeUrl">
                                Link Video YouTube
                                <span class="galeri-required">*</span>
                            </label>

                            <input
                                type="url"
                                class="galeri-input"
                                id="youtubeUrl"
                                name="youtube_url"
                                value="<?= esc($youtubeValue) ?>"
                                placeholder="https://www.youtube.com/watch?v=xxxxxxxxxxx"
                                maxlength="255"
                                inputmode="url"
                                autocomplete="url"
                                <?= $mediaTypeValue === 'youtube' ? 'required' : '' ?>
                            >

                            <p class="galeri-help">
                                Mendukung link youtube.com, YouTube Shorts, dan youtu.be.
                                Pratinjau akan muncul setelah link video valid.
                            </p>

                            <?php $youtubeEmbedValue = galeri_youtube_embed($youtubeValue); ?>
                            <div class="galeri-youtube-preview" id="youtubePreview">
                                <div
                                    class="galeri-youtube-placeholder"
                                    id="youtubePlaceholder"
                                    <?= $youtubeEmbedValue !== '' ? 'hidden' : '' ?>
                                >
                                    <i class="ri-video-line"></i>
                                    <span>Masukkan link YouTube untuk melihat pratinjau.</span>
                                </div>
                                <iframe
                                    id="youtubeFrame"
                                    src="<?= esc($youtubeEmbedValue) ?>"
                                    title="Pratinjau video YouTube"
                                    loading="lazy"
                                    referrerpolicy="strict-origin-when-cross-origin"
                                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                                    allowfullscreen
                                    <?= $youtubeEmbedValue === '' ? 'hidden' : '' ?>
                                ></iframe>
                            </div>
                        </div>
                    </div>


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

                        <span>
                            Pilih salah satu sumber media. Jika jenis media diubah dari foto
                            menjadi video YouTube, file foto lama akan dihapus setelah data
                            berhasil diperbarui. Link YouTube harus mengarah langsung ke video.
                        </span>
                    </div>

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

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

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

    <?php endif; ?>

</div>


<div
    class="galeri-modal"
    id="galeriModal"
    onclick="tutupGaleriModal(event)"
>
    <div class="galeri-modal-content">
        <button
            type="button"
            class="galeri-modal-close"
            onclick="tutupGaleriModalLangsung()"
            aria-label="Tutup"
        >
            <i class="ri-close-line"></i>
        </button>

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


<script>
(() => {
    const searchInput = document.querySelector(
        '.galeri-search input'
    );

    let searchTimer = null;

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

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


    const imageInput = document.getElementById('image');
    const imagePreview = document.getElementById(
        'imagePreview'
    );
    const imagePlaceholder = document.getElementById(
        'imagePlaceholder'
    );

    if (imageInput && imagePreview) {
        imageInput.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(
                    'Format gambar harus 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) {
                imagePreview.src = event.target.result;
                imagePreview.style.display = 'block';

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

            reader.readAsDataURL(file);
        });
    }


    const mediaTypeInputs = document.querySelectorAll(
        'input[name="media_type"]'
    );
    const imageMediaPanel = document.getElementById(
        'imageMediaPanel'
    );
    const youtubeMediaPanel = document.getElementById(
        'youtubeMediaPanel'
    );
    const youtubeInput = document.getElementById(
        'youtubeUrl'
    );
    const youtubeFrame = document.getElementById(
        'youtubeFrame'
    );
    const youtubePlaceholder = document.getElementById(
        'youtubePlaceholder'
    );
    const imageCanRemain = <?= $imageValue !== '' ? 'true' : 'false' ?>;

    function youtubeIdFromUrl(value) {
        let raw = String(value || '').trim();

        if (/^[a-zA-Z0-9_-]{11}$/.test(raw)) {
            return raw;
        }

        if (!/^https?:\/\//i.test(raw)) {
            raw = 'https://' + raw;
        }

        try {
            const parsed = new URL(raw);
            const host = parsed.hostname.toLowerCase().replace(/^www\./, '');
            const path = parsed.pathname;
            let id = '';

            if (host === 'youtu.be') {
                id = path.replace(/^\//, '').split('/')[0] || '';
            } else if ([
                'youtube.com',
                'm.youtube.com',
                'music.youtube.com',
                'youtube-nocookie.com'
            ].includes(host)) {
                if (path === '/watch') {
                    id = parsed.searchParams.get('v') || '';
                } else {
                    const match = path.match(/^\/(?:embed|shorts|live)\/([a-zA-Z0-9_-]{11})(?:\/|$)/);
                    id = match ? match[1] : '';
                }
            }

            return /^[a-zA-Z0-9_-]{11}$/.test(id) ? id : '';
        } catch (error) {
            return '';
        }
    }

    function updateYoutubePreview() {
        if (!youtubeInput || !youtubeFrame || !youtubePlaceholder) {
            return;
        }

        const videoId = youtubeIdFromUrl(youtubeInput.value);
        const youtubeMode = document.querySelector(
            'input[name="media_type"]:checked'
        )?.value === 'youtube';

        youtubeInput.setCustomValidity(
            youtubeMode && youtubeInput.value.trim() !== '' && videoId === ''
                ? 'Masukkan link video YouTube yang valid.'
                : ''
        );

        if (videoId !== '') {
            const embedUrl = 'https://www.youtube-nocookie.com/embed/' + videoId + '?rel=0';
            if (youtubeFrame.src !== embedUrl) {
                youtubeFrame.src = embedUrl;
            }
            youtubeFrame.hidden = false;
            youtubePlaceholder.hidden = true;
        } else {
            youtubeFrame.hidden = true;
            youtubeFrame.removeAttribute('src');
            youtubePlaceholder.hidden = false;
        }
    }

    function syncMediaType() {
        const selected = document.querySelector(
            'input[name="media_type"]:checked'
        )?.value || 'image';
        const youtubeMode = selected === 'youtube';

        if (imageMediaPanel) imageMediaPanel.hidden = youtubeMode;
        if (youtubeMediaPanel) youtubeMediaPanel.hidden = !youtubeMode;
        if (imageInput) imageInput.required = !youtubeMode && !imageCanRemain;
        if (youtubeInput) youtubeInput.required = youtubeMode;

        if (youtubeMode) {
            updateYoutubePreview();
        } else if (youtubeInput) {
            youtubeInput.setCustomValidity('');
        }
    }

    mediaTypeInputs.forEach(function (input) {
        input.addEventListener('change', syncMediaType);
    });

    youtubeInput?.addEventListener('input', updateYoutubePreview);
    syncMediaType();


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

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


function bukaGaleriModal(url, judul)
{
    const modal = document.getElementById(
        'galeriModal'
    );

    const image = document.getElementById(
        'galeriModalImage'
    );

    if (!modal || !image) {
        return;
    }

    image.src = url;
    image.alt = judul || 'Foto galeri';

    modal.classList.add('active');

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


function tutupGaleriModal(event)
{
    const modal = document.getElementById(
        'galeriModal'
    );

    if (
        modal &&
        event.target === modal
    ) {
        tutupGaleriModalLangsung();
    }
}


function tutupGaleriModalLangsung()
{
    const modal = document.getElementById(
        'galeriModal'
    );

    const image = document.getElementById(
        'galeriModalImage'
    );

    if (modal) {
        modal.classList.remove('active');
    }

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

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


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

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