<?php
include_once 'shikanisha.kts.php';

// Get the data from the AJAX request
$product_name = $_POST['product-name-input'];
$buying_price = $_POST['buying-price-input'];
$selling_price = $_POST['selling-price-input'];
$product_id = $_POST['product-id-input'];
$reorder = $_POST['reorder-qty-input'];
$foodgroup = $_POST['food-group-input'];
$description = $_POST['description-input'];

// Retrieve the uploaded file
$image = $_FILES['image-input'];
$fileName = $image['name'];
$fileTmpName = $image['tmp_name'];
$fileError = $image['error'];

// Check if the image upload encountered any errors
if ($fileError !== UPLOAD_ERR_OK) {
    echo json_encode(['error' => 'File upload error: ' . $fileError]);
    exit();
}

// Move the uploaded file to the destination folder
$destination = "../uploaded/" . $fileName;
if (!move_uploaded_file($fileTmpName, $destination)) {
    echo json_encode(['error' => 'Error moving uploaded file']);
    exit();
}

// Prepare and execute the UPDATE statement for product information
$updateInfo_sql = "UPDATE products SET product_name=?, buying_price=?, selling_price=?, reorder_qty=?, food_group=?, description=? WHERE product_id=?";
$stmtInfo = $conn->prepare($updateInfo_sql);

if (!$stmtInfo) {
    // Handle prepare failure for product information update
    echo json_encode(['error' => 'Prepare failed for product info update: ' . $conn->error]);
    exit();
}

// Bind parameters for product information update
$stmtInfo->bind_param("sddissi", $product_name, $buying_price, $selling_price, $reorder, $foodgroup,$description, $product_id);

// Execute the product information update
if (!$stmtInfo->execute()) {
    // Handle execute failure for product information update
    echo json_encode(['error' => 'Update failed for product info: ' . $stmtInfo->error]);
    exit();
}

// Close the product information statement
$stmtInfo->close();

// Prepare and execute the UPDATE statement for the image
$updateImage_sql = "UPDATE products SET image=? WHERE product_id=?";
$stmtImageUpdate = $conn->prepare($updateImage_sql);

if (!$stmtImageUpdate) {
    // Handle prepare failure for image update
    echo json_encode(['error' => 'Prepare failed for image update: ' . $conn->error]);
    exit();
}

// Bind parameters for image update
$stmtImageUpdate->bind_param("si", $fileName, $product_id);

// Execute the image update
if (!$stmtImageUpdate->execute()) {
    // Handle execute failure for image update
    echo json_encode(['error' => 'Update failed for image: ' . $stmtImageUpdate->error]);
    exit();
}

// Close the image update statement and the database connection
$stmtImageUpdate->close();
$conn->close();

// Return success message
echo json_encode(['success' => 'Product updated successfully']);
?>
