<?php
// ============================================================
// FILE: admin/produk_tambah.php — Tambah Produk Baru
// Fitur:
//  - Multi-upload foto (drag & drop, preview grid real-time)
//  - Urutan foto bisa diatur (foto pertama = foto utama)
//  - Spesifikasi dalam format JSON key-value (bisa tambah/hapus baris)
//  - Auto-generate slug dari nama
//  - Validasi server-side lengkap
// ============================================================
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();
$kategoriList = $pdo->query("SELECT * FROM kategori ORDER BY nama")->fetchAll();
$errors = [];
$post   = ['nama'=>'','kategori_id'=>'','deskripsi'=>'','spesifikasi'=>'',
           'satuan'=>'meter','harga'=>'','stok'=>'','stok_minimum'=>'1',
           'berat_per_m'=>'','is_aktif'=>'1'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $post['nama']         = trim($_POST['nama']         ?? '');
    $post['kategori_id']  = (int)($_POST['kategori_id'] ?? 0);
    $post['deskripsi']    = trim($_POST['deskripsi']    ?? '');
    $post['spesifikasi']  = trim($_POST['spesifikasi']  ?? '');
    $post['satuan']       = $_POST['satuan']            ?? 'meter';
    $post['harga']        = trim($_POST['harga']        ?? '');
    $post['stok']         = trim($_POST['stok']         ?? '');
    $post['stok_minimum'] = trim($_POST['stok_minimum'] ?? '1');
    $post['berat_per_m']  = trim($_POST['berat_per_m']  ?? '');
    $post['is_aktif']     = isset($_POST['is_aktif']) ? 1 : 0;

    $harga    = (float) str_replace(['.', ','], ['', '.'], $post['harga']);
    $stok     = (float) str_replace(['.', ','], ['', '.'], $post['stok']);
    $stokMin  = (float) str_replace(['.', ','], ['', '.'], $post['stok_minimum']);
    $berat    = $post['berat_per_m'] !== '' ? (float)str_replace(',', '.', $post['berat_per_m']) : null;

    // ── Validasi ──────────────────────────────────────────────
    if (!$post['nama'])          $errors[] = 'Nama produk wajib diisi.';
    if (!$post['kategori_id'])   $errors[] = 'Kategori wajib dipilih.';
    if (!$post['deskripsi'])     $errors[] = 'Deskripsi wajib diisi.';
    if ($harga <= 0)             $errors[] = 'Harga harus lebih dari 0.';
    if ($stok < 0)               $errors[] = 'Stok tidak boleh negatif.';
    if (!in_array($post['satuan'], ['meter','unit','lembar']))
        $errors[] = 'Satuan tidak valid.';

    // Cek slug unik
    $slug = buatSlug($post['nama']);
    $chk  = $pdo->prepare("SELECT COUNT(*) FROM produk WHERE slug=?");
    $chk->execute([$slug]);
    if ((int)$chk->fetchColumn() > 0) $slug .= '-' . substr(uniqid(), -5);

    // ── Upload foto ───────────────────────────────────────────
    $uploadedFotos = [];
    if (!empty($_FILES['foto']['name'][0])) {
        foreach ($_FILES['foto']['tmp_name'] as $i => $tmp) {
            if (!$_FILES['foto']['name'][$i] || $_FILES['foto']['error'][$i] !== UPLOAD_ERR_OK) continue;
            $f = [
                'name'     => $_FILES['foto']['name'][$i],
                'type'     => $_FILES['foto']['type'][$i],
                'tmp_name' => $tmp,
                'error'    => $_FILES['foto']['error'][$i],
                'size'     => $_FILES['foto']['size'][$i],
            ];
            $namaFile = uploadGambar($f, 'produk');
            if ($namaFile) {
                $uploadedFotos[] = $namaFile;
            } else {
                $errors[] = 'Gagal upload foto ke-' . ($i + 1) . '. Cek format (JPG/PNG/WEBP) & ukuran (maks 5 MB).';
            }
            if (count($uploadedFotos) >= MAX_FOTO_PRODUK) break;
        }
    }

    if (empty($errors)) {
        $pdo->prepare("
            INSERT INTO produk
                (kategori_id,nama,slug,deskripsi,spesifikasi,satuan,harga,stok,stok_minimum,berat_per_m,is_aktif)
            VALUES (?,?,?,?,?,?,?,?,?,?,?)
        ")->execute([
            $post['kategori_id'], $post['nama'], $slug,
            $post['deskripsi'], $post['spesifikasi'] ?: null,
            $post['satuan'], $harga, $stok, $stokMin, $berat, $post['is_aktif'],
        ]);
        $produkId = (int)$pdo->lastInsertId();

        foreach ($uploadedFotos as $urutan => $namaFile) {
            $pdo->prepare("INSERT INTO produk_foto (produk_id,nama_file,urutan) VALUES (?,?,?)")
                ->execute([$produkId, $namaFile, $urutan]);
        }

        setFlash('success', 'Produk <strong>' . e($post['nama']) . '</strong> berhasil ditambahkan!');
        redirect(BASE_URL . '/admin/produk.php');
    } else {
        // Hapus file yang telanjur terupload
        foreach ($uploadedFotos as $f) hapusGambar($f, 'produk');
    }
}

$pageTitle = 'Tambah Produk';
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/produk.php">Produk</a></li>
        <li class="breadcrumb-item active">Tambah Baru</li>
      </ol>
    </nav>
    <h4 class="adm-page-title"><i class="bi bi-plus-circle me-2"></i>Tambah Produk Baru</h4>
  </div>
  <a href="<?= BASE_URL ?>/admin/produk.php" class="btn btn-outline-secondary btn-sm">
    <i class="bi bi-arrow-left me-1"></i>Batal
  </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>Mohon perbaiki:</strong>
    <ul class="mb-0 mt-1 ps-3"><?php foreach($errors as $e): ?><li><?= $e ?></li><?php endforeach; ?></ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  </div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data" id="frmTambah" novalidate>
  <div class="row g-4">

    <!-- ═══ KIRI: Info Produk ══════════════════════════════ -->
    <div class="col-lg-8">

      <!-- Info Dasar -->
      <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 Produk</h6>
        </div>
        <div class="p-4">

          <div class="mb-3">
            <label class="ck-label" for="iNama">Nama Produk <span class="text-danger">*</span></label>
            <input type="text" id="iNama" name="nama" class="form-control ck-input"
                   value="<?= e($post['nama']) ?>"
                   placeholder="Contoh: Kusen Kayu Jati Premium 4×6"
                   oninput="genSlug(this.value)" required>
            <div class="ck-hint mt-1">
              <i class="bi bi-link-45deg me-1"></i>
              Slug: <code id="slugPreview" class="text-primary"><?= e(buatSlug($post['nama'] ?: 'nama-produk')) ?></code>
            </div>
          </div>

          <div class="row g-3 mb-3">
            <div class="col-md-6">
              <label class="ck-label" for="iKat">Kategori <span class="text-danger">*</span></label>
              <select id="iKat" name="kategori_id" class="form-select ck-input" required>
                <option value="">— Pilih Kategori —</option>
                <?php foreach ($kategoriList as $k): ?>
                  <option value="<?= $k['id'] ?>"
                    <?= (int)$post['kategori_id']===$k['id']?'selected':'' ?>>
                    <?= e($k['nama']) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="ck-label" for="iSatuan">Satuan <span class="text-danger">*</span></label>
              <select id="iSatuan" name="satuan" class="form-select ck-input">
                <option value="meter"  <?= $post['satuan']==='meter' ?'selected':'' ?>>Meter (m)</option>
                <option value="unit"   <?= $post['satuan']==='unit'  ?'selected':'' ?>>Unit / Pcs</option>
                <option value="lembar" <?= $post['satuan']==='lembar'?'selected':'' ?>>Lembar</option>
              </select>
            </div>
          </div>

          <div class="mb-3">
            <label class="ck-label" for="iDesk">Deskripsi <span class="text-danger">*</span></label>
            <textarea id="iDesk" name="deskripsi" class="form-control ck-input"
                      rows="5" required
                      placeholder="Jelaskan produk secara lengkap: bahan, keunggulan, finishing, ukuran tersedia…"><?= e($post['deskripsi']) ?></textarea>
          </div>

          <!-- Spesifikasi dinamis -->
          <div class="mb-2">
            <label class="ck-label">
              Spesifikasi Teknis
              <span class="text-muted small">(opsional — tampil sebagai tabel di halaman produk)</span>
            </label>
            <div id="spesList">
              <!-- Baris spesifikasi di-generate JS atau di-pre-fill dari POST -->
              <?php
              $specRows = [];
              if ($post['spesifikasi']) {
                  $decoded = json_decode($post['spesifikasi'], true);
                  if (is_array($decoded)) $specRows = $decoded;
                  else $specRows = [['key'=>'','value'=>$post['spesifikasi']]];
              }
              if (empty($specRows)) $specRows = [['key'=>'','value'=>''],['key'=>'','value'=>'']];
              foreach ($specRows as $sr):
              ?>
                <div class="adm-spec-row" id="specRow_<?= uniqid() ?>">
                  <input type="text" name="spec_key[]" class="form-control form-control-sm adm-spec-key"
                         placeholder="Nama (misal: Ukuran)" value="<?= e($sr['key']) ?>">
                  <input type="text" name="spec_val[]" class="form-control form-control-sm adm-spec-val"
                         placeholder="Nilai (misal: 4 × 6 cm)" value="<?= e($sr['value']) ?>">
                  <button type="button" class="adm-spec-del btn btn-sm btn-outline-danger"
                          onclick="this.closest('.adm-spec-row').remove()">
                    <i class="bi bi-dash"></i>
                  </button>
                </div>
              <?php endforeach; ?>
            </div>
            <button type="button" class="btn btn-sm btn-outline-secondary mt-2" onclick="tambahSpec()">
              <i class="bi bi-plus-lg me-1"></i>Tambah Baris
            </button>
            <!-- Hidden field yang akan diisi JSON sebelum submit -->
            <input type="hidden" name="spesifikasi" id="spesFinal">
          </div>

        </div>
      </div>

      <!-- Upload Foto -->
      <div class="admin-card">
        <div class="admin-card-header">
          <h6 class="mb-0"><i class="bi bi-images me-2"></i>Foto Produk</h6>
          <small class="text-muted">Maks <?= MAX_FOTO_PRODUK ?> foto · JPG/PNG/WEBP · 5 MB/foto · Foto pertama = foto utama</small>
        </div>
        <div class="p-4">
          <!-- Drop zone -->
          <div class="multi-upload-zone" id="dropZone"
               onclick="document.getElementById('iFoto').click()"
               role="button" tabindex="0">
            <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">Pilih 1–<?= MAX_FOTO_PRODUK ?> foto sekaligus</p>
          </div>
          <input type="file" id="iFoto" name="foto[]" multiple
                 accept="image/jpeg,image/png,image/webp" class="d-none"
                 onchange="previewFoto(this)">

          <!-- Preview grid -->
          <div class="foto-preview-grid mt-3" id="previewGrid"></div>
        </div>
      </div>

    </div><!-- /col kiri -->

    <!-- ═══ KANAN: Harga & Stok ════════════════════════════ -->
    <div class="col-lg-4">

      <!-- Harga & Stok -->
      <div class="admin-card mb-4">
        <div class="admin-card-header">
          <h6 class="mb-0"><i class="bi bi-currency-dollar me-2"></i>Harga &amp; Stok</h6>
        </div>
        <div class="p-4">
          <div class="mb-3">
            <label class="ck-label" for="iHarga">Harga per Satuan (Rp) <span class="text-danger">*</span></label>
            <div class="input-group">
              <span class="input-group-text ck-input-addon">Rp</span>
              <input type="number" id="iHarga" name="harga" class="form-control ck-input"
                     value="<?= e($post['harga']) ?>"
                     placeholder="250000" min="0" step="500" required>
            </div>
          </div>
          <div class="mb-3">
            <label class="ck-label" for="iStok">Stok Awal <span class="text-danger">*</span></label>
            <input type="number" id="iStok" name="stok" class="form-control ck-input"
                   value="<?= e($post['stok']) ?>"
                   placeholder="0" min="0" step="0.01" required>
          </div>
          <div class="mb-3">
            <label class="ck-label" for="iStokMin">Batas Stok Rendah</label>
            <input type="number" id="iStokMin" name="stok_minimum" class="form-control ck-input"
                   value="<?= e($post['stok_minimum'] ?: '1') ?>"
                   placeholder="1" min="0" step="0.1">
            <div class="ck-hint">Sistem akan memberi peringatan bila stok ≤ nilai ini.</div>
          </div>
          <div class="mb-3">
            <label class="ck-label" for="iBerat">Berat per Meter (kg) <span class="text-muted small">(opsional)</span></label>
            <input type="number" id="iBerat" name="berat_per_m" class="form-control ck-input"
                   value="<?= e($post['berat_per_m']) ?>"
                   placeholder="Misal: 2.5" min="0" step="0.001">
          </div>
        </div>
      </div>

      <!-- Status -->
      <div class="admin-card mb-4">
        <div class="admin-card-header">
          <h6 class="mb-0"><i class="bi bi-toggle-on me-2"></i>Status</h6>
        </div>
        <div class="p-4">
          <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" role="switch"
                   id="swAktif" name="is_aktif" value="1"
                   <?= $post['is_aktif'] ? 'checked' : '' ?>>
            <label class="form-check-label fw-semibold" for="swAktif">
              Produk Aktif & Ditampilkan
            </label>
          </div>
          <div class="ck-hint mt-2">Jika dinonaktifkan, produk tidak muncul di katalog.</div>
        </div>
      </div>

      <!-- Tombol submit -->
      <div class="d-grid gap-2">
        <button type="submit" class="btn btn-primary-brand btn-lg fw-bold" id="btnSimpan">
          <i class="bi bi-check-lg me-2"></i>Simpan Produk
        </button>
        <a href="<?= BASE_URL ?>/admin/produk.php" class="btn btn-outline-secondary">
          Batal
        </a>
      </div>

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

<script>
/* ── Auto-slug dari nama ─────────────────────────────────── */
function genSlug(nama) {
  const slug = nama.toLowerCase()
    .replace(/[^a-z0-9\s-]/g, '')
    .trim()
    .replace(/[\s-]+/g, '-');
  document.getElementById('slugPreview').textContent = slug || 'nama-produk';
}

/* ── Preview multi foto ──────────────────────────────────── */
function previewFoto(input) {
  const grid = document.getElementById('previewGrid');
  grid.innerHTML = '';
  const files = Array.from(input.files).slice(0, <?= MAX_FOTO_PRODUK ?>);
  files.forEach((file, i) => {
    const r = new FileReader();
    r.onload = e => {
      const item = document.createElement('div');
      item.className = 'foto-preview-item';
      item.innerHTML = `
        <img src="${e.target.result}" alt="Foto ${i+1}">
        <div class="foto-preview-label">${i===0?'★ Utama':'Foto '+(i+1)}</div>`;
      grid.appendChild(item);
    };
    r.readAsDataURL(file);
  });
}

/* ── Drag & drop foto ────────────────────────────────────── */
(function(){
  const dz = document.getElementById('dropZone');
  if (!dz) 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 inp = document.getElementById('iFoto');
    const dt  = new DataTransfer();
    Array.from(e.dataTransfer.files).forEach(f => dt.items.add(f));
    inp.files = dt.files;
    previewFoto(inp);
  });
  dz.addEventListener('keydown', e => { if (e.key==='Enter'||e.key===' '){ e.preventDefault(); document.getElementById('iFoto').click(); }});
})();

/* ── Spesifikasi rows ────────────────────────────────────── */
function tambahSpec() {
  const cont = document.getElementById('spesList');
  const id   = 'specRow_' + Date.now();
  const row  = document.createElement('div');
  row.className = 'adm-spec-row';
  row.id        = id;
  row.innerHTML = `
    <input type="text" name="spec_key[]" class="form-control form-control-sm adm-spec-key" placeholder="Nama">
    <input type="text" name="spec_val[]" class="form-control form-control-sm adm-spec-val" placeholder="Nilai">
    <button type="button" class="adm-spec-del btn btn-sm btn-outline-danger"
            onclick="this.closest('.adm-spec-row').remove()">
      <i class="bi bi-dash"></i>
    </button>`;
  cont.appendChild(row);
}

/* ── Serialisasi spesifikasi → JSON sebelum submit ───────── */
document.getElementById('frmTambah').addEventListener('submit', function() {
  const keys = [...document.querySelectorAll('input[name="spec_key[]"]')].map(i => i.value.trim());
  const vals = [...document.querySelectorAll('input[name="spec_val[]"]')].map(i => i.value.trim());
  const rows = keys.map((k,i) => ({key:k,value:vals[i]})).filter(r => r.key || r.value);
  document.getElementById('spesFinal').value = rows.length ? JSON.stringify(rows) : '';

  // Loading state
  const btn = document.getElementById('btnSimpan');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Menyimpan…';
});
</script>

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