<?php
$adminTitle = 'Gallery Manager';
require_once __DIR__ . '/includes/header.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id    = (int)($_POST['id'] ?? 0);
    $title = sanitize($_POST['title'] ?? '');
    $desc  = sanitize($_POST['description'] ?? '');
    $cat   = sanitize($_POST['category'] ?? '');
    $sort  = (int)($_POST['sort_order'] ?? 0);
    $active = isset($_POST['is_active']) ? 1 : 0;

    if ($id > 0) {
        Database::execute("UPDATE gallery SET title=?,description=?,category=?,sort_order=?,is_active=? WHERE id=?",
            [$title,$desc,$cat,$sort,$active,$id]);
        $_SESSION['flash']['success'] = 'Gallery item updated.';
    } else {
        if (empty($_FILES['image']['tmp_name'])) { $_SESSION['flash']['error'] = 'Image required.'; header('Location: /admin/gallery.php'); exit; }
        $res = handleFileUpload($_FILES['image'], 'gallery', ALLOWED_IMAGE_TYPES);
        if (!$res['success']) { $_SESSION['flash']['error'] = $res['error']; header('Location: /admin/gallery.php'); exit; }
        Database::insert("INSERT INTO gallery (title,description,image,category,sort_order,is_active) VALUES (?,?,?,?,?,?)",
            [$title,$desc,$res['filename'],$cat,$sort,$active]);
        $_SESSION['flash']['success'] = 'Image added to gallery.';
    }
    header('Location: /admin/gallery.php');
    exit;
}

if (isset($_GET['delete'])) {
    Database::execute("UPDATE gallery SET is_active=0 WHERE id=?", [(int)$_GET['delete']]);
    $_SESSION['flash']['success'] = 'Item removed from gallery.';
    header('Location: /admin/gallery.php');
    exit;
}

$items = Database::fetchAll("SELECT * FROM gallery ORDER BY sort_order, id DESC");
$categories = Database::fetchAll("SELECT DISTINCT category FROM gallery WHERE category IS NOT NULL");
?>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
  <!-- Upload Form -->
  <div class="card-dark p-5">
    <h3 class="font-semibold mb-4">Upload Image</h3>
    <form method="POST" enctype="multipart/form-data" class="space-y-3">
      <div>
        <label class="text-xs text-gray-400 block mb-1">Image File *</label>
        <input type="file" name="image" accept="image/*" required style="width:auto">
      </div>
      <div>
        <label class="text-xs text-gray-400 block mb-1">Title</label>
        <input type="text" name="title" placeholder="Optional caption">
      </div>
      <div>
        <label class="text-xs text-gray-400 block mb-1">Category</label>
        <input type="text" name="category" placeholder="e.g. Workshop, Products">
      </div>
      <div>
        <label class="text-xs text-gray-400 block mb-1">Description</label>
        <textarea name="description" rows="2"></textarea>
      </div>
      <div>
        <label class="text-xs text-gray-400 block mb-1">Sort Order</label>
        <input type="number" name="sort_order" value="0">
      </div>
      <label class="flex items-center gap-2 text-sm">
        <input type="checkbox" name="is_active" value="1" checked style="width:auto"> Active
      </label>
      <button class="btn-primary w-full text-sm">Upload Image</button>
    </form>
  </div>

  <!-- Gallery Grid -->
  <div class="lg:col-span-2">
    <h3 class="font-semibold mb-4">Gallery (<?= count($items) ?> items)</h3>
    <div class="grid grid-cols-3 gap-3">
      <?php foreach ($items as $img): ?>
      <div class="relative group">
        <img src="/uploads/<?= e($img['image']) ?>" class="w-full h-32 object-cover rounded-lg">
        <div class="absolute inset-0 bg-black/70 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg flex flex-col items-center justify-center gap-2 p-2">
          <div class="text-xs text-center text-white"><?= e($img['title'] ?? '') ?></div>
          <div class="flex gap-2">
            <a href="?delete=<?= $img['id'] ?>" class="text-xs text-red-400 hover:underline" onclick="return confirm('Remove from gallery?')">Delete</a>
            <span class="text-xs <?= $img['is_active']?'text-green-400':'text-gray-400' ?>"><?= $img['is_active']?'Active':'Hidden' ?></span>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
      <?php if (empty($items)): ?>
      <div class="col-span-3 text-center text-gray-400 py-8">No gallery images yet.</div>
      <?php endif; ?>
    </div>
  </div>
</div>

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