<?php
if(!isset($_SESSION)) { 
  session_start(); 
  include('../includes/dbcon.php');
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $item_id = $_POST['item_id'];

    // File upload settings
    $target_dir = "uploads/";
    $imageFileType = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));
    $allowed_types = array("jpg", "jpeg", "png");

    // Validate file type
    if (!in_array($imageFileType, $allowed_types)) {
        echo "Only JPG, JPEG, and PNG files are allowed.";
        exit;
    }

    // Set new filename based on item_id
    $new_filename = $item_id . "." . $imageFileType;
    $target_file = $target_dir . $new_filename;

    // Check if the file already exists
    $sql = "SELECT image_path FROM item_master WHERE item_id = '$item_id'";
    $result = mysqli_query($con, $sql);
    if ($row = mysqli_fetch_assoc($result)) {
        $old_image_path = $row['image_path'];
        
        // If the old image exists, delete it
        if (!empty($old_image_path) && file_exists($target_dir . $old_image_path)) {
            unlink($target_dir . $old_image_path); // Delete the old image
        }
    }

    // Load the image and compress
    if ($imageFileType == "jpg" || $imageFileType == "jpeg") {
        $image = imagecreatefromjpeg($_FILES["image"]["tmp_name"]);
    } elseif ($imageFileType == "png") {
        $image = imagecreatefrompng($_FILES["image"]["tmp_name"]);
    }

    if ($image) {
        // Compress image
        if ($imageFileType == "jpg" || $imageFileType == "jpeg") {
            imagejpeg($image, $target_file, 70); // 70% quality
        } elseif ($imageFileType == "png") {
            imagepng($image, $target_file, 7); // Compression level 0-9 (7 is good)
        }
        imagedestroy($image); // Free memory

        // Update database with new image filename
        $sql = "UPDATE item_master SET image_path='$new_filename' WHERE item_id='$item_id'";
        if (mysqli_query($con, $sql)) {
            echo "Image uploaded and compressed successfully.";
            echo "<script>document.location='admin_item_view.php'</script>";
        } else {
            echo "Database update failed: " . mysqli_error($con);
        }
    } else {
        echo "Error processing image.";
    }
}
?>
