<?php
require_once 'config/config.php';
require_once 'includes/functions.php';
startSecureSession();
$pageTitle = 'Gallery';

$catFilter = trim($_GET['cat'] ?? '');
$params = $catFilter ? ['cat' => $catFilter] : [];
$where  = $catFilter ? "AND category=?" : "";
$galleryItems = Database::fetchAll(
    "SELECT * FROM gallery WHERE is_active=1 $where ORDER BY sort_order ASC, id DESC",
    $catFilter ? [$catFilter] : []
);
$galleryCategories = Database::fetchAll("SELECT DISTINCT category FROM gallery WHERE is_active=1 AND category IS NOT NULL");

include 'includes/header.php';
?>

<div class="max-w-7xl mx-auto px-4 py-14">
  <div class="text-center mb-10 fade-in">
    <div class="section-tag">📸 Our Work</div>
    <h1 class="section-title">Project Gallery</h1>
    <div class="section-divider mx-auto"></div>
    <p class="text-gray-400">A showcase of our projects, products, and workshop capabilities.</p>
  </div>

  <!-- Category Filter -->
  <?php if (!empty($galleryCategories)): ?>
  <div class="flex flex-wrap gap-2 justify-center mb-8">
    <a href="/gallery.php" class="text-sm px-4 py-1.5 rounded-full <?= !$catFilter?'bg-orange-600 text-white':'bg-navy-700 text-gray-300 hover:bg-navy-600' ?>">All</a>
    <?php foreach ($galleryCategories as $gc): ?>
    <a href="?cat=<?= urlencode($gc['category']) ?>" class="text-sm px-4 py-1.5 rounded-full <?= $catFilter===$gc['category']?'bg-orange-600 text-white':'bg-navy-700 text-gray-300 hover:bg-navy-600' ?>"><?= e($gc['category']) ?></a>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>

  <?php if (empty($galleryItems)): ?>
  <div class="text-center py-16 text-gray-400">
    <div class="text-5xl mb-4">📷</div>
    <p>Gallery coming soon. Check back for project photos and workshop images.</p>
  </div>
  <?php else: ?>
  <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
    <?php foreach ($galleryItems as $img): ?>
    <div class="group overflow-hidden rounded-xl cursor-pointer relative fade-in" onclick="openLightbox(<?= $img['id'] ?>)">
      <img src="/uploads/<?= e($img['image']) ?>" class="w-full h-48 object-cover transition-transform duration-300 group-hover:scale-110" alt="<?= e($img['title'] ?? '') ?>">
      <div class="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-end p-3">
        <div>
          <?php if ($img['title']): ?><div class="text-sm font-semibold text-white"><?= e($img['title']) ?></div><?php endif; ?>
          <?php if ($img['category']): ?><div class="text-xs text-orange-400"><?= e($img['category']) ?></div><?php endif; ?>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- Lightbox -->
  <div id="lightbox" class="fixed inset-0 bg-black/95 z-[200] hidden flex items-center justify-center" onclick="closeLightbox()">
    <button onclick="closeLightbox()" class="absolute top-4 right-4 text-white text-3xl hover:text-orange-400">✕</button>
    <button onclick="prevImage(event)" class="absolute left-4 text-white text-3xl hover:text-orange-400">‹</button>
    <button onclick="nextImage(event)" class="absolute right-14 text-white text-3xl hover:text-orange-400">›</button>
    <div class="text-center">
      <img id="lightbox-img" src="" class="max-h-[80vh] max-w-[90vw] object-contain rounded-lg">
      <div id="lightbox-caption" class="mt-3 text-sm text-gray-300"></div>
    </div>
  </div>
  <?php endif; ?>
</div>

<script>
const images = <?= json_encode(array_map(fn($img)=>['src'=>'/uploads/'.$img['image'],'title'=>$img['title']??'','cat'=>$img['category']??''], $galleryItems)) ?>;
let current = 0;
function openLightbox(id) {
  const idx = images.findIndex((_, i) => i === id);
  current = idx >= 0 ? idx : 0;
  showImage();
  document.getElementById('lightbox').classList.remove('hidden');
}
function closeLightbox() { document.getElementById('lightbox').classList.add('hidden'); }
function showImage() {
  if (!images[current]) return;
  document.getElementById('lightbox-img').src = images[current].src;
  document.getElementById('lightbox-caption').textContent = images[current].title;
}
function prevImage(e) { e.stopPropagation(); current = (current - 1 + images.length) % images.length; showImage(); }
function nextImage(e) { e.stopPropagation(); current = (current + 1) % images.length; showImage(); }
// Fix openLightbox to use array index
document.querySelectorAll('[onclick^="openLightbox"]').forEach((el, i) => {
  el.onclick = () => { current = i; showImage(); document.getElementById('lightbox').classList.remove('hidden'); };
});
</script>

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