<?php
require '../../config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $id          = (int) $_POST['id'];
  $nama        = mysqli_real_escape_string($conn, $_POST['nama']);
  $deskripsi   = mysqli_real_escape_string($conn, $_POST['deskripsi']);
  $harga       = (int) $_POST['harga'];
  $kategori_id = (int) $_POST['kategori_id'];
  $diskon_id = !empty($_POST['diskon_id']) ? (int)$_POST['diskon_id'] : null;

  // Ambil data lama untuk cek gambar sebelumnya
  $query = "SELECT gambar FROM produk WHERE id = $id";
  $result = mysqli_query($conn, $query);
  $row = mysqli_fetch_assoc($result);
  $gambarLama = $row['gambar'];
  $gambarBaru = $gambarLama;

  // Jika user mengupload gambar baru
  if (!empty($_FILES['gambar']['name'])) {
    $fileTmp  = $_FILES['gambar']['tmp_name'];
    $fileExt  = pathinfo($_FILES['gambar']['name'], PATHINFO_EXTENSION);
    $hashName = sha1_file($fileTmp) . '.' . $fileExt;

    // Simpan ke folder upload
    move_uploaded_file($fileTmp, '../../upload/' . $hashName);
    $gambarBaru = $hashName;

    // Hapus gambar lama
    if ($gambarLama && file_exists('../../upload/' . $gambarLama)) {
      unlink('../../upload/' . $gambarLama);
    }
  }

  // Update data produk
  $queryUpdate = "UPDATE produk SET
    nama = '$nama',
    deskripsi = '$deskripsi',
    harga = $harga,
    gambar = '$gambarBaru',
    kategori_id = $kategori_id,
    diskon_id = " . ($diskon_id ? $diskon_id : 'NULL') . "
    WHERE id = $id";

  $updateResult = mysqli_query($conn, $queryUpdate);

  if ($updateResult) {
    // Hapus semua ukuran lama
    mysqli_query($conn, "DELETE FROM ukuran_produk WHERE produk_id = $id");

    // Masukkan ukuran baru dari form
    if (isset($_POST['ukuran']) && isset($_POST['stok_ukuran'])) {
      $ukuran_array = $_POST['ukuran'];
      $stok_array = $_POST['stok_ukuran'];

      for ($i = 0; $i < count($ukuran_array); $i++) {
        $ukuran = mysqli_real_escape_string($conn, $ukuran_array[$i]);
        $stokUkuran = (int) $stok_array[$i];

        if (!empty($ukuran)) {
          $insertUkuran = "INSERT INTO ukuran_produk (produk_id, ukuran, stok) 
                           VALUES ($id, '$ukuran', $stokUkuran)";
          mysqli_query($conn, $insertUkuran);
        }
      }
    }

    header("Location: daftar_produk.php?pesan=edit_berhasil");
    exit;
  } else {
    echo "Gagal mengupdate data: " . mysqli_error($conn);
  }
} else {
  echo "Akses tidak sah!";
}
?>
