<?php
include ("../../include/session.php");
include ("../../include/db.php");
if(!$session->isRadstoneReceptionUser() && !$session->isAdmin()){
	header("Location: ../../storeMenu.php");
} else {

	$productId = mysql_real_escape_string($_POST['productId']);
	//		$empId = mysql_real_escape_string($_POST['empId']);
	$orderNo = mysql_real_escape_string($_POST['order']);
	$client = mysql_real_escape_string($_POST['client']);
	$quantity = mysql_real_escape_string($_POST['quantity']);
	$price = mysql_real_escape_string($_POST['price']);
	$comments = mysql_real_escape_string($_POST['comments']);
	$delNote = mysql_real_escape_string($_POST['delNote']);
	$date = isset ($_REQUEST["date1"]) ? $_REQUEST["date1"] : "";
	$q2 = "SELECT quantity FROM nam_products WHERE productId = '$productId'";
	$result2 = execsql($q2);
	$totalQuantity = mysql_result($result2, 0, "quantity") - $quantity;
	$order = mysql_real_escape_string($_POST['ordered']);
	$batchCodeOne = strtoupper(mysql_real_escape_string($_POST['batchCodeOne']));
	$batchCodeTwo = strtoupper(mysql_real_escape_string($_POST['batchCodeTwo']));
	

	if($order == ""){
	$qO = "UPDATE nam_orders SET reserved = reserved - $quantity WHERE orderNo = '$orderNo' AND productId = '$productId'";
	execsql($qO);
	}

	$qP = "UPDATE nam_products SET quantity = quantity - $quantity, reserved = reserved - $quantity WHERE productId = '$productId'";
	execsql($qP);
	$q = "";
//	$q1 = "UPDATE nam_products SET quantity = quantity - '$quantity', reserved = reserved + $quantity WHERE productId = '$productId'";
	$q3 = "";

	$q = "INSERT INTO nam_sales (productId, client, orderNo, delNote, quantity, price, comments, date, value, reserved, batchCodeOne, batchCodeTwo) VALUES ('" . $productId . "', '$client','" . $orderNo . "', '" . $delNote . "' ,'" . $quantity . "','" . $price . "', '$comments', '" . $date . "', '$client', '$quantity', '$batchCodeOne', '$batchCodeTwo')";
	$q3 = "INSERT INTO nam_itemhistory (productId, details, quantity, total, date) VALUES ('" . $productId . "', 'Del Note: <a href=\"../Store/displayDelNote.php?delNote=$delNote\">" . $delNote . "</a>" . "','" . $quantity . "','" . $totalQuantity . "','" . $date . "')";
	
	
	$return = mysql_real_escape_string($_POST['submitok']);
	
//	echo $q;

	$result = execsql($q);
	$resultH = execsql($q3);
	
	$qC = "SELECT reserved FROM nam_orders WHERE orderNo = '$orderNo'";
	$rC = execsql($qC);
	$nC = mysql_num_rows($rC);
	$i = 0;
	while($i < $nC){
		$reserved += mysql_result($rC, $i, "reserved");
		$i++;
	}
	if($reserved < 1){
		$orderComplete = "UPDATE nam_orders SET complete = '1' WHERE orderNo = '$orderNo'";
		execsql($orderComplete);
	}
	
	if ($result && $resultH) {
		if ($return == "Save and New") {
			$cat = mysql_real_escape_string($_POST['cat']);
			header("Location: ../orderByDates.php?orderNo=$orderNo&delNote=$delNote&date=$date");
		} else {
						header("Location: ../displayDelNote.php?delNote=$delNote");
		}
	}
}
?>
