<?php
session_start(); // Pastikan session dimulai
include '../auth.php';
include '../../koneksi.php';

$user_id = $_SESSION['user_id']; 

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id_produk = $_POST['id'];
    $nama_produk = $_POST['namaproduk'];
    $harga_produk = $_POST['harga'];

    // Ambil data produk lama dari database
    $query = "SELECT gambar_produk FROM detail_produk WHERE id_detail_produk = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $id_produk);
    $stmt->execute();
    $stmt->bind_result($gambar_lama);
    $stmt->fetch();
    $stmt->close();

    $gambar_produk = $gambar_lama; // Default tetap pakai gambar lama

    // Cek apakah ada file yang diunggah
    if (!empty($_FILES['gambar']['name'])) {
    $target_dir = "../../uploads/produk/";

    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    $imageFileType = strtolower(pathinfo($_FILES["gambar"]["name"], PATHINFO_EXTENSION));
    $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

    if (in_array($imageFileType, $allowed_types)) {
        $tmp_file = $_FILES["gambar"]["tmp_name"];

        if ($_FILES["gambar"]["error"] !== UPLOAD_ERR_OK) {
            $_SESSION['error'] = "Gagal upload file. Ukuran terlalu besar atau bermasalah.";
            header("Location: update.php?id=$id_produk");
            exit();
        }

        // Cek MIME type
        $mime_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $tmp_file);
        finfo_close($finfo);
        if (!in_array($mime, $mime_types)) {
            $_SESSION['error'] = "File bukan gambar yang valid.";
            header("Location: update.php?id=$id_produk");
            exit();
        }

        $unique_name = time() . '_' . md5(uniqid()) . '.' . $imageFileType;
        $target_file = $target_dir . $unique_name;

        $compressed = false;
        $quality = 85;

        // Buat image resource
        if ($imageFileType == 'jpg' || $imageFileType == 'jpeg') {
            $src_image = imagecreatefromjpeg($tmp_file);
        } elseif ($imageFileType == 'png') {
            $src_image = imagecreatefrompng($tmp_file);
        } elseif ($imageFileType == 'webp') {
            $src_image = imagecreatefromwebp($tmp_file);
        } elseif ($imageFileType == 'gif') {
            // Tidak dikompres, langsung simpan
            move_uploaded_file($tmp_file, $target_file);
            $compressed = true;
        }

        // Kompres jika bukan GIF
        if (!$compressed && isset($src_image)) {
            do {
                ob_start();
                if ($imageFileType == 'jpg' || $imageFileType == 'jpeg') {
                    imagejpeg($src_image, null, $quality);
                } elseif ($imageFileType == 'png') {
                    imagepng($src_image, null, (int)((100 - $quality) / 10));
                } elseif ($imageFileType == 'webp') {
                    imagewebp($src_image, null, $quality);
                }
                $image_data = ob_get_clean();

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

            imagedestroy($src_image);
        }

        if ($compressed) {
            if (!empty($gambar_lama) && file_exists(realpath($target_dir . $gambar_lama))) {
                unlink(realpath($target_dir . $gambar_lama));
            }
            $gambar_produk = $unique_name;
        } else {
            $_SESSION['error'] = "Gagal mengompres gambar di bawah 1MB.";
            header("Location: update.php?id=$id_produk");
            exit();
        }
    } else {
        $_SESSION['error'] = "Format gambar tidak valid! Gunakan JPG, JPEG, PNG, atau WEBP.";
        header("Location: update.php?id=$id_produk");
        exit();
    }
}



    // Update produk
    $sql_update = "UPDATE detail_produk SET nama_produk = ?, harga_produk = ?, gambar_produk = ? WHERE id_detail_produk = ?";
    $stmt_update = $conn->prepare($sql_update);
    $stmt_update->bind_param("sssi", $nama_produk, $harga_produk, $gambar_produk, $id_produk);

    if ($stmt_update->execute()) {
        $_SESSION['success'] = "Data Produk berhasil diperbarui!";
    } else {
        $_SESSION['error'] = "Gagal memperbarui produk! " . $stmt_update->error;
        error_log("MySQL Error: " . $stmt_update->error);
    }

    $stmt_update->close();
    header("Location: ../produk/");
    exit();
}
?>
