<?php
session_start();
include '../../koneksi.php'; // Koneksi ke database

if (!isset($_SESSION['user_id'])) {
    header("Location: ../../login/"); // Redirect ke login jika belum login
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $user_id = $_SESSION['user_id']; // Ambil ID pengguna yang login
    $nama_produk = $_POST['nama_produk'];
    $harga_produk = $_POST['harga'];
    $gambar_produk = NULL; // Default null jika tidak ada gambar

    $_SESSION['old_input'] = [
        'nama_produk' => $nama_produk,
        'harga_produk' => $harga_produk,
    ]; 

    // Cek apakah produk sudah ada untuk user ini
    $stmt_check = $conn->prepare("SELECT id_produk FROM produk WHERE id_user = ?");
    $stmt_check->bind_param("i", $user_id);
    $stmt_check->execute();
    $stmt_check->store_result();

    if ($stmt_check->num_rows > 0) {
        // Jika produk sudah ada, gunakan ID yang sudah ada
        $stmt_check->bind_result($id_produk);
        $stmt_check->fetch();
    } else {
        // Jika belum ada, buat produk baru
        $stmt_insert = $conn->prepare("INSERT INTO produk (id_user) VALUES (?)");
        $stmt_insert->bind_param("i", $user_id);
        if ($stmt_insert->execute()) {
            $id_produk = $stmt_insert->insert_id;
        } else {
            $_SESSION['error'] = "Gagal menyimpan produk!";
            header("Location: ../produk");
            exit();
        }
        $stmt_insert->close();
    }
    $stmt_check->close();

    // 🔹 Upload Gambar jika ada file diunggah
    if (!empty($_FILES["gambar"]["name"])) {
    $target_dir = "../../uploads/produk/";
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    $file_name = basename($_FILES["gambar"]["name"]);
    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    $allowed_ext = ["jpg", "jpeg", "png", "webp"];

    if (in_array($file_ext, $allowed_ext)) {
        $new_file_name = "produk_" . time() . "_" . uniqid() . "." . $file_ext;
        $target_file = $target_dir . $new_file_name;

        $tmp_file = $_FILES["gambar"]["tmp_name"];
        list($width, $height) = getimagesize($tmp_file);

        // Baca gambar sesuai ekstensi
        if ($file_ext == "jpg" || $file_ext == "jpeg") {
            $src_image = imagecreatefromjpeg($tmp_file);
        } elseif ($file_ext == "png") {
            $src_image = imagecreatefrompng($tmp_file);
        } elseif ($file_ext == "webp") {
            $src_image = imagecreatefromwebp($tmp_file);
        }

        // Kompres gambar
        $quality = 75; // Awal kualitas
        $compressed = false;

        do {
            ob_start();
            if ($file_ext == "jpg" || $file_ext == "jpeg") {
                imagejpeg($src_image, null, $quality);
            } elseif ($file_ext == "png") {
                imagepng($src_image, null, (int)((100 - $quality) / 10)); // untuk PNG: 0-9
            } elseif ($file_ext == "webp") {
                imagewebp($src_image, null, $quality); // WebP: 0-100
            }
            $image_data = ob_get_clean();

            if (strlen($image_data) <= 1048576) { // maksimal 1MB
                file_put_contents($target_file, $image_data);
                $compressed = true;
            } else {
                $quality -= 5;
            }
        } while (!$compressed && $quality > 10);

        imagedestroy($src_image);

        if ($compressed) {
            $gambar_produk = $new_file_name;
        } else {
            $_SESSION['error'] = "Gagal mengompres gambar di bawah 1MB.";
            header("Location: ../produk/tambah.php");
            exit();
        }
    } else {
        $_SESSION['error'] = "Format gambar tidak valid! Gunakan JPG, JPEG, PNG, atau WEBP.";
        header("Location: ../produk/tambah.php");
        exit();
    }
}



    // Simpan ke tabel `detail_produk`
    $stmt_detail = $conn->prepare("INSERT INTO detail_produk (id_produk, nama_produk, harga_produk, gambar_produk) VALUES (?, ?, ?, ?)");
    $stmt_detail->bind_param("isis", $id_produk, $nama_produk, $harga_produk, $gambar_produk);

    if ($stmt_detail->execute()) {
        unset($_SESSION['old_input']);
        $_SESSION['success'] = "Data Produk berhasil ditambahkan!";
    } else {
        $_SESSION['error'] = "Gagal menyimpan data produk!";
    }

    $stmt_detail->close();
    $conn->close();
}

// Redirect ke halaman produk setelah submit
header("Location: ../produk");
exit();
?>
