<?php
// public/galeri.php - Galeri Foto & Video dengan Pencarian, Filter & Pagination
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/db.php';
$db = get_db();

// Get parameters
$search = $_GET['search'] ?? '';
$filter = $_GET['filter'] ?? 'all';
$category = $_GET['category'] ?? '';
$sort = $_GET['sort'] ?? 'newest';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 12;
$offset = ($page - 1) * $per_page;

// Build query for counting
$count_sql = 'SELECT COUNT(*) FROM media WHERE active = 1';
$sql = 'SELECT * FROM media WHERE active = 1';
$params = [];

// Search filter
if (!empty($search)) {
  $search_condition = ' AND (title LIKE :search OR description LIKE :search)';
  $count_sql .= $search_condition;
  $sql .= $search_condition;
  $params[':search'] = '%' . $search . '%';
}

// Type filter
if ($filter === 'photo') {
  $count_sql .= ' AND type = :type';
  $sql .= ' AND type = :type';
  $params[':type'] = 'photo';
} elseif ($filter === 'video') {
  $count_sql .= ' AND type = :type';
  $sql .= ' AND type = :type';
  $params[':type'] = 'video';
}

// Category filter
if (!empty($category)) {
  $count_sql .= ' AND category = :cat';
  $sql .= ' AND category = :cat';
  $params[':cat'] = $category;
}

// Get total count
$count_stmt = $db->prepare($count_sql);
$count_stmt->execute($params);
$total_items = $count_stmt->fetchColumn();
$total_pages = ceil($total_items / $per_page);

// Sorting
switch ($sort) {
  case 'oldest':
    $sql .= ' ORDER BY date_uploaded ASC';
    break;
  case 'title':
    $sql .= ' ORDER BY title ASC';
    break;
  default: // newest
    $sql .= ' ORDER BY date_uploaded DESC';
}

// Pagination
$sql .= ' LIMIT :limit OFFSET :offset';

// Execute query
$stmt = $db->prepare($sql);
foreach ($params as $key => $value) {
  $stmt->bindValue($key, $value);
}
$stmt->bindValue(':limit', $per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$media_list = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get categories
$categories = $db->query('SELECT DISTINCT category FROM media WHERE active = 1 AND category IS NOT NULL AND category != "" ORDER BY category')->fetchAll(PDO::FETCH_COLUMN);

// Build query string for pagination
function build_query_string($exclude = []) {
  $params = $_GET;
  foreach ($exclude as $key) {
    unset($params[$key]);
  }
  return http_build_query($params);
}

require __DIR__ . '/_header.php';
?>

<div class="container py-5">
  <!-- Header -->
  <div class="row mb-5">
    <div class="col-lg-8 mx-auto text-center">
      <span class="badge bg-primary-subtle text-primary mb-3">Galeri</span>
      <h1 class="display-5 fw-bold mb-3">Foto & Video Kegiatan</h1>
      <p class="text-muted lead">Dokumentasi kegiatan dan fasilitas sekolah kami</p>
    </div>
  </div>

  <!-- Search & Filter Bar -->
  <div class="row mb-4">
    <div class="col-12">
      <div class="card border-0 shadow-sm">
        <div class="card-body">
          <form method="GET" action="galeri.php" class="row g-3">
            <!-- Search -->
            <div class="col-md-4">
              <div class="input-group">
                <span class="input-group-text"><i class="fa fa-search"></i></span>
                <input type="text" name="search" class="form-control" placeholder="Cari foto/video..." value="<?php echo e($search); ?>">
              </div>
            </div>
            
            <!-- Type Filter -->
            <div class="col-md-2">
              <select name="filter" class="form-select">
                <option value="all" <?php echo $filter === 'all' ? 'selected' : ''; ?>>Semua Tipe</option>
                <option value="photo" <?php echo $filter === 'photo' ? 'selected' : ''; ?>>Foto</option>
                <option value="video" <?php echo $filter === 'video' ? 'selected' : ''; ?>>Video</option>
              </select>
            </div>
            
            <!-- Category Filter -->
            <div class="col-md-3">
              <select name="category" class="form-select">
                <option value="">Semua Kategori</option>
                <?php foreach ($categories as $cat): ?>
                  <option value="<?php echo e($cat); ?>" <?php echo $category === $cat ? 'selected' : ''; ?>>
                    <?php echo e($cat); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            
            <!-- Sort -->
            <div class="col-md-2">
              <select name="sort" class="form-select">
                <option value="newest" <?php echo $sort === 'newest' ? 'selected' : ''; ?>>Terbaru</option>
                <option value="oldest" <?php echo $sort === 'oldest' ? 'selected' : ''; ?>>Terlama</option>
                <option value="title" <?php echo $sort === 'title' ? 'selected' : ''; ?>>Judul A-Z</option>
              </select>
            </div>
            
            <!-- Buttons -->
            <div class="col-md-1">
              <button type="submit" class="btn btn-primary w-100" title="Cari">
                <i class="fa fa-search">Cari</i>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>

  <!-- Results Info -->
  <div class="row mb-3">
    <div class="col-12">
      <div class="d-flex justify-content-between align-items-center">
        <p class="text-muted mb-0">
          Menampilkan <?php echo count($media_list); ?> dari <?php echo $total_items; ?> media
          <?php if (!empty($search)): ?>
            untuk "<strong><?php echo e($search); ?></strong>"
          <?php endif; ?>
        </p>
        <?php if (!empty($search) || $filter !== 'all' || !empty($category)): ?>
          <a href="galeri.php" class="btn btn-sm btn-outline-secondary">
            <i class="fa fa-times me-1"></i>Reset Filter
          </a>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- Media Grid -->
  <div class="row g-4">
    <?php foreach ($media_list as $media): ?>
      <div class="col-lg-4 col-md-6">
        <div class="card h-100 border-0 shadow-sm hover-lift">
          <?php if ($media['type'] === 'photo'): ?>
            <!-- Photo Thumbnail -->
            <div class="position-relative overflow-hidden" style="height: 250px; cursor: pointer;"
                 data-bs-toggle="modal" 
                 data-bs-target="#mediaModal<?php echo $media['id']; ?>">
              <img src="<?php echo base_url(); ?>/data/uploads/media/<?php echo e($media['file_path']); ?>" 
                   class="w-100 h-100" 
                   style="object-fit: cover;"
                   alt="<?php echo e($media['title']); ?>">
              <div class="position-absolute top-0 start-0 m-3">
                <span class="badge bg-info"><i class="fa fa-image me-1"></i>Foto</span>
              </div>
            </div>
          <?php else: ?>
            <!-- Video Thumbnail -->
            <div class="position-relative overflow-hidden" 
                 style="height: 250px; background: linear-gradient(135deg, #e0f2fe 0%, #dbeafe 100%); cursor: pointer;"
                 data-bs-toggle="modal" 
                 data-bs-target="#mediaModal<?php echo $media['id']; ?>">
              <div class="d-flex align-items-center justify-content-center h-100">
                <div class="text-center">
                  <i class="fa fa-play-circle fa-5x text-primary mb-3" style="opacity: 0.8;"></i>
                  <p class="text-primary fw-bold mb-0">Klik untuk memutar</p>
                </div>
              </div>
              <div class="position-absolute top-0 start-0 m-3">
                <span class="badge bg-danger"><i class="fa fa-video me-1"></i>Video</span>
              </div>
            </div>
          <?php endif; ?>
          
          <div class="card-body">
            <?php if (!empty($media['category'])): ?>
              <span class="badge bg-primary-subtle text-primary mb-2"><?php echo e($media['category']); ?></span>
            <?php endif; ?>
            <h5 class="card-title"><?php echo e($media['title']); ?></h5>
            <?php if (!empty($media['description'])): ?>
              <p class="card-text text-muted small"><?php echo e(mb_substr($media['description'], 0, 100)); ?><?php echo mb_strlen($media['description']) > 100 ? '...' : ''; ?></p>
            <?php endif; ?>
            <small class="text-muted">
              <i class="fa fa-calendar me-1"></i><?php echo date('d M Y', strtotime($media['date_uploaded'])); ?>
            </small>
          </div>
        </div>
      </div>

      <!-- Modal -->
      <div class="modal fade" id="mediaModal<?php echo $media['id']; ?>" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title"><?php echo e($media['title']); ?></h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0">
              <?php if ($media['type'] === 'photo'): ?>
                <img src="<?php echo base_url(); ?>/data/uploads/media/<?php echo e($media['file_path']); ?>" 
                     class="w-100" 
                     alt="<?php echo e($media['title']); ?>">
              <?php else: ?>
                <div class="ratio ratio-16x9">
                  <iframe data-src="<?php echo e($media['video_url']); ?>" 
                          frameborder="0"
                          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                          allowfullscreen></iframe>
                </div>
              <?php endif; ?>
            </div>
            <?php if (!empty($media['description'])): ?>
              <div class="modal-footer">
                <p class="text-muted mb-0 w-100"><?php echo e($media['description']); ?></p>
              </div>
            <?php endif; ?>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
    
    <?php if (empty($media_list)): ?>
      <div class="col-12">
        <div class="text-center py-5">
          <i class="fa fa-images fa-4x text-muted mb-3"></i>
          <p class="text-muted mb-2">Tidak ada media yang ditemukan</p>
          <?php if (!empty($search) || $filter !== 'all' || !empty($category)): ?>
            <a href="galeri.php" class="btn btn-primary">Reset Filter</a>
          <?php endif; ?>
        </div>
      </div>
    <?php endif; ?>
  </div>

  <!-- Pagination -->
  <?php if ($total_pages > 1): ?>
    <div class="row mt-5">
      <div class="col-12">
        <nav aria-label="Page navigation">
          <ul class="pagination justify-content-center">
            <!-- Previous -->
            <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
              <a class="page-link" href="?<?php echo build_query_string(['page']); ?>&page=<?php echo $page - 1; ?>">
                <i class="fa fa-chevron-left"></i>
              </a>
            </li>
            
            <?php
            $start = max(1, $page - 2);
            $end = min($total_pages, $page + 2);
            
            if ($start > 1): ?>
              <li class="page-item">
                <a class="page-link" href="?<?php echo build_query_string(['page']); ?>&page=1">1</a>
              </li>
              <?php if ($start > 2): ?>
                <li class="page-item disabled"><span class="page-link">...</span></li>
              <?php endif; ?>
            <?php endif; ?>
            
            <?php for ($i = $start; $i <= $end; $i++): ?>
              <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                <a class="page-link" href="?<?php echo build_query_string(['page']); ?>&page=<?php echo $i; ?>">
                  <?php echo $i; ?>
                </a>
              </li>
            <?php endfor; ?>
            
            <?php if ($end < $total_pages): ?>
              <?php if ($end < $total_pages - 1): ?>
                <li class="page-item disabled"><span class="page-link">...</span></li>
              <?php endif; ?>
              <li class="page-item">
                <a class="page-link" href="?<?php echo build_query_string(['page']); ?>&page=<?php echo $total_pages; ?>">
                  <?php echo $total_pages; ?>
                </a>
              </li>
            <?php endif; ?>
            
            <!-- Next -->
            <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
              <a class="page-link" href="?<?php echo build_query_string(['page']); ?>&page=<?php echo $page + 1; ?>">
                <i class="fa fa-chevron-right"></i>
              </a>
            </li>
          </ul>
        </nav>
        
        <p class="text-center text-muted small">
          Halaman <?php echo $page; ?> dari <?php echo $total_pages; ?>
        </p>
      </div>
    </div>
  <?php endif; ?>
</div>

<style>
/* Force modal and backdrop to be on top with high z-index */
.modal {
  z-index: 9999 !important;
}

.modal-backdrop {
  z-index: 9998 !important;
}

.modal-dialog {
  z-index: 10000 !important;
}

/* Ensure backdrop is clickable */
.modal-backdrop.show {
  opacity: 0.5;
  cursor: pointer;
}

/* Prevent body scroll when modal is open */
body.modal-open {
  overflow: hidden;
}

/* Pagination styling */
.pagination .page-link {
  border-radius: 0.375rem;
  margin: 0 0.25rem;
  border: 1px solid #dee2e6;
}

.pagination .page-item.active .page-link {
  background-color: var(--primary-color, #4f46e5);
  border-color: var(--primary-color, #4f46e5);
}

.pagination .page-link:hover {
  background-color: #f8f9fa;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // Get all modals
  const modals = document.querySelectorAll('.modal');
  
  modals.forEach(modal => {
    // Initialize Bootstrap Modal with backdrop click enabled
    const bsModal = new bootstrap.Modal(modal, {
      backdrop: true,
      keyboard: true
    });
    
    // Load video when modal is shown
    modal.addEventListener('shown.bs.modal', function() {
      const iframe = this.querySelector('iframe[data-src]');
      if (iframe && !iframe.src) {
        iframe.src = iframe.getAttribute('data-src');
      }
    });
    
    // Stop video when modal closes
    modal.addEventListener('hidden.bs.modal', function() {
      const iframe = this.querySelector('iframe[src]');
      if (iframe) {
        iframe.src = '';
      }
    });
    
    // Explicitly handle backdrop click
    modal.addEventListener('click', function(event) {
      if (event.target === this) {
        const modalInstance = bootstrap.Modal.getInstance(this);
        if (modalInstance) {
          modalInstance.hide();
        }
      }
    });
  });
});
</script>

<?php require __DIR__ . '/_footer.php'; ?>
