<?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."' ";
execsql($update_query);
}
else {
$table_name = $_SESSION['db_prefix']."_orders";
$update_query = "UPDATE $table_name SET ordered = 'no' WHERE order_reference = '".$order_reference."' ";
execsql($update_query);
}

$table_name = $_SESSION['db_prefix']."_order_lines";
$qty_query = "SELECT store_item_id, quantity, delivered, returned FROM $table_name WHERE order_reference = '".$order_reference."'  "; 
$qty_result = mySQL_query($qty_query);
$qty_num = mysql_num_rows($qty_result);

$i=0;
while ($i<$qty_num) {
	$store_item_id = mysql_result($qty_result, $i, "store_item_id");
	$qty = mysql_result($qty_result, $i, "quantity");
	$delivered = mysql_result($qty_result, $i, "delivered");
	$returned = mysql_result($qty_result, $i, "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 store_item_id = '".$store_item_id."'  ";
	execsql($update_query);
	$i++;
}

$table_name = $_SESSION['db_prefix']."_tracking_orders";
	$trackingQuery = "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."', '' ,'','' )";
	$trackingResult = mySQL_query($trackingQuery);	
?>

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