<?php
$pageTitle = 'Gallery';
$currentPage = 'gallery';
require_once __DIR__ . '/backend/includes/head.php';
require_once __DIR__ . '/backend/includes/navbar.php';

require_once __DIR__ . '/backend/config/database.php';
$db = getDB();

function detectGalleryMediaType(array $item): string {
  $rawType = strtolower(trim((string)($item['media_type'] ?? '')));
  if (in_array($rawType, ['image', 'video'], true)) {
    return $rawType;
  }

  $path = strtolower(parse_url((string)($item['image_url'] ?? ''), PHP_URL_PATH) ?? '');
  $ext = pathinfo($path, PATHINFO_EXTENSION);
  if (in_array($ext, ['mp4', 'webm', 'ogg', 'mov', 'm4v', 'avi', 'mkv'], true)) {
    return 'video';
  }

  // Fallback for old rows where media_type/extension are unreliable.
  if (!empty($item['image_url'])) {
    $urlPath = parse_url((string)$item['image_url'], PHP_URL_PATH);
    if (is_string($urlPath) && $urlPath !== '') {
      $rel = $urlPath;
      if (str_starts_with($rel, '/stile-lpg')) {
        $rel = substr($rel, strlen('/stile-lpg'));
      }
      $localPath = realpath(__DIR__ . $rel);
      if ($localPath && file_exists($localPath)) {
        $mime = @mime_content_type($localPath);
        if (is_string($mime) && str_starts_with($mime, 'video/')) {
          return 'video';
        }
      }
    }
  }

  return 'image';
}

// Gallery with category and description - check if media_type column exists
try {
    $stmt = $db->query("SELECT id,title,description,image_url,media_type,category,created_at FROM gallery ORDER BY created_at DESC");
    $galleryItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // If media_type column doesn't exist, query without it
    $stmt = $db->query("SELECT id,title,description,image_url,category,created_at FROM gallery ORDER BY created_at DESC");
    $galleryItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
  // Keep media_type unset for backward compatibility; detection helper will infer type.
    foreach ($galleryItems as &$item) {
    $item['media_type'] = null;
    }
}

// Category color mapping
$categoryColors = [
    'Delivery'       => ['bg' => '#fff7ed', 'color' => '#f97316'],
    'Installation'   => ['bg' => '#eff6ff', 'color' => '#2563eb'],
    'Infrastructure' => ['bg' => '#f5f3ff', 'color' => '#7c3aed'],
    'Commercial'     => ['bg' => '#f0fdf4', 'color' => '#15803d'],
    'Products'       => ['bg' => '#fef9c3', 'color' => '#a16207'],
    'General'        => ['bg' => '#f1f5f9', 'color' => '#475569'],
];
?>

<!-- Hero -->
<section style="background:linear-gradient(145deg,#0f172a 0%,#1e293b 60%,#0f172a 100%);padding:5rem 0 4rem;position:relative;overflow:hidden">
  <div style="position:absolute;inset:0;background-image:radial-gradient(circle,rgba(255,255,255,.02) 1px,transparent 1px);background-size:28px 28px;pointer-events:none"></div>
  <div style="position:absolute;bottom:-60px;left:50%;transform:translateX(-50%);width:500px;height:200px;background:radial-gradient(ellipse,rgba(249,115,22,.12) 0%,transparent 70%);pointer-events:none"></div>
  <div style="max-width:860px;margin:0 auto;padding:0 1.5rem;text-align:center;position:relative">
    <div style="display:inline-flex;align-items:center;gap:.5rem;background:rgba(249,115,22,.15);border:1px solid rgba(249,115,22,.3);border-radius:50px;padding:.4rem 1.1rem;margin-bottom:1.75rem">
      <svg width="14" height="14" fill="none" stroke="#f97316" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z"/><circle cx="12" cy="13" r="4"/></svg>
      <span style="color:#f97316;font-size:.78rem;font-weight:700;letter-spacing:.08em">OUR GALLERY</span>
    </div>
    <h1 style="color:#fff;font-weight:900;font-size:clamp(2rem,5vw,3rem);line-height:1.1;margin-bottom:1.25rem">
      See Our <span style="background:linear-gradient(90deg,#f97316,#fbbf24);-webkit-background-clip:text;-webkit-text-fill-color:transparent">Work in Action</span>
    </h1>
    <p style="color:#94a3b8;font-size:1.05rem;line-height:1.7;max-width:560px;margin:0 auto 2rem">Explore our delivery team, safety practices, and happy customers enjoying reliable LPG service.</p>
    
    <!-- Category badges -->
    <div style="display:flex;gap:.6rem;flex-wrap:wrap;justify-content:center">
      <?php foreach ($categoryColors as $cat => $style): ?>
      <span style="background:<?= $style['bg'] ?>;color:<?= $style['color'] ?>;border-radius:20px;padding:.35rem .85rem;font-size:.75rem;font-weight:700"><?= $cat ?></span>
      <?php endforeach; ?>
    </div>
  </div>
</section>

<!-- Gallery Grid -->
<section style="max-width:1200px;margin:0 auto;padding:4rem 1.5rem">
  <?php if(empty($galleryItems)): ?>
  <div style="text-align:center;padding:5rem 1rem">
    <div style="width:80px;height:80px;border-radius:20px;background:#f1f5f9;display:flex;align-items:center;justify-content:center;margin:0 auto 1.5rem;opacity:.5">
      <svg width="40" height="40" fill="none" stroke="#94a3b8" stroke-width="1.5" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline stroke-linecap="round" stroke-linejoin="round" points="21 15 16 10 5 21"/></svg>
    </div>
    <h3 style="color:#94a3b8;font-weight:700;font-size:1.2rem;margin:0 0 .5rem">No images yet</h3>
    <p style="color:#cbd5e1;font-size:.9rem">Check back soon for gallery updates.</p>
  </div>
  <?php else: ?>
  <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:1.5rem">
    <?php foreach($galleryItems as $item): 
      $cat = $item['category'] ?: 'General';
      $catStyle = $categoryColors[$cat] ?? ['bg' => '#f1f5f9', 'color' => '#475569'];
      $mediaType = detectGalleryMediaType($item);
      $isVideo = $mediaType === 'video';
    ?>
    <div class="gallery-card anim-fade-up" <?= $isVideo ? '' : 'onclick="openLightbox(' . htmlspecialchars(json_encode($item['image_url']), ENT_QUOTES) . ',' . htmlspecialchars(json_encode($item['title']), ENT_QUOTES) . ', false)"' ?>
         style="background:#fff;border:1px solid #e8ecf0;border-radius:18px;overflow:hidden;cursor:<?= $isVideo ? 'default' : 'pointer' ?>;position:relative;transition:all .3s;box-shadow:0 2px 12px rgba(0,0,0,.08)">
      
      <div style="height:280px;background:#f8fafc;overflow:hidden;position:relative">
        <?php if($item['image_url']): 
          if ($isVideo): ?>
        <video src="<?= htmlspecialchars($item['image_url']) ?>" width="100%" height="100%" style="object-fit:cover; position:relative; z-index:20;" preload="metadata" controls playsinline autoplay muted loop>
          Your browser does not support video playback.
        </video>
        
        <!-- Play Button Overlay Indicator -->
        <div style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;z-index:25;pointer-events:none;">
            <div style="width:60px;height:60px;background:rgba(15,23,42,0.6);border-radius:50%;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(4px);border:2px solid rgba(255,255,255,0.2);">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="#fff" style="margin-left:4px;"><polygon points="5 3 19 12 5 21 5 3"/></svg>
            </div>
        </div>

        <div style="position:absolute;top:14px;right:14px;background:rgba(239,68,68,.95);color:#fff;border-radius:20px;padding:.4rem .8rem;font-size:.68rem;font-weight:700;display:flex;align-items:center;gap:.4rem;box-shadow:0 2px 10px rgba(0,0,0,.3);z-index:30; pointer-events:none;">
          <svg width="11" height="11" viewBox="0 0 24 24" fill="#fff"><polygon points="5 3 19 12 5 21 5 3"/></svg>
          VIDEO
        </div>
        <?php else: ?>
        <img src="<?= htmlspecialchars($item['image_url']) ?>" alt="<?= htmlspecialchars($item['title']) ?>"
             class="gallery-img" style="width:100%;height:100%;object-fit:cover;transition:transform .35s ease">
        <?php endif; ?>
        
        <!-- Base gradient overlay -->
        <div class="gallery-base-overlay" style="position:absolute;inset:0;background:linear-gradient(to top,rgba(15,23,42,.7) 0%,rgba(15,23,42,.12) 50%,transparent 100%);transition:all .3s; pointer-events:none; z-index:10;"></div>
        
        <!-- Category badge (top-left) -->
        <span style="position:absolute;top:14px;left:14px;background:<?= $catStyle['bg'] ?>;color:<?= $catStyle['color'] ?>;border-radius:8px;padding:.4rem .8rem;font-size:.72rem;font-weight:700;box-shadow:0 2px 10px rgba(0,0,0,.2);border:1.5px solid <?= $catStyle['color'] ?>30;backdrop-filter:blur(4px)"><?= htmlspecialchars($cat) ?></span>
        
        <!-- Title and Description at bottom left (always visible) -->
        <div class="gallery-title-overlay" style="position:absolute;bottom:0;left:0;right:0;padding:1.2rem 1.3rem;<?= $mediaType === 'video' ? 'pointer-events:none' : '' ?>;z-index:15;">
          <h3 style="color:#fff;font-weight:800;font-size:1.05rem;margin:0 0 .4rem;text-shadow:0 2px 12px rgba(0,0,0,.6);line-height:1.3"><?= htmlspecialchars($item['title']) ?></h3>
          <?php if ($item['description']): ?>
          <p style="color:#e2e8f0;font-size:.85rem;margin:0;text-shadow:0 1px 4px rgba(0,0,0,.5);line-height:1.5"><?= htmlspecialchars($item['description']) ?></p>
          <?php endif; ?>
        </div>
        
        <?php else: ?>
        <div style="width:100%;height:100%;background:linear-gradient(135deg,#f1f5f9,#e2e8f0);display:flex;align-items:center;justify-content:center;opacity:.4">
          <svg width="48" height="48" fill="none" stroke="#94a3b8" stroke-width="1.5" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline stroke-linecap="round" stroke-linejoin="round" points="21 15 16 10 5 21"/></svg>
        </div>
        <?php endif; ?>
      </div>
      
      <div style="padding:1rem 1.3rem;background:#fafbfc;border-top:1px solid #f1f5f9">
        <div style="color:#94a3b8;font-size:.75rem;font-weight:500;display:flex;align-items:center;gap:.4rem">
          <svg width="12" height="12" fill="none" stroke="#94a3b8" stroke-width="2" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
          <?= date('M j, Y', strtotime($item['created_at'])) ?>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>
</section>

<!-- Lightbox -->
<div id="lightbox" onclick="closeLightbox()" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.9);z-index:9999;align-items:center;justify-content:center;padding:2rem;backdrop-filter:blur(8px)">
  <button onclick="closeLightbox()" style="position:absolute;top:1.5rem;right:1.5rem;background:rgba(255,255,255,.1);border:none;color:#fff;width:44px;height:44px;border-radius:50%;font-size:20px;cursor:pointer;z-index:10000;display:flex;align-items:center;justify-content:center;">✕</button>
  <div onclick="event.stopPropagation()" style="max-width:900px;width:100%;max-height:85vh;background:#1e293b;border-radius:20px;overflow:hidden;position:relative;display:flex;flex-direction:column;">
    
    <div id="lightbox_content" style="flex-grow:1;display:flex;align-items:center;justify-content:center;background:#0f172a;position:relative;min-height:300px;">
        <img id="lightbox_img" src="" alt="" style="width:100%;max-height:75vh;object-fit:contain;display:none;">
        <video id="lightbox_video" controls autoplay playsinline style="width:100%;max-height:75vh;object-fit:contain;display:none;">
            Your browser does not support HTML5 video.
        </video>
    </div>

    <div style="padding:1rem 1.5rem;background:#1e293b;border-top:1px solid #334155;">
      <p id="lightbox_title" style="color:#f1f5f9;font-weight:700;font-size:1.05rem;margin:0"></p>
    </div>
  </div>
</div>

<script>
function openLightbox(url, title, isVideo = false) {
    const lightbox = document.getElementById('lightbox');
    const img = document.getElementById('lightbox_img');
    const video = document.getElementById('lightbox_video');
    const titleEl = document.getElementById('lightbox_title');
    
    titleEl.textContent = title;
    
    if (isVideo) {
        img.style.display = 'none';
        video.style.display = 'block';
        video.src = url; // Set src directly on video element for better compatibility
        video.load(); // Reload the video element to fetch the new source
        video.play().catch(e => console.log('Autoplay prevented', e));
    } else {
        video.style.display = 'none';
        video.pause(); // Pause any playing video
        img.style.display = 'block';
        img.src = url;
    }
    
    lightbox.style.display = 'flex';
    document.body.style.overflow = 'hidden'; // Prevent scrolling
}

function closeLightbox() {
    const lightbox = document.getElementById('lightbox');
    const video = document.getElementById('lightbox_video');
    
    lightbox.style.display = 'none';
    document.body.style.overflow = 'auto'; // Restore scrolling
    video.pause(); // Stop video playing when closed
}

// Close on escape key
document.addEventListener('keydown', function(event) {
    if (event.key === "Escape") {
        closeLightbox();
    }
});
</script>

<style>
.gallery-card:hover {
  box-shadow: 0 16px 48px rgba(0,0,0,.18)!important;
  transform: translateY(-8px);
}
</style>



<?php require_once __DIR__ . '/backend/includes/footer.php'; ?>
