<?php
session_start();
require_once __DIR__ . '/config/db.php';

$page_title = 'Gallery - Faren Interior Design';
$user_name = isset($_SESSION['user_name']) ? htmlspecialchars($_SESSION['user_name']) : '';

function ensureGalleryTable(mysqli $connection): bool
{
    $sql = "CREATE TABLE IF NOT EXISTS gallery_items (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        category VARCHAR(100) NOT NULL,
        image VARCHAR(500) NOT NULL,
        sort_order INT NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

    if (!$connection->query($sql)) {
        return false;
    }

    $requiredColumns = [
        'title' => "ALTER TABLE gallery_items ADD COLUMN title VARCHAR(255) NOT NULL DEFAULT ''",
        'category' => "ALTER TABLE gallery_items ADD COLUMN category VARCHAR(100) NOT NULL DEFAULT 'Interior'",
        'image' => "ALTER TABLE gallery_items ADD COLUMN image VARCHAR(500) NOT NULL DEFAULT ''",
        'sort_order' => "ALTER TABLE gallery_items ADD COLUMN sort_order INT NOT NULL DEFAULT 0",
        'is_active' => "ALTER TABLE gallery_items ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1",
        'created_at' => "ALTER TABLE gallery_items ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP",
        'updated_at' => "ALTER TABLE gallery_items ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP",
    ];

    $columnsResult = $connection->query("SHOW COLUMNS FROM gallery_items");
    $existingColumns = [];
    if ($columnsResult) {
        while ($column = $columnsResult->fetch_assoc()) {
            $existingColumns[] = $column['Field'];
        }
    }

    foreach ($requiredColumns as $columnName => $alterSql) {
        if (!in_array($columnName, $existingColumns, true) && !$connection->query($alterSql)) {
            return false;
        }
    }

    return true;
}

function seedGalleryFromHtmlIfEmpty(mysqli $connection): void
{
    $countResult = $connection->query("SELECT COUNT(*) AS total FROM gallery_items");
    $total = 0;
    if ($countResult) {
        $row = $countResult->fetch_assoc();
        $total = (int)($row['total'] ?? 0);
    }

    if ($total > 0) {
        return;
    }

    $galleryFile = __DIR__ . '/gallery.html';
    if (!file_exists($galleryFile)) {
        return;
    }

    $html = file_get_contents($galleryFile);
    if ($html === false) {
        return;
    }

    $pattern = '/<div class="[^\"]*filter-item\s+([^\"]*)"[^>]*data-gallery-id="(\d+)"[^>]*>.*?<img src="([^"]+)"[^>]*>.*?<h2 class="box-title">([^<]+)<\/h2>/si';
    if (!preg_match_all($pattern, $html, $matches, PREG_SET_ORDER)) {
        return;
    }

    $insert = $connection->prepare("INSERT INTO gallery_items (title, category, image, sort_order, is_active) VALUES (?, ?, ?, ?, 1)");
    if (!$insert) {
        return;
    }

    foreach ($matches as $idx => $item) {
        $classes = trim($item[1]);
        $image = trim($item[3]);
        $title = trim(html_entity_decode($item[4], ENT_QUOTES | ENT_HTML5, 'UTF-8'));

        $category = 'Interior';
        if (stripos($classes, 'cat2') !== false) $category = 'Architecture';
        elseif (stripos($classes, 'cat3') !== false) $category = 'Building';
        elseif (stripos($classes, 'cat4') !== false) $category = 'Exterior';
        elseif (stripos($classes, 'cat5') !== false) $category = 'Shape';

        if ($title === '' || $image === '') {
            continue;
        }

        $sortOrder = $idx + 1;
        $insert->bind_param('sssi', $title, $category, $image, $sortOrder);
        $insert->execute();
    }

    $insert->close();
}

function slugCategory(string $value): string
{
    $slug = strtolower(trim($value));
    $slug = preg_replace('/[^a-z0-9]+/', '-', $slug) ?? '';
    $slug = trim($slug, '-');
    return $slug !== '' ? $slug : 'uncategorized';
}

$galleries = [];
$categories = [];
if (ensureGalleryTable($connection)) {
    seedGalleryFromHtmlIfEmpty($connection);

    $query = $connection->query("SELECT id, title, category, image FROM gallery_items WHERE is_active = 1 ORDER BY sort_order ASC, id ASC");
    if ($query) {
        while ($row = $query->fetch_assoc()) {
            $galleries[] = $row;
            $cat = trim((string)($row['category'] ?? ''));
            if ($cat !== '' && !in_array($cat, $categories, true)) {
                $categories[] = $cat;
            }
        }
    }
}

if (empty($galleries)) {
    $galleries = [
        ['id' => 1, 'title' => 'Open Kitchen Interior Design', 'category' => 'Interior', 'image' => 'assets/img/gallery/gallery_2_6.jpg'],
        ['id' => 2, 'title' => 'Modern Architecture View', 'category' => 'Architecture', 'image' => 'assets/img/gallery/gallery_2_7.jpg'],
        ['id' => 3, 'title' => 'Living Room Styling', 'category' => 'Interior', 'image' => 'assets/img/gallery/gallery_2_8.jpg'],
    ];
    $categories = ['Interior', 'Architecture'];
}
?>
<!doctype html>
<html class="no-js" lang="zxx">

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Faren Interior Design</title>
    <meta name="author" content="themeholy">
    <meta name="description" content="Faren - Architecture & Interior Design Template">
    <meta name="keywords" content="Faren - Architecture & Interior Design Template">
    <meta name="robots" content="INDEX,FOLLOW">
    <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
    <link rel="apple-touch-icon" sizes="57x57" href="assets/img/favicons/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="assets/img/favicons/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="assets/img/favicons/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="assets/img/favicons/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="assets/img/favicons/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="assets/img/favicons/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="assets/img/favicons/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="assets/img/favicons/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="assets/img/favicons/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192" href="assets/img/favicons/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="assets/img/favicons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="assets/img/favicons/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="assets/img/favicons/favicon-16x16.png">
    <link rel="manifest" href="assets/img/favicons/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="assets/img/favicons/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="">
    <link href="../../css2-1?family=DM+Sans:ital,opsz,wght@0,9..40,100..1000;1,9..40,100..1000&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/fontawesome.min.css">
    <link rel="stylesheet" href="assets/css/magnific-popup.min.css">
    <link rel="stylesheet" href="assets/css/swiper-bundle.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <!-- Responsive Design System -->
    <link rel="stylesheet" href="assets/css/responsive-utilities.css">
    <link rel="stylesheet" href="assets/css/responsive-chat.css">
    <script src="assets/js/auth-ui-global.js"></script>
</head>

<body id="show-grid">
    <?php include 'header-php.php'; ?>

    <div class="overflow-hidden" id="project-sec">
        <div class="container">
            <style>
                #project-sec { padding: 10px;}
                .gallery-row {
                    display: grid !important;
                    grid-template-columns: repeat(3, minmax(0, 1fr)) !important;
                    gap: 24px;
                }
                .gallery-row .filter-item {
                    width: auto !important;
                    max-width: none !important;
                    padding-left: 0;
                    padding-right: 0;
                    margin-bottom: 0;
                }
                .gallery-card { background: #0d1c17; border-radius: 14px; overflow: hidden; transition: .3s; }
                .gallery-card:hover { transform: translateY(-6px); }
                .gallery-card .box-img img { width: 100%; height: 280px; object-fit: cover; }
                .gallery-content .box-title { color: #fff; padding: 14px 16px 18px; margin: 0; font-size: 18px; }

                @media (max-width: 992px) {
                    .gallery-row {
                        grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
                        gap: 20px;
                    }
                    .gallery-card .box-img img { height: 240px; }
                }

                @media (max-width: 576px) {
                    #project-sec { margin-top: 0; }
                    .gallery-row {
                        grid-template-columns: 1fr !important;
                        gap: 16px;
                    }
                    .gallery-card .box-img img { height: 210px; }
                    .gallery-content .box-title { font-size: 16px; text-align: center; }
                    .filter-menu { text-align: center; }
                }
            </style>

            <div class="row justify-content-center">
                <div class="col-xl-10">
                    <div class="filter-menu indicator-active mb-60 filter-menu-active">
                        <button data-filter="*" class="tab-btn active" type="button">View All</button>
                        <?php foreach ($categories as $category): ?>
                            <?php $categorySlug = slugCategory($category); ?>
                            <button data-filter=".cat-<?php echo htmlspecialchars($categorySlug); ?>" class="tab-btn" type="button"><?php echo htmlspecialchars($category); ?></button>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <div class="gallery-row js-gallery-grid">
                <?php foreach ($galleries as $gallery): ?>
                    <?php
                    $id = (int)($gallery['id'] ?? 0);
                    $title = htmlspecialchars((string)($gallery['title'] ?? 'Gallery Item'));
                    $category = (string)($gallery['category'] ?? 'Interior');
                    $categorySlug = slugCategory($category);
                    $image = htmlspecialchars((string)($gallery['image'] ?? 'assets/img/gallery/gallery_2_6.jpg'));
                    ?>
                    <div class="filter-item cat-<?php echo htmlspecialchars($categorySlug); ?>" data-gallery-id="<?php echo $id; ?>" data-category="cat-<?php echo htmlspecialchars($categorySlug); ?>">
                        <div class="gallery-card">
                            <div class="box-img global-img">
                                <img src="<?php echo $image; ?>" alt="<?php echo $title; ?>">
                                <a href="<?php echo $image; ?>" class="icon-btn th-popup-image"><i class="far fa-plus"></i></a>
                                <div class="shape">
                                    <div class="dot"></div>
                                    <div class="dot"></div>
                                    <div class="dot"></div>
                                    <div class="dot"></div>
                                </div>
                            </div>
                            <div class="gallery-content">
                                <h2 class="box-title"><?php echo $title; ?></h2>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <?php include 'footer-section.html'; ?>

    
    <script src="assets/js/vendor/jquery-3.7.1.min.js"></script>
    <script src="assets/js/swiper-bundle.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="assets/js/jquery.magnific-popup.min.js"></script>
    <script src="assets/js/jquery.counterup.min.js"></script>
    <script src="assets/js/circle-progress.js"></script>
    <script src="assets/js/jquery-ui.min.js"></script>
    <script src="assets/js/imagesloaded.pkgd.min.js"></script>
    <script src="assets/js/isotope.pkgd.min.js"></script>
    <script src="assets/js/nice-select.min.js"></script>
    <script src="assets/js/wow.min.js"></script>
    <script src="assets/js/threesixty.min.js"></script>
    <script src="assets/js/panolens.min.js"></script>
    <script src="assets/js/gsap.min.js"></script>
    <script src="assets/js/ScrollTrigger.min.js"></script>
    <script src="assets/js/SplitText.js"></script>
    <script src="assets/js/SplitType.js"></script>
    <script src="assets/js/lenis.min.js"></script>
    <script src="assets/js/CustomEase.min.js"></script>
    <script src="assets/js/main.js"></script>
    <script>
        (function () {
            const menu = document.querySelector('.filter-menu-active');
            const items = document.querySelectorAll('.js-gallery-grid .filter-item');
            if (!menu || !items.length) return;

            menu.addEventListener('click', function (e) {
                const btn = e.target.closest('button[data-filter]');
                if (!btn) return;

                e.preventDefault();
                const filter = btn.getAttribute('data-filter');

                menu.querySelectorAll('button[data-filter]').forEach(function (b) {
                    b.classList.remove('active');
                });
                btn.classList.add('active');

                items.forEach(function (item) {
                    if (filter === '*' || item.classList.contains(filter.replace('.', ''))) {
                        item.style.display = '';
                    } else {
                        item.style.display = 'none';
                    }
                });
            });
        })();
    </script>

    <!-- Chat Widget -->
    <?php include 'includes/chat-widget.html'; ?>
    <!-- Responsive Chat Script -->
    <script src="assets/js/responsive-chat-ai.js"></script>
</body>
</html>
