<?php
// ============================================================
// FILE: admin/galeri.php — Daftar & Kelola Galeri Portofolio
// Tambah  → galeri_tambah.php
// Hapus   → galeri_hapus.php (POST)
// Edit    → inline modal POST ke sini (aksi=edit)
// ============================================================
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
requireAdmin();

$pdo = db();

// ── Edit judul / kategori / urutan (inline modal) ────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['aksi'] ?? '') === 'edit') {
    $gid    = (int)($_POST['gid']          ?? 0);
    $judul  = trim($_POST['judul']          ?? '');
    $katId  = (int)($_POST['kategori_id']  ?? 0) ?: null;
    $urutan = (int)($_POST['urutan']        ?? 0);

    if ($gid && $judul) {
        $pdo->prepare("UPDATE galeri SET judul=?, kategori_id=?, urutan=? WHERE id=?")
            ->execute([$judul, $katId, $urutan, $gid]);
        setFlash('success', 'Data galeri berhasil diperbarui.');
    }
    redirect(BASE_URL . '/admin/galeri.php');
}

$galeriList   = $pdo->query("
    SELECT g.*, k.nama AS nama_kategori
    FROM galeri g
    LEFT JOIN kategori k ON k.id = g.kategori_id
    ORDER BY g.urutan ASC, g.id DESC
")->fetchAll();

$kategoriList = $pdo->query("SELECT * FROM kategori ORDER BY nama")->fetchAll();
$pageTitle    = 'Galeri Portofolio';
include __DIR__ . '/admin_layout.php';
?>

<!-- Header -->
<div class="adm-page-header mb-4">
  <div>
    <h4 class="adm-page-title"><i class="bi bi-images me-2"></i>Galeri Portofolio</h4>
    <p class="adm-page-sub mb-0"><?= count($galeriList) ?> foto terdaftar</p>
  </div>
  <a href="<?= BASE_URL ?>/admin/galeri_tambah.php" class="btn btn-primary-brand">
    <i class="bi bi-plus-lg me-2"></i>Upload Foto Baru
  </a>
</div>

<!-- Grid Foto -->
<?php if (empty($galeriList)): ?>
  <div class="admin-card">
    <div class="p-5 text-center">
      <i class="bi bi-images fs-1 text-muted d-block mb-3"></i>
      <h5 class="text-muted">Belum ada foto galeri</h5>
      <p class="text-muted small mb-4">Tambahkan foto hasil pengerjaan untuk ditampilkan di halaman utama.</p>
      <a href="<?= BASE_URL ?>/admin/galeri_tambah.php" class="btn btn-primary-brand">
        <i class="bi bi-cloud-arrow-up me-2"></i>Upload Foto Pertama
      </a>
    </div>
  </div>

<?php else: ?>
  <!-- Toolbar filter kategori -->
  <?php if (count($kategoriList) > 0): ?>
    <div class="mb-3 d-flex flex-wrap gap-2 align-items-center">
      <span class="small fw-semibold text-muted me-1">Filter:</span>
      <a href="?" class="btn btn-sm <?= !isset($_GET['kat']) ? 'btn-primary' : 'btn-outline-secondary' ?>">
        Semua (<?= count($galeriList) ?>)
      </a>
      <?php foreach ($kategoriList as $k):
        $cntKat = count(array_filter($galeriList, fn($g) => $g['kategori_id'] == $k['id']));
        if ($cntKat === 0) continue;
      ?>
        <a href="?kat=<?= $k['id'] ?>"
           class="btn btn-sm <?= ($_GET['kat'] ?? '') == $k['id'] ? 'btn-primary' : 'btn-outline-secondary' ?>">
          <?= e($k['nama']) ?> (<?= $cntKat ?>)
        </a>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>

  <!-- Grid -->
  <?php
  // Filter by kategori jika ada
  $filtered = isset($_GET['kat'])
    ? array_filter($galeriList, fn($g) => $g['kategori_id'] == $_GET['kat'])
    : $galeriList;
  ?>
  <div class="adm-galeri-grid">
    <?php foreach ($filtered as $g): ?>
      <div class="adm-galeri-item">
        <img src="<?= UPLOAD_URL ?>/galeri/<?= e($g['nama_file']) ?>"
             alt="<?= e($g['judul']) ?>" loading="lazy">

        <div class="adm-galeri-overlay">
          <div class="adm-galeri-title"><?= e($g['judul']) ?></div>
          <?php if ($g['nama_kategori']): ?>
            <div class="adm-galeri-kat">
              <i class="bi bi-tag me-1"></i><?= e($g['nama_kategori']) ?>
            </div>
          <?php endif; ?>
          <div class="adm-galeri-urutan">Urutan: <?= $g['urutan'] ?></div>

          <div class="adm-galeri-btns mt-1">
            <!-- Tombol Edit (buka modal) -->
            <button class="adm-foto-btn adm-foto-btn--star"
                    onclick="bukaEditGaleri(
                      <?= $g['id'] ?>,
                      '<?= addslashes(e($g['judul'])) ?>',
                      <?= (int)$g['kategori_id'] ?>,
                      <?= (int)$g['urutan'] ?>
                    )"
                    title="Edit judul / kategori / urutan">
              <i class="bi bi-pencil-fill"></i>
            </button>

            <!-- Tombol Hapus → galeri_hapus.php -->
            <form method="POST"
                  action="<?= BASE_URL ?>/admin/galeri_hapus.php"
                  class="d-inline"
                  onsubmit="return confirm('Hapus foto «<?= e(addslashes($g['judul'])) ?>»?\nTindakan ini tidak bisa dibatalkan.')">
              <input type="hidden" name="hapus_id" value="<?= $g['id'] ?>">
              <button type="submit" class="adm-foto-btn adm-foto-btn--del" title="Hapus foto">
                <i class="bi bi-trash3-fill"></i>
              </button>
            </form>
          </div>
        </div>

        <!-- Badge urutan -->
        <div class="adm-galeri-num"><?= $g['urutan'] ?></div>
      </div>
    <?php endforeach; ?>
  </div>

  <div class="mt-3 text-muted small">
    <i class="bi bi-info-circle me-1"></i>
    Hover pada foto untuk aksi edit / hapus. Urutan kecil = tampil lebih awal.
  </div>
<?php endif; ?>


<!-- ── Modal Edit Galeri ─────────────────────────────────── -->
<div class="modal fade" id="modalEditGaleri" tabindex="-1" aria-labelledby="modalEditLabel">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h6 class="modal-title" id="modalEditLabel">
          <i class="bi bi-pencil me-2"></i>Edit Foto Galeri
        </h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="<?= BASE_URL ?>/admin/galeri.php">
        <input type="hidden" name="aksi" value="edit">
        <input type="hidden" name="gid"  id="editGid">
        <div class="modal-body">
          <div class="mb-3">
            <label class="ck-label" for="editJudul">Judul <span class="text-danger">*</span></label>
            <input type="text" name="judul" id="editJudul" class="form-control ck-input" required>
          </div>
          <div class="mb-3">
            <label class="ck-label" for="editKat">Kategori</label>
            <select name="kategori_id" id="editKat" class="form-select ck-input">
              <option value="">— Tanpa Kategori —</option>
              <?php foreach ($kategoriList as $k): ?>
                <option value="<?= $k['id'] ?>"><?= e($k['nama']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="mb-0">
            <label class="ck-label" for="editUrutan">Urutan Tampil</label>
            <input type="number" name="urutan" id="editUrutan"
                   class="form-control ck-input" min="0">
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary btn-sm"
                  data-bs-dismiss="modal">Batal</button>
          <button type="submit" class="btn btn-primary-brand btn-sm">
            <i class="bi bi-check-lg me-1"></i>Simpan
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<style>
/* Badge nomor urutan di pojok foto */
.adm-galeri-num {
  position: absolute;
  top: 6px; right: 6px;
  background: rgba(0,0,0,.55);
  color: white;
  font-size: .65rem;
  font-weight: 800;
  padding: .1rem .45rem;
  border-radius: 20px;
  pointer-events: none;
}
</style>

<script>
function bukaEditGaleri(id, judul, katId, urutan) {
  document.getElementById('editGid').value    = id;
  document.getElementById('editJudul').value  = judul;
  document.getElementById('editUrutan').value = urutan;

  const sel = document.getElementById('editKat');
  Array.from(sel.options).forEach(opt => {
    opt.selected = parseInt(opt.value) === katId;
  });

  new bootstrap.Modal(document.getElementById('modalEditGaleri')).show();
}
</script>

<?php include __DIR__ . '/admin_footer.php'; ?>