<?php
if (session_status() == PHP_SESSION_NONE) {
  session_start();
}
include '../../config.php';

// Ambil data dari form
$nama = $_POST['nama'];
$deskripsi = $_POST['deskripsi'];
$harga = $_POST['harga'];
// $stok = $_POST['stok'];
$kategori_id = $_POST['kategori_id'];
$ukuran = $_POST['ukuran']; // array
$stok_ukuran = $_POST['stok_ukuran']; // array
$diskon_id = !empty($_POST['diskon_id']) ? (int)$_POST['diskon_id'] : null;

// Upload gambar
$gambar = $_FILES['gambar']['name'];
$tmp = $_FILES['gambar']['tmp_name'];
move_uploaded_file($tmp, "../../upload/$gambar");

// Insert ke tabel produk
$query = "INSERT INTO produk (nama, deskripsi, harga, kategori_id, gambar, dibuat_pada, diskon_id) 
          VALUES (?, ?, ?, ?, ?, NOW(), ?)";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "ssiisi", $nama, $deskripsi, $harga, $kategori_id, $gambar, $diskon_id);
$success = mysqli_stmt_execute($stmt);

if ($success) {
  $produk_id = mysqli_insert_id($conn);

  // Simpan ukuran dan stoknya
  $stmt_ukuran = mysqli_prepare($conn, "INSERT INTO ukuran_produk (produk_id, ukuran, stok) VALUES (?, ?, ?)");
  for ($i = 0; $i < count($ukuran); $i++) {
    mysqli_stmt_bind_param($stmt_ukuran, "isi", $produk_id, $ukuran[$i], $stok_ukuran[$i]);
    mysqli_stmt_execute($stmt_ukuran);
  }

  $_SESSION['alert'] = ['type' => 'success', 'message' => 'Produk berhasil ditambahkan.'];
} else {
  $_SESSION['alert'] = ['type' => 'danger', 'message' => 'Gagal menambahkan produk.'];
}

header("Location: daftar_produk.php?pesan=edit_berhasil");
exit;
