<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/auth.php';
$gallery    = readJSON(GALLERY_FILE);
$categories = array_unique(array_column($gallery, 'category'));
$pageTitle  = 'Gallery Manager | KTE Admin';
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo htmlspecialchars($pageTitle); ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700;900&family=DM+Sans:wght@300;400;500&family=Bebas+Neue&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="/assets/css/style.css">
</head>
<body class="admin-body">
<div class="admin-sidebar d-none d-lg-block">
  <div class="admin-sidebar-logo"><a href="/admin/dashboard.php">KTE Admin</a><span>20th Kenya Expo</span></div>
  <ul class="admin-nav">
    <li><a href="/admin/dashboard.php"><i class="fas fa-chart-line"></i> Dashboard</a></li>
    <li><a href="/admin/leads.php"><i class="fas fa-users"></i> All Leads</a></li>
    <li><a href="/admin/packages.php"><i class="fas fa-box-open"></i> Packages Manager</a></li>
    <li><a href="/admin/sponsorship.php"><i class="fas fa-crown"></i> Sponsorship Manager</a></li>
    <li><a href="/admin/gallery.php" class="active"><i class="fas fa-images"></i> Gallery Manager</a></li>
    <li><a href="/admin/export.php"><i class="fas fa-file-csv"></i> Export CSV</a></li>
    <li><a href="/admin/logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
  </ul>
</div>
<div class="admin-main">
  <div class="admin-header">
    <div><h4 style="font-family:var(--font-heading);margin-bottom:4px;">Gallery Manager</h4><p style="color:var(--text-muted);font-size:0.85rem;margin:0;"><?php echo count($gallery); ?> images &middot; <?php echo count(array_filter($gallery, fn($g) => !empty($g['featured']))); ?> featured</p></div>
    <div class="d-flex gap-2">
      <button class="btn btn-outline-gold btn-sm" onclick="adminGallery.openUrlModal()"><i class="fas fa-link me-2"></i>Add via URL</button>
      <button class="btn btn-gold btn-sm" onclick="adminGallery.openAddModal()"><i class="fas fa-plus me-2"></i>Add Image</button>
    </div>
  </div>

  <div class="row g-3 mb-4">
    <div class="col-6 col-lg-3"><div class="kpi-card"><div class="kpi-number"><?php echo count($gallery); ?></div><div class="kpi-label">Total Images</div></div></div>
    <div class="col-6 col-lg-3"><div class="kpi-card"><div class="kpi-number" style="color:var(--success);"><?php echo count(array_filter($gallery, fn($g) => !empty($g['featured']))); ?></div><div class="kpi-label">Featured</div></div></div>
    <div class="col-6 col-lg-3"><div class="kpi-card"><div class="kpi-number"><?php echo count($categories); ?></div><div class="kpi-label">Categories</div></div></div>
    <div class="col-6 col-lg-3"><div class="kpi-card"><div class="kpi-number"><?php echo count(array_filter($gallery, fn($g) => ($g['category'] ?? '') === 'expo')); ?></div><div class="kpi-label">Expo Photos</div></div></div>
  </div>

  <div class="row g-3">
    <?php foreach ($gallery as $img): ?>
    <div class="col-6 col-md-4 col-lg-3 admin-gallery-card" data-id="<?php echo htmlspecialchars($img['id']); ?>">
      <div class="glass-card" style="padding:0;overflow:hidden;">
        <div style="position:relative;">
          <img src="<?php echo htmlspecialchars($img['url']); ?>" alt="<?php echo htmlspecialchars($img['alt']); ?>" style="width:100%;height:160px;object-fit:cover;">
          <?php if (!empty($img['featured'])): ?><span class="badge" style="position:absolute;top:8px;left:8px;background:var(--secondary);color:#0A0F0D;font-size:0.65rem;">FEATURED</span><?php endif; ?>
        </div>
        <div style="padding:16px;">
          <h6 style="font-family:var(--font-heading);font-size:0.95rem;margin-bottom:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?php echo htmlspecialchars($img['title']); ?></h6>
          <p style="color:var(--text-muted);font-size:0.75rem;margin-bottom:10px;"><span class="badge" style="background:rgba(212,175,55,0.1);color:var(--secondary);font-size:0.65rem;"><?php echo htmlspecialchars($img['category']); ?></span> &middot; #<?php echo $img['sort_order'] ?? 0; ?></p>
          <div class="d-flex gap-2">
            <button class="btn btn-sm btn-outline-gold gallery-edit-btn" data-id="<?php echo htmlspecialchars($img['id']); ?>"><i class="fas fa-edit"></i></button>
            <button class="btn btn-sm btn-outline-danger gallery-delete-btn" data-id="<?php echo htmlspecialchars($img['id']); ?>" data-title="<?php echo htmlspecialchars($img['title']); ?>"><i class="fas fa-trash"></i></button>
          </div>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>

<!-- Hidden file input — triggered directly by "Add Image" button, no modal in between -->
<input type="file" id="bulkFileInput" accept="image/jpeg,image/png,image/webp,image/gif" multiple style="display:none;">

<!-- Upload Progress Modal — appears automatically once files are picked -->
<div class="modal fade" id="uploadProgressModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog"><div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title">Uploading Photos</h5>
      <button type="button" class="btn-close" id="uploadProgressClose" data-bs-dismiss="modal" style="display:none;"></button>
    </div>
    <div class="modal-body">
      <div id="uploadProgressText" style="margin-bottom:10px;font-size:0.9rem;color:var(--text-muted);">Preparing...</div>
      <div class="progress" style="height:10px;">
        <div id="uploadProgressBar" class="progress-bar bg-warning" role="progressbar" style="width:0%;"></div>
      </div>
      <div id="uploadProgressLog" style="margin-top:14px;max-height:200px;overflow-y:auto;font-size:0.8rem;"></div>
    </div>
  </div></div>
</div>

<!-- Add via URL Modal (secondary path, kept minimal) -->
<div class="modal fade" id="addUrlModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">Add Image via URL</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body">
    <form id="addUrlForm">
      <div class="mb-3"><label class="form-label">Image URL *</label><input type="url" name="url" id="addUrlInput" class="form-control" placeholder="https://..." required></div>
    </form>
    <div id="addUrlStatus" style="display:none;"></div>
  </div>
  <div class="modal-footer"><button type="button" class="btn btn-outline-gold btn-sm" data-bs-dismiss="modal">Cancel</button><button type="button" class="btn btn-gold btn-sm" id="addUrlSubmitBtn" onclick="adminGallery.submitUrlForm()">Add Image</button></div>
</div></div></div>

<!-- Edit Image Modal — unchanged, still used to fine-tune metadata after upload -->
<div class="modal fade" id="editImageModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">Edit Image</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body">
    <form id="editImageForm">
      <input type="hidden" name="id" id="editImageId">
      <div class="mb-3"><label class="form-label">Image URL *</label><input type="url" name="url" id="editImageUrl" class="form-control" required></div>
      <div class="mb-3"><label class="form-label">Title *</label><input type="text" name="title" id="editImageTitle" class="form-control" required></div>
      <div class="mb-3"><label class="form-label">Category</label><select name="category" id="editImageCategory" class="form-select"><option value="expo">Expo</option><option value="networking">Networking</option><option value="conference">Conference</option><option value="kenya">Kenya</option></select></div>
      <div class="mb-3"><label class="form-label">Caption</label><textarea name="caption" id="editImageCaption" class="form-control" rows="2"></textarea></div>
      <div class="mb-3"><label class="form-label">Alt Text</label><input type="text" name="alt" id="editImageAlt" class="form-control"></div>
      <div class="row"><div class="col-6"><div class="form-check"><input class="form-check-input" type="checkbox" name="featured" id="editImageFeatured"><label class="form-check-label" for="editImageFeatured">Featured</label></div></div><div class="col-6"><label class="form-label">Sort Order</label><input type="number" name="sort_order" id="editImageSort" class="form-control"></div></div>
    </form>
  </div>
  <div class="modal-footer"><button type="button" class="btn btn-outline-gold btn-sm" data-bs-dismiss="modal">Cancel</button><button type="button" class="btn btn-gold btn-sm" onclick="adminGallery.submitEditForm()">Update Image</button></div>
</div></div></div>

<script id="galleryData" type="application/json"><?php echo json_encode($gallery); ?></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="/assets/js/main.js" defer></script>
<script>
const BATCH_SIZE = 10;
let _uploadProgressModalInstance = null;

// IMPORTANT: main.js loads with `defer`, so it executes AFTER this inline
// script block but BEFORE 'DOMContentLoaded' fires. If we assign our
// adminGallery methods at the top level here, main.js's own definitions
// (which run later) can silently overwrite them. To guarantee our
// overrides always win, we assign them inside 'DOMContentLoaded' — which
// fires only after ALL deferred scripts, including main.js, have finished.
document.addEventListener('DOMContentLoaded', () => {
  if (!window.adminGallery) window.adminGallery = {};

  if (document.getElementById('galleryData')) adminGallery.init();

  // "Add Image" button -> opens the OS file picker directly. No form modal.
  adminGallery.openAddModal = function() {
    document.getElementById('bulkFileInput').click();
  };

  adminGallery.openUrlModal = function() {
    const modalEl = document.getElementById('addUrlModal');
    new bootstrap.Modal(modalEl).show();
  };

  const bulkInput = document.getElementById('bulkFileInput');
  if (bulkInput) {
    bulkInput.addEventListener('change', function() {
      const files = Array.from(this.files || []);
      this.value = ''; // reset so selecting the same files again still fires 'change'
      if (files.length === 0) return;
      uploadFilesInBatches(files);
    });
  }

  adminGallery.submitUrlForm = submitUrlFormImpl;
});

async function uploadFilesInBatches(files) {
  const modalEl   = document.getElementById('uploadProgressModal');
  const closeBtn  = document.getElementById('uploadProgressClose');
  const textEl    = document.getElementById('uploadProgressText');
  const barEl     = document.getElementById('uploadProgressBar');
  const logEl     = document.getElementById('uploadProgressLog');

  closeBtn.style.display = 'none';
  textEl.textContent = 'Preparing...';
  barEl.style.width = '0%';
  logEl.innerHTML = '';

  _uploadProgressModalInstance = new bootstrap.Modal(modalEl);
  _uploadProgressModalInstance.show();

  // Split into batches of 10
  const batches = [];
  for (let i = 0; i < files.length; i += BATCH_SIZE) {
    batches.push(files.slice(i, i + BATCH_SIZE));
  }

  let uploadedCount = 0;
  let failedCount = 0;

  for (let b = 0; b < batches.length; b++) {
    const batch = batches[b];
    textEl.textContent = `Uploading batch ${b + 1} of ${batches.length} (${batch.length} photo${batch.length > 1 ? 's' : ''})...`;

    const formData = new FormData();
    batch.forEach(file => formData.append('image_file[]', file));

    try {
      const res = await fetch('/admin/gallery_upload.php', { method: 'POST', body: formData });
      const data = await res.json();

      if (data.success) {
        uploadedCount += data.count || batch.length;
        logEl.innerHTML += `<div class="text-success"><i class="fas fa-check-circle me-1"></i>Batch ${b + 1}: ${data.message || 'Uploaded'}</div>`;
      } else {
        failedCount += batch.length;
        logEl.innerHTML += `<div class="text-danger"><i class="fas fa-times-circle me-1"></i>Batch ${b + 1} failed: ${data.error || 'Unknown error'}</div>`;
      }
    } catch (err) {
      failedCount += batch.length;
      logEl.innerHTML += `<div class="text-danger"><i class="fas fa-times-circle me-1"></i>Batch ${b + 1} failed: ${err.message}</div>`;
    }

    logEl.scrollTop = logEl.scrollHeight;
    barEl.style.width = Math.round(((b + 1) / batches.length) * 100) + '%';
  }

  textEl.textContent = failedCount > 0
    ? `Done — ${uploadedCount} uploaded, ${failedCount} failed.`
    : `Done — ${uploadedCount} photo${uploadedCount > 1 ? 's' : ''} uploaded successfully.`;
  closeBtn.style.display = '';

  // Auto-reload shortly after so new cards render from server data
  setTimeout(() => window.location.reload(), 1200);
}

// Add via URL — single image, minimal fields, auto title from URL filename server-side
function submitUrlFormImpl() {
  const input     = document.getElementById('addUrlInput');
  const btn       = document.getElementById('addUrlSubmitBtn');
  const statusBox = document.getElementById('addUrlStatus');
  const url       = input.value.trim();

  if (!url) {
    statusBox.style.display = 'block';
    statusBox.className = 'text-danger small';
    statusBox.textContent = 'URL is required.';
    return;
  }

  const formData = new FormData();
  formData.append('url', url);

  btn.disabled = true;
  const originalText = btn.innerHTML;
  btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Adding...';

  fetch('/admin/gallery_upload.php', { method: 'POST', body: formData })
    .then(res => res.json())
    .then(data => {
      btn.disabled = false;
      btn.innerHTML = originalText;
      statusBox.style.display = 'block';
      if (data.success) {
        statusBox.className = 'text-success small';
        statusBox.textContent = data.message || 'Added.';
        setTimeout(() => window.location.reload(), 600);
      } else {
        statusBox.className = 'text-danger small';
        statusBox.textContent = data.error || 'Something went wrong.';
      }
    })
    .catch(err => {
      btn.disabled = false;
      btn.innerHTML = originalText;
      statusBox.style.display = 'block';
      statusBox.className = 'text-danger small';
      statusBox.textContent = 'Failed: ' + err.message;
    });
}
</script>
</body>
</html>