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

$notif = '';

// Fungsi resize gambar
function resize_image($source, $destination, $width, $height) {
    $info = getimagesize($source);
    if ($info['mime'] === 'image/jpeg') {
        $image = imagecreatefromjpeg($source);
    } elseif ($info['mime'] === 'image/png') {
        $image = imagecreatefrompng($source);
    } else {
        return false;
    }
    $resized = imagecreatetruecolor($width, $height);
    imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $height, imagesx($image), imagesy($image));
    imagejpeg($resized, $destination, 90);
    return true;
}

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

    $thumbnail_url = '';
    if (!is_dir('uploads')) mkdir('uploads', 0755, true);

    if (isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] === 0) {
        $ext = pathinfo($_FILES['thumbnail']['name'], PATHINFO_EXTENSION);
        $newName = uniqid('thumb_', true) . '.jpg';
        $tmp = $_FILES['thumbnail']['tmp_name'];
        $uploadPath = 'uploads/' . $newName;
        if (resize_image($tmp, $uploadPath, 400, 400)) {
            $thumbnail_url = $uploadPath;
        }
    }

    if ($thumbnail_url !== '') {
        $sql = "INSERT INTO produk (nama_produk, deskripsi, harga, thumbnail_url, kategori, checkout_link)
                VALUES ('$nama_produk', '$deskripsi', $harga_awal, '$thumbnail_url', '$kategori', '$checkout_link')";
        if ($conn->query($sql)) {
            $produk_id = $conn->insert_id;

            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 ($produk_id, '{$conn->real_escape_string($vnama)}', $vharga)");
                }
            }

            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;
                    if (resize_image($tmp_name, $uploadImg, 400, 400)) {
                        $conn->query("INSERT INTO produk_gambar (produk_id, url_gambar)
                                      VALUES ($produk_id, '$uploadImg')");
                    }
                }
            }

            header("Location: tambah_produk.php?sukses=1");
            exit;
        } else {
            $notif = "❌ Gagal menambahkan produk.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Tambah Produk - <?= $toko_nama ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: 'Segoe UI', Tahoma, sans-serif;
      background: #f4f6f8;
      color: #333;
      padding: 30px 16px;
    }
    .container {
      max-width: 700px;
      margin: auto;
      background: #fff;
      padding: 24px;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    }
    h1 {
      font-size: 24px;
      margin-bottom: 24px;
      text-align: center;
      color: #222;
    }
    .alert-success {
      background: #e6ffed;
      color: #276749;
      padding: 12px 20px;
      border-radius: 8px;
      border: 1px solid #c6f6d5;
      margin-bottom: 20px;
      text-align: center;
    }
    form label {
      display: block;
      margin-bottom: 6px;
      font-weight: 600;
      margin-top: 14px;
    }
    input[type="text"],
    input[type="number"],
    input[type="file"],
    textarea {
      width: 100%;
      padding: 12px;
      font-size: 15px;
      border-radius: 8px;
      border: 1px solid #ccc;
    }
    textarea {
      resize: vertical;
      min-height: 100px;
    }
    .varian-row {
      display: flex;
      gap: 10px;
      margin-bottom: 10px;
    }
    .varian-row input {
      flex: 1;
    }
    .button-mini {
      background: #007bff;
      color: white;
      border: none;
      padding: 10px 14px;
      font-size: 14px;
      border-radius: 6px;
      cursor: pointer;
      margin-top: 10px;
    }
    .button-mini:hover {
      background: #0056b3;
    }
    .button {
      background: #28a745;
      color: white;
      font-weight: bold;
      border: none;
      font-size: 16px;
      padding: 14px;
      border-radius: 8px;
      cursor: pointer;
      width: 100%;
      margin-top: 20px;
    }
    .button:hover {
      background: #218838;
    }
    @media (max-width: 600px) {
      .varian-row {
        flex-direction: column;
      }
    }
  </style>
</head>
<body>

<div class="container">
  <h1>Tambah Produk Digital</h1>

  <?php if (isset($_GET['sukses']) && !isset($_SERVER['HTTP_CACHE_CONTROL'])): ?>

    <div class="alert-success" id="notif-box">
      ✅ Produk berhasil ditambahkan.
      <button onclick="document.getElementById('notif-box').style.display='none'" style="float:right;border:none;background:none;font-weight:bold;cursor:pointer;">×</button>
    </div>
  <?php endif; ?>


  <form method="post" enctype="multipart/form-data">
    <label>Nama Produk</label>
    <input type="text" name="nama_produk" required>

    <label>Deskripsi</label>
    <textarea name="deskripsi" required></textarea>

    <label>Harga Awal (Rp)</label>
    <input type="number" name="harga" required min="0">

    <label>Kategori</label>
    <input type="text" name="kategori">

    <label>Link Checkout (opsional)</label>
    <input type="text" name="checkout_link" placeholder="https://example.com/produk">

    <label>Thumbnail Utama</label>
    <input type="file" name="thumbnail" accept="image/*" required>

    <label>Gambar Tambahan (untuk slider)</label>
    <input type="file" name="gambar_lain[]" multiple accept="image/*">

    <label>Varian Produk</label>
    <div id="varian-box">
      <div class="varian-row">
        <input type="text" name="varian_nama[]" placeholder="Nama Varian">
        <input type="number" name="varian_harga[]" placeholder="Harga Varian">
      </div>
    </div>
    <button type="button" class="button-mini" onclick="tambahVarian()">+ Tambah Varian</button>

    <button type="submit" class="button">Simpan Produk</button>
  </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>
