<?php
include 'connect.php';
    $item_id = $_POST['itemID'];
$name = mysqli_real_escape_string($con, $_POST['itemName']);
$desc = mysqli_real_escape_string($con, $_POST['itemDesc']);
    $category_id=$_POST['catID'];
    $show=$_POST['show'];
    $out=$_POST['out'];
    $promotion=$_POST['promotion'];
    // Check if the 'categoryImage' field is set (user has changed the image)
    if (isset($_FILES['itemImage'])) {
        $imageName = $_FILES['itemImage']['name'];
        $imageTmp = $_FILES['itemImage']['tmp_name'];
        $imageExtension = pathinfo($imageName, PATHINFO_EXTENSION); // Get the file extension
        
        $folderName = "../images/Items/";
        $newImageName = uniqid() . '.' . $imageExtension;
        $destination = $folderName . $newImageName;
        $image = "images/Items/" . $newImageName;
        
        
        if (move_uploaded_file($imageTmp, $destination)) {
            // Update all fields
            $sql = "UPDATE a_items SET ItemName = '$name',ItemDescription='$desc', ItemImage = '$image', ItemShow_status = $show,ItemOutOfStock_status=$out,Promotion=$promotion,CategoryID_FK=$category_id WHERE ItemID=$item_id";
        } else {
            echo "Error uploading the image.";
        }
    } else {
        // User hasn't changed the image, update only specific fields
        $sql = "UPDATE a_items SET ItemName = '$name',ItemDescription='$desc',ItemShow_status = $show,ItemOutOfStock_status=$out,Promotion=$promotion,CategoryID_FK=$category_id WHERE ItemID=$item_id";
    }
    $result = mysqli_query($con, $sql);

    if ($result) {
        echo "Category updated successfully.";
    } else {
        echo "Error updating category: " . mysqli_error($con);
    }

?>
