<?php

include('../include/session.php');

date_default_timezone_set('Africa/Gaborone');
$entry_date = date("Y-m-d H:i:s", time()); 

$order_reference = $_GET['order_reference'];
$delivered = $_GET['delivered'];

if ($delivered=='part') { 
$table_name = $_SESSION['db_prefix']."_orders";
$update_query = "UPDATE $table_name SET ordered = 'part' WHERE order_reference = '".$order_reference."' ";
$update_result = $con->query($update_query);
}
else {
$table_name = $_SESSION['db_prefix']."_orders";
$update_query = "UPDATE $table_name SET ordered = 'no' WHERE order_reference = '".$order_reference."' ";
$update_result = $con->query($update_query);
}

$table_name = $_SESSION['db_prefix']."_order_lines";
$qty_query = "SELECT product_item_id, quantity, delivered, returned FROM $table_name WHERE order_reference = '".$order_reference."'  "; 
$qty_result = $con->query($qty_query);

while($row = $qty_result->fetch_assoc()) {
	$product_item_id = $row["product_item_id"];
	$qty = $row["quantity"];
	$delivered = $row["delivered"];
	$returned = $row["returned"];
	$cancelled = $qty - $delivered + $returned;
	
	$table_name = $_SESSION['db_prefix']."_order_lines";
	$update_query = "UPDATE $table_name SET cancelled = '".$cancelled."' WHERE order_reference = '".$order_reference."' AND product_item_id = '".$product_item_id."'  ";
	$update_result = $con->query($update_query);
}

$table_name = $_SESSION['db_prefix']."_tracking_orders";
	$tracking_query = "INSERT INTO $table_name (entry_date, user_name, action, details_1, details_2, details_3, details_4) VALUES ('".$entry_date."' ,'".$_SESSION['username']."', '48', '".$order_reference."', '' ,'','' )";
	$tracking_result = $con->query($tracking_query);	
?>

<script>
	  window.location="cancel_order.php?order_reference=<?php echo $order_reference?>";
</script>