<?php
include 'config/koneksi.php';
include 'config/config.php';

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$produk = $conn->query("SELECT * FROM produk WHERE id = $id")->fetch_assoc();
$varian = $conn->query("SELECT * FROM produk_varian WHERE produk_id = $id");
$gambar_lain = $conn->query("SELECT * FROM produk_gambar WHERE produk_id = $id");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nama_produk = $conn->real_escape_string($_POST['nama_produk']);
    $deskripsi = $conn->real_escape_string($_POST['deskripsi']);
    $harga = (int)$_POST['harga'];
    $kategori = $conn->real_escape_string($_POST['kategori']);
    $checkout_link = $conn->real_escape_string($_POST['checkout_link']);

    // Update thumbnail jika diunggah ulang
    $thumbnail_url = $produk['thumbnail_url'];
    if (isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] === 0) {
        $ext = pathinfo($_FILES['thumbnail']['name'], PATHINFO_EXTENSION);
        $newName = uniqid('thumb_', true) . '.jpg';
        $uploadPath = 'uploads/' . $newName;
        move_uploaded_file($_FILES['thumbnail']['tmp_name'], $uploadPath);
        $thumbnail_url = $uploadPath;
    }

    $conn->query("UPDATE produk SET nama_produk='$nama_produk', deskripsi='$deskripsi', harga=$harga, kategori='$kategori', checkout_link='$checkout_link', thumbnail_url='$thumbnail_url' WHERE id = $id");

    // Hapus varian lama
    $conn->query("DELETE FROM produk_varian WHERE produk_id = $id");

    // Simpan ulang varian
    if (!empty($_POST['varian_nama'])) {
        foreach ($_POST['varian_nama'] as $i => $vnama) {
            $vharga = (int) $_POST['varian_harga'][$i];
            $conn->query("INSERT INTO produk_varian (produk_id, nama_varian, harga) VALUES ($id, '{$conn->real_escape_string($vnama)}', $vharga)");
        }
    }

    // Simpan gambar tambahan baru
    if (!empty($_FILES['gambar_lain']['name'][0])) {
        foreach ($_FILES['gambar_lain']['tmp_name'] as $i => $tmp_name) {
            $imgname = uniqid('img_', true) . '.jpg';
            $uploadImg = 'uploads/' . $imgname;
            move_uploaded_file($tmp_name, $uploadImg);
            $conn->query("INSERT INTO produk_gambar (produk_id, url_gambar) VALUES ($id, '$uploadImg')");
        }
    }

    header("Location: admin_dashboard.php?sukses_edit=1");
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Edit Produk</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
      body { font-family: Arial, sans-serif; background: #f7f7f7; padding: 20px; }
      .container { max-width: 700px; margin: auto; background: white; padding: 24px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.08); }
      h2 { text-align: center; margin-bottom: 20px; }
      label { display: block; margin-top: 14px; font-weight: bold; }
      input, textarea { width: 100%; padding: 12px; margin-top: 6px; border: 1px solid #ccc; border-radius: 8px; }
      .varian-row { display: flex; gap: 10px; margin-top: 10px; }
      .varian-row input { flex: 1; }
      .gambar-preview img { height: 60px; margin: 6px; }
      .button { background: #28a745; color: white; font-weight: bold; border: none; padding: 12px; border-radius: 8px; margin-top: 20px; cursor: pointer; width: 100%; }
      .kembali { background: #ccc; text-align: center; margin-top: 12px; padding: 10px; border-radius: 8px; text-decoration: none; display: block; color: #333; }
      @media(max-width: 600px) {
        .varian-row { flex-direction: column; }
      }
    </style>
</head>
<body>
<div class="container">
    <h2>Edit Produk</h2>
    <form method="POST" enctype="multipart/form-data">
        <label>Nama Produk</label>
        <input type="text" name="nama_produk" value="<?= htmlspecialchars($produk['nama_produk']) ?>" required>

        <label>Deskripsi</label>
        <textarea name="deskripsi" required><?= htmlspecialchars($produk['deskripsi']) ?></textarea>

        <label>Harga Awal</label>
        <input type="number" name="harga" value="<?= $produk['harga'] ?>" required>

        <label>Kategori</label>
        <input type="text" name="kategori" value="<?= htmlspecialchars($produk['kategori']) ?>">

        <label>Link Checkout</label>
        <input type="text" name="checkout_link" value="<?= htmlspecialchars($produk['checkout_link']) ?>">

        <label>Thumbnail Sekarang</label>
        <div class="gambar-preview">
            <img src="<?= $produk['thumbnail_url'] ?>" alt="thumb">
        </div>
        <input type="file" name="thumbnail" accept="image/*">

        <label>Varian Produk</label>
        <div id="varian-box">
            <?php while ($v = $varian->fetch_assoc()): ?>
            <div class="varian-row">
                <input type="text" name="varian_nama[]" value="<?= htmlspecialchars($v['nama_varian']) ?>" placeholder="Nama Varian">
                <input type="number" name="varian_harga[]" value="<?= $v['harga'] ?>" placeholder="Harga Varian">
            </div>
            <?php endwhile; ?>
        </div>
        <button type="button" onclick="tambahVarian()" style="margin-top: 10px;">+ Tambah Varian</button>

        <label>Tambah Gambar Tambahan</label>
        <input type="file" name="gambar_lain[]" multiple accept="image/*">
        <div class="gambar-preview">
            <?php while ($g = $gambar_lain->fetch_assoc()): ?>
                <img src="<?= $g['url_gambar'] ?>" alt="gambar">
            <?php endwhile; ?>
        </div>

        <button type="submit" class="button">Simpan Perubahan</button>
        <a href="admin_dashboard.php" class="kembali">← Kembali ke Dashboard</a>
    </form>
</div>

<script>
function tambahVarian() {
  const box = document.getElementById('varian-box');
  const row = document.createElement('div');
  row.className = 'varian-row';
  row.innerHTML = `
    <input type="text" name="varian_nama[]" placeholder="Nama Varian">
    <input type="number" name="varian_harga[]" placeholder="Harga Varian">
  `;
  box.appendChild(row);
}
</script>
</body>
</html>
