<?php
include('include/session.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('connection.php');
include('class.php');
$dbConnection = new DbConnection();
$connection = $dbConnection->connection;

// Instantiate the NewOrder class
$Orders = new NewOrder();

// Check if the HTTP request method is POST
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Get the values as an array
    $order_id = $_POST["order_id"];
    $c_uid = $_POST["cuid"];
    
    // Process arrays from form submission
    $category = is_array($_POST["category"]) ? $_POST["category"] : array($_POST["category"]);
    $product = is_array($_POST['product']) ? $_POST['product'] : array($_POST['product']);
    $variation = is_array($_POST['variation']) ? $_POST['variation'] : array($_POST['variation']);
    $product_id = is_array($_POST['product_id']) ? $_POST['product_id'] : array($_POST['product_id']);
    $price = is_array($_POST['price']) ? $_POST['price'] : array($_POST['price']);
    $quantity = is_array($_POST['quantity']) ? $_POST['quantity'] : array($_POST['quantity']);
    $items = is_array($_POST['items']) ? $_POST['items'] : array($_POST['items']);
    $total_price = $_POST['total_price'];
    $payment_reference = $_POST['payment_reference'];

    // Calculate updated quantity
    $updated_quantity = array_map(function($q, $i) {
        return $q - $i;
    }, $quantity, $items);

    // Update product_variation table
    $updateStmt = $connection->prepare("UPDATE product_variation SET quantity = ? WHERE variation = ? AND price = ?");
    if (!$updateStmt) {
        die('Error preparing update statement: ' . $connection->error);
    }

    foreach ($updated_quantity as $key => $value) {
        // Cast the values to integers to ensure they are treated as numbers
        $quantity_int = (int) $quantity[$key];
        $items_int = (int) $items[$key];
        $variation_str = (string) $variation[$key];
        $price_str = (string) $price[$key];
        
        $updateStmt->bind_param("iss", $value, $variation_str, $price_str);
        $updateResult = $updateStmt->execute();

        if (!$updateResult) {
            die('Error executing update statement: ' . $updateStmt->error);
        }
    }

    $updateStmt->close();

    // Insert the serialized array into the database
    $result = $Orders->order($order_id, $c_uid, implode(', ', $category), implode(', ', $product), implode(', ', $variation), implode(', ', $product_id), implode(', ', $price), implode(', ', $items), $total_price, $payment_reference);

    // Check the result of the insertion
    if ($result == 1) {
        echo "<script> alert('Added Successful'); window.location.href = '_new_order.php'; </script>";
    } else {
        echo "<script> alert('Something went wrong'); window.location.href = '_new_order.php'; </script>";
    }
}
?>
