<?php
$page_title  = "Gallery — CY Consultancy Centre";
$page_desc   = "Photo gallery of CY Consultancy Centre — visa approvals, student events, international fairs.";
$active_page = "gallery";
require_once __DIR__ . '/includes/config.php';
include 'includes/header.php';
$B = BASE_PATH;

// Load from DB first
$db_photos = [];
$db = site_db();
if ($db) {
    $res = $db->query("SELECT * FROM gallery ORDER BY sort_order, id DESC");
    if ($res) $db_photos = $res->fetch_all(MYSQLI_ASSOC);
}

// Fallback to static images if DB is empty
$static_images = [];
if (empty($db_photos)) {
    $imgDir = __DIR__ . '/assets/images/gallery/';
    if (is_dir($imgDir)) {
        $files = glob($imgDir . '*.{jpg,jpeg,png,webp,gif}', GLOB_BRACE);
        foreach ($files as $f) {
            $static_images[] = 'assets/images/gallery/' . basename($f);
        }
    }
    // hardcoded fallback
    if (empty($static_images)) {
        $static_images = [
            "assets/images/gallery/gallery_001.jpg","assets/images/gallery/gallery_002.jpg",
            "assets/images/gallery/gallery_003.jpg","assets/images/gallery/gallery_004.jpg",
            "assets/images/gallery/gallery_005.jpg","assets/images/gallery/gallery_008.jpg",
        ];
    }
}

// Get unique categories from DB
$categories = [];
if (!empty($db_photos)) {
    foreach ($db_photos as $p) {
        if (!empty($p['category']) && !in_array($p['category'], $categories))
            $categories[] = $p['category'];
    }
}
?>
<style>
.gallery-wrap{max-width:1200px;margin:0 auto;padding:60px 20px}
.gallery-head{text-align:center;margin-bottom:40px}
.gallery-head h1{font-size:clamp(28px,5vw,42px);font-weight:800;margin-bottom:10px}
.gallery-head p{color:#6b7280;font-size:16px}
.gallery-filters{display:flex;gap:8px;flex-wrap:wrap;justify-content:center;margin-bottom:32px}
.gf-btn{padding:7px 18px;border-radius:20px;border:1.5px solid #e5e7eb;background:#fff;font-size:13px;font-weight:600;cursor:pointer;transition:all .2s;color:#374151}
.gf-btn:hover,.gf-btn.active{background:#1a56db;color:#fff;border-color:#1a56db}
.gallery-grid{columns:3;column-gap:16px}
@media(max-width:900px){.gallery-grid{columns:2}}
@media(max-width:500px){.gallery-grid{columns:1}}
.gallery-item{break-inside:avoid;margin-bottom:16px;border-radius:12px;overflow:hidden;position:relative;cursor:pointer;display:block}
.gallery-item img{width:100%;display:block;transition:transform .4s cubic-bezier(.16,1,.3,1)}
.gallery-item:hover img{transform:scale(1.05)}
.gallery-item .overlay{position:absolute;inset:0;background:linear-gradient(to top,rgba(0,0,0,.5),transparent);opacity:0;transition:opacity .3s;display:flex;align-items:flex-end;padding:14px}
.gallery-item:hover .overlay{opacity:1}
.overlay-title{color:#fff;font-size:13px;font-weight:600}
/* Lightbox */
.lightbox{display:none;position:fixed;inset:0;background:rgba(0,0,0,.92);z-index:9999;place-items:center}
.lightbox.open{display:grid}
.lb-inner{position:relative;max-width:90vw;max-height:90vh}
.lb-inner img{max-width:90vw;max-height:85vh;object-fit:contain;border-radius:8px;display:block}
.lb-close{position:absolute;top:-40px;right:0;color:#fff;font-size:28px;cursor:pointer;background:none;border:none;line-height:1}
.lb-nav{position:absolute;top:50%;transform:translateY(-50%);color:#fff;font-size:32px;cursor:pointer;background:rgba(255,255,255,.1);border:none;border-radius:50%;width:50px;height:50px;display:grid;place-items:center;transition:background .2s}
.lb-nav:hover{background:rgba(255,255,255,.25)}
.lb-prev{left:-64px}.lb-next{right:-64px}
@media(max-width:600px){.lb-prev{left:-10px}.lb-next{right:-10px}}
.lb-caption{color:#ccc;font-size:13px;text-align:center;margin-top:10px}
.lb-counter{color:#888;font-size:12px;text-align:center;margin-top:4px}
</style>

<div class="gallery-wrap">
    <div class="gallery-head">
        <span style="display:inline-block;background:#dbeafe;color:#1e40af;font-size:11px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;padding:5px 14px;border-radius:20px;margin-bottom:12px">Our Gallery</span>
        <h1>Memories & Milestones</h1>
        <p>Events, visa approvals, student achievements and office moments</p>
    </div>

    <?php if (!empty($categories)): ?>
    <div class="gallery-filters">
        <button class="gf-btn active" onclick="filterGallery('all',this)">All</button>
        <?php foreach($categories as $cat): ?>
        <button class="gf-btn" onclick="filterGallery('<?=htmlspecialchars($cat)?>',this)"><?=htmlspecialchars(ucfirst($cat))?></button>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <div class="gallery-grid" id="galleryGrid">
        <?php if (!empty($db_photos)): ?>
            <?php foreach($db_photos as $i=>$p): ?>
            <a class="gallery-item" data-category="<?=htmlspecialchars($p['category']??'general')?>"
               onclick="openLightbox(<?=$i?>);return false" href="#">
                <img src="<?=htmlspecialchars(BASE_URL.'/'.$p['image'])?>"
                     alt="<?=htmlspecialchars($p['title']??'Gallery')?>"
                     loading="lazy"
                     onerror="this.closest('.gallery-item').style.display='none'">
                <div class="overlay">
                    <span class="overlay-title"><?=htmlspecialchars($p['title']??'')?></span>
                </div>
            </a>
            <?php endforeach; ?>
        <?php else: ?>
            <?php foreach($static_images as $i=>$img): ?>
            <a class="gallery-item" onclick="openLightbox(<?=$i?>);return false" href="#">
                <img src="<?=htmlspecialchars($B.$img)?>" alt="Gallery <?=$i+1?>" loading="lazy"
                     onerror="this.closest('.gallery-item').style.display='none'">
                <div class="overlay"></div>
            </a>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <?php if (empty($db_photos) && empty($static_images)): ?>
    <div style="text-align:center;padding:60px;color:#9ca3af">
        <i class="fas fa-images" style="font-size:48px;opacity:.3;display:block;margin-bottom:16px"></i>
        <p>Gallery coming soon.</p>
    </div>
    <?php endif; ?>
</div>

<!-- Lightbox -->
<div class="lightbox" id="lightbox" onclick="if(event.target===this)closeLightbox()">
    <div class="lb-inner">
        <button class="lb-close" onclick="closeLightbox()"><i class="fas fa-times"></i></button>
        <button class="lb-nav lb-prev" onclick="lbNav(-1)"><i class="fas fa-chevron-left"></i></button>
        <img id="lbImg" src="" alt="">
        <button class="lb-nav lb-next" onclick="lbNav(1)"><i class="fas fa-chevron-right"></i></button>
        <div class="lb-caption" id="lbCaption"></div>
        <div class="lb-counter" id="lbCounter"></div>
    </div>
</div>

<script>
var items = Array.from(document.querySelectorAll('.gallery-item:not([style*="none"])'));
var cur = 0;

function openLightbox(i) {
    var visible = items.filter(el => el.style.display !== 'none');
    cur = visible.indexOf(items[i]);
    if (cur < 0) cur = 0;
    showLb(visible);
}

function showLb(visible) {
    if (!visible) visible = items.filter(el => el.style.display !== 'none');
    var el = visible[cur];
    if (!el) return;
    document.getElementById('lbImg').src = el.querySelector('img').src;
    document.getElementById('lbCaption').textContent = el.querySelector('.overlay-title')?.textContent || '';
    document.getElementById('lbCounter').textContent = (cur+1) + ' / ' + visible.length;
    document.getElementById('lightbox').classList.add('open');
}

function lbNav(dir) {
    var visible = items.filter(el => el.style.display !== 'none');
    cur = (cur + dir + visible.length) % visible.length;
    showLb(visible);
}

function closeLightbox() {
    document.getElementById('lightbox').classList.remove('open');
}

document.addEventListener('keydown', function(e) {
    var lb = document.getElementById('lightbox');
    if (!lb.classList.contains('open')) return;
    if (e.key === 'ArrowLeft')  lbNav(-1);
    if (e.key === 'ArrowRight') lbNav(1);
    if (e.key === 'Escape')     closeLightbox();
});

function filterGallery(cat, btn) {
    document.querySelectorAll('.gf-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    items.forEach(el => {
        if (cat === 'all' || el.dataset.category === cat) {
            el.style.display = '';
        } else {
            el.style.display = 'none';
        }
    });
}
</script>

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