<?php
/**
 * admin/galleries.php
 *
 * Pure Chemical
 * Gallery Management
 *
 * Uses existing `galleries` table only.
 * No new tables are created.
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (function_exists('requireAdmin')) {
    requireAdmin();
}

if (file_exists(__DIR__ . '/includes/csrf.php')) {
    require_once __DIR__ . '/includes/csrf.php';
}

/* =========================================================
   HELPERS
========================================================= */

function h($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function slugifyGallery($text)
{
    $text = trim((string)$text);

    if ($text === '') {
        return '';
    }

    $text = html_entity_decode(
        $text,
        ENT_QUOTES,
        'UTF-8'
    );

    $text = preg_replace(
        '/[^\pL\pN]+/u',
        '-',
        $text
    );

    $text = trim($text, '-');

    $text = function_exists('mb_strtolower')
        ? mb_strtolower($text, 'UTF-8')
        : strtolower($text);

    return $text;
}

function getCsrfTokenGallery()
{
    if (function_exists('csrf_token')) {
        return csrf_token();
    }

    if (empty($_SESSION['gallery_csrf_token'])) {
        $_SESSION['gallery_csrf_token'] =
            bin2hex(random_bytes(32));
    }

    return $_SESSION['gallery_csrf_token'];
}

function verifyCsrfGallery($token)
{
    if (function_exists('csrf_verify')) {
        return csrf_verify($token);
    }

    if (empty($_SESSION['gallery_csrf_token'])) {
        return false;
    }

    return hash_equals(
        $_SESSION['gallery_csrf_token'],
        (string)$token
    );
}

function galleryFlash($type, $message)
{
    $_SESSION['gallery_flash'] = [
        'type' => $type,
        'message' => $message
    ];
}

function getGalleryFlash()
{
    $flash = $_SESSION['gallery_flash'] ?? null;

    unset($_SESSION['gallery_flash']);

    return $flash;
}

function galleryRedirect($query = '')
{
    $url = basename($_SERVER['PHP_SELF']);

    if ($query !== '') {
        $url .= '?' . ltrim($query, '?');
    }

    header('Location: ' . $url);
    exit;
}

function galleryPageUrl($page)
{
    $query = $_GET;

    $query['page'] = $page;

    return '?' . http_build_query($query);
}


/* =========================================================
   CSRF
========================================================= */

$csrfToken = getCsrfTokenGallery();


/* =========================================================
   POST ACTIONS
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $postedToken = $_POST['csrf_token'] ?? '';

    if (!verifyCsrfGallery($postedToken)) {

        galleryFlash(
            'error',
            'Security token expired. Please try again.'
        );

        galleryRedirect();
    }

    $action = $_POST['action'] ?? '';


    /* =====================================================
       SAVE GALLERY
    ===================================================== */

    if ($action === 'save') {

        $id = isset($_POST['id'])
            ? (int)$_POST['id']
            : 0;

        $name = trim(
            $_POST['name'] ?? ''
        );

        $slug = trim(
            $_POST['slug'] ?? ''
        );

        $description = trim(
            $_POST['description'] ?? ''
        );

        $coverImageIdRaw = trim(
            $_POST['cover_image_id'] ?? ''
        );

        $coverImageId =
            $coverImageIdRaw !== ''
                ? (int)$coverImageIdRaw
                : null;

        $status = isset($_POST['status'])
            ? 1
            : 0;


        /* ---------------------------------------------
           Validation
        --------------------------------------------- */

        $errors = [];

        if ($name === '') {
            $errors[] = 'Gallery name is required.';
        }

        /*
         * If slug is empty, generate from name.
         */
        if ($slug === '') {
            $slug = slugifyGallery($name);
        } else {
            $slug = slugifyGallery($slug);
        }

        if ($slug === '') {
            $errors[] = 'A valid gallery slug is required.';
        }

        if (
            $coverImageId !== null &&
            $coverImageId < 1
        ) {
            $coverImageId = null;
        }

        /*
         * Optional cover image upload. The uploaded file is
         * registered in the existing media table, then linked
         * through galleries.cover_image_id.
         */
        if (
            isset($_FILES['cover_image']) &&
            ($_FILES['cover_image']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE
        ) {
            $upload = $_FILES['cover_image'];
            $uploadError = (int)($upload['error'] ?? UPLOAD_ERR_NO_FILE);

            if ($uploadError !== UPLOAD_ERR_OK) {
                galleryFlash('error', 'Cover image upload failed. Please try again.');
                galleryRedirect($id > 0 ? 'edit=' . $id : 'add=1');
            }

            if ((int)($upload['size'] ?? 0) > 8 * 1024 * 1024) {
                galleryFlash('error', 'Cover image must be 8 MB or smaller.');
                galleryRedirect($id > 0 ? 'edit=' . $id : 'add=1');
            }

            $imageInfo = @getimagesize($upload['tmp_name'] ?? '');
            $allowedMimeTypes = [
                'image/jpeg' => 'jpg',
                'image/png'  => 'png',
                'image/gif'  => 'gif',
                'image/webp' => 'webp',
            ];

            $mimeType = is_array($imageInfo) ? (string)($imageInfo['mime'] ?? '') : '';

            if (!$imageInfo || !isset($allowedMimeTypes[$mimeType]) || !is_uploaded_file($upload['tmp_name'] ?? '')) {
                galleryFlash('error', 'Please upload a valid JPG, PNG, GIF, or WEBP image.');
                galleryRedirect($id > 0 ? 'edit=' . $id : 'add=1');
            }

            $projectRoot = dirname(__DIR__);
            $uploadDirectory = $projectRoot . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'media';

            if (!is_dir($uploadDirectory) && !@mkdir($uploadDirectory, 0755, true) && !is_dir($uploadDirectory)) {
                galleryFlash('error', 'Upload folder could not be created. Check folder permissions.');
                galleryRedirect($id > 0 ? 'edit=' . $id : 'add=1');
            }

            $extension = $allowedMimeTypes[$mimeType];
            $fileName = 'gallery_cover_' . bin2hex(random_bytes(12)) . '.' . $extension;
            $destination = $uploadDirectory . DIRECTORY_SEPARATOR . $fileName;
            $relativePath = 'uploads/media/' . $fileName;

            if (!move_uploaded_file($upload['tmp_name'], $destination)) {
                galleryFlash('error', 'Image could not be saved. Check uploads/media folder permissions.');
                galleryRedirect($id > 0 ? 'edit=' . $id : 'add=1');
            }

            try {
                $mediaStmt = $pdo->prepare("
                    INSERT INTO media
                    (
                        original_name, file_name, file_path, mime_type,
                        file_type, extension, file_size, width, height,
                        alt_text, title, uploaded_by, status
                    )
                    VALUES
                    (
                        :original_name, :file_name, :file_path, :mime_type,
                        'image', :extension, :file_size, :width, :height,
                        :alt_text, :title, NULL, 1
                    )
                ");

                $mediaStmt->execute([
                    ':original_name' => basename((string)($upload['name'] ?? $fileName)),
                    ':file_name' => $fileName,
                    ':file_path' => $relativePath,
                    ':mime_type' => $mimeType,
                    ':extension' => $extension,
                    ':file_size' => (int)filesize($destination),
                    ':width' => (int)$imageInfo[0],
                    ':height' => (int)$imageInfo[1],
                    ':alt_text' => $name,
                    ':title' => $name,
                ]);

                $coverImageId = (int)$pdo->lastInsertId();
            } catch (Throwable $e) {
                @unlink($destination);
                error_log('Gallery Cover Media Insert Error: ' . $e->getMessage());
                galleryFlash('error', 'Image upload failed while saving to the media library. Check the media table structure.');
                galleryRedirect($id > 0 ? 'edit=' . $id : 'add=1');
            }
        }

        /* Validate that a selected cover ID exists and is an image. */
        if ($coverImageId !== null) {
            try {
                $mediaCheck = $pdo->prepare("
                    SELECT id FROM media
                    WHERE id = :id AND file_type = 'image' AND status = 1
                    LIMIT 1
                ");
                $mediaCheck->execute([':id' => $coverImageId]);
                if (!$mediaCheck->fetchColumn()) {
                    galleryFlash('error', 'Selected cover image was not found in the active media library.');
                    galleryRedirect($id > 0 ? 'edit=' . $id : 'add=1');
                }
            } catch (Throwable $e) {
                error_log('Gallery Cover Validation Error: ' . $e->getMessage());
                galleryFlash('error', 'Unable to validate the selected cover image.');
                galleryRedirect($id > 0 ? 'edit=' . $id : 'add=1');
            }
        }


        /* ---------------------------------------------
           Duplicate Slug Check
        --------------------------------------------- */

        if (empty($errors)) {

            try {

                $duplicateSql = "
                    SELECT id
                    FROM galleries
                    WHERE slug = :slug
                ";

                $duplicateParams = [
                    ':slug' => $slug
                ];

                if ($id > 0) {

                    $duplicateSql .= "
                        AND id != :id
                    ";

                    $duplicateParams[':id'] = $id;
                }

                $duplicateSql .= "
                    LIMIT 1
                ";

                $stmt = $pdo->prepare(
                    $duplicateSql
                );

                $stmt->execute(
                    $duplicateParams
                );

                if ($stmt->fetch()) {
                    $errors[] =
                        'This gallery slug already exists.';
                }

            } catch (PDOException $e) {

                error_log(
                    'Gallery Slug Check Error: ' .
                    $e->getMessage()
                );

                $errors[] =
                    'Unable to validate gallery slug.';
            }
        }


        if (!empty($errors)) {

            galleryFlash(
                'error',
                implode(' ', $errors)
            );

            galleryRedirect(
                $id > 0
                    ? 'edit=' . $id
                    : 'add=1'
            );
        }


        /* ---------------------------------------------
           INSERT / UPDATE
        --------------------------------------------- */

        try {

            if ($id > 0) {

                $stmt = $pdo->prepare("
                    UPDATE galleries
                    SET
                        name = :name,
                        slug = :slug,
                        description = :description,
                        cover_image_id = :cover_image_id,
                        status = :status
                    WHERE id = :id
                    LIMIT 1
                ");

                $stmt->execute([
                    ':name' => $name,
                    ':slug' => $slug,
                    ':description' =>
                        $description !== ''
                            ? $description
                            : null,
                    ':cover_image_id' =>
                        $coverImageId,
                    ':status' => $status,
                    ':id' => $id
                ]);

                galleryFlash(
                    'success',
                    'Gallery updated successfully.'
                );

            } else {

                $stmt = $pdo->prepare("
                    INSERT INTO galleries
                    (
                        name,
                        slug,
                        description,
                        cover_image_id,
                        status
                    )
                    VALUES
                    (
                        :name,
                        :slug,
                        :description,
                        :cover_image_id,
                        :status
                    )
                ");

                $stmt->execute([
                    ':name' => $name,
                    ':slug' => $slug,
                    ':description' =>
                        $description !== ''
                            ? $description
                            : null,
                    ':cover_image_id' =>
                        $coverImageId,
                    ':status' => $status
                ]);

                galleryFlash(
                    'success',
                    'Gallery created successfully.'
                );
            }

        } catch (PDOException $e) {

            error_log(
                'Gallery Save Error: ' .
                $e->getMessage()
            );

            galleryFlash(
                'error',
                'Unable to save gallery. Please try again.'
            );
        }

        galleryRedirect();
    }


    /* =====================================================
       DELETE
    ===================================================== */

    if ($action === 'delete') {

        $id = (int)(
            $_POST['id'] ?? 0
        );

        if ($id < 1) {

            galleryFlash(
                'error',
                'Invalid gallery ID.'
            );

            galleryRedirect();
        }

        try {

            $stmt = $pdo->prepare("
                DELETE FROM galleries
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $id
            ]);

            galleryFlash(
                'success',
                'Gallery deleted successfully.'
            );

        } catch (PDOException $e) {

            error_log(
                'Gallery Delete Error: ' .
                $e->getMessage()
            );

            galleryFlash(
                'error',
                'Unable to delete gallery.'
            );
        }

        galleryRedirect();
    }


    /* =====================================================
       TOGGLE STATUS
    ===================================================== */

    if ($action === 'toggle_status') {

        $id = (int)(
            $_POST['id'] ?? 0
        );

        if ($id < 1) {

            galleryFlash(
                'error',
                'Invalid gallery ID.'
            );

            galleryRedirect();
        }

        try {

            $stmt = $pdo->prepare("
                UPDATE galleries
                SET status =
                    CASE
                        WHEN status = 1 THEN 0
                        ELSE 1
                    END
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $id
            ]);

            galleryFlash(
                'success',
                'Gallery status updated.'
            );

        } catch (PDOException $e) {

            error_log(
                'Gallery Status Error: ' .
                $e->getMessage()
            );

            galleryFlash(
                'error',
                'Unable to update gallery status.'
            );
        }

        galleryRedirect();
    }
}


/* =========================================================
   EDIT RECORD
========================================================= */

$editId = isset($_GET['edit'])
    ? (int)$_GET['edit']
    : 0;

$editGallery = null;

if ($editId > 0) {

    $stmt = $pdo->prepare("
        SELECT
            id,
            name,
            slug,
            description,
            cover_image_id,
            status,
            created_at,
            updated_at
        FROM galleries
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':id' => $editId
    ]);

    $editGallery = $stmt->fetch();

    if (!$editGallery) {

        galleryFlash(
            'error',
            'Gallery not found.'
        );

        galleryRedirect();
    }
}


/* =========================================================
   FILTERS
========================================================= */

$search = trim(
    $_GET['search'] ?? ''
);

$statusFilter = $_GET['status'] ?? '';

$page = max(
    1,
    (int)($_GET['page'] ?? 1)
);

$perPageOptions = [
    10,
    20,
    30,
    50
];

$perPage = (int)(
    $_GET['per_page'] ?? 20
);

if (!in_array(
    $perPage,
    $perPageOptions,
    true
)) {
    $perPage = 20;
}

$offset =
    ($page - 1) * $perPage;


/* =========================================================
   STATS
========================================================= */

$stats = [
    'total' => 0,
    'active' => 0,
    'inactive' => 0
];

try {

    $stmt = $pdo->query("
        SELECT
            COUNT(*) AS total,
            COALESCE(
                SUM(status = 1),
                0
            ) AS active,
            COALESCE(
                SUM(status = 0),
                0
            ) AS inactive
        FROM galleries
    ");

    $result = $stmt->fetch();

    if ($result) {
        $stats = $result;
    }

} catch (PDOException $e) {

    error_log(
        'Gallery Stats Error: ' .
        $e->getMessage()
    );
}


/* =========================================================
   BUILD WHERE
========================================================= */

$where = [];

$params = [];

if ($search !== '') {

    $where[] = "
        (
            name LIKE :search
            OR slug LIKE :search
            OR description LIKE :search
        )
    ";

    $params[':search'] =
        '%' . $search . '%';
}

if (
    $statusFilter !== '' &&
    in_array(
        $statusFilter,
        ['0', '1'],
        true
    )
) {

    $where[] =
        "status = :status";

    $params[':status'] =
        (int)$statusFilter;
}

$whereSql = '';

if (!empty($where)) {

    $whereSql =
        'WHERE ' .
        implode(
            ' AND ',
            $where
        );
}


/* =========================================================
   TOTAL ROWS
========================================================= */

$totalRows = 0;

try {

    $countSql = "
        SELECT COUNT(*)
        FROM galleries
        {$whereSql}
    ";

    $stmt = $pdo->prepare(
        $countSql
    );

    $stmt->execute(
        $params
    );

    $totalRows =
        (int)$stmt->fetchColumn();

} catch (PDOException $e) {

    error_log(
        'Gallery Count Error: ' .
        $e->getMessage()
    );
}

$totalPages = max(
    1,
    (int)ceil(
        $totalRows / $perPage
    )
);

if ($page > $totalPages) {

    $page = $totalPages;

    $offset =
        ($page - 1) * $perPage;
}


/* =========================================================
   GALLERIES
========================================================= */

$galleries = [];

try {

    $sql = "
        SELECT
            id,
            name,
            slug,
            description,
            cover_image_id,
            status,
            created_at,
            updated_at
        FROM galleries
        {$whereSql}
        ORDER BY
            id DESC
        LIMIT :limit
        OFFSET :offset
    ";

    $stmt = $pdo->prepare($sql);

    foreach ($params as $key => $value) {

        $stmt->bindValue(
            $key,
            $value,
            is_int($value)
                ? PDO::PARAM_INT
                : PDO::PARAM_STR
        );
    }

    $stmt->bindValue(
        ':limit',
        $perPage,
        PDO::PARAM_INT
    );

    $stmt->bindValue(
        ':offset',
        $offset,
        PDO::PARAM_INT
    );

    $stmt->execute();

    $galleries =
        $stmt->fetchAll();

} catch (PDOException $e) {

    error_log(
        'Gallery List Error: ' .
        $e->getMessage()
    );
}


/* =========================================================
   FLASH
========================================================= */

$flash =
    getGalleryFlash();


/* =========================================================
   FORM DATA
========================================================= */

$formData = [
    'id' => 0,
    'name' => '',
    'slug' => '',
    'description' => '',
    'cover_image_id' => '',
    'status' => 1
];

if ($editGallery) {

    $formData = [
        'id' =>
            (int)$editGallery['id'],

        'name' =>
            $editGallery['name'],

        'slug' =>
            $editGallery['slug'],

        'description' =>
            $editGallery['description'],

        'cover_image_id' =>
            $editGallery['cover_image_id'],

        'status' =>
            (int)$editGallery['status']
    ];
}

/* Active images available in the existing Media Library. */
$galleryMediaImages = [];
$galleryMediaById = [];

try {
    $mediaStmt = $pdo->query("
        SELECT id, original_name, file_name, file_path, mime_type, title
        FROM media
        WHERE file_type = 'image' AND status = 1
        ORDER BY id DESC
        LIMIT 1000
    ");
    $galleryMediaImages = $mediaStmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($galleryMediaImages as $mediaImage) {
        $galleryMediaById[(int)$mediaImage['id']] = $mediaImage;
    }
} catch (Throwable $e) {
    error_log('Gallery Media List Error: ' . $e->getMessage());
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Galleries | Pure Chemical Admin
    </title>

    <meta
        name="theme-color"
        content="#0f172a"
    >

    <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
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >

    <style>

        :root {

            --primary: #0f766e;
            --primary-dark: #115e59;
            --primary-light: #ccfbf1;

            --dark: #0f172a;
            --dark-2: #1e293b;

            --muted: #64748b;
            --muted-light: #94a3b8;

            --bg: #f8fafc;
            --white: #ffffff;

            --border: #e2e8f0;

            --success: #15803d;
            --success-bg: #dcfce7;

            --danger: #dc2626;
            --danger-bg: #fee2e2;

            --blue: #2563eb;
            --blue-bg: #dbeafe;

            --shadow-sm:
                0 1px 2px rgba(15, 23, 42, .05);

            --shadow:
                0 12px 35px rgba(15, 23, 42, .07);

            --radius: 18px;
        }


        * {
            box-sizing: border-box;
        }


        html {
            scroll-behavior: smooth;
        }


        body {

            margin: 0;

            background: var(--bg);

            color: var(--dark);

            font-family:
                Inter,
                system-ui,
                -apple-system,
                BlinkMacSystemFont,
                "Segoe UI",
                sans-serif;
        }


        button,
        input,
        textarea,
        select {
            font-family: inherit;
        }


        button {
            cursor: pointer;
        }


        a {
            color: inherit;
            text-decoration: none;
        }


        /* =====================================================
           LAYOUT
        ===================================================== */

        .page-shell {

            min-height: 100vh;

            margin-left: 280px;
        }


        .topbar {

            position: sticky;

            top: 0;

            z-index: 100;

            height: 76px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            padding: 0 30px;

            background:
                rgba(255,255,255,.92);

            backdrop-filter:
                blur(18px);

            border-bottom:
                1px solid rgba(226,232,240,.9);
        }


        .topbar-left {

            display: flex;

            align-items: center;

            gap: 14px;
        }


        .page-icon {

            width: 44px;
            height: 44px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 14px;

            background:
                linear-gradient(
                    135deg,
                    #0f766e,
                    #14b8a6
                );

            color: white;

            box-shadow:
                0 8px 20px
                rgba(13,148,136,.22);
        }


        .topbar-title {

            font-size: 16px;

            font-weight: 800;

            letter-spacing: -.02em;
        }


        .topbar-subtitle {

            margin-top: 3px;

            color: var(--muted);

            font-size: 12px;
        }


        .topbar-right {

            display: flex;

            align-items: center;

            gap: 10px;
        }


        .admin-pill {

            display: flex;

            align-items: center;

            gap: 9px;

            padding: 8px 12px;

            border:
                1px solid var(--border);

            border-radius: 12px;

            background: white;
        }


        .admin-avatar {

            width: 32px;
            height: 32px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 10px;

            background: var(--dark);

            color: white;

            font-size: 12px;

            font-weight: 800;
        }


        .admin-name {

            font-size: 12px;

            font-weight: 700;
        }


        /* =====================================================
           CONTENT
        ===================================================== */

        .content {

            max-width: 1700px;

            margin: 0 auto;

            padding: 30px;
        }


        .hero {

            display: flex;

            align-items: flex-end;

            justify-content: space-between;

            gap: 25px;

            margin-bottom: 25px;
        }


        .hero h1 {

            margin: 0;

            font-size: 31px;

            line-height: 1.15;

            letter-spacing: -.04em;
        }


        .hero p {

            max-width: 720px;

            margin: 9px 0 0;

            color: var(--muted);

            font-size: 14px;

            line-height: 1.7;
        }


        .hero-actions {

            display: flex;

            gap: 10px;
        }


        /* =====================================================
           BUTTONS
        ===================================================== */

        .btn {

            min-height: 42px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            gap: 8px;

            padding: 0 15px;

            border:
                1px solid transparent;

            border-radius: 12px;

            font-size: 13px;

            font-weight: 700;

            transition:
                .18s ease;
        }


        .btn:hover {

            transform:
                translateY(-1px);
        }


        .btn-primary {

            color: white;

            background:
                linear-gradient(
                    135deg,
                    #0f766e,
                    #0d9488
                );

            box-shadow:
                0 8px 18px
                rgba(13,148,136,.18);
        }


        .btn-secondary {

            color: var(--dark-2);

            background: white;

            border-color:
                var(--border);
        }


        .btn-danger {

            color: var(--danger);

            background:
                var(--danger-bg);

            border-color:
                #fecaca;
        }


        .btn-sm {

            min-height: 36px;

            padding: 0 11px;

            border-radius: 10px;

            font-size: 12px;
        }


        /* =====================================================
           STATS
        ===================================================== */

        .stats-grid {

            display: grid;

            grid-template-columns:
                repeat(3, minmax(0, 1fr));

            gap: 15px;

            margin-bottom: 20px;
        }


        .stat-card {

            position: relative;

            overflow: hidden;

            padding: 20px;

            background: white;

            border:
                1px solid var(--border);

            border-radius:
                var(--radius);

            box-shadow:
                var(--shadow-sm);
        }


        .stat-card::after {

            content: "";

            position: absolute;

            width: 100px;
            height: 100px;

            right: -40px;
            bottom: -40px;

            border-radius: 50%;

            background:
                rgba(15,118,110,.06);
        }


        .stat-top {

            display: flex;

            align-items: center;

            justify-content: space-between;

            margin-bottom: 15px;
        }


        .stat-label {

            color: var(--muted);

            font-size: 11px;

            font-weight: 800;

            text-transform: uppercase;

            letter-spacing: .06em;
        }


        .stat-icon {

            width: 40px;
            height: 40px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 12px;

            background:
                var(--primary-light);

            color:
                var(--primary);
        }


        .stat-value {

            font-size: 27px;

            font-weight: 800;

            letter-spacing: -.04em;
        }


        /* =====================================================
           ALERT
        ===================================================== */

        .alert {

            display: flex;

            align-items: flex-start;

            gap: 11px;

            padding: 14px 16px;

            margin-bottom: 18px;

            border-radius: 14px;

            font-size: 13px;

            font-weight: 600;
        }


        .alert-success {

            color: #166534;

            background:
                var(--success-bg);

            border:
                1px solid #bbf7d0;
        }


        .alert-error {

            color: #991b1b;

            background:
                var(--danger-bg);

            border:
                1px solid #fecaca;
        }


        /* =====================================================
           FILTER
        ===================================================== */

        .filter-card {

            padding: 18px;

            margin-bottom: 18px;

            background: white;

            border:
                1px solid var(--border);

            border-radius:
                var(--radius);

            box-shadow:
                var(--shadow-sm);
        }


        .filter-form {

            display: grid;

            grid-template-columns:
                minmax(260px, 1fr)
                180px
                130px
                auto;

            gap: 10px;
        }


        .input-wrap {

            position: relative;
        }


        .input-icon {

            position: absolute;

            left: 13px;
            top: 50%;

            transform:
                translateY(-50%);

            color:
                var(--muted-light);

            pointer-events: none;
        }


        .form-control,
        .form-select,
        .form-textarea {

            width: 100%;

            outline: none;

            border:
                1px solid var(--border);

            border-radius: 12px;

            background: white;

            color: var(--dark);

            font-size: 13px;

            transition:
                .18s ease;
        }


        .form-control,
        .form-select {

            height: 44px;

            padding: 0 13px;
        }


        .has-icon .form-control {

            padding-left: 39px;
        }


        .form-textarea {

            min-height: 130px;

            padding: 13px;

            resize: vertical;

            line-height: 1.65;
        }


        .form-control:focus,
        .form-select:focus,
        .form-textarea:focus {

            border-color:
                #14b8a6;

            box-shadow:
                0 0 0 4px
                rgba(20,184,166,.10);
        }


        /* =====================================================
           TABLE
        ===================================================== */

        .table-card {

            overflow: hidden;

            background: white;

            border:
                1px solid var(--border);

            border-radius:
                var(--radius);

            box-shadow:
                var(--shadow-sm);
        }


        .table-header {

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 15px;

            padding: 19px 20px;

            border-bottom:
                1px solid var(--border);
        }


        .table-title {

            font-size: 14px;

            font-weight: 800;
        }


        .table-count {

            margin-top: 4px;

            color: var(--muted);

            font-size: 12px;
        }


        .table-scroll {

            overflow-x: auto;
        }


        table {

            width: 100%;

            min-width: 1050px;

            border-collapse: collapse;
        }


        th {

            padding: 13px 18px;

            background:
                #f8fafc;

            border-bottom:
                1px solid var(--border);

            color: var(--muted);

            font-size: 10px;

            font-weight: 800;

            text-align: left;

            text-transform: uppercase;

            letter-spacing: .07em;

            white-space: nowrap;
        }


        td {

            padding: 15px 18px;

            border-bottom:
                1px solid #eef2f7;

            vertical-align: middle;

            font-size: 13px;
        }


        tbody tr {

            transition:
                background .15s ease;
        }


        tbody tr:hover {

            background:
                #fbfefd;
        }


        tbody tr:last-child td {

            border-bottom: 0;
        }


        /* =====================================================
           GALLERY CELL
        ===================================================== */

        .gallery-cell {

            display: flex;

            align-items: center;

            gap: 12px;

            min-width: 260px;
        }


        .gallery-icon {

            width: 46px;
            height: 46px;

            flex: 0 0 46px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 14px;

            background:
                linear-gradient(
                    135deg,
                    #ccfbf1,
                    #99f6e4
                );

            color:
                #115e59;

            font-size: 17px;
        }


        .gallery-name {

            font-weight: 800;

            color:
                var(--dark);
        }


        .gallery-slug {

            margin-top: 4px;

            color:
                var(--muted);

            font-size: 11px;

            font-family:
                ui-monospace,
                SFMono-Regular,
                Menlo,
                Monaco,
                Consolas,
                monospace;
        }


        .description {

            max-width: 380px;

            color: #475569;

            line-height: 1.55;

            display:
                -webkit-box;

            -webkit-line-clamp: 2;

            -webkit-box-orient: vertical;

            overflow: hidden;
        }


        .cover-id {

            display: inline-flex;

            align-items: center;

            gap: 6px;

            padding: 7px 9px;

            border-radius: 9px;

            background:
                #f1f5f9;

            color:
                #475569;

            font-size: 11px;

            font-weight: 700;
        }


        /* =====================================================
           BADGES
        ===================================================== */

        .badge {

            display: inline-flex;

            align-items: center;

            gap: 6px;

            min-height: 28px;

            padding: 0 9px;

            border: 0;

            border-radius: 999px;

            font-size: 10px;

            font-weight: 800;

            white-space: nowrap;
        }


        .badge-active {

            color:
                #166534;

            background:
                var(--success-bg);
        }


        .badge-inactive {

            color:
                #991b1b;

            background:
                var(--danger-bg);
        }


        /* =====================================================
           ACTIONS
        ===================================================== */

        .actions {

            display: flex;

            align-items: center;

            gap: 7px;
        }


        .icon-btn {

            width: 34px;
            height: 34px;

            display: inline-flex;

            align-items: center;
            justify-content: center;

            border:
                1px solid var(--border);

            border-radius: 10px;

            background: white;

            color: var(--muted);

            transition:
                .18s ease;
        }


        .icon-btn:hover {

            color:
                var(--primary);

            border-color:
                #99f6e4;

            background:
                #f0fdfa;
        }


        .icon-btn.danger:hover {

            color:
                var(--danger);

            border-color:
                #fecaca;

            background:
                #fff1f2;
        }


        .inline-form {

            display: inline;

            margin: 0;

            padding: 0;
        }


        /* =====================================================
           EMPTY
        ===================================================== */

        .empty {

            padding: 70px 25px;

            text-align: center;
        }


        .empty-icon {

            width: 64px;
            height: 64px;

            display: flex;

            align-items: center;
            justify-content: center;

            margin: 0 auto 15px;

            border-radius: 18px;

            background:
                #f1f5f9;

            color:
                #94a3b8;

            font-size: 22px;
        }


        .empty h3 {

            margin: 0;

            font-size: 16px;
        }


        .empty p {

            margin: 7px 0 0;

            color:
                var(--muted);

            font-size: 13px;
        }


        /* =====================================================
           PAGINATION
        ===================================================== */

        .pagination {

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 15px;

            padding: 15px 18px;

            border-top:
                1px solid var(--border);
        }


        .pagination-info {

            color:
                var(--muted);

            font-size: 12px;
        }


        .pagination-links {

            display: flex;

            align-items: center;

            gap: 5px;
        }


        .page-link {

            min-width: 34px;

            height: 34px;

            display: inline-flex;

            align-items: center;
            justify-content: center;

            border:
                1px solid var(--border);

            border-radius: 9px;

            background: white;

            color:
                var(--muted);

            font-size: 12px;

            font-weight: 700;
        }


        .page-link:hover,
        .page-link.active {

            color: white;

            background:
                var(--primary);

            border-color:
                var(--primary);
        }


        .page-link.disabled {

            opacity: .45;

            pointer-events: none;
        }


        /* =====================================================
           MODAL
        ===================================================== */

        .modal-backdrop {

            position: fixed;

            inset: 0;

            z-index: 9999;

            display: none;

            align-items: center;

            justify-content: center;

            padding: 25px;

            background:
                rgba(15,23,42,.60);

            backdrop-filter:
                blur(7px);
        }


        .modal-backdrop.show {

            display: flex;
        }


        .modal {

            width:
                min(720px, 100%);

            max-height:
                calc(100vh - 50px);

            overflow-y: auto;

            background: white;

            border-radius: 22px;

            box-shadow:
                0 30px 80px
                rgba(15,23,42,.25);

            animation:
                modalIn .22s ease;
        }


        @keyframes modalIn {

            from {

                opacity: 0;

                transform:
                    translateY(15px)
                    scale(.98);
            }

            to {

                opacity: 1;

                transform:
                    translateY(0)
                    scale(1);
            }
        }


        .modal-header {

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 15px;

            padding: 20px 22px;

            border-bottom:
                1px solid var(--border);
        }


        .modal-title {

            font-size: 17px;

            font-weight: 800;
        }


        .modal-subtitle {

            margin-top: 4px;

            color:
                var(--muted);

            font-size: 12px;
        }


        .modal-close {

            width: 36px;
            height: 36px;

            border: 0;

            border-radius: 10px;

            background:
                #f1f5f9;

            color:
                var(--muted);
        }


        .modal-body {

            padding: 22px;
        }


        .modal-footer {

            display: flex;

            justify-content: flex-end;

            gap: 9px;

            padding: 17px 22px;

            border-top:
                1px solid var(--border);
        }


        .form-grid {

            display: grid;

            grid-template-columns:
                repeat(2, minmax(0, 1fr));

            gap: 16px;
        }


        .form-group.full {

            grid-column:
                1 / -1;
        }


        .form-label {

            display: block;

            margin-bottom: 7px;

            color:
                #334155;

            font-size: 12px;

            font-weight: 800;
        }


        .required {

            color:
                var(--danger);
        }


        .form-help {

            margin-top: 6px;

            color:
                var(--muted-light);

            font-size: 11px;

            line-height: 1.5;
        }


        .switch-box {

            display: inline-flex;

            align-items: center;

            gap: 9px;

            padding: 10px 12px;

            border:
                1px solid var(--border);

            border-radius: 12px;

            background:
                #f8fafc;

            cursor: pointer;
        }


        .switch-box input {

            accent-color:
                var(--primary);
        }


        .switch-text {

            font-size: 12px;

            font-weight: 700;
        }


        /* =====================================================
           RESPONSIVE
        ===================================================== */

        @media (max-width: 1100px) {

            .page-shell {

                margin-left: 0;
            }


            .filter-form {

                grid-template-columns:
                    1fr 1fr;
            }
        }


        @media (max-width: 800px) {

            .stats-grid {

                grid-template-columns:
                    1fr;
            }


            .hero {

                align-items:
                    flex-start;

                flex-direction:
                    column;
            }


            .hero-actions {

                width: 100%;
            }


            .hero-actions .btn {

                flex: 1;
            }
        }


        @media (max-width: 650px) {

            .topbar {

                padding:
                    0 15px;
            }


            .admin-pill {

                display: none;
            }


            .content {

                padding:
                    20px 14px;
            }


            .hero h1 {

                font-size:
                    25px;
            }


            .filter-form {

                grid-template-columns:
                    1fr;
            }


            .form-grid {

                grid-template-columns:
                    1fr;
            }


            .form-group.full {

                grid-column:
                    auto;
            }


            .modal-backdrop {

                padding:
                    10px;
            }


            .modal {

                max-height:
                    calc(100vh - 20px);

                border-radius:
                    18px;
            }


            .pagination {

                flex-direction:
                    column;

                align-items:
                    flex-start;
            }
        }

    </style>

</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| Existing Sidebar
|--------------------------------------------------------------------------
|
| Sidebar is deliberately included separately.
| No header.php is loaded here.
|
*/
require_once __DIR__ . '/sidebar.php';
?>


<div class="page-shell">

    <!-- =====================================================
         TOPBAR
    ====================================================== -->

    <header class="topbar">

        <div class="topbar-left">

            <div class="page-icon">

                <i class="fa-solid fa-images"></i>

            </div>

            <div>

                <div class="topbar-title">
                    Galleries
                </div>

                <div class="topbar-subtitle">
                    Manage website photo galleries
                </div>

            </div>

        </div>


        <div class="topbar-right">

            <div class="admin-pill">

                <?php

                $adminName =
                    $_SESSION['ADMIN_NAME']
                    ?? $_SESSION['admin_name']
                    ?? 'Admin';

                $adminInitial =
                    strtoupper(
                        substr(
                            trim($adminName),
                            0,
                            1
                        )
                    );

                ?>

                <div class="admin-avatar">

                    <?php
                    echo h(
                        $adminInitial
                    );
                    ?>

                </div>

                <div class="admin-name">

                    <?php
                    echo h(
                        $adminName
                    );
                    ?>

                </div>

            </div>

        </div>

    </header>


    <!-- =====================================================
         MAIN CONTENT
    ====================================================== -->

    <main class="content">


        <!-- HERO -->

        <section class="hero">

            <div>

                <h1>
                    Galleries
                </h1>

                <p>
                    Create and manage image galleries,
                    descriptions, cover images and
                    publishing status for your website.
                </p>

            </div>


            <div class="hero-actions">

                <button
                    type="button"
                    class="btn btn-primary"
                    onclick="openGalleryModal()"
                >

                    <i class="fa-solid fa-plus"></i>

                    Add Gallery

                </button>

            </div>

        </section>


        <!-- FLASH -->

        <?php if ($flash): ?>

            <div
                class="alert <?php
                    echo $flash['type'] === 'success'
                        ? 'alert-success'
                        : 'alert-error';
                ?>"
            >

                <i
                    class="fa-solid <?php
                        echo $flash['type'] === 'success'
                            ? 'fa-circle-check'
                            : 'fa-circle-exclamation';
                    ?>"
                ></i>

                <div>
                    <?php
                    echo h(
                        $flash['message']
                    );
                    ?>
                </div>

            </div>

        <?php endif; ?>


        <!-- =================================================
             STATS
        ================================================== -->

        <section class="stats-grid">


            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-label">
                        Total Galleries
                    </div>

                    <div class="stat-icon">

                        <i class="fa-solid fa-images"></i>

                    </div>

                </div>

                <div class="stat-value">

                    <?php
                    echo number_format(
                        (int)$stats['total']
                    );
                    ?>

                </div>

            </div>


            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-label">
                        Active
                    </div>

                    <div class="stat-icon">

                        <i class="fa-solid fa-circle-check"></i>

                    </div>

                </div>

                <div class="stat-value">

                    <?php
                    echo number_format(
                        (int)$stats['active']
                    );
                    ?>

                </div>

            </div>


            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-label">
                        Inactive
                    </div>

                    <div class="stat-icon">

                        <i class="fa-solid fa-eye-slash"></i>

                    </div>

                </div>

                <div class="stat-value">

                    <?php
                    echo number_format(
                        (int)$stats['inactive']
                    );
                    ?>

                </div>

            </div>


        </section>


        <!-- =================================================
             FILTER
        ================================================== -->

        <section class="filter-card">

            <form
                method="GET"
                class="filter-form"
            >


                <div
                    class="input-wrap has-icon"
                >

                    <i
                        class="fa-solid fa-magnifying-glass input-icon"
                    ></i>

                    <input
                        type="search"
                        name="search"
                        class="form-control"
                        value="<?php
                            echo h($search);
                        ?>"
                        placeholder="Search gallery name, slug or description..."
                    >

                </div>


                <select
                    name="status"
                    class="form-select"
                >

                    <option value="">
                        All Status
                    </option>

                    <option
                        value="1"
                        <?php
                        echo $statusFilter === '1'
                            ? 'selected'
                            : '';
                        ?>
                    >
                        Active
                    </option>

                    <option
                        value="0"
                        <?php
                        echo $statusFilter === '0'
                            ? 'selected'
                            : '';
                        ?>
                    >
                        Inactive
                    </option>

                </select>


                <select
                    name="per_page"
                    class="form-select"
                >

                    <?php foreach (
                        $perPageOptions
                        as $option
                    ): ?>

                        <option
                            value="<?php
                                echo $option;
                            ?>"
                            <?php
                            echo $perPage === $option
                                ? 'selected'
                                : '';
                            ?>
                        >

                            <?php
                            echo $option;
                            ?>

                            / page

                        </option>

                    <?php endforeach; ?>

                </select>


                <button
                    type="submit"
                    class="btn btn-secondary"
                >

                    <i class="fa-solid fa-filter"></i>

                    Filter

                </button>

            </form>

        </section>


        <!-- =================================================
             TABLE
        ================================================== -->

        <section class="table-card">


            <div class="table-header">

                <div>

                    <div class="table-title">
                        All Galleries
                    </div>

                    <div class="table-count">

                        <?php
                        echo number_format(
                            $totalRows
                        );
                        ?>

                        gallery
                        <?php
                        echo $totalRows === 1
                            ? ''
                            : 'ies';
                        ?>

                        found

                    </div>

                </div>


                <?php
                if (
                    $search !== '' ||
                    $statusFilter !== ''
                ):
                ?>

                    <a
                        href="<?php
                            echo h(
                                basename(
                                    $_SERVER['PHP_SELF']
                                )
                            );
                        ?>"
                        class="btn btn-secondary btn-sm"
                    >

                        <i class="fa-solid fa-rotate-left"></i>

                        Reset

                    </a>

                <?php endif; ?>

            </div>


            <div class="table-scroll">


                <?php if (empty($galleries)): ?>


                    <div class="empty">

                        <div class="empty-icon">

                            <i
                                class="fa-regular fa-images"
                            ></i>

                        </div>

                        <h3>
                            No galleries found
                        </h3>

                        <p>
                            Create your first gallery
                            to start managing website images.
                        </p>

                    </div>


                <?php else: ?>


                    <table>

                        <thead>

                            <tr>

                                <th>
                                    Gallery
                                </th>

                                <th>
                                    Description
                                </th>

                                <th>
                                    Cover Image
                                </th>

                                <th>
                                    Status
                                </th>

                                <th>
                                    Created
                                </th>

                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>


                        <tbody>


                        <?php foreach (
                            $galleries
                            as $gallery
                        ): ?>


                            <?php

                            $galleryName =
                                trim(
                                    (string)$gallery['name']
                                );

                            $galleryDescription =
                                trim(
                                    (string)(
                                        $gallery['description']
                                        ?? ''
                                    )
                                );

                            ?>


                            <tr>


                                <!-- GALLERY -->

                                <td>

                                    <div class="gallery-cell">

                                        <div class="gallery-icon">

                                            <i
                                                class="fa-solid fa-photo-film"
                                            ></i>

                                        </div>

                                        <div>

                                            <div class="gallery-name">

                                                <?php
                                                echo h(
                                                    $galleryName
                                                );
                                                ?>

                                            </div>

                                            <div class="gallery-slug">

                                                /
                                                <?php
                                                echo h(
                                                    $gallery['slug']
                                                );
                                                ?>

                                            </div>

                                        </div>

                                    </div>

                                </td>


                                <!-- DESCRIPTION -->

                                <td>

                                    <?php if (
                                        $galleryDescription !== ''
                                    ): ?>

                                        <div class="description">

                                            <?php
                                            echo h(
                                                $galleryDescription
                                            );
                                            ?>

                                        </div>

                                    <?php else: ?>

                                        <span
                                            style="
                                                color:#94a3b8;
                                                font-size:12px;
                                            "
                                        >
                                            No description
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- COVER IMAGE -->

                                <td>

                                    <?php
                                    if (
                                        !empty(
                                            $gallery['cover_image_id']
                                        )
                                    ):
                                    ?>

                                        <?php
                                        $coverMedia = $galleryMediaById[(int)$gallery['cover_image_id']] ?? null;
                                        ?>
                                        <?php if ($coverMedia): ?>
                                            <div style="display:flex;align-items:center;gap:9px;">
                                                <img
                                                    src="<?php echo h('../' . ltrim((string)$coverMedia['file_path'], '/')); ?>"
                                                    alt=""
                                                    style="width:54px;height:44px;object-fit:cover;border-radius:9px;border:1px solid #e2e8f0;"
                                                >
                                                <span class="cover-id">ID #<?php echo (int)$gallery['cover_image_id']; ?></span>
                                            </div>
                                        <?php else: ?>
                                            <span class="cover-id">
                                                <i class="fa-regular fa-image"></i>
                                                ID #<?php echo (int)$gallery['cover_image_id']; ?>
                                            </span>
                                        <?php endif; ?>

                                    <?php else: ?>

                                        <span
                                            style="
                                                color:#94a3b8;
                                                font-size:12px;
                                            "
                                        >
                                            No cover
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- STATUS -->

                                <td>

                                    <form
                                        method="POST"
                                        class="inline-form"
                                    >

                                        <input
                                            type="hidden"
                                            name="csrf_token"
                                            value="<?php
                                                echo h(
                                                    $csrfToken
                                                );
                                            ?>"
                                        >

                                        <input
                                            type="hidden"
                                            name="action"
                                            value="toggle_status"
                                        >

                                        <input
                                            type="hidden"
                                            name="id"
                                            value="<?php
                                                echo (int)(
                                                    $gallery['id']
                                                );
                                            ?>"
                                        >

                                        <button
                                            type="submit"
                                            class="badge <?php
                                                echo (int)(
                                                    $gallery['status']
                                                ) === 1
                                                    ? 'badge-active'
                                                    : 'badge-inactive';
                                            ?>"
                                            title="Click to change status"
                                        >

                                            <i
                                                class="fa-solid fa-circle"
                                            ></i>

                                            <?php
                                            echo (int)(
                                                $gallery['status']
                                            ) === 1
                                                ? 'Active'
                                                : 'Inactive';
                                            ?>

                                        </button>

                                    </form>

                                </td>


                                <!-- CREATED -->

                                <td>

                                    <span
                                        style="
                                            color:#64748b;
                                            font-size:12px;
                                        "
                                    >

                                        <?php
                                        if (
                                            !empty(
                                                $gallery[
                                                    'created_at'
                                                ]
                                            )
                                        ) {

                                            echo h(
                                                date(
                                                    'd M Y',
                                                    strtotime(
                                                        $gallery[
                                                            'created_at'
                                                        ]
                                                    )
                                                )
                                            );

                                        } else {

                                            echo '—';
                                        }
                                        ?>

                                    </span>

                                </td>


                                <!-- ACTIONS -->

                                <td>

                                    <div class="actions">


                                        <a
                                            href="?edit=<?php
                                                echo (int)(
                                                    $gallery['id']
                                                );
                                            ?>"
                                            class="icon-btn"
                                            title="Edit Gallery"
                                        >

                                            <i
                                                class="fa-solid fa-pen"
                                            ></i>

                                        </a>


                                        <button
                                            type="button"
                                            class="icon-btn danger"
                                            title="Delete Gallery"
                                            onclick="deleteGallery(
                                                <?php
                                                echo (int)(
                                                    $gallery['id']
                                                );
                                                ?>,
                                                '<?php
                                                echo h(
                                                    addslashes(
                                                        $galleryName
                                                    )
                                                );
                                                ?>'
                                            )"
                                        >

                                            <i
                                                class="fa-solid fa-trash"
                                            ></i>

                                        </button>


                                    </div>

                                </td>


                            </tr>


                        <?php endforeach; ?>


                        </tbody>

                    </table>


                <?php endif; ?>


            </div>


            <!-- PAGINATION -->

            <?php if (
                $totalPages > 1
            ): ?>


                <div class="pagination">


                    <div class="pagination-info">

                        Showing

                        <strong>
                            <?php
                            echo $totalRows > 0
                                ? $offset + 1
                                : 0;
                            ?>
                        </strong>

                        –

                        <strong>
                            <?php
                            echo min(
                                $offset + $perPage,
                                $totalRows
                            );
                            ?>
                        </strong>

                        of

                        <strong>
                            <?php
                            echo $totalRows;
                            ?>
                        </strong>

                    </div>


                    <div class="pagination-links">


                        <a
                            href="<?php
                                echo $page > 1
                                    ? h(
                                        galleryPageUrl(
                                            $page - 1
                                        )
                                    )
                                    : '#';
                            ?>"
                            class="page-link <?php
                                echo $page <= 1
                                    ? 'disabled'
                                    : '';
                            ?>"
                        >

                            <i
                                class="fa-solid fa-chevron-left"
                            ></i>

                        </a>


                        <?php

                        $startPage =
                            max(
                                1,
                                $page - 2
                            );

                        $endPage =
                            min(
                                $totalPages,
                                $page + 2
                            );

                        for (
                            $p = $startPage;
                            $p <= $endPage;
                            $p++
                        ):

                        ?>


                            <a
                                href="<?php
                                    echo h(
                                        galleryPageUrl(
                                            $p
                                        )
                                    );
                                ?>"
                                class="page-link <?php
                                    echo $p === $page
                                        ? 'active'
                                        : '';
                                ?>"
                            >

                                <?php
                                echo $p;
                                ?>

                            </a>


                        <?php endfor; ?>


                        <a
                            href="<?php
                                echo $page < $totalPages
                                    ? h(
                                        galleryPageUrl(
                                            $page + 1
                                        )
                                    )
                                    : '#';
                            ?>"
                            class="page-link <?php
                                echo $page >= $totalPages
                                    ? 'disabled'
                                    : '';
                            ?>"
                        >

                            <i
                                class="fa-solid fa-chevron-right"
                            ></i>

                        </a>


                    </div>

                </div>


            <?php endif; ?>


        </section>


    </main>

</div>


<!-- =========================================================
     ADD / EDIT MODAL
========================================================== -->

<div
    class="modal-backdrop <?php
        echo $editGallery
            ? 'show'
            : '';
    ?>"
    id="galleryModal"
>


    <div class="modal">


        <form
            method="POST"
            action=""
            enctype="multipart/form-data"
        >


            <input
                type="hidden"
                name="csrf_token"
                value="<?php
                    echo h(
                        $csrfToken
                    );
                ?>"
            >


            <input
                type="hidden"
                name="action"
                value="save"
            >


            <input
                type="hidden"
                name="id"
                value="<?php
                    echo (int)$formData['id'];
                ?>"
            >


            <!-- MODAL HEADER -->

            <div class="modal-header">


                <div>

                    <div class="modal-title">

                        <?php
                        echo $formData['id'] > 0
                            ? 'Edit Gallery'
                            : 'Create Gallery';
                        ?>

                    </div>

                    <div class="modal-subtitle">

                        Manage gallery information
                        and publishing settings.

                    </div>

                </div>


                <button
                    type="button"
                    class="modal-close"
                    onclick="closeGalleryModal()"
                >

                    <i
                        class="fa-solid fa-xmark"
                    ></i>

                </button>


            </div>


            <!-- MODAL BODY -->

            <div class="modal-body">


                <div class="form-grid">


                    <!-- NAME -->

                    <div class="form-group">


                        <label class="form-label">

                            Gallery Name

                            <span class="required">
                                *
                            </span>

                        </label>


                        <input
                            type="text"
                            name="name"
                            id="galleryName"
                            class="form-control"
                            maxlength="255"
                            required
                            value="<?php
                                echo h(
                                    $formData['name']
                                );
                            ?>"
                            placeholder="e.g. Manufacturing Facility"
                        >


                    </div>


                    <!-- SLUG -->

                    <div class="form-group">


                        <label class="form-label">

                            Slug

                            <span class="required">
                                *
                            </span>

                        </label>


                        <input
                            type="text"
                            name="slug"
                            id="gallerySlug"
                            class="form-control"
                            maxlength="255"
                            required
                            value="<?php
                                echo h(
                                    $formData['slug']
                                );
                            ?>"
                            placeholder="manufacturing-facility"
                        >


                        <div class="form-help">

                            Used for the gallery URL.
                            Lowercase letters and hyphens
                            are recommended.

                        </div>


                    </div>


                    <!-- DESCRIPTION -->

                    <div
                        class="form-group full"
                    >


                        <label class="form-label">

                            Description

                        </label>


                        <textarea
                            name="description"
                            class="form-textarea"
                            placeholder="Write a short description of this gallery..."
                        ><?php
                        echo h(
                            $formData['description']
                        );
                        ?></textarea>


                    </div>


                    <!-- COVER IMAGE / MEDIA LIBRARY -->

                    <div class="form-group full">

                        <label class="form-label">
                            Cover Image
                        </label>

                        <select
                            name="cover_image_id"
                            id="galleryCoverImageId"
                            class="form-select"
                        >
                            <option value="">No cover image</option>
                            <?php foreach ($galleryMediaImages as $mediaImage): ?>
                                <option
                                    value="<?php echo (int)$mediaImage['id']; ?>"
                                    data-path="<?php echo h('../' . ltrim((string)$mediaImage['file_path'], '/')); ?>"
                                    <?php echo (string)$formData['cover_image_id'] === (string)$mediaImage['id'] ? 'selected' : ''; ?>
                                >
                                    #<?php echo (int)$mediaImage['id']; ?> —
                                    <?php echo h($mediaImage['title'] ?: $mediaImage['original_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <div class="form-help">
                            Select an existing image from Media Library, or upload a new cover image below.
                        </div>

                        <div id="galleryCoverPreview" style="margin-top:12px;<?php echo empty($formData['cover_image_id']) || empty($galleryMediaById[(int)$formData['cover_image_id']]) ? 'display:none;' : ''; ?>">
                            <?php if (!empty($formData['cover_image_id']) && !empty($galleryMediaById[(int)$formData['cover_image_id']])): ?>
                                <img
                                    src="<?php echo h('../' . ltrim((string)$galleryMediaById[(int)$formData['cover_image_id']]['file_path'], '/')); ?>"
                                    alt="Selected cover image"
                                    style="width:110px;height:80px;object-fit:cover;border-radius:12px;border:1px solid #e2e8f0;"
                                >
                            <?php endif; ?>
                        </div>

                    </div>

                    <div class="form-group full">

                        <label class="form-label" for="galleryCoverUpload">
                            <i class="fa-solid fa-cloud-arrow-up"></i>
                            Upload New Cover Image
                        </label>

                        <input
                            type="file"
                            name="cover_image"
                            id="galleryCoverUpload"
                            class="form-control"
                            accept=".jpg,.jpeg,.png,.gif,.webp,image/jpeg,image/png,image/gif,image/webp"
                            style="height:auto;padding:11px;"
                        >

                        <div class="form-help">
                            JPG, PNG, GIF or WEBP · Maximum 8 MB. A newly uploaded image is added to the Media Library and linked as this gallery's cover.
                        </div>

                        <div id="galleryUploadPreview" style="display:none;margin-top:12px;">
                            <img id="galleryUploadPreviewImage" src="" alt="Upload preview" style="width:110px;height:80px;object-fit:cover;border-radius:12px;border:1px solid #e2e8f0;">
                        </div>

                    </div>


                    <!-- STATUS -->

                    <div class="form-group">


                        <label class="form-label">

                            Publishing Status

                        </label>


                        <label class="switch-box">


                            <input
                                type="checkbox"
                                name="status"
                                value="1"
                                <?php
                                echo (int)(
                                    $formData['status']
                                ) === 1
                                    ? 'checked'
                                    : '';
                                ?>
                            >


                            <span class="switch-text">

                                Active Gallery

                            </span>


                        </label>


                        <div class="form-help">

                            Inactive galleries can remain
                            stored without being published.

                        </div>


                    </div>


                </div>


            </div>


            <!-- MODAL FOOTER -->

            <div class="modal-footer">


                <button
                    type="button"
                    class="btn btn-secondary"
                    onclick="closeGalleryModal()"
                >

                    Cancel

                </button>


                <button
                    type="submit"
                    class="btn btn-primary"
                >

                    <i
                        class="fa-solid fa-check"
                    ></i>


                    <?php
                    echo $formData['id'] > 0
                        ? 'Update Gallery'
                        : 'Create Gallery';
                    ?>

                </button>


            </div>


        </form>


    </div>

</div>


<!-- =========================================================
     DELETE FORM
========================================================== -->

<form
    method="POST"
    id="deleteGalleryForm"
    style="display:none;"
>

    <input
        type="hidden"
        name="csrf_token"
        value="<?php
            echo h(
                $csrfToken
            );
        ?>"
    >


    <input
        type="hidden"
        name="action"
        value="delete"
    >


    <input
        type="hidden"
        name="id"
        id="deleteGalleryId"
        value=""
    >

</form>


<script>

/* =========================================================
   MODAL
========================================================= */

function openGalleryModal()
{
    const modal =
        document.getElementById(
            'galleryModal'
        );

    if (!modal) {
        return;
    }

    /*
     * New gallery mode.
     */
    window.history.replaceState(
        {},
        document.title,
        window.location.pathname
    );

    modal.classList.add('show');

    document.body.style.overflow =
        'hidden';
}


function closeGalleryModal()
{
    const modal =
        document.getElementById(
            'galleryModal'
        );

    if (!modal) {
        return;
    }

    /*
     * If current page was opened in edit mode,
     * return to clean listing page.
     */
    const params =
        new URLSearchParams(
            window.location.search
        );

    if (params.has('edit')) {

        window.location.href =
            window.location.pathname;

        return;
    }

    modal.classList.remove('show');

    document.body.style.overflow =
        '';
}


/* =========================================================
   DELETE
========================================================= */

function deleteGallery(id, name)
{
    const message =
        'Delete gallery "' +
        name +
        '"?\n\n' +
        'This action cannot be undone.';

    if (!window.confirm(message)) {
        return;
    }

    const idInput =
        document.getElementById(
            'deleteGalleryId'
        );

    const form =
        document.getElementById(
            'deleteGalleryForm'
        );

    if (!idInput || !form) {
        return;
    }

    idInput.value = id;

    form.submit();
}


/* =========================================================
   SLUG AUTO GENERATOR
========================================================= */

(function () {

    const nameInput =
        document.getElementById(
            'galleryName'
        );

    const slugInput =
        document.getElementById(
            'gallerySlug'
        );

    if (!nameInput || !slugInput) {
        return;
    }

    let slugManuallyChanged =
        <?php
        echo !empty($formData['slug'])
            ? 'true'
            : 'false';
        ?>;


    slugInput.addEventListener(
        'input',
        function () {

            slugManuallyChanged = true;

        }
    );


    nameInput.addEventListener(
        'input',
        function () {

            if (slugManuallyChanged) {
                return;
            }

            let value =
                this.value
                    .toLowerCase()
                    .trim()
                    .replace(
                        /[^a-z0-9]+/g,
                        '-'
                    )
                    .replace(
                        /^-+|-+$/g,
                        ''
                    );

            slugInput.value = value;

        }
    );

})();


/* =========================================================
   COVER IMAGE PREVIEWS
========================================================= */

(function () {
    const mediaSelect = document.getElementById('galleryCoverImageId');
    const uploadInput = document.getElementById('galleryCoverUpload');
    const mediaPreview = document.getElementById('galleryCoverPreview');
    const uploadPreview = document.getElementById('galleryUploadPreview');
    const uploadPreviewImage = document.getElementById('galleryUploadPreviewImage');

    if (mediaSelect && mediaPreview) {
        mediaSelect.addEventListener('change', function () {
            if (uploadInput) uploadInput.value = '';
            if (uploadPreview) uploadPreview.style.display = 'none';

            const option = this.options[this.selectedIndex];
            const path = option ? option.getAttribute('data-path') : '';
            if (!this.value || !path) {
                mediaPreview.style.display = 'none';
                mediaPreview.innerHTML = '';
                return;
            }

            mediaPreview.innerHTML = '';
            const img = document.createElement('img');
            img.src = path;
            img.alt = 'Selected cover image';
            img.style.cssText = 'width:110px;height:80px;object-fit:cover;border-radius:12px;border:1px solid #e2e8f0;';
            mediaPreview.appendChild(img);
            mediaPreview.style.display = 'block';
        });
    }

    if (uploadInput) {
        uploadInput.addEventListener('change', function () {
            if (mediaSelect && this.files && this.files.length) mediaSelect.value = '';
            const file = this.files && this.files[0];
            if (!file || !uploadPreview || !uploadPreviewImage) {
                if (uploadPreview) uploadPreview.style.display = 'none';
                return;
            }
            if (!/^image\/(jpeg|png|gif|webp)$/i.test(file.type) || file.size > 8 * 1024 * 1024) {
                alert('Choose a JPG, PNG, GIF, or WEBP image up to 8 MB.');
                this.value = '';
                uploadPreview.style.display = 'none';
                return;
            }
            uploadPreviewImage.src = URL.createObjectURL(file);
            uploadPreview.style.display = 'block';
        });
    }
})();


/* =========================================================
   ESCAPE KEY
========================================================= */

document.addEventListener(
    'keydown',
    function (event) {

        if (event.key !== 'Escape') {
            return;
        }

        const modal =
            document.getElementById(
                'galleryModal'
            );

        if (
            modal &&
            modal.classList.contains(
                'show'
            )
        ) {

            closeGalleryModal();

        }

    }
);


/* =========================================================
   CLICK OUTSIDE MODAL
========================================================= */

document
    .getElementById(
        'galleryModal'
    )
    ?.addEventListener(
        'click',
        function (event) {

            if (
                event.target === this
            ) {

                closeGalleryModal();

            }

        }
    );


/* =========================================================
   EDIT MODE SCROLL LOCK
========================================================= */

<?php if ($editGallery): ?>

document.body.style.overflow =
    'hidden';

<?php endif; ?>

</script>


</body>
</html>