<?php
require_once 'config/db.php';
$settings   = getAllSettings($pdo);
$activePage = 'gallery';

$tab      = $_GET['tab']      ?? 'photo';
$filter   = $_GET['cat']      ?? 'all';
$album_id = (int)($_GET['album_id'] ?? 0);

/* ── Photo mode ─────────────────────────────────────────────────────────── */
$album   = null;
$albums  = [];
$photos  = [];
$albCats = [];

if ($tab === 'photo') {
    if ($album_id) {
        // Album-detail view
        $stmt = $pdo->prepare("SELECT * FROM gallery_albums WHERE id=? AND is_active=1");
        $stmt->execute([$album_id]);
        $album = $stmt->fetch();
        if (!$album) { header('Location: gallery.php?tab=photo'); exit; }

        $stmt2 = $pdo->prepare("SELECT * FROM gallery_photos WHERE album_id=? ORDER BY sort_order ASC, id ASC");
        $stmt2->execute([$album_id]);
        $photos = $stmt2->fetchAll();

        $pageTitle = htmlspecialchars($album['title']).' - Gallery - '.($settings['site_name']??'');
    } else {
        // Albums grid view
        $pageTitle = 'Gallery - '.($settings['site_name']??'');

        $albCats = $pdo->query("SELECT DISTINCT category FROM gallery_albums WHERE is_active=1")->fetchAll(PDO::FETCH_COLUMN);

        if ($filter !== 'all') {
            $stmt = $pdo->prepare("
                SELECT a.*, COUNT(p.id) AS photo_count
                FROM gallery_albums a
                LEFT JOIN gallery_photos p ON p.album_id = a.id
                WHERE a.is_active=1 AND a.category=?
                GROUP BY a.id ORDER BY a.sort_order ASC, a.id DESC
            ");
            $stmt->execute([$filter]);
        } else {
            $stmt = $pdo->query("
                SELECT a.*, COUNT(p.id) AS photo_count
                FROM gallery_albums a
                LEFT JOIN gallery_photos p ON p.album_id = a.id
                WHERE a.is_active=1
                GROUP BY a.id ORDER BY a.sort_order ASC, a.id DESC
            ");
        }
        $albums = $stmt->fetchAll();
    }
} else {
    // Video tab
    $pageTitle = 'Gallery - '.($settings['site_name']??'');
    $videos = $pdo->query("SELECT * FROM gallery_videos WHERE is_active=1 ORDER BY sort_order ASC")->fetchAll();
}

include 'partials/header.php';
?>

<div class="page-hero">
    <div class="container">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-2">
                <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                <li class="breadcrumb-item<?= (!$album_id)?'  active':'' ?>">
                    <?php if ($album_id): ?><a href="gallery.php?tab=photo"><?php endif; ?>
                    <span data-en="Gallery" data-id="Galeri">Gallery</span>
                    <?php if ($album_id): ?></a><?php endif; ?>
                </li>
                <?php if ($album_id): ?>
                    <li class="breadcrumb-item active"><?= htmlspecialchars($album['title']) ?></li>
                <?php endif; ?>
            </ol>
        </nav>
        <?php if ($album_id && $album): ?>
            <h1 class="fw-bold mb-1 fs-2"><?= htmlspecialchars($album['title']) ?></h1>
            <div class="d-flex flex-wrap gap-3 align-items-center" style="color:rgba(255,255,255,.7)">
                <span class="badge" style="background:var(--accent);color:#000"><?= htmlspecialchars(ucwords($album['category'])) ?></span>
                <?php if ($album['location']): ?><span><i class="bi bi-geo-alt me-1"></i><?= htmlspecialchars($album['location']) ?></span><?php endif; ?>
                <?php if ($album['project_date']): ?><span><i class="bi bi-calendar3 me-1"></i><?= date('d M Y', strtotime($album['project_date'])) ?></span><?php endif; ?>
                <span><i class="bi bi-images me-1"></i><?= count($photos) ?> foto</span>
            </div>
        <?php else: ?>
            <h1 class="fw-bold mb-1 fs-2" data-en="Gallery" data-id="Galeri">Gallery</h1>
            <p class="mb-0" style="color:rgba(255,255,255,.6);" data-en="Our project documentation in photos and videos" data-id="Dokumentasi proyek kami dalam foto dan video">Dokumentasi proyek kami dalam foto dan video</p>
        <?php endif; ?>
    </div>
</div>

<section class="py-5 py-lg-6">
    <div class="container">

        <?php if (!$album_id): ?>
        <!-- Tab Switcher (only on main gallery page) -->
        <ul class="nav nav-tabs gallery-tabs mb-4 fade-up">
            <li class="nav-item">
                <a class="nav-link <?= $tab==='photo'?'active':'' ?>" href="gallery.php?tab=photo">
                    <i class="bi bi-images me-2"></i><span data-en="Photo Gallery" data-id="Galeri Foto">Galeri Foto</span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?= $tab==='video'?'active':'' ?>" href="gallery.php?tab=video">
                    <i class="bi bi-play-circle me-2"></i><span data-en="Video Gallery" data-id="Galeri Video">Galeri Video</span>
                </a>
            </li>
        </ul>
        <?php endif; ?>

        <!-- ══ ALBUM DETAIL VIEW ══════════════════════════════════════════ -->
        <?php if ($tab === 'photo' && $album_id && $album): ?>

            <div class="mb-4 fade-up">
                <a href="gallery.php?tab=photo" class="btn btn-sm btn-outline-secondary">
                    <i class="bi bi-arrow-left me-1"></i> Kembali ke Semua Album
                </a>
            </div>

            <?php if ($album['description']): ?>
                <p class="text-muted mb-4 fade-up"><?= nl2br(htmlspecialchars($album['description'])) ?></p>
            <?php endif; ?>

            <?php if (empty($photos)): ?>
                <div class="text-center py-5 text-muted fade-up">
                    <i class="bi bi-images display-4 d-block mb-3"></i>
                    Belum ada foto di album ini.
                </div>
            <?php else: ?>
                <div class="gallery-grid fade-up">
                    <?php foreach ($photos as $i => $p): ?>
                        <div class="gallery-item" onclick="openGalleryLightbox(<?= $i ?>)">
                            <img src="<?= htmlspecialchars($p['image_path']) ?>"
                                 alt="<?= htmlspecialchars($p['title'] ?: 'Foto '.($i+1)) ?>"
                                 onerror="this.src='https://placehold.co/400x300/e0e0e0/888?text=Photo'">
                            <div class="gallery-overlay">
                                <span class="gallery-title"><?= htmlspecialchars($p['title'] ?: 'Foto '.($i+1)) ?></span>
                                <i class="bi bi-zoom-in fs-4"></i>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- JS photo array for lightbox navigation -->
                <script>
                const galleryPhotos = <?= json_encode(array_map(fn($p) => [
                    'src'   => $p['image_path'] ?? '',
                    'title' => $p['title'] ?? '',
                    'cap'   => $p['caption'] ?? '',
                ], $photos), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
                </script>
            <?php endif; ?>

        <!-- ══ ALBUMS GRID VIEW ══════════════════════════════════════════ -->
        <?php elseif ($tab === 'photo'): ?>

            <!-- Category filter -->
            <?php if (!empty($albCats)): ?>
            <div class="filter-tabs fade-up">
                <a href="gallery.php?tab=photo&cat=all" class="filter-tab <?= $filter==='all'?'active':'' ?>" data-en="All" data-id="Semua">Semua</a>
                <?php foreach ($albCats as $c): ?>
                    <a href="gallery.php?tab=photo&cat=<?= urlencode($c) ?>" class="filter-tab <?= $filter===$c?'active':'' ?>"><?= htmlspecialchars(ucwords($c)) ?></a>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <div class="row g-4 fade-up mt-1">
                <?php if (empty($albums)): ?>
                    <div class="col-12 text-center py-5 text-muted">
                        <i class="bi bi-folder-x display-4 d-block mb-3"></i>Belum ada album tersedia.
                    </div>
                <?php endif; ?>
                <?php foreach ($albums as $a): ?>
                <div class="col-sm-6 col-lg-4">
                    <a href="gallery.php?album_id=<?= $a['id'] ?>" class="text-decoration-none text-dark">
                        <div class="card border-0 shadow-sm h-100 album-card">
                            <div class="album-cover-wrap">
                                <img src="<?= htmlspecialchars($a['cover_image'] ?? '') ?>"
                                     alt="<?= htmlspecialchars($a['title']) ?>"
                                     class="album-cover"
                                     onerror="this.src='https://placehold.co/480x300/e0e0e0/888?text=Album'">
                                <div class="album-photo-count">
                                    <i class="bi bi-images me-1"></i><?= (int)$a['photo_count'] ?> foto
                                </div>
                            </div>
                            <div class="card-body">
                                <span class="badge mb-2" style="background:var(--accent);color:#000;font-size:.7rem"><?= htmlspecialchars(ucwords($a['category'])) ?></span>
                                <h6 class="fw-bold mb-1"><?= htmlspecialchars($a['title']) ?></h6>
                                <div class="text-muted small d-flex flex-column gap-1">
                                    <?php if ($a['location']): ?>
                                        <span><i class="bi bi-geo-alt me-1"></i><?= htmlspecialchars($a['location']) ?></span>
                                    <?php endif; ?>
                                    <?php if ($a['project_date']): ?>
                                        <span><i class="bi bi-calendar3 me-1"></i><?= date('d M Y', strtotime($a['project_date'])) ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="card-footer bg-transparent border-top-0 pb-3 px-3">
                                <span class="btn btn-sm btn-outline-dark w-100">
                                    <i class="bi bi-eye me-1"></i> Lihat Foto
                                </span>
                            </div>
                        </div>
                    </a>
                </div>
                <?php endforeach; ?>
            </div>

        <!-- ══ VIDEO TAB ════════════════════════════════════════════════ -->
        <?php else: ?>
            <div class="row g-4 fade-up">
                <?php foreach ($videos as $v):
                    $yt_url = $v['youtube_url'] ?? '';
                    $thumb  = $v['thumbnail']   ?? '';
                    // Extract YouTube video ID from any YouTube URL format
                    if (!$thumb && $yt_url) {
                        preg_match('/(?:v=|\/embed\/|youtu\.be\/)([a-zA-Z0-9_-]{11})/', $yt_url, $m);
                        if (!empty($m[1])) $thumb = 'https://img.youtube.com/vi/'.$m[1].'/hqdefault.jpg';
                    }
                    // Build embed URL for iframe
                    $embed_url = '';
                    if ($yt_url) {
                        preg_match('/(?:v=|\/embed\/|youtu\.be\/)([a-zA-Z0-9_-]{11})/', $yt_url, $m2);
                        if (!empty($m2[1])) $embed_url = 'https://www.youtube.com/embed/'.$m2[1].'?autoplay=1';
                    }
                ?>
                <div class="col-sm-6 col-lg-4">
                    <div class="video-card" onclick="openVideo('<?= htmlspecialchars($embed_url) ?>')">
                        <div class="video-thumb-wrap">
                            <img src="<?= htmlspecialchars($thumb) ?>" alt="<?= htmlspecialchars($v['title']) ?>"
                                 onerror="this.src='https://placehold.co/480x270/1a1a2e/fff?text=Video'">
                            <div class="video-play-btn"><i class="bi bi-play-fill"></i></div>
                        </div>
                        <div class="p-3">
                            <h6 class="fw-semibold mb-1"><?= htmlspecialchars($v['title']) ?></h6>
                            <small class="text-muted"><?= htmlspecialchars($v['description']??'') ?></small>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php if (empty($videos)): ?>
                    <div class="col-12 text-center py-5 text-muted">
                        <i class="bi bi-camera-video display-4 d-block mb-3"></i>Belum ada video tersedia.
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>

    </div>
</section>

<!-- Lightbox Modal (with navigation) -->
<div class="modal fade" id="lightboxModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-xl">
        <div class="modal-content bg-dark border-0">
            <div class="modal-header border-0 pb-0">
                <div>
                    <h6 class="modal-title text-white mb-0" id="lightboxTitle"></h6>
                    <small class="text-white-50" id="lightboxCaption"></small>
                </div>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center p-2 position-relative">
                <button class="btn btn-sm btn-dark position-absolute start-0 top-50 translate-middle-y ms-2" id="lbPrev" onclick="lbNav(-1)" style="z-index:5"><i class="bi bi-chevron-left"></i></button>
                <img id="lightboxImg" src="" alt="" class="img-fluid rounded" style="max-height:78vh;object-fit:contain;">
                <button class="btn btn-sm btn-dark position-absolute end-0 top-50 translate-middle-y me-2" id="lbNext" onclick="lbNav(1)" style="z-index:5"><i class="bi bi-chevron-right"></i></button>
            </div>
            <div class="modal-footer border-0 pt-0 justify-content-center">
                <span class="text-white-50 small" id="lbCounter"></span>
            </div>
        </div>
    </div>
</div>

<!-- Video Modal -->
<div class="modal fade" id="videoModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content bg-dark border-0">
            <div class="modal-header border-0 pb-0">
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" onclick="stopVideo()"></button>
            </div>
            <div class="modal-body p-2">
                <div class="ratio ratio-16x9">
                    <iframe id="videoFrame" src="" allow="autoplay; encrypted-media" allowfullscreen></iframe>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
/* ── Video Modal ─────────────────────────────────────────── */
function openVideo(embedUrl) {
    if (!embedUrl) return;
    document.getElementById('videoFrame').src = embedUrl;
    new bootstrap.Modal(document.getElementById('videoModal')).show();
}
function stopVideo() {
    document.getElementById('videoFrame').src = '';
}
document.getElementById('videoModal').addEventListener('hidden.bs.modal', stopVideo);

/* ── Gallery Lightbox with navigation ─────────────────────── */
let lbPhotos = [], lbIndex = 0;
function openGalleryLightbox(idx) {
    lbPhotos = galleryPhotos || [];
    lbIndex  = idx;
    renderLb();
    new bootstrap.Modal(document.getElementById('lightboxModal')).show();
}
function renderLb() {
    const p = lbPhotos[lbIndex];
    if (!p) return;
    document.getElementById('lightboxImg').src      = p.src;
    document.getElementById('lightboxTitle').textContent   = p.title;
    document.getElementById('lightboxCaption').textContent = p.cap;
    document.getElementById('lbCounter').textContent = (lbIndex+1) + ' / ' + lbPhotos.length;
    document.getElementById('lbPrev').style.display = lbPhotos.length > 1 ? '' : 'none';
    document.getElementById('lbNext').style.display = lbPhotos.length > 1 ? '' : 'none';
}
function lbNav(dir) {
    lbIndex = (lbIndex + dir + lbPhotos.length) % lbPhotos.length;
    renderLb();
}
document.addEventListener('keydown', e => {
    const modal = document.getElementById('lightboxModal');
    if (!modal.classList.contains('show')) return;
    if (e.key === 'ArrowRight') lbNav(1);
    if (e.key === 'ArrowLeft')  lbNav(-1);
    if (e.key === 'Escape') bootstrap.Modal.getInstance(modal)?.hide();
});
</script>

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