<?php
/**
 * PURE CHEMICAL ADMIN
 * Gallery Items Management
 *
 * Main table:
 * gallery_items
 *
 * Related tables:
 * galleries
 * media
 */

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 (file_exists(__DIR__ . '/includes/functions.php')) {
    require_once __DIR__ . '/includes/functions.php';
}

if (file_exists(__DIR__ . '/includes/csrf.php')) {
    require_once __DIR__ . '/includes/csrf.php';
}

if (function_exists('requireAdmin')) {
    requireAdmin();
}

/* =========================================================
   HELPERS
========================================================= */

function gi_e($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function gi_post_string(string $key, string $default = ''): string
{
    return isset($_POST[$key])
        ? trim((string)$_POST[$key])
        : $default;
}

function gi_post_int(string $key, int $default = 0): int
{
    return isset($_POST[$key])
        ? (int)$_POST[$key]
        : $default;
}

function gi_get_string(string $key, string $default = ''): string
{
    return isset($_GET[$key])
        ? trim((string)$_GET[$key])
        : $default;
}

function gi_get_int(string $key, int $default = 0): int
{
    return isset($_GET[$key])
        ? (int)$_GET[$key]
        : $default;
}

function gi_csrf_field(): string
{
    if (function_exists('csrf_field')) {
        return csrf_field();
    }

    if (function_exists('csrf_token')) {
        $token = csrf_token();

        return '<input type="hidden" name="csrf_token" value="' .
            gi_e($token) .
            '">';
    }

    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }

    return '<input type="hidden" name="csrf_token" value="' .
        gi_e($_SESSION['csrf_token']) .
        '">';
}

function gi_verify_csrf(): bool
{
    if (function_exists('csrf_verify')) {
        return (bool)csrf_verify();
    }

    $token = $_POST['csrf_token'] ?? '';

    if (
        empty($_SESSION['csrf_token']) ||
        empty($token)
    ) {
        return false;
    }

    return hash_equals(
        (string)$_SESSION['csrf_token'],
        (string)$token
    );
}

function gi_redirect(array $params = []): never
{
    $url = 'gallery_items.php';

    if (!empty($params)) {
        $url .= '?' . http_build_query($params);
    }

    header('Location: ' . $url);
    exit;
}

function gi_flash(string $type, string $message): never
{
    $_SESSION['gi_flash'] = [
        'type' => $type,
        'message' => $message
    ];

    gi_redirect();
}

function gi_get_flash(): ?array
{
    if (empty($_SESSION['gi_flash'])) {
        return null;
    }

    $flash = $_SESSION['gi_flash'];

    unset($_SESSION['gi_flash']);

    return $flash;
}

/* =========================================================
   FLASH / ERRORS
========================================================= */

$flash = gi_get_flash();
$errorMessage = '';

/* =========================================================
   POST ACTIONS
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!gi_verify_csrf()) {

        $errorMessage =
            'Security verification failed. Please refresh the page and try again.';

    } else {

        $action = gi_post_string('action');

        /* =================================================
           SAVE / UPDATE
        ================================================= */

        if ($action === 'save') {

            $id = gi_post_int('id');

            $galleryId = gi_post_int('gallery_id');
            $mediaId = gi_post_int('media_id');

            $title = gi_post_string('title');
            $caption = gi_post_string('caption');

            $sortOrder = gi_post_int('sort_order', 0);
            $status = gi_post_int('status', 1);

            /* ---------------------------------------------
               Validation
            --------------------------------------------- */

            if ($galleryId <= 0) {

                $errorMessage =
                    'Please select a gallery.';

            } elseif ($mediaId <= 0) {

                $errorMessage =
                    'Please select a media file.';

            } elseif ($sortOrder < 0) {

                $errorMessage =
                    'Sort order cannot be negative.';

            } elseif (!in_array($status, [0, 1], true)) {

                $errorMessage =
                    'Invalid status selected.';
            }

            /* ---------------------------------------------
               Verify gallery
            --------------------------------------------- */

            if ($errorMessage === '') {

                $stmt = $pdo->prepare("
                    SELECT
                        id,
                        name,
                        slug,
                        description,
                        cover_image_id,
                        status
                    FROM galleries
                    WHERE id = ?
                    LIMIT 1
                ");

                $stmt->execute([$galleryId]);

                $galleryExists = $stmt->fetch();

                if (!$galleryExists) {

                    $errorMessage =
                        'Selected gallery does not exist.';
                }
            }

            /* ---------------------------------------------
               Verify media
            --------------------------------------------- */

            if ($errorMessage === '') {

                $stmt = $pdo->prepare("
                    SELECT
                        id,
                        file_name,
                        file_path,
                        mime_type,
                        title,
                        alt_text
                    FROM media
                    WHERE id = ?
                    LIMIT 1
                ");

                $stmt->execute([$mediaId]);

                $mediaExists = $stmt->fetch();

                if (!$mediaExists) {

                    $errorMessage =
                        'Selected media does not exist.';
                }
            }

            /* ---------------------------------------------
               Duplicate assignment check
            --------------------------------------------- */

            if ($errorMessage === '') {

                if ($id > 0) {

                    $stmt = $pdo->prepare("
                        SELECT id
                        FROM gallery_items
                        WHERE gallery_id = ?
                          AND media_id = ?
                          AND id <> ?
                        LIMIT 1
                    ");

                    $stmt->execute([
                        $galleryId,
                        $mediaId,
                        $id
                    ]);

                } else {

                    $stmt = $pdo->prepare("
                        SELECT id
                        FROM gallery_items
                        WHERE gallery_id = ?
                          AND media_id = ?
                        LIMIT 1
                    ");

                    $stmt->execute([
                        $galleryId,
                        $mediaId
                    ]);
                }

                if ($stmt->fetch()) {

                    $errorMessage =
                        'This media is already assigned to the selected gallery.';
                }
            }

            /* ---------------------------------------------
               Insert / Update
            --------------------------------------------- */

            if ($errorMessage === '') {

                if ($id > 0) {

                    $stmt = $pdo->prepare("
                        UPDATE gallery_items
                        SET
                            gallery_id = ?,
                            media_id = ?,
                            title = ?,
                            caption = ?,
                            sort_order = ?,
                            status = ?
                        WHERE id = ?
                        LIMIT 1
                    ");

                    $stmt->execute([
                        $galleryId,
                        $mediaId,
                        $title !== '' ? $title : null,
                        $caption !== '' ? $caption : null,
                        $sortOrder,
                        $status,
                        $id
                    ]);

                    gi_flash(
                        'success',
                        'Gallery item updated successfully.'
                    );

                } else {

                    $stmt = $pdo->prepare("
                        INSERT INTO gallery_items
                        (
                            gallery_id,
                            media_id,
                            title,
                            caption,
                            sort_order,
                            status
                        )
                        VALUES
                        (
                            ?, ?, ?, ?, ?, ?
                        )
                    ");

                    $stmt->execute([
                        $galleryId,
                        $mediaId,
                        $title !== '' ? $title : null,
                        $caption !== '' ? $caption : null,
                        $sortOrder,
                        $status
                    ]);

                    gi_flash(
                        'success',
                        'Gallery item added successfully.'
                    );
                }
            }
        }

        /* =================================================
           DELETE
        ================================================= */

        elseif ($action === 'delete') {

            $id = gi_post_int('id');

            if ($id <= 0) {

                $errorMessage =
                    'Invalid gallery item selected.';

            } else {

                $stmt = $pdo->prepare("
                    DELETE FROM gallery_items
                    WHERE id = ?
                    LIMIT 1
                ");

                $stmt->execute([$id]);

                gi_flash(
                    'success',
                    'Gallery item deleted successfully.'
                );
            }
        }

        /* =================================================
           TOGGLE STATUS
        ================================================= */

        elseif ($action === 'toggle_status') {

            $id = gi_post_int('id');

            if ($id <= 0) {

                $errorMessage =
                    'Invalid gallery item selected.';

            } else {

                $stmt = $pdo->prepare("
                    UPDATE gallery_items
                    SET status = CASE
                        WHEN status = 1 THEN 0
                        ELSE 1
                    END
                    WHERE id = ?
                    LIMIT 1
                ");

                $stmt->execute([$id]);

                gi_flash(
                    'success',
                    'Gallery item status updated successfully.'
                );
            }
        }
    }
}

/* =========================================================
   FILTERS
========================================================= */

$search = gi_get_string('search');
$filterGalleryId = gi_get_int('gallery_id');
$filterStatus = gi_get_string('status');

/* =========================================================
   LOAD GALLERIES
========================================================= */

$galleries = [];

try {

    $stmt = $pdo->query("
        SELECT
            id,
            name,
            slug,
            description,
            cover_image_id,
            status
        FROM galleries
        ORDER BY
            name ASC,
            id DESC
    ");

    $galleries = $stmt->fetchAll();

} catch (Throwable $e) {

    $galleries = [];
}

/* =========================================================
   LOAD MEDIA
========================================================= */

$mediaLibrary = [];

try {

    $stmt = $pdo->query("
        SELECT
            id,
            file_name,
            file_path,
            mime_type,
            title,
            alt_text
        FROM media
        ORDER BY id DESC
    ");

    $mediaLibrary = $stmt->fetchAll();

} catch (Throwable $e) {

    $mediaLibrary = [];
}

/* =========================================================
   EDIT RECORD
========================================================= */

$editId = gi_get_int('edit');

$editRecord = null;

if ($editId > 0) {

    $stmt = $pdo->prepare("
        SELECT
            id,
            gallery_id,
            media_id,
            title,
            caption,
            sort_order,
            status,
            created_at
        FROM gallery_items
        WHERE id = ?
        LIMIT 1
    ");

    $stmt->execute([$editId]);

    $editRecord = $stmt->fetch();

    if (!$editRecord) {
        $editId = 0;
    }
}

/* =========================================================
   STATS
========================================================= */

$stats = [
    'total' => 0,
    'active' => 0,
    'inactive' => 0,
    'galleries' => count($galleries),
    'media' => count($mediaLibrary)
];

try {

    $stmt = $pdo->query("
        SELECT
            COUNT(*) AS total,
            COALESCE(SUM(status = 1), 0) AS active,
            COALESCE(SUM(status = 0), 0) AS inactive
        FROM gallery_items
    ");

    $row = $stmt->fetch();

    if ($row) {

        $stats['total'] = (int)$row['total'];
        $stats['active'] = (int)$row['active'];
        $stats['inactive'] = (int)$row['inactive'];
    }

} catch (Throwable $e) {
    // Safe fallback
}

/* =========================================================
   LIST QUERY
========================================================= */

$listSql = "
    SELECT

        gi.id,
        gi.gallery_id,
        gi.media_id,
        gi.title,
        gi.caption,
        gi.sort_order,
        gi.status,
        gi.created_at,

        g.name AS gallery_name,
        g.slug AS gallery_slug,
        g.cover_image_id,

        m.file_name,
        m.file_path,
        m.mime_type,
        m.title AS media_title,
        m.alt_text AS media_alt_text

    FROM gallery_items gi

    INNER JOIN galleries g
        ON g.id = gi.gallery_id

    LEFT JOIN media m
        ON m.id = gi.media_id

    WHERE 1 = 1
";

$listParams = [];

/* ---------------------------------------------
   Search
--------------------------------------------- */

if ($search !== '') {

    $listSql .= "
        AND (
            gi.title LIKE ?
            OR gi.caption LIKE ?
            OR g.name LIKE ?
            OR g.slug LIKE ?
            OR m.file_name LIKE ?
            OR m.title LIKE ?
        )
    ";

    $searchLike = '%' . $search . '%';

    for ($i = 0; $i < 6; $i++) {
        $listParams[] = $searchLike;
    }
}

/* ---------------------------------------------
   Gallery
--------------------------------------------- */

if ($filterGalleryId > 0) {

    $listSql .= "
        AND gi.gallery_id = ?
    ";

    $listParams[] = $filterGalleryId;
}

/* ---------------------------------------------
   Status
--------------------------------------------- */

if (
    $filterStatus !== '' &&
    in_array($filterStatus, ['0', '1'], true)
) {

    $listSql .= "
        AND gi.status = ?
    ";

    $listParams[] = (int)$filterStatus;
}

/* ---------------------------------------------
   Order
--------------------------------------------- */

$listSql .= "
    ORDER BY
        g.name ASC,
        gi.sort_order ASC,
        gi.id DESC
";

$listStmt = $pdo->prepare($listSql);
$listStmt->execute($listParams);

$records = $listStmt->fetchAll();

/* =========================================================
   FORM
========================================================= */

$form = [
    'id' => '',
    'gallery_id' => '',
    'media_id' => '',
    'title' => '',
    'caption' => '',
    'sort_order' => 0,
    'status' => 1
];

if ($editRecord) {

    $form = [
        'id' => $editRecord['id'],
        'gallery_id' => $editRecord['gallery_id'],
        'media_id' => $editRecord['media_id'],
        'title' => $editRecord['title'],
        'caption' => $editRecord['caption'],
        'sort_order' => $editRecord['sort_order'],
        'status' => $editRecord['status']
    ];
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Gallery Items | Pure Chemical Admin
    </title>

    <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 {
            --gi-primary: #2563eb;
            --gi-primary-dark: #1d4ed8;
            --gi-bg: #f5f7fb;
            --gi-card: #ffffff;
            --gi-text: #172033;
            --gi-muted: #718096;
            --gi-border: #e6eaf0;
            --gi-success: #16a34a;
            --gi-danger: #dc2626;
            --gi-shadow:
                0 12px 40px rgba(15, 23, 42, .07);
            --gi-radius: 18px;
        }

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            background: var(--gi-bg);
            color: var(--gi-text);
            font-family: "Inter", sans-serif;
            font-size: 14px;
        }

        button,
        input,
        select,
        textarea {
            font-family: inherit;
        }

        a {
            color: inherit;
            text-decoration: none;
        }

        .gi-main {
            margin-left: 285px;
            min-height: 100vh;
        }

        .gi-topbar {
            position: sticky;
            top: 0;
            z-index: 100;
            min-height: 76px;
            padding: 0 28px;
            background: rgba(255, 255, 255, .94);
            backdrop-filter: blur(18px);
            border-bottom: 1px solid var(--gi-border);
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 20px;
        }

        .gi-top-left {
            display: flex;
            align-items: center;
            gap: 14px;
        }

        .gi-menu-btn {
            width: 42px;
            height: 42px;
            border: 1px solid var(--gi-border);
            background: #fff;
            border-radius: 12px;
            display: none;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }

        .gi-heading h1 {
            margin: 0;
            font-size: 21px;
            font-weight: 800;
            letter-spacing: -.4px;
        }

        .gi-heading p {
            margin: 4px 0 0;
            color: var(--gi-muted);
            font-size: 12px;
        }

        .gi-top-badge {
            display: inline-flex;
            align-items: center;
            gap: 7px;
            padding: 9px 13px;
            border-radius: 999px;
            background: #eff6ff;
            color: #1d4ed8;
            font-size: 12px;
            font-weight: 700;
        }

        .gi-content {
            padding: 28px;
        }

        .gi-alert {
            margin-bottom: 20px;
            padding: 14px 16px;
            border-radius: 14px;
            display: flex;
            align-items: flex-start;
            gap: 11px;
            font-weight: 600;
        }

        .gi-alert.success {
            background: #ecfdf3;
            color: #15803d;
            border: 1px solid #bbf7d0;
        }

        .gi-alert.error {
            background: #fef2f2;
            color: #b91c1c;
            border: 1px solid #fecaca;
        }

        .gi-stats {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 17px;
            margin-bottom: 24px;
        }

        .gi-stat {
            background: var(--gi-card);
            border: 1px solid var(--gi-border);
            border-radius: var(--gi-radius);
            padding: 19px;
            box-shadow: var(--gi-shadow);
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;
        }

        .gi-stat-info span {
            display: block;
            color: var(--gi-muted);
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 7px;
        }

        .gi-stat-info strong {
            display: block;
            font-size: 25px;
            font-weight: 800;
        }

        .gi-stat-icon {
            width: 46px;
            height: 46px;
            border-radius: 14px;
            background: #eff6ff;
            color: var(--gi-primary);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
        }

        .gi-layout {
            display: grid;
            grid-template-columns: minmax(0, 1fr) 390px;
            gap: 22px;
            align-items: start;
        }

        .gi-card {
            background: var(--gi-card);
            border: 1px solid var(--gi-border);
            border-radius: var(--gi-radius);
            box-shadow: var(--gi-shadow);
            min-width: 0; /* Prevents flex/grid blowouts */
        }

        .gi-card-header {
            padding: 19px 20px;
            border-bottom: 1px solid var(--gi-border);
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;
        }

        .gi-card-title h2 {
            margin: 0;
            font-size: 16px;
            font-weight: 800;
        }

        .gi-card-title p {
            margin: 4px 0 0;
            color: var(--gi-muted);
            font-size: 12px;
        }

        .gi-card-body {
            padding: 20px;
            min-width: 0;
        }

        .gi-filters {
            padding: 16px;
            background: #f8fafc;
            border-bottom: 1px solid var(--gi-border);
        }

      .gi-filter-grid {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 12px;
            align-items: end;
        }

        .gi-filter-actions {
            grid-column: 1 / -1;
            display: flex;
            gap: 8px;
            padding-top: 4px;
        }

        .gi-field {
            margin-bottom: 15px;
            min-width: 0;
        }

        .gi-field label,
        label.gi-label {
            display: block;
            margin-bottom: 7px;
            color: #344054;
            font-size: 12px;
            font-weight: 700;
        }

        .gi-input,
        .gi-select,
        .gi-textarea {
            width: 100%;
            max-width: 100%;
            border: 1px solid #dfe4ec;
            background: #fff;
            border-radius: 11px;
            padding: 11px 12px;
            outline: none;
            color: var(--gi-text);
            transition: .2s ease;
        }

        .gi-input:focus,
        .gi-select:focus,
        .gi-textarea:focus {
            border-color: #93c5fd;
            box-shadow:
                0 0 0 4px rgba(37, 99, 235, .08);
        }

        .gi-textarea {
            min-height: 95px;
            resize: vertical;
        }

        .gi-btn {
            border: 0;
            border-radius: 11px;
            min-height: 42px;
            padding: 0 15px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            font-size: 13px;
            font-weight: 700;
            cursor: pointer;
            transition: .2s ease;
            white-space: nowrap;
        }

        .gi-btn:hover {
            transform: translateY(-1px);
        }

        .gi-btn-primary {
            color: #fff;
            background: var(--gi-primary);
            box-shadow:
                0 7px 18px rgba(37, 99, 235, .18);
        }

        .gi-btn-primary:hover {
            background: var(--gi-primary-dark);
        }

        .gi-btn-light {
            background: #fff;
            color: #344054;
            border: 1px solid var(--gi-border);
        }

        .gi-table-wrap {
            width: 100%;
            overflow-x: auto;
        }

        .gi-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 850px;
        }

        .gi-table th {
            background: #fbfcfe;
            color: #667085;
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: .4px;
            font-weight: 800;
            text-align: left;
            padding: 13px 15px;
            border-bottom: 1px solid var(--gi-border);
            white-space: nowrap;
        }

        .gi-table td {
            padding: 14px 15px;
            border-bottom: 1px solid #edf0f5;
            vertical-align: middle;
        }

        .gi-table tbody tr:hover {
            background: #fbfdff;
        }

        .gi-gallery-name {
            font-weight: 750;
            max-width: 230px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .gi-subtext {
            color: var(--gi-muted);
            font-size: 11px;
            margin-top: 4px;
        }

        .gi-media-box {
            display: flex;
            align-items: center;
            gap: 11px;
            min-width: 230px;
        }

        .gi-media-preview {
            width: 52px;
            height: 52px;
            flex: 0 0 52px;
            border-radius: 12px;
            overflow: hidden;
            background: #f1f5f9;
            border: 1px solid var(--gi-border);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #64748b;
        }

        .gi-media-preview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .gi-media-name {
            min-width: 0;
        }

        .gi-media-name strong {
            display: block;
            max-width: 180px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 12px;
        }

        .gi-status {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 9px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: 800;
        }

        .gi-status.active {
            background: #ecfdf3;
            color: #15803d;
        }

        .gi-status.inactive {
            background: #fef2f2;
            color: #b91c1c;
        }

        .gi-dot {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: currentColor;
        }

        .gi-actions {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .gi-icon-btn {
            width: 34px;
            height: 34px;
            border-radius: 9px;
            border: 1px solid var(--gi-border);
            background: #fff;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            color: #475467;
            transition: .2s ease;
        }

        .gi-icon-btn:hover {
            transform: translateY(-1px);
        }

        .gi-icon-btn.edit:hover {
            color: var(--gi-primary);
            background: #eff6ff;
            border-color: #bfdbfe;
        }

        .gi-icon-btn.status:hover {
            color: var(--gi-success);
            background: #ecfdf3;
            border-color: #bbf7d0;
        }

        .gi-icon-btn.delete:hover {
            color: var(--gi-danger);
            background: #fef2f2;
            border-color: #fecaca;
        }

        .gi-form-card {
            position: sticky;
            top: 96px;
        }

        .gi-form-icon {
            width: 38px;
            height: 38px;
            border-radius: 11px;
            background: #eff6ff;
            color: var(--gi-primary);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .gi-form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 14px;
            min-width: 0;
        }

        .gi-full {
            grid-column: 1 / -1;
            min-width: 0;
        }

        .gi-form-footer {
            margin-top: 5px;
            padding-top: 17px;
            border-top: 1px solid var(--gi-border);
            display: flex;
            gap: 9px;
        }

        .gi-form-footer .gi-btn {
            flex: 1;
        }

        .gi-help {
            margin-top: 6px;
            color: #98a2b3;
            font-size: 11px;
            line-height: 1.5;
            word-break: break-word;
        }

        .gi-preview {
            margin-top: 10px;
            padding: 10px;
            border: 1px dashed #cbd5e1;
            border-radius: 13px;
            background: #f8fafc;
            display: none;
        }

        .gi-preview.show {
            display: block;
        }

        .gi-preview img {
            display: block;
            width: 100%;
            max-height: 170px;
            object-fit: contain;
            border-radius: 10px;
            background: #fff;
        }

        .gi-empty {
            text-align: center;
            padding: 55px 20px;
            color: var(--gi-muted);
        }

        .gi-empty-icon {
            width: 58px;
            height: 58px;
            border-radius: 18px;
            background: #f1f5f9;
            color: #94a3b8;
            margin: 0 auto 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 22px;
        }

        .gi-empty strong {
            display: block;
            color: #344054;
            font-size: 14px;
            margin-bottom: 5px;
        }

        .gi-empty span {
            font-size: 12px;
        }

        @media (max-width: 1250px) {

            .gi-layout {
                grid-template-columns: 1fr;
            }

            .gi-form-card {
                position: static;
            }

            .gi-filter-grid {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }
        }

        @media (max-width: 991px) {

            .gi-main {
                margin-left: 0;
            }

            .gi-menu-btn {
                display: inline-flex;
            }

            .gi-content {
                padding: 20px;
            }

            .gi-stats {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }
        }

        @media (max-width: 650px) {

            .gi-topbar {
                padding: 0 15px;
            }

            .gi-heading h1 {
                font-size: 17px;
            }

            .gi-heading p,
            .gi-top-badge {
                display: none;
            }

            .gi-content {
                padding: 15px;
            }

            .gi-stats {
                gap: 10px;
            }

            .gi-stat {
                padding: 14px;
            }

            .gi-stat-info strong {
                font-size: 21px;
            }

            .gi-filter-grid {
                grid-template-columns: 1fr;
            }

            .gi-form-grid {
                grid-template-columns: 1fr;
            }

            .gi-full {
                grid-column: auto;
            }
        }

    </style>

</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| Existing admin sidebar
|--------------------------------------------------------------------------
*/
require_once __DIR__ . '/sidebar.php';
?>

<div class="gi-main">

    <!-- =================================================
         TOPBAR
    ================================================== -->

    <header class="gi-topbar">

        <div class="gi-top-left">

            <button
                type="button"
                class="gi-menu-btn"
                id="giMenuBtn"
                aria-label="Open menu"
            >
                <i class="fa-solid fa-bars"></i>
            </button>

            <div class="gi-heading">

                <h1>
                    Gallery Items
                </h1>

                <p>
                    Manage media items inside your galleries
                </p>

            </div>

        </div>

        <div class="gi-top-badge">

            <i class="fa-solid fa-images"></i>

            Gallery Management

        </div>

    </header>


    <!-- =================================================
         CONTENT
    ================================================== -->

    <main class="gi-content">


        <?php if ($flash): ?>

            <div class="gi-alert <?= $flash['type'] === 'success' ? 'success' : 'error' ?>">

                <i class="fa-solid <?= $flash['type'] === 'success'
                    ? 'fa-circle-check'
                    : 'fa-circle-exclamation'
                ?>"></i>

                <span>
                    <?= gi_e($flash['message']) ?>
                </span>

            </div>

        <?php endif; ?>


        <?php if ($errorMessage !== ''): ?>

            <div class="gi-alert error">

                <i class="fa-solid fa-circle-exclamation"></i>

                <span>
                    <?= gi_e($errorMessage) ?>
                </span>

            </div>

        <?php endif; ?>


        <!-- =================================================
             STATS
        ================================================== -->

        <section class="gi-stats">


            <div class="gi-stat">

                <div class="gi-stat-info">

                    <span>
                        Total Gallery Items
                    </span>

                    <strong>
                        <?= number_format($stats['total']) ?>
                    </strong>

                </div>

                <div class="gi-stat-icon">

                    <i class="fa-solid fa-images"></i>

                </div>

            </div>


            <div class="gi-stat">

                <div class="gi-stat-info">

                    <span>
                        Active
                    </span>

                    <strong>
                        <?= number_format($stats['active']) ?>
                    </strong>

                </div>

                <div class="gi-stat-icon">

                    <i class="fa-solid fa-circle-check"></i>

                </div>

            </div>


            <div class="gi-stat">

                <div class="gi-stat-info">

                    <span>
                        Inactive
                    </span>

                    <strong>
                        <?= number_format($stats['inactive']) ?>
                    </strong>

                </div>

                <div class="gi-stat-icon">

                    <i class="fa-solid fa-circle-pause"></i>

                </div>

            </div>


            <div class="gi-stat">

                <div class="gi-stat-info">

                    <span>
                        Galleries
                    </span>

                    <strong>
                        <?= number_format($stats['galleries']) ?>
                    </strong>

                </div>

                <div class="gi-stat-icon">

                    <i class="fa-solid fa-photo-film"></i>

                </div>

            </div>


        </section>


        <!-- =================================================
             MAIN GRID
        ================================================== -->

        <div class="gi-layout">


            <!-- =================================================
                 LIST
            ================================================== -->

            <section class="gi-card">


                <div class="gi-card-header">

                    <div class="gi-card-title">

                        <h2>
                            Gallery Media
                        </h2>

                        <p>
                            <?= number_format(count($records)) ?>
                            record<?= count($records) === 1 ? '' : 's' ?>
                            found
                        </p>

                    </div>

                </div>


                <!-- FILTERS -->

                <form
                    method="get"
                    class="gi-filters"
                >

                    <div class="gi-filter-grid">


                        <div>

                            <label class="gi-label">
                                Search
                            </label>

                            <input
                                type="search"
                                name="search"
                                class="gi-input"
                                value="<?= gi_e($search) ?>"
                                placeholder="Search gallery, title, media..."
                            >

                        </div>


                        <div>

                            <label class="gi-label">
                                Gallery
                            </label>

                            <select
                                name="gallery_id"
                                class="gi-select"
                            >

                                <option value="">
                                    All Galleries
                                </option>

                                <?php foreach ($galleries as $gallery): ?>

                                    <option
                                        value="<?= (int)$gallery['id'] ?>"
                                        <?= $filterGalleryId === (int)$gallery['id']
                                            ? 'selected'
                                            : ''
                                        ?>
                                    >

                                        <?= gi_e($gallery['name']) ?>

                                    </option>

                                <?php endforeach; ?>

                            </select>

                        </div>


                        <div>

                            <label class="gi-label">
                                Status
                            </label>

                            <select
                                name="status"
                                class="gi-select"
                            >

                                <option value="">
                                    All Status
                                </option>

                                <option
                                    value="1"
                                    <?= $filterStatus === '1'
                                        ? 'selected'
                                        : ''
                                    ?>
                                >
                                    Active
                                </option>

                                <option
                                    value="0"
                                    <?= $filterStatus === '0'
                                        ? 'selected'
                                        : ''
                                    ?>
                                >
                                    Inactive
                                </option>

                            </select>

                        </div>


                        <div class="gi-filter-actions">

                            <button
                                type="submit"
                                class="gi-btn gi-btn-primary"
                            >

                                <i class="fa-solid fa-filter"></i>

                                Filter

                            </button>


                            <a
                                href="gallery_items.php"
                                class="gi-btn gi-btn-light"
                            >

                                <i class="fa-solid fa-rotate-left"></i>

                                Reset

                            </a>

                        </div>


                    </div>

                </form>


                <!-- TABLE -->

                <div class="gi-table-wrap">

                    <?php if (!$records): ?>

                        <div class="gi-empty">

                            <div class="gi-empty-icon">

                                <i class="fa-solid fa-images"></i>

                            </div>

                            <strong>
                                No gallery items found
                            </strong>

                            <span>
                                Add media to a gallery using the form.
                            </span>

                        </div>

                    <?php else: ?>


                        <table class="gi-table">

                            <thead>

                                <tr>

                                    <th>
                                        Gallery
                                    </th>

                                    <th>
                                        Media
                                    </th>

                                    <th>
                                        Title / Caption
                                    </th>

                                    <th>
                                        Order
                                    </th>

                                    <th>
                                        Status
                                    </th>

                                    <th>
                                        Actions
                                    </th>

                                </tr>

                            </thead>


                            <tbody>


                            <?php foreach ($records as $record): ?>

                                <?php

                                $previewUrl = '';

                                if (!empty($record['file_path'])) {
                                    $previewUrl = $record['file_path'];
                                }

                                $mime =
                                    strtolower(
                                        (string)$record['mime_type']
                                    );

                                $isImage =
                                    str_starts_with(
                                        $mime,
                                        'image/'
                                    );

                                if (
                                    !$isImage &&
                                    $previewUrl !== ''
                                ) {

                                    $extension =
                                        strtolower(
                                            pathinfo(
                                                parse_url(
                                                    $previewUrl,
                                                    PHP_URL_PATH
                                                ) ?: '',
                                                PATHINFO_EXTENSION
                                            )
                                        );

                                    $isImage =
                                        in_array(
                                            $extension,
                                            [
                                                'jpg',
                                                'jpeg',
                                                'png',
                                                'gif',
                                                'webp',
                                                'avif',
                                                'svg'
                                            ],
                                            true
                                        );
                                }

                                ?>


                                <tr>


                                    <!-- GALLERY -->

                                    <td>

                                        <div class="gi-gallery-name">

                                            <?= gi_e(
                                                $record['gallery_name']
                                            ) ?>

                                        </div>

                                        <div class="gi-subtext">

                                            <?= gi_e(
                                                $record['gallery_slug']
                                            ) ?>

                                        </div>

                                        <div class="gi-subtext">

                                            Gallery #<?= (int)$record['gallery_id'] ?>

                                        </div>

                                    </td>


                                    <!-- MEDIA -->

                                    <td>

                                        <div class="gi-media-box">


                                            <div class="gi-media-preview">

                                                <?php if (
                                                    $isImage &&
                                                    $previewUrl !== ''
                                                ): ?>

                                                    <img
                                                        src="<?= gi_e($previewUrl) ?>"
                                                        alt="<?= gi_e(
                                                            $record['media_alt_text']
                                                                ?: $record['media_title']
                                                                ?: $record['file_name']
                                                        ) ?>"
                                                        loading="lazy"
                                                    >

                                                <?php else: ?>

                                                    <?php

                                                    $mediaIcon =
                                                        'fa-file';

                                                    if (
                                                        str_contains(
                                                            $mime,
                                                            'video'
                                                        )
                                                    ) {

                                                        $mediaIcon =
                                                            'fa-file-video';

                                                    } elseif (
                                                        str_contains(
                                                            $mime,
                                                            'pdf'
                                                        )
                                                    ) {

                                                        $mediaIcon =
                                                            'fa-file-pdf';

                                                    } elseif (
                                                        str_contains(
                                                            $mime,
                                                            'audio'
                                                        )
                                                    ) {

                                                        $mediaIcon =
                                                            'fa-file-audio';
                                                    }

                                                    ?>

                                                    <i
                                                        class="fa-solid <?= $mediaIcon ?>"
                                                    ></i>

                                                <?php endif; ?>

                                            </div>


                                            <div class="gi-media-name">

                                                <strong>

                                                    <?= gi_e(
                                                        $record['media_title']
                                                            ?: $record['file_name']
                                                            ?: (
                                                                'Media #' .
                                                                $record['media_id']
                                                            )
                                                    ) ?>

                                                </strong>

                                                <div class="gi-subtext">

                                                    Media #<?= (int)$record['media_id'] ?>

                                                </div>

                                                <?php if (
                                                    !empty($record['mime_type'])
                                                ): ?>

                                                    <div class="gi-subtext">

                                                        <?= gi_e(
                                                            $record['mime_type']
                                                        ) ?>

                                                    </div>

                                                <?php endif; ?>

                                            </div>

                                        </div>

                                    </td>


                                    <!-- TITLE -->

                                    <td>

                                        <div class="gi-gallery-name">

                                            <?= gi_e(
                                                $record['title']
                                                    ?: 'Untitled item'
                                            ) ?>

                                        </div>

                                        <?php if (
                                            !empty($record['caption'])
                                        ): ?>

                                            <div
                                                class="gi-subtext"
                                                style="
                                                    max-width:220px;
                                                    overflow:hidden;
                                                    text-overflow:ellipsis;
                                                    white-space:nowrap;
                                                "
                                            >

                                                <?= gi_e(
                                                    $record['caption']
                                                ) ?>

                                            </div>

                                        <?php endif; ?>

                                    </td>


                                    <!-- ORDER -->

                                    <td>

                                        <strong>

                                            <?= (int)$record['sort_order'] ?>

                                        </strong>

                                    </td>


                                    <!-- STATUS -->

                                    <td>

                                        <?php if (
                                            (int)$record['status'] === 1
                                        ): ?>

                                            <span
                                                class="gi-status active"
                                            >

                                                <span
                                                    class="gi-dot"
                                                ></span>

                                                Active

                                            </span>

                                        <?php else: ?>

                                            <span
                                                class="gi-status inactive"
                                            >

                                                <span
                                                    class="gi-dot"
                                                ></span>

                                                Inactive

                                            </span>

                                        <?php endif; ?>

                                    </td>


                                    <!-- ACTIONS -->

                                    <td>

                                        <div class="gi-actions">


                                            <a
                                                href="gallery_items.php?edit=<?= (int)$record['id'] ?>"
                                                class="gi-icon-btn edit"
                                                title="Edit"
                                            >

                                                <i class="fa-solid fa-pen"></i>

                                            </a>


                                            <form
                                                method="post"
                                                style="display:inline"
                                                onsubmit="
                                                    return confirm(
                                                        'Change status for this gallery item?'
                                                    );
                                                "
                                            >

                                                <?= gi_csrf_field() ?>

                                                <input
                                                    type="hidden"
                                                    name="action"
                                                    value="toggle_status"
                                                >

                                                <input
                                                    type="hidden"
                                                    name="id"
                                                    value="<?= (int)$record['id'] ?>"
                                                >

                                                <button
                                                    type="submit"
                                                    class="gi-icon-btn status"
                                                    title="Toggle Status"
                                                >

                                                    <i
                                                        class="fa-solid fa-power-off"
                                                    ></i>

                                                </button>

                                            </form>


                                            <form
                                                method="post"
                                                style="display:inline"
                                                onsubmit="
                                                    return confirm(
                                                        'Delete this gallery item permanently?'
                                                    );
                                                "
                                            >

                                                <?= gi_csrf_field() ?>

                                                <input
                                                    type="hidden"
                                                    name="action"
                                                    value="delete"
                                                >

                                                <input
                                                    type="hidden"
                                                    name="id"
                                                    value="<?= (int)$record['id'] ?>"
                                                >

                                                <button
                                                    type="submit"
                                                    class="gi-icon-btn delete"
                                                    title="Delete"
                                                >

                                                    <i
                                                        class="fa-solid fa-trash"
                                                    ></i>

                                                </button>

                                            </form>


                                        </div>

                                    </td>


                                </tr>

                            <?php endforeach; ?>


                            </tbody>

                        </table>


                    <?php endif; ?>

                </div>

            </section>


            <!-- =================================================
                 ADD / EDIT FORM
            ================================================== -->

            <aside class="gi-card gi-form-card">


                <div class="gi-card-header">

                    <div
                        style="
                            display:flex;
                            align-items:center;
                            gap:10px;
                        "
                    >

                        <div class="gi-form-icon">

                            <i
                                class="fa-solid <?= $editRecord
                                    ? 'fa-pen'
                                    : 'fa-plus'
                                ?>"
                            ></i>

                        </div>

                        <div class="gi-card-title">

                            <h2>

                                <?= $editRecord
                                    ? 'Edit Gallery Item'
                                    : 'Add Gallery Item'
                                ?>

                            </h2>

                            <p>

                                <?= $editRecord
                                    ? 'Update gallery media'
                                    : 'Add media to a gallery'
                                ?>

                            </p>

                        </div>

                    </div>

                </div>


                <div class="gi-card-body">


                    <form
                        method="post"
                        autocomplete="off"
                    >

                        <?= gi_csrf_field() ?>

                        <input
                            type="hidden"
                            name="action"
                            value="save"
                        >

                        <input
                            type="hidden"
                            name="id"
                            value="<?= gi_e($form['id']) ?>"
                        >


                        <div class="gi-form-grid">


                            <!-- GALLERY -->

                            <div class="gi-field gi-full">

                                <label
                                    for="gallery_id"
                                    class="gi-label"
                                >

                                    Gallery
                                    <span style="color:#dc2626">*</span>

                                </label>

                                <select
                                    id="gallery_id"
                                    name="gallery_id"
                                    class="gi-select"
                                    required
                                >

                                    <option value="">
                                        Select gallery
                                    </option>

                                    <?php foreach (
                                        $galleries as $gallery
                                    ): ?>

                                        <option
                                            value="<?= (int)$gallery['id'] ?>"
                                            <?= (int)$form['gallery_id']
                                                === (int)$gallery['id']
                                                ? 'selected'
                                                : ''
                                            ?>
                                        >

                                            <?= gi_e(
                                                $gallery['name']
                                            ) ?>

                                            —
                                            <?= gi_e(
                                                $gallery['slug']
                                            ) ?>

                                        </option>

                                    <?php endforeach; ?>

                                </select>


                                <?php if (!$galleries): ?>

                                    <div class="gi-help">

                                        No galleries are available.
                                        Create a gallery first.

                                    </div>

                                <?php endif; ?>

                            </div>


                            <!-- MEDIA -->

                            <div class="gi-field gi-full">

                                <label
                                    for="media_id"
                                    class="gi-label"
                                >

                                    Media
                                    <span style="color:#dc2626">*</span>

                                </label>

                                <select
                                    id="media_id"
                                    name="media_id"
                                    class="gi-select"
                                    required
                                >

                                    <option value="">
                                        Select media
                                    </option>

                                    <?php foreach (
                                        $mediaLibrary as $media
                                    ): ?>

                                        <option
                                            value="<?= (int)$media['id'] ?>"
                                            data-url="<?= gi_e(
                                                $media['file_path']
                                            ) ?>"
                                            data-mime="<?= gi_e(
                                                $media['mime_type']
                                            ) ?>"
                                            <?= (int)$form['media_id']
                                                === (int)$media['id']
                                                ? 'selected'
                                                : ''
                                            ?>
                                        >

                                            #<?= (int)$media['id'] ?>

                                            —
                                            <?= gi_e(
                                                $media['title']
                                                    ?: $media['file_name']
                                                    ?: 'Untitled media'
                                            ) ?>

                                        </option>

                                    <?php endforeach; ?>

                                </select>


                                <?php if (!$mediaLibrary): ?>

                                    <div class="gi-help">

                                        No media is available.
                                        Upload media from Media Library first.

                                    </div>

                                <?php endif; ?>


                                <div
                                    class="gi-preview"
                                    id="giPreview"
                                >

                                    <img
                                        src=""
                                        alt="Media preview"
                                        id="giPreviewImage"
                                    >

                                </div>

                            </div>


                            <!-- TITLE -->

                            <div class="gi-field gi-full">

                                <label
                                    for="title"
                                    class="gi-label"
                                >
                                    Title
                                </label>

                                <input
                                    type="text"
                                    id="title"
                                    name="title"
                                    class="gi-input"
                                    maxlength="255"
                                    value="<?= gi_e($form['title']) ?>"
                                    placeholder="Gallery item title"
                                >

                            </div>


                            <!-- SORT -->

                            <div class="gi-field">

                                <label
                                    for="sort_order"
                                    class="gi-label"
                                >
                                    Sort Order
                                </label>

                                <input
                                    type="number"
                                    min="0"
                                    step="1"
                                    id="sort_order"
                                    name="sort_order"
                                    class="gi-input"
                                    value="<?= gi_e(
                                        $form['sort_order']
                                    ) ?>"
                                >

                                <div class="gi-help">

                                    Lower number appears first.

                                </div>

                            </div>


                            <!-- STATUS -->

                            <div class="gi-field">

                                <label
                                    for="status"
                                    class="gi-label"
                                >
                                    Status
                                </label>

                                <select
                                    id="status"
                                    name="status"
                                    class="gi-select"
                                >

                                    <option
                                        value="1"
                                        <?= (int)$form['status'] === 1
                                            ? 'selected'
                                            : ''
                                        ?>
                                    >
                                        Active
                                    </option>

                                    <option
                                        value="0"
                                        <?= (int)$form['status'] === 0
                                            ? 'selected'
                                            : ''
                                        ?>
                                    >
                                        Inactive
                                    </option>

                                </select>

                            </div>


                            <!-- CAPTION -->

                            <div class="gi-field gi-full">

                                <label
                                    for="caption"
                                    class="gi-label"
                                >
                                    Caption
                                </label>

                                <textarea
                                    id="caption"
                                    name="caption"
                                    class="gi-textarea"
                                    placeholder="Optional gallery item caption..."
                                ><?= gi_e($form['caption']) ?></textarea>

                            </div>


                        </div>


                        <!-- FOOTER -->

                        <div class="gi-form-footer">


                            <?php if ($editRecord): ?>

                                <a
                                    href="gallery_items.php"
                                    class="gi-btn gi-btn-light"
                                >

                                    <i class="fa-solid fa-xmark"></i>

                                    Cancel

                                </a>

                            <?php endif; ?>


                            <button
                                type="submit"
                                class="gi-btn gi-btn-primary"
                            >

                                <i
                                    class="fa-solid <?= $editRecord
                                        ? 'fa-floppy-disk'
                                        : 'fa-plus'
                                    ?>"
                                ></i>

                                <?= $editRecord
                                    ? 'Update Item'
                                    : 'Add Item'
                                ?>

                            </button>


                        </div>


                    </form>


                </div>

            </aside>


        </div>

    </main>

</div>


<script>

(function () {

    /* =====================================================
       MOBILE SIDEBAR
    ===================================================== */

    const menuBtn =
        document.getElementById('giMenuBtn');

    if (menuBtn) {

        menuBtn.addEventListener(
            'click',
            function () {

                const sidebar =
                    document.getElementById('pcSidebar');

                if (sidebar) {
                    sidebar.classList.toggle('is-open');
                }

                document.body.classList.toggle(
                    'pc-sidebar-open'
                );

            }
        );
    }


    /* =====================================================
       MEDIA PREVIEW
    ===================================================== */

    const mediaSelect =
        document.getElementById('media_id');

    const previewBox =
        document.getElementById('giPreview');

    const previewImage =
        document.getElementById('giPreviewImage');


    function updatePreview() {

        if (
            !mediaSelect ||
            !previewBox ||
            !previewImage
        ) {
            return;
        }


        const option =
            mediaSelect.options[
                mediaSelect.selectedIndex
            ];


        if (!option) {

            previewBox.classList.remove('show');

            previewImage.removeAttribute('src');

            return;
        }


        const url =
            option.getAttribute('data-url') || '';

        const mime =
            (
                option.getAttribute('data-mime') || ''
            ).toLowerCase();


        const isImage =
            mime.indexOf('image/') === 0 ||
            /\.(jpg|jpeg|png|gif|webp|avif|svg)(\?.*)?$/i.test(
                url
            );


        if (
            url &&
            isImage
        ) {

            previewImage.src = url;

            previewBox.classList.add('show');

        } else {

            previewBox.classList.remove('show');

            previewImage.removeAttribute('src');
        }

    }


    if (mediaSelect) {

        mediaSelect.addEventListener(
            'change',
            updatePreview
        );

        updatePreview();
    }


})();

</script>

</body>
</html>