<?php
// ============================================================
// FILE: admin/produk_edit.php — Edit Produk
// Fitur sama dengan tambah, plus:
//  - Tampilkan & hapus foto existing satu per satu
//  - Upload tambah foto baru (total tidak melebihi MAX_FOTO_PRODUK)
//  - Reorder foto (urutan 0 = foto utama)
//  - Toggle aktif/nonaktif
// ============================================================
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();
$id  = (int)($_GET['id'] ?? 0);
if (!$id) redirect(BASE_URL . '/admin/produk.php');

$produk = $pdo->prepare("SELECT * FROM produk WHERE id=? LIMIT 1");
$produk->execute([$id]);
$produk = $produk->fetch();
if (!$produk) redirect(BASE_URL . '/admin/produk.php');

$kategoriList = $pdo->query("SELECT * FROM kategori ORDER BY nama")->fetchAll();
$fotoList     = $pdo->prepare("SELECT * FROM produk_foto WHERE produk_id=? ORDER BY urutan ASC");
$fotoList->execute([$id]); $fotoList = $fotoList->fetchAll();

$errors = [];

// ── Hapus satu foto ───────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['hapus_foto_id'])) {
    $fid  = (int)$_POST['hapus_foto_id'];
    $r    = $pdo->prepare("SELECT nama_file FROM produk_foto WHERE id=? AND produk_id=?");
    $r->execute([$fid, $id]); $row = $r->fetch();
    if ($row) {
        hapusGambar($row['nama_file'], 'produk');
        $pdo->prepare("DELETE FROM produk_foto WHERE id=?")->execute([$fid]);
        // Re-urutan
        $remaining = $pdo->prepare("SELECT id FROM produk_foto WHERE produk_id=? ORDER BY urutan ASC");
        $remaining->execute([$id]);
        foreach ($remaining->fetchAll() as $i => $r) {
            $pdo->prepare("UPDATE produk_foto SET urutan=? WHERE id=?")->execute([$i, $r['id']]);
        }
    }
    setFlash('info', 'Foto dihapus.');
    redirect(BASE_URL . '/admin/produk_edit.php?id=' . $id);
}

// ── Jadikan foto utama ────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['jadikan_utama'])) {
    $fid = (int)$_POST['jadikan_utama'];
    // Set semua urutan +1, lalu foto terpilih = 0
    $pdo->prepare("UPDATE produk_foto SET urutan=urutan+100 WHERE produk_id=?")->execute([$id]);
    $pdo->prepare("UPDATE produk_foto SET urutan=0 WHERE id=?")->execute([$fid]);
    // Normalisasi urutan
    $remaining = $pdo->prepare("SELECT id FROM produk_foto WHERE produk_id=? ORDER BY urutan ASC");
    $remaining->execute([$id]);
    foreach ($remaining->fetchAll() as $i => $r) {
        $pdo->prepare("UPDATE produk_foto SET urutan=? WHERE id=?")->execute([$i, $r['id']]);
    }
    redirect(BASE_URL . '/admin/produk_edit.php?id=' . $id);
}

// ── Simpan edit ───────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['aksi_edit'])) {
    $nama        = trim($_POST['nama']         ?? '');
    $kategori_id = (int)($_POST['kategori_id'] ?? 0);
    $deskripsi   = trim($_POST['deskripsi']    ?? '');
    $satuan      = $_POST['satuan']            ?? 'meter';
    $harga       = (float) str_replace(['.', ','], ['', '.'], $_POST['harga'] ?? '0');
    $stok        = (float) str_replace(['.', ','], ['', '.'], $_POST['stok']  ?? '0');
    $stokMin     = (float) str_replace(['.', ','], ['', '.'], $_POST['stok_minimum'] ?? '1');
    $berat       = $_POST['berat_per_m'] !== '' ? (float)str_replace(',', '.', $_POST['berat_per_m']) : null;
    $isAktif     = isset($_POST['is_aktif']) ? 1 : 0;

    // AMAN: SINKRONISASI DATA SPESIFIKASI DARI POST FORM
    $postKeys = $_POST['spec_key'] ?? [];
    $postVals = $_POST['spec_val'] ?? [];
    $specRowsArr = [];
    foreach ($postKeys as $i => $k) {
        $kTrim = trim($k);
        $vTrim = trim($postVals[$i] ?? '');
        if ($kTrim !== '' || $vTrim !== '') {
            $specRowsArr[] = ['key' => $kTrim, 'value' => $vTrim];
        }
    }
    $spesifikasi = !empty($specRowsArr) ? json_stringify_clean($specRowsArr) : null;

    if (!$nama)        $errors[] = 'Nama produk wajib diisi.';
    if (!$kategori_id) $errors[] = 'Kategori wajib dipilih.';
    if (!$deskripsi)   $errors[] = 'Deskripsi wajib diisi.';
    if ($harga <= 0)   $errors[] = 'Harga harus lebih dari 0.';

    // Upload tambahan
    $newFotos = [];
    $totalFoto = count($fotoList);
    if (!empty($_FILES['foto_baru']['name'][0])) {
        foreach ($_FILES['foto_baru']['tmp_name'] as $i => $tmp) {
            if (!$_FILES['foto_baru']['name'][$i] || $_FILES['foto_baru']['error'][$i] !== UPLOAD_ERR_OK) continue;
            if ($totalFoto >= MAX_FOTO_PRODUK) { $errors[] = 'Maksimal ' . MAX_FOTO_PRODUK . ' foto.'; break; }
            $f = [
                'name'     => $_FILES['foto_baru']['name'][$i],
                'type'     => $_FILES['foto_baru']['type'][$i],
                'tmp_name' => $tmp,
                'error'    => $_FILES['foto_baru']['error'][$i],
                'size'     => $_FILES['foto_baru']['size'][$i],
            ];
            $namaFile = uploadGambar($f, 'produk');
            if ($namaFile) { $newFotos[] = $namaFile; $totalFoto++; }
            else $errors[] = 'Gagal upload foto baru ke-' . ($i+1) . '.';
        }
    }

    if (empty($errors)) {
        // Update slug hanya jika nama berubah
        $slug = $produk['slug'];
        if ($nama !== $produk['nama']) {
            $slug = buatSlug($nama);
            $chk  = $pdo->prepare("SELECT COUNT(*) FROM produk WHERE slug=? AND id != ?");
            $chk->execute([$slug, $id]);
            if ((int)$chk->fetchColumn() > 0) $slug .= '-' . substr(uniqid(), -5);
        }

        $pdo->prepare("
            UPDATE produk SET
                kategori_id=?, nama=?, slug=?, deskripsi=?, spesifikasi=?,
                satuan=?, harga=?, stok=?, stok_minimum=?, berat_per_m=?, is_aktif=?,
                updated_at=NOW()
            WHERE id=?
        ")->execute([
            $kategori_id, $nama, $slug, $deskripsi, $spesifikasi,
            $satuan, $harga, $stok, $stokMin, $berat, $isAktif, $id,
        ]);

        // Simpan foto baru
        $nextUrutan = count($fotoList);
        foreach ($newFotos as $nf) {
            $pdo->prepare("INSERT INTO produk_foto (produk_id,nama_file,urutan) VALUES (?,?,?)")
                ->execute([$id, $nf, $nextUrutan++]);
        }

        setFlash('success', 'Produk <strong>' . e($nama) . '</strong> berhasil diperbarui!');
        redirect(BASE_URL . '/admin/produk.php');
    } else {
        foreach ($newFotos as $nf) hapusGambar($nf, 'produk');
    }

    // Re-fetch produk untuk pre-fill
    $p = $pdo->prepare("SELECT * FROM produk WHERE id=?"); $p->execute([$id]);
    $produk = $p->fetch();
}

// Helper lokal untuk membersihkan JSON string tanpa merusak karakter khusus
function json_stringify_clean($array) {
    return json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

// Decode spesifikasi untuk form tampilan setelah post/fetch
$specRows = [];
if ($produk['spesifikasi']) {
    $dec = json_decode($produk['spesifikasi'], true);
    $specRows = is_array($dec) ? $dec : [['key'=>'','value'=>$produk['spesifikasi']]];
}
if (empty($specRows)) $specRows = [['key'=>'','value'=>'']];

// Re-fetch foto
$fotoList = $pdo->prepare("SELECT * FROM produk_foto WHERE produk_id=? ORDER BY urutan ASC");
$fotoList->execute([$id]); $fotoList = $fotoList->fetchAll();

$pageTitle = 'Edit Produk — ' . e($produk['nama']);
include __DIR__ . '/admin_layout.php';
?>

<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">Edit</li>
      </ol>
    </nav>
    <h4 class="adm-page-title"><i class="bi bi-pencil-square me-2"></i>Edit Produk</h4>
    <p class="adm-page-sub mb-0"><?= e($produk['nama']) ?></p>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= BASE_URL ?>/produk.php?slug=<?= e($produk['slug']) ?>"
       target="_blank" class="btn btn-outline-info btn-sm">
      <i class="bi bi-eye me-1"></i>Lihat Toko
    </a>
    <a href="<?= BASE_URL ?>/admin/produk.php" class="btn btn-outline-secondary btn-sm">
      <i class="bi bi-arrow-left me-1"></i>Kembali
    </a>
  </div>
</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="frmEdit" novalidate>
  <input type="hidden" name="aksi_edit" value="1">
  <div class="row g-4">

    <div class="col-lg-8">

      <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($produk['nama']) ?>"
                   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($produk['slug']) ?></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 —</option>
                <?php foreach ($kategoriList as $k): ?>
                  <option value="<?= $k['id'] ?>" <?= $produk['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"  <?= $produk['satuan']==='meter' ?'selected':'' ?>>Meter (m)</option>
                <option value="unit"   <?= $produk['satuan']==='unit'  ?'selected':'' ?>>Unit / Pcs</option>
                <option value="lembar" <?= $produk['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><?= e($produk['deskripsi']) ?></textarea>
          </div>

          <div class="mb-2">
            <label class="ck-label">Spesifikasi Teknis <span class="text-muted small">(opsional)</span></label>
            <div id="spesList">
              <?php foreach ($specRows as $sr): ?>
                <div class="adm-spec-row">
                  <input type="text" name="spec_key[]" class="form-control form-control-sm adm-spec-key"
                         placeholder="Nama" value="<?= e($sr['key']) ?>">
                  <input type="text" name="spec_val[]" class="form-control form-control-sm adm-spec-val"
                         placeholder="Nilai" 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>
            <input type="hidden" name="spesifikasi" id="spesFinal">
          </div>

        </div>
      </div>

      <div class="admin-card mb-4">
        <div class="admin-card-header">
          <h6 class="mb-0"><i class="bi bi-images me-2"></i>Foto Produk Sekarang</h6>
          <small class="text-muted"><?= count($fotoList) ?>/<?= MAX_FOTO_PRODUK ?> foto · Bintang = foto utama</small>
        </div>
        <div class="p-4">
          <?php if (empty($fotoList)): ?>
            <div class="text-center text-muted py-3">
              <i class="bi bi-image fs-3 d-block mb-2"></i>Belum ada foto.
            </div>
          <?php else: ?>
            <div class="adm-foto-grid">
              <?php foreach ($fotoList as $i => $f): ?>
                <div class="adm-foto-item <?= $i===0?'adm-foto-item--utama':'' ?>">
                  <img src="<?= UPLOAD_URL ?>/produk/<?= e($f['nama_file']) ?>"
                       alt="Foto <?= $i+1 ?>" loading="lazy">
                  <?php if ($i===0): ?>
                    <div class="adm-foto-badge-utama">★ Utama</div>
                  <?php else: ?>
                    <div class="adm-foto-badge"><?= $i+1 ?></div>
                  <?php endif; ?>
                  <div class="adm-foto-actions">
                    <?php if ($i > 0): ?>
                      <form method="POST" class="d-inline">
                        <input type="hidden" name="jadikan_utama" value="<?= $f['id'] ?>">
                        <button class="adm-foto-btn adm-foto-btn--star" title="Jadikan foto utama">
                          <i class="bi bi-star-fill"></i>
                        </button>
                      </form>
                    <?php endif; ?>
                    <form method="POST" class="d-inline"
                          onsubmit="return confirm('Hapus foto ini?')">
                      <input type="hidden" name="hapus_foto_id" value="<?= $f['id'] ?>">
                      <button class="adm-foto-btn adm-foto-btn--del" title="Hapus foto">
                        <i class="bi bi-trash3-fill"></i>
                      </button>
                    </form>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>

          <?php if (count($fotoList) < MAX_FOTO_PRODUK): ?>
            <div class="mt-3 pt-3 border-top">
              <label class="ck-label mb-2">
                <i class="bi bi-plus-circle me-1 text-primary"></i>
                Tambah Foto Baru (<?= MAX_FOTO_PRODUK - count($fotoList) ?> slot tersisa)
              </label>
              <div class="multi-upload-zone" id="dropZoneEdit"
                   onclick="document.getElementById('iFotoBaru').click()"
                   role="button" tabindex="0" style="padding:1.5rem">
                <i class="bi bi-cloud-arrow-up adm-dz-icon" style="font-size:1.8rem"></i>
                <p class="small mb-0">Klik atau drag foto baru ke sini</p>
              </div>
              <input type="file" id="iFotoBaru" name="foto_baru[]" multiple
                     accept="image/jpeg,image/png,image/webp" class="d-none"
                     onchange="previewFotoBaru(this)">
              <div class="foto-preview-grid mt-2" id="previewGridBaru"></div>
            </div>
          <?php else: ?>
            <div class="alert alert-info small mt-3 mb-0">
              <i class="bi bi-info-circle me-1"></i>
              Sudah mencapai batas <?= MAX_FOTO_PRODUK ?> foto. Hapus foto lama untuk menambah yang baru.
            </div>
          <?php endif; ?>
        </div>
      </div>

    </div><div class="col-lg-4">

      <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="<?= (int)$produk['harga'] ?>" min="0" step="500" required>
            </div>
          </div>
          <div class="mb-3">
            <label class="ck-label" for="iStok">Stok Saat Ini <span class="text-danger">*</span></label>
            <input type="number" id="iStok" name="stok" class="form-control ck-input"
                   value="<?= (int)$produk['stok'] ?>" min="0" step="1" 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="<?= (int)$produk['stok_minimum'] ?>" min="0" step="1">
          </div>
          <div class="mb-2">
            <label class="ck-label" for="iBerat">Berat per Meter (kg)</label>
            <input type="number" id="iBerat" name="berat_per_m" class="form-control ck-input"
                   value="<?= e($produk['berat_per_m'] ?? '') ?>" min="0" step="0.001">
          </div>
        </div>
      </div>

      <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"
                   <?= $produk['is_aktif'] ? 'checked' : '' ?>>
            <label class="form-check-label fw-semibold" for="swAktif">
              Produk Aktif &amp; Ditampilkan
            </label>
          </div>
        </div>
      </div>

      <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 Perubahan
        </button>
        <a href="<?= BASE_URL ?>/admin/produk.php" class="btn btn-outline-secondary">Batal</a>
      </div>
    </div>

  </div>
</form>

<script>
function genSlug(nama) {
  const slug = nama.toLowerCase().replace(/[^a-z0-9\s-]/g,'').trim().replace(/[\s-]+/g,'-');
  document.getElementById('slugPreview').textContent = slug || 'nama-produk';
}
function tambahSpec() {
  const cont = document.getElementById('spesList');
  const row  = document.createElement('div');
  row.className = 'adm-spec-row';
  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);
}
function previewFotoBaru(input) {
  const grid = document.getElementById('previewGridBaru');
  grid.innerHTML = '';
  Array.from(input.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="Baru ${i+1}">
        <div class="foto-preview-label">+ Baru ${i+1}</div>`;
      grid.appendChild(item);
    };
    r.readAsDataURL(file);
  });
}
(function(){
  const dz = document.getElementById('dropZoneEdit'); 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('iFotoBaru');
    const dt  = new DataTransfer();
    Array.from(e.dataTransfer.files).forEach(f => dt.items.add(f));
    inp.files = dt.files; previewFotoBaru(inp);
  });
})();
document.getElementById('frmEdit').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) : '';
  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'; ?>