<?php
session_start();
include 'shikanisha.kts.php';

// Get the order ID from the POST request
$order_id = $_POST['order_id'];

// Initialize the $_SESSION['order'] array if it doesn't exist
if (!isset($_SESSION['order'])) {
  $_SESSION['order'] = array();
}

// Prepare a query to retrieve the order details
$sql = "SELECT product_id, product_name, price, quantity FROM sales_order WHERE order_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $order_id);

// Execute the query
$stmt->execute();

// Get the result set
$result = $stmt->get_result();

// Create an array to store the order details
while ($row = $result->fetch_assoc()) {
  $order_details = array(
    'id'    =>  $row['product_id'],
    'name'  =>  $row['product_name'],
    'price' =>  $row['price'],
    'qty'   =>  $row['quantity']
  );
  
  // Check if the product already exists in the cart
  $session_array_id = array_column($_SESSION['order'],'id');
  if(in_array($order_details['id'], $session_array_id))
  {
    // If the product already exists, increase the quantity
    foreach($_SESSION['order'] as $key => $val){
      if($_SESSION['order'][$key]['id']===$order_details['id']){
        $_SESSION['order'][$key]['qty'] = $_SESSION['order'][$key]['qty'] + $order_details['qty'];
      }
    }
  } else {
    // If the product does not exist, add it to the cart
    $_SESSION['order'][] = $order_details;
  }
}

// Close the statement
$stmt->close();

// Prepare a query to delete the order
$sql = "DELETE FROM orders WHERE order_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $order_id);

// Execute the query
$stmt->execute();

// Check if the order was successfully deleted
if ($stmt->affected_rows > 0) {
  // Set a success message
  $_SESSION['success_message'] = "Order with ID $order_id has been successfully deleted.";
} else {
  // Set an error message
  $_SESSION['error_message'] = "Failed to delete order with ID $order_id.";
}

// Close the statement and database connection
$stmt->close();
$conn->close();

// Redirect to orders.php
header("Location: ../orders.php");
exit;
?>