<?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'];
$product_item_id = $_GET['product_item_id_select'];
$qty = $_GET['qty_text'];

$table_name = $_SESSION['db_prefix']."_orders";
$order_query = "SELECT order_no, cust_id, order_date FROM $table_name WHERE order_reference = '".$order_reference."' ";
$order_result = $con->query($order_query);
$row = mysqli_fetch_assoc($order_result);
$order_no = $row["order_no"];
$order_no = $row["order_no"];
$cust_id = $row["cust_id"];
$order_date = $row["order_date"];

$table_name = $_SESSION['db_prefix']."_product_store";
$item_query = "SELECT item_name, subCategory, price FROM $table_name WHERE product_item_id = '".$product_item_id."'  ";
$item_result = $con->query($item_query);
$row = mysqli_fetch_assoc($item_result);
$item_name = $row["item_name"];
$sub_category = $row["subCategory"];
$price = $row["price"];


$table_name = $_SESSION['db_prefix']."_order_lines";
$check_query = "SELECT order_reference FROM $table_name WHERE order_reference = '".$order_reference."' AND product_item_id = '".$product_item_id."'  ";
$check_result = $con->query($check_query);
$check_num = mysqli_num_rows($check_result);

if ($check_num==0) {

$table_name = $_SESSION['db_prefix']."_order_lines";
$add_query = "INSERT INTO $table_name (order_reference, order_no, order_date, cust_id, product_item_id, sub_category, quantity, price) VALUES ('".$order_reference."', '".$order_no."', '".$order_date."', '".$cust_id."', '".$product_item_id."', '".$sub_category."', '".$qty."', '".$price."' ) ";
$add_result = $con->query($add_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']."', '46', '".$order_reference."' , '".$product_item_id."','".$item_name."','".$qty."' )";
$tracking_result = $con->query($tracking_query);


$error=0;

}
else {
$error=1;
}
?>


<script language="javascript" type="text/javascript">
        window.location="../store/edit_order.php?order_reference=<?php echo $order_reference ?>&e=<?php echo $error ?>";
</script>