<?php
include ("../../include/session.php");
if(!$session->isAdmin() && !$session->isRadstoneReceptionUser()){
	header("Location: ../../main.php");
} else {
	include ("../../include/db.php");
	$date = isset ($_REQUEST["date3"]) ? $_REQUEST["date3"] : "";
	$dep = mysql_real_escape_string($_POST['dep']);
	$recipieId = mysql_real_escape_string($_POST['recipieId']);
	$depRecId = mysql_real_escape_string($_POST['depRecipieId']);
	$prices = "SELECT * FROM nam_perdepaletprice WHERE id = '$depRecId'";
	$r1 = execsql($prices);
	$search = "SELECT * FROM nam_recipiedepalet WHERE id = '$depRecId'";
	$r = execsql($search);
	$row = mysql_fetch_assoc($r);
	$cost = 0;
	$reference="";
	$entry="70";
	$userId = $_SESSION['username'];
	
	date_default_timezone_set('Africa/Khartoum');
	$entryDate = date("Y-m-d H:i:s",time()-3600);
	
	foreach ($row as $key => $value) {
		if ($key != "id" && $value != 0) {
			if ($key != "size") {
				//calculating cost before amount of tiles
				$cost += mysql_result($r1, 0, "$key") * $dep;

				$used = $dep * mysql_result($r, 0, "$key");
				
				//getting product name for history ect
				$prodName = str_replace("_", " ", $key);
				$q = "SELECT productId, quantity FROM nam_products WHERE productName = '$prodName'";
				$result = execsql($q);
				$prodId = mysql_result($result, 0, "productId");
				$amountOfProduct = mysql_result($result, 0, "quantity");
				$tAmount = $amountOfProduct - $used;


				//item history
				$q3 = "INSERT INTO nam_itemhistory (productId, entry, reference, quantity, total, date, entryDate, userId) VALUES ('$prodId','".$entry."','".$reference."', '$used', '$tAmount', '$date','".$entryDate."','".$userId."')";
				execsql($q3);
//				echo $q3;
				//setting amount of product 
				$q4 = "UPDATE nam_products SET quantity = '$tAmount' WHERE productId = '$prodId'";
				execsql($q4);
				
			}

		}

	}
$q2 = "INSERT INTO nam_productiondepalet (date, recipieId, cost, amountOfTiles) VALUES ('$date', '$recipieId', '$cost', '$dep')";
execsql($q2);
$return = mysql_real_escape_string($_POST['submitok']);
if ($return == "Save and New") {
				$cat = mysql_real_escape_string($_POST['cat']);
				header("Location: ../depaletised.php?date=$date");
			} else {
				header("Location: ../productionMenu.php");
			}
//header("Location: ../productionMenu.php");
}
?>