<?php
include ("../../include/session.php");
include ("../../include/db.php");
if(!$session->isAdmin() && !$session->isRadstoneReceptionUser()){
	header("Location: ../../main.php");
} else {
//		$date = isset ($_REQUEST["date2"]) ? $_REQUEST["date2"] : "";
		$date = mysql_real_escape_string($_REQUEST['date']);
		$wet = mysql_real_escape_string($_REQUEST['wet']);
		$hours = mysql_real_escape_string($_REQUEST['hours']);
		$recipieId = mysql_real_escape_string($_REQUEST['recipieId']);
		$return = mysql_real_escape_string($_REQUEST['return']);
//		echo $recipieId;
//		foreach($_REQUEST as $key => $value){
//			echo "$key>>>> $value<br />";
//		}
		$recipie = "SELECT * FROM nam_perwetprice ORDER BY id DESC LIMIT 1";
		$rRecipie = execsql($recipie);
		$row = mysql_fetch_assoc($rRecipie);
		$amount = 0;
		$itemName = "";
		foreach ($row as $key => $value) {
			if ($key != "id" && $value != 0) {
				$amount += $value * $hours;
				$itemName = $key;
			}
	
		}
		$q2 = "SELECT productId FROM nam_products WHERE productName = '$itemName'";
		$r = execsql($q2);
		$prodId = mysql_result($r, 0, "productId");
		
		$q3 = "SELECT $itemName FROM nam_recipiewet ORDER BY id DESC LIMIT 1";
		$r3 = execsql($q3);
		$amount = mysql_result($r3, 0, "$itemName") * $hours;
		
		$q4 = "SELECT quantity FROM nam_products WHERE productId = '$prodId'";
		$r4 = execsql($q4);
		$totalAmount = mysql_result($r4, 0, "quantity") - $amount;
		
		$qF = "SELECT productionId FROM nam_production WHERE date = '$date' AND recipieId = '$recipieId' ORDER BY productionId DESC LIMIT 1";
		$rF = execsql($qF);
		$insertId = mysql_result($rF, 0, "productionId");
//		echo $qF;
		
		
		if ($prodId!="100127") {
		$q1 = "INSERT INTO nam_itemhistory (productId, details, quantity, total, date) VALUES ('$prodId', 'Used in production', '$amount', '$totalAmount', '$date')";}
		$q = "UPDATE nam_production SET wet = '$wet', heatingHours = '$hours',cost = cost + '$amount' WHERE productionId = '$insertId'";
		echo $q1;
		$r = execsql($q);
		$r1 = execsql($q1);
		$q5 = "UPDATE nam_products SET quantity = $totalAmount WHERE productId = '$prodId'";
		$r5 = execsql($q5);
		if($r &&  $r5){
			if ($return == "Save and New") {
				$cat = mysql_real_escape_string($_POST['cat']);
				header("Location: ../production.php?date=$date");
			} else {
				header("Location: ../productionMenu.php");
			}
		}else{
			echo "Failed";
		}
	}
?>
