<?php
// Start or resume the PHP session
session_start();

//Connection info
// Step 1: Connect to the MySQL database
require_once('shikanisha.kts.php');

// Connect to the database
$mysqli = mysqli_connect($host, $username, $password, $database);

// Check for connection errors
if ($mysqli->connect_errno) {
  die("Failed to connect to MySQL: " . $mysqli->connect_error);
}

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

// Prepare a query to retrieve the order details
$sql = "SELECT product_id, product_name, price,  quantity FROM sales_order WHERE order_id = ?";
$stmt = $mysqli->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']
  );
}


// Store the order details array in the session variable named "cart"
$_SESSION['cart'] = $order_details;

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


// Prepare a query to retrieve the order details
$sql = "SELECT `total_amount`,`table_name` FROM `orders` WHERE `order_id` = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $order_id);

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

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

// Check if the query returned any rows
if ($result->num_rows > 0) {
  // Get the first row of the result set (there should only be one row)
  $row = $result->fetch_assoc();
  // Store the total_amount in the session named "total"
  $_SESSION['total'] = $row['total_amount'];
  // Store the table_name in the session named "table", or set to "Takeaway" if the value is null
  $_SESSION['table'] = ($row['table_name'] !== null) ? $row['table_name'] : 'Takeaway';
} else {
  // If no rows were returned, display an error message and redirect to the previous page
  $_SESSION['error_message'] = "Could not retrieve order details";
  header("Location: ../orders.php ");
  exit;
}

$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'] = "Sale successfully created.";
} else {
  // Set an error message
  $_SESSION['error_message'] = "Failed to delete order with ID $order_id.";
}

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

// Redirect to trans.php if the process is successful
header("Location: ./trans.kts.php");
exit;

?>
