<?php
// ============================================================
// FILE: admin/galeri_tambah.php — Upload Foto Galeri Portofolio
// Fitur:
//   - Form upload foto galeri dengan drag & drop
//   - Preview foto sebelum upload
//   - Pilih kategori (opsional)
//   - Set urutan tampil
//   - Validasi server-side (judul, file, tipe, ukuran)
// ============================================================
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();
$errors       = [];
$kategoriList = $pdo->query("SELECT * FROM kategori ORDER BY nama")->fetchAll();
$jumlahGaleri = (int)$pdo->query("SELECT COUNT(*) FROM galeri")->fetchColumn();

// Nilai default form
$post = [
    'judul'       => '',
    'deskripsi'   => '',
    'kategori_id' => '',
    'urutan'      => $jumlahGaleri, // default urutan = paling akhir
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $post['judul']       = trim($_POST['judul']       ?? '');
    $post['deskripsi']   = trim($_POST['deskripsi']   ?? '');
    $post['kategori_id'] = (int)($_POST['kategori_id'] ?? 0) ?: null;
    $post['urutan']      = (int)($_POST['urutan']     ?? $jumlahGaleri);

    // Validasi
    if (!$post['judul']) {
        $errors[] = 'Judul foto wajib diisi.';
    }
    if (empty($_FILES['foto']['name']) || $_FILES['foto']['error'] !== UPLOAD_ERR_OK) {
        $errors[] = 'Foto wajib dipilih.';
    }

    if (empty($errors)) {
        $namaFile = uploadGambar($_FILES['foto'], 'galeri');

        if (!$namaFile) {
            $errors[] = 'Upload gagal. Pastikan format foto JPG/PNG/WEBP dan ukuran maksimal 5 MB.';
        } else {
            $pdo->prepare("
                INSERT INTO galeri (judul, deskripsi, nama_file, kategori_id, urutan)
                VALUES (?, ?, ?, ?, ?)
            ")->execute([
                $post['judul'],
                $post['deskripsi'] ?: null,
                $namaFile,
                $post['kategori_id'],
                $post['urutan'],
            ]);

            setFlash('success', 'Foto <strong>' . e($post['judul']) . '</strong> berhasil ditambahkan ke galeri!');
            redirect(BASE_URL . '/admin/galeri.php');
        }
    }
}

$pageTitle = 'Upload Foto Galeri';
include __DIR__ . '/admin_layout.php';
?>

<!-- Header -->
<div class="adm-page-header mb-4">
  <div>
    <nav aria-label="breadcrumb" class="mb-1">
      <ol class="breadcrumb small mb-0">
        <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/admin/galeri.php">Galeri</a></li>
        <li class="breadcrumb-item active">Upload Foto Baru</li>
      </ol>
    </nav>
    <h4 class="adm-page-title"><i class="bi bi-cloud-arrow-up me-2"></i>Upload Foto Galeri</h4>
    <p class="adm-page-sub mb-0">Tambah foto portofolio hasil pengerjaan ke halaman galeri</p>
  </div>
  <a href="<?= BASE_URL ?>/admin/galeri.php" class="btn btn-outline-secondary btn-sm">
    <i class="bi bi-arrow-left me-1"></i>Kembali ke Galeri
  </a>
</div>

<?php if (!empty($errors)): ?>
  <div class="alert alert-danger alert-dismissible fade show mb-4">
    <strong><i class="bi bi-exclamation-triangle-fill me-2"></i>Gagal upload:</strong>
    <ul class="mb-0 mt-1 ps-3">
      <?php foreach ($errors as $err): ?>
        <li><?= $err ?></li>
      <?php endforeach; ?>
    </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  </div>
<?php endif; ?>

<div class="row g-4 justify-content-center">
  <div class="col-lg-8">

    <form method="POST" enctype="multipart/form-data" id="frmGaleriTambah" novalidate>

      <!-- Upload Area -->
      <div class="admin-card mb-4">
        <div class="admin-card-header">
          <h6 class="mb-0"><i class="bi bi-image me-2"></i>Pilih Foto</h6>
          <small class="text-muted">JPG / PNG / WEBP · Maks 5 MB</small>
        </div>
        <div class="p-4">

          <!-- Drop Zone -->
          <div class="multi-upload-zone" id="dzGaleri"
               onclick="document.getElementById('iFoto').click()"
               role="button" tabindex="0"
               aria-label="Klik atau drag foto ke area ini">
            <i class="bi bi-cloud-arrow-up-fill adm-dz-icon"></i>
            <p class="fw-semibold mb-1">Klik atau drag foto ke sini</p>
            <p class="small text-muted mb-0">Format: JPG, PNG, WEBP &nbsp;·&nbsp; Ukuran maks: 5 MB</p>
          </div>

          <input type="file" id="iFoto" name="foto"
                 accept="image/jpeg,image/png,image/webp"
                 class="d-none" required
                 onchange="previewFoto(this)">

          <!-- Preview -->
          <div id="previewWrap" class="mt-3 d-none">
            <p class="small fw-semibold text-muted mb-2">Preview:</p>
            <div class="adm-galeri-preview-box">
              <img id="previewImg" src="" alt="Preview foto" class="adm-galeri-preview-img">
              <div class="adm-galeri-preview-info" id="previewInfo"></div>
            </div>
          </div>

        </div>
      </div>

      <!-- Info Foto -->
      <div class="admin-card mb-4">
        <div class="admin-card-header">
          <h6 class="mb-0"><i class="bi bi-info-circle me-2"></i>Informasi Foto</h6>
        </div>
        <div class="p-4">

          <div class="mb-3">
            <label class="ck-label" for="iJudul">
              Judul Foto <span class="text-danger">*</span>
            </label>
            <input type="text" id="iJudul" name="judul"
                   class="form-control ck-input"
                   value="<?= e($post['judul']) ?>"
                   placeholder="Contoh: Pemasangan Kusen Kayu Jati — Bekasi Timur"
                   required>
            <div class="ck-hint">Judul tampil saat foto di-hover di halaman galeri.</div>
          </div>

          <div class="mb-3">
            <label class="ck-label" for="iDesk">
              Deskripsi <span class="text-muted small">(opsional)</span>
            </label>
            <textarea id="iDesk" name="deskripsi" class="form-control ck-input" rows="3"
                      placeholder="Keterangan singkat proyek, lokasi, material yang digunakan…"><?= e($post['deskripsi']) ?></textarea>
          </div>

          <div class="row g-3">
            <div class="col-sm-7">
              <label class="ck-label" for="iKat">
                Kategori <span class="text-muted small">(opsional)</span>
              </label>
              <select id="iKat" name="kategori_id" class="form-select ck-input">
                <option value="">— Tanpa Kategori —</option>
                <?php foreach ($kategoriList as $k): ?>
                  <option value="<?= $k['id'] ?>"
                    <?= $post['kategori_id'] == $k['id'] ? 'selected' : '' ?>>
                    <?= e($k['nama']) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-sm-5">
              <label class="ck-label" for="iUrutan">Urutan Tampil</label>
              <input type="number" id="iUrutan" name="urutan"
                     class="form-control ck-input"
                     value="<?= e($post['urutan']) ?>"
                     min="0" placeholder="0 = paling awal">
              <div class="ck-hint">Angka kecil tampil lebih awal.</div>
            </div>
          </div>

        </div>
      </div>

      <!-- Tombol -->
      <div class="d-flex gap-3">
        <button type="submit" class="btn btn-primary-brand btn-lg flex-grow-1" id="btnUpload">
          <i class="bi bi-cloud-arrow-up me-2"></i>Upload ke Galeri
        </button>
        <a href="<?= BASE_URL ?>/admin/galeri.php" class="btn btn-outline-secondary btn-lg">
          Batal
        </a>
      </div>

    </form>
  </div>
</div>

<style>
.adm-galeri-preview-box {
  border-radius: 12px;
  overflow: hidden;
  border: 2px solid #E2E8F0;
  background: #F8FAFC;
  position: relative;
}
.adm-galeri-preview-img {
  width: 100%;
  max-height: 300px;
  object-fit: cover;
  display: block;
}
.adm-galeri-preview-info {
  padding: .5rem .75rem;
  font-size: .78rem;
  color: var(--admin-muted);
  background: #FAFBFC;
  border-top: 1px solid #E2E8F0;
}
</style>

<script>
/* ── Preview foto ─────────────────────────────────────────── */
function previewFoto(input) {
  const file = input.files?.[0];
  if (!file) return;

  const wrap = document.getElementById('previewWrap');
  const img  = document.getElementById('previewImg');
  const info = document.getElementById('previewInfo');

  const r = new FileReader();
  r.onload = e => {
    img.src = e.target.result;
    wrap.classList.remove('d-none');
    const kb = (file.size / 1024).toFixed(0);
    info.textContent = file.name + ' · ' + (kb > 1024 ? (kb/1024).toFixed(1)+' MB' : kb+' KB');
  };
  r.readAsDataURL(file);

  // Update drop zone visual
  const dz = document.getElementById('dzGaleri');
  dz.style.borderColor = '#8B5E3C';
  dz.querySelector('p').textContent = '✓ ' + file.name;
}

/* ── Drag & drop ─────────────────────────────────────────── */
(function () {
  const dz  = document.getElementById('dzGaleri');
  const inp = document.getElementById('iFoto');
  if (!dz || !inp) return;

  dz.addEventListener('dragover',  e => { e.preventDefault(); dz.classList.add('drag-over'); });
  dz.addEventListener('dragleave', ()  => dz.classList.remove('drag-over'));
  dz.addEventListener('drop', e => {
    e.preventDefault();
    dz.classList.remove('drag-over');
    const dt = new DataTransfer();
    if (e.dataTransfer.files[0]) {
      dt.items.add(e.dataTransfer.files[0]);
      inp.files = dt.files;
      previewFoto(inp);
    }
  });
  dz.addEventListener('keydown', e => {
    if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); inp.click(); }
  });
})();

/* ── Loading state saat submit ───────────────────────────── */
document.getElementById('frmGaleriTambah').addEventListener('submit', function () {
  const btn = document.getElementById('btnUpload');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Mengupload…';
});
</script>

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