<?php
/*
27/08/2010 - Started

*/

include("Functions_Sales.php");
error_reporting(E_ERROR);
if($_SESSION['dbName']==""){
	header("location:../index.php");
}

//Open MySQLI Connection
$aconn = openALConnection();
$conn = openConnection();
$iconn = openIConnection();

//Get User Rights - Disabled for Now
$querylog="select * from ".$_SESSION['label'].".login where user_account='".$_SESSION['useraccount']."'";
$resultlog=mysql_query($querylog) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

//Background Colours
$query1="select grid_color1, grid_color2 from setup";
$result1=mysql_query($query1) or die(mysql_error());
while($rows=mysql_fetch_array($result1)){
	extract($rows);
}

$txtID = $_POST["txtID"]; if ($txtID == ""){$txtID = $_GET["txtID"];}
$txtRef = $_POST["txtRef"]; if ($txtRef == ""){$txtRef = $_GET["txtRef"];}
$txtSearchRef = $_POST["txtSearchRef"]; if ($txtSearchRef == ""){$txtSearchRef = $_GET["txtSearchRef"];}
$txtDate = $_POST["txtDate"]; if ($txtDate== ""){$txtDate = $_GET["txtDate"];} if ($txtDate== ""){$txtDate = displayToday();}
$txtRequestDate = $_POST["txtRequestDate"]; if ($txtRequestDate == ""){$txtRequestDate = $_GET["txtRequestDate"];} if ($txtRequestDate== ""){$txtRequestDate = displayToday();}
$txtRemark = $_POST["txtRemark"]; if ($txtRemark == ""){$txtRemark = $_GET["txtRemark"];}
$txtIAddress = $_POST["txtIAddress"]; if ($txtIAddress == ""){$txtIAddress = $_GET["txtIAddress"];}
$txtDAddress = $_POST["txtDAddress"]; if ($txtDAddress == ""){$txtDAddress = $_GET["txtDAddress"];}

$lstClient = $_POST['lstClient']; if ($lstClient == ""){$lstClient = $_GET["lstClient"];}
$lstCurrency = $_POST['lstCurrency']; if ($lstCurrency == ""){$lstCurrency = $_GET["lstCurrency"];} if ($lstCurrency == ""){$lstCurrency = "NGN";}
$lstCostCentre = $_POST['lstCostCentre']; if ($lstCostCentre == ""){$lstCostCentre = $_GET["lstCostCentre"];}
$lstProject = $_POST['lstProject']; if ($lstProject == ""){$lstProject = $_GET["lstProject"];}
$lstSalesman = $_POST['lstSalesman']; if ($lstSalesman == ""){$lstSalesman = $_GET["lstSalesman"];}

$lstWarehouse = $_POST['lstWarehouse']; if ($lstWarehouse == ""){$lstWarehouse = $_GET["lstWarehouse"];}
$lstItem = $_POST['lstItem']; if ($lstItem == ""){$lstItem = $_GET["lstItem"];}
$txtQty = $_POST['txtQty']; if ($txtQty == ""){$txtQty = $_GET["txtQty"];}
$txtSP = $_POST['txtSP']; if ($txtSP == ""){$txtSP = $_GET["txtSP"];}
$txtDiscount = $_POST['txtDiscount']; if ($txtDiscount == ""){$txtDiscount = $_GET["txtDiscount"];}
$lstItemType = $_POST['lstItemType']; if ($lstItemType == ""){$lstItemType = $_GET["lstItemType"];} if ($lstItemType == ""){$lstItemType = "Not Packed";}
$txtConfirmed = "No";
$txtCreditLimit = "";

$act = $_POST['act']; if ($act == ""){$act = $_GET["act"];}
$prints = $_POST['prints']; if ($prints == ""){$prints = $_GET["prints"];}
$message = $_GET["message"];

//$user_level = $_POST['user_level']; if ($user_level == ""){$user_level = $_GET["user_level"];} 
$user_level = $_SESSION['user_level'];
$warehouseQuery1 = $_SESSION['warehouseQuery1'];	
$warehouseQuery2 = $_SESSION['warehouseQuery2'];
$projectQuery = $_SESSION['projectQuery'];	
$defaultProject = $_SESSION['defaultProject'];
$defaultWarehouse = $_SESSION['defaultWarehouse'];

//echo "52".$user_level;
if ($user_level == ""){
	$query = "SELECT FA_receiptMod, FA_receiptDel, FA_receiptApp, FA_receipt FROM ".$_SESSION['label'].".login where user_account= '".$_SESSION['useraccount']."'";
	$result = selectData($aconn, $query);	
	
	//$result = getUserAccess($_SESSION['label'], $_SESSION['useraccount']);
	if ($result[0] == "1"){$user_level = $user_level . "-RE-";}
	if ($result[1] == "1"){$user_level = $user_level . "-RD-";}
	if ($result[2] == "1"){$user_level = $user_level . "-RA-";}
	if ($result[3] == "1"){$user_level = $user_level . "-RV-";}

	if ($result[3] == "0"){
		header("Location: logout5.php");
	}else{
		$_SESSION['user_level'] = $user_level;	
	}
	
	$this_query = "SELECT Project_code FROM ".$_SESSION['label'].".loginstk WHERE user_account = '".$_SESSION['useraccount']."' AND Project_code IS NOT NULL ";
	$result = selectData($aconn, $this_query);
	if ($result[0] != "0" && $result[0] != "" && $result[0] != "NULL"){
		$projectQuery = " AND Project.Project_code IN (".$this_query.")";
	}
	$_SESSION['projectQuery'] = $projectQuery;

	$this_query = "SELECT Project_code FROM ".$_SESSION['label'].".loginstk WHERE user_account = '".$_SESSION['useraccount']."' AND Default_Project = 1 ";
	$result = selectData($aconn, $this_query);
	if ($result[0] != "0" && $result[0] != "" && $result[0] != "NULL"){
		$defaultProject = $result[0];
	}
	$_SESSION['defaultProject'] = $defaultProject;
	//echo "106".$defaultProject;
}
//echo "<br><br>".$user_level;


if ($act == "addItem"){
	$query = "SELECT curdt_rate FROM curdt WHERE Currency_Code = 'NGN' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = 'NGN' )";
	$result = selectData($conn, $query);
	$rate_dt = $result[0];

	$query = "SELECT curdt_parity FROM curdt WHERE Currency_Code = 'NGN' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = 'NGN' )";
	$result = selectData($conn, $query);
	$parity_dt = $result[0];

	$query = "SELECT Item_Vat FROM Items WHERE item_Code = '".$lstItem."'";
	$result = selectData($conn, $query);
	$item_vat = $result[0];
	$item_vat = $item_vat/100;
	$tax_flag = 0;
	$notax_flag = 1;
	if ($item_vat > 0){
		$tax_flag = 1;
		$notax_flag = 0;
	}

	if ($txtID == ""){
		$query = "SELECT sorder_id+1 FROM sequence";
		$result = selectData($conn, $query);
		$txtID = $result[0];
		$query = "UPDATE sequence SET sorder_id = ".$txtID;
		updateData($conn, $query, true);	

		//Insert into Master Table
		$query = "INSERT INTO sorder (sorder_id, sorder_date, sorder_requestdate, sorder_remark, Client_Code, sorder_Clientcontact, Currency_Code, Costcent_code, sorder_DeliveryPlace, Project_Code, sorder_totalQuantity, sorder_totalQuantityUsed, sorder_posted, sorder_taxable, sorder_vat, sorder_discountamount, sorder_type, sorder_confirmed, journal_type, User_Account, Salesman_code, Sorder_MaturityDate, sorder_nonetaxable) VALUES (".$txtID.", CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), CONCAT('".displayParadoxDate(insertDate($txtRequestDate))." ', RIGHT(NOW(), 8)), '".$txtRemark."', '".$lstClient."', '".$txtIAddress."', '".$lstCurrency."', NULL, '".$txtDAddress."', '".$lstProject."', '0', '0', '0', '0', '0', '0', 'SO', '0', 'SO', '".$_SESSION['useraccount']."', '".$lstSalesman."', NOW(), '0')";
		updateIData($iconn, $query, false);
		//echo "<br><br>".$query;	

		$query = "UPDATE sorder SET sorder_taxableBase1 = sorder_taxable * ".$rate_dt.", sorder_taxableBase2 = sorder_taxable / ".$parity_dt.", sorder_noneTaxableBase1 = sorder_nonetaxable * ".$rate_dt.", sorder_noneTaxableBase2 = sorder_nonetaxable / ".$parity_dt.", sorder_discountbase1 = sorder_discountamount * ".$rate_dt.", sorder_discountbase2 = sorder_discountamount / ".$parity_dt.", sorder_vatbase1 = sorder_vat * ".$rate_dt.", sorder_vatbase2 = sorder_vat / ".$parity_dt." WHERE sorder_id = ".$txtID."";
		updateIData($iconn, $query, true);
		//echo "<br><br>".$query;
	}
		
	//echo "<br><br>".$query;
	if ($lstItemType == "Not Packed"){
		//Check If Page was refreshed
		$query = "SELECT sorderdt_id FROM sorderdt WHERE User_Account = '".$_SESSION['useraccount']."' AND item_code = '".$lstItem."' AND sorder_id = '".$txtID."'";
		//echo "<br><br>".$query;
		$result = selectData($conn, $query);		
		if (is_numeric($result[0]) == false){
			$query = "SELECT sorderdt_id+1 FROM sequence";
			$result = selectData($conn, $query);
			$txt_ID = $result[0];
			$query = "UPDATE sequence SET sorderdt_id = ".$txt_ID;
			updateData($conn, $query, true);

			$query = "SELECT SUM(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered) FROM stktransaction WHERE item_code = '".$lstItem."' AND warehouse_code = '".$lstWarehouse."'";
			//echo "<br><br>".$query;
			$result = selectData($conn, $query);
			if ($result[0] >= $txtQty){
				$query = "SELECT transactionsetup.Trans_directstkDbt, transactionsetup.Trans_directstkcrd, transactionsetup.Trans_directstkcur, transactionsetup.Trans_discountacc, transactionsetup.Trans_RMAcc from transactionsetup, items WHERE transactionsetup.Group_Code = items.Group_Code AND items.Item_Code = '".$lstItem."'";				
				$super_sub_result = selectData($conn, $query);
				//echo "<br><br>".$query;

				$query = "INSERT INTO sorderdt (sorderdt_id, sorder_id, sorderdt.item_code, sorderdt_quantity, sorderdt_quantityUsed, sorderdt_price, sorderdt_discount, warehouse_code, Currency_Code, Item_Vat, sorderdt_priceTTC, Item_QtyPacked, sorderdt_posted, sorderdt_oqty, User_Account, Client_code, sorder_date, Project_code, sorderdt_directstkDbt, sorderdt_directstkcrd, sorderdt_directstkcur, sorderdt_ItemAccount, sorderdt_pricebase1, SroderDt_PriceBase2) VALUES (".$txt_ID.", ".$txtID.", '".$lstItem."', '".$txtQty."', '0', '".($txtSP/(1 + $item_vat))."', '".$txtDiscount."', '".$lstWarehouse."', '".$lstCurrency."', '".($item_vat*100)."', '".$txtSP."', '0', '0', '".$txtQty."', '".$_SESSION['useraccount']."', '".$lstClient."', CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), '".$lstProject."', '".$super_sub_result[0]."', '".$super_sub_result[1]."', '".$super_sub_result[2]."', '".$super_sub_result[4]."', '".(($txtSP/(1 + $item_vat))*$rate_dt)."', '".(($txtSP/(1 + $item_vat))/$parity_dt)."')";
				updateIData($iconn, $query, false);
				//echo "<br><br>".$query;

				$query = "UPDATE sorder SET sorder_totalQuantity = (sorder_totalQuantity + ".$txtQty."), sorder_taxable = (sorder_taxable + ".($txtQty * ($txtSP/(1 + $item_vat)) * $tax_flag)."), sorder_nonetaxable = (sorder_nonetaxable + ".($txtQty * $txtSP * $notax_flag)."), sorder_vat = (sorder_vat + ".($txtQty * ($txtSP - ($txtSP/(1 + $item_vat))))."), sorder_discountamount = (sorder_discountamount + ".($txtDiscount * $txtQty).") WHERE sorder_id = ".$txtID."";
				updateIData($iconn, $query, false);
				//echo "<br><br>".$query;

				$query = "UPDATE sorder SET sorder_taxableBase1 = sorder_taxable * ".$rate_dt.", sorder_taxableBase2 = sorder_taxable / ".$parity_dt.", sorder_noneTaxableBase1 = sorder_nonetaxable * ".$rate_dt.", sorder_noneTaxableBase2 = sorder_nonetaxable / ".$parity_dt.", sorder_discountbase1 = sorder_discountamount * ".$rate_dt.", sorder_discountbase2 = sorder_discountamount / ".$parity_dt.", sorder_vatbase1 = sorder_vat * ".$rate_dt.", sorder_vatbase2 = sorder_vat / ".$parity_dt." WHERE sorder_id = ".$txtID."";
				updateIData($iconn, $query, true);
				//echo "<br><br>".$query;

				$message = "Item ".$lstItem." Added";
			}else{
				$message = "Item ".$lstItem." COULD NOT be Added. Order Qty EXCEEDS Balance Qty";
			}
		}else{
			$message = "Item ".$lstItem." ALREADY Exists. Please Delete and Re-Add the Item if Qty needs to be changed";
		}
	}else{
		$count = 0;
		$promo_display = true;
		$packed_qty = true;
		//Check Balance Promo Qty
		if($lstItemType == 'Promotion'){
			$sub_query = "SELECT SUM(PackDt_Quantity) FROM packdt WHERE Item_Code = '".$lstItem."'";
			$sub_result = selectData($conn, $sub_query);
			$promo_qty = $sub_result[0];

			$sub_query = "SELECT Packdt_totalpromotion, PackDt_FromDate, PackDt_ToDate FROM packdt WHERE Item_Code = '".$lstItem."'";
			$sub_result = selectData($conn, $sub_query);
			$total_qty = $sub_result[0];

			if (displayParadoxDate(substr($sub_result[1], 0, 10)) <= insertToday() && displayParadoxDate(substr($sub_result[2], 0, 10)) >= insertToday()){
				$sub_query = "SELECT sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered) FROM stktransaction WHERE Item_CodePacked = '".$lstItem."' AND Transaction_Date >= '".$sub_result[0]."' AND Transaction_Date <= '".$sub_result[1]."'";
				$sub_result = selectData($conn, $sub_query);

				if ($total_qty < $sub_result[0]/$promo_qty){
					$promo_display = false;
				}
			}else{
				$promo_display = false;
			}
		}

		if ($promo_display){
			//Get Relevant Items for the Packed Items - For Promotion Item - Neglect the Item with Packdt_promotion = 1
			if ($lstItemType == "Promotion"){
				$query = "SELECT Item_CodePackDt, Packdt_CostPercentage, PackDt_Quantity FROM packdt WHERE Item_Code = '".$lstItem."'";
			}else{
				$query = "SELECT Item_CodePackDt, Packdt_CostPercentage, PackDt_Quantity FROM packdt WHERE Item_Code = '".$lstItem."'";
			}
			//echo "<br><br>".$query;
			$_result = mysql_query($query, $conn);
			while ($cur = mysql_fetch_row($_result)){
				$query = "SELECT sorderdt_id FROM sorderdt WHERE User_Account = '".$_SESSION['useraccount']."' AND Item_Code = '".$cur[0]."' AND sorder_id = '".$txtID."'";
				//echo "<br><br>".$query;
				$result = selectData($conn, $query);
				//if (is_numeric($result[0]) == false){
					$query = "SELECT sorderdt_id+1 FROM sequence";
					$result = selectData($conn, $query);
					$txt_ID = $result[0];
					$query = "UPDATE sequence SET sorderdt_id = ".$txt_ID;
					updateData($conn, $query, true);

					$query = "SELECT SUM(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered) FROM stktransaction WHERE item_code = '".$cur[0]."' AND warehouse_code = '".$lstWarehouse."'";
					//echo "<br><br>".$query;
					$_result_ = selectData($conn, $query);
					if ($_result_[0] >= ($txtQty*$cur[2])){
						$query = "SELECT transactionsetup.Trans_directstkDbt, transactionsetup.Trans_directstkcrd, transactionsetup.Trans_directstkcur, transactionsetup.Trans_discountacc, transactionsetup.Trans_RMAcc from transactionsetup, items WHERE transactionsetup.Group_Code = items.Group_Code AND items.Item_Code = '".$cur[0]."'";
						$super_sub_result = selectData($conn, $query);
						//echo "<br><br>".$query;
						
						$query = "INSERT INTO sorderdt (sorderdt_id, sorder_id, sorderdt.item_code, sorderdt_quantity, sorderdt_quantityUsed, sorderdt_price, sorderdt_discount, warehouse_code, Item_Codepacked, Currency_Code, Item_Vat, sorderdt_priceTTC, Item_QtyPacked, sorderdt_posted, sorderdt_oqty, User_Account, Client_code, sorder_date, Project_code, sorderdt_directstkDbt, sorderdt_directstkcrd, sorderdt_directstkcur, sorderdt_ItemAccount, sorderdt_pricebase1, SroderDt_PriceBase2) VALUES (".$txt_ID.", ".$txtID.", '".$cur[0]."', '".($txtQty*$cur[2])."', '0', '".(($txtSP*$cur[1]/100)/(1+$item_vat))."', '".($txtDiscount*$cur[1]/100)."', '".$lstWarehouse."', '".$lstItem."', '".$lstCurrency."', '".($item_vat*100)."', '".(($txtSP)*$cur[1]/100)."', '".($txtQty*$cur[2])."', '0', '".($txtQty*$cur[2])."', '".$_SESSION['useraccount']."', '".$lstClient."', CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), '".$lstProject."', '".$super_sub_result[0]."', '".$super_sub_result[1]."', '".$super_sub_result[2]."', '".$super_sub_result[4]."', ".(($txtSP*$cur[1]/100)/(1+$item_vat))*$rate_dt.", ".(($txtSP*$cur[1]/100)/(1+$item_vat))/$parity_dt.")";
						updateIData($iconn, $query, false);
						//echo "<br><br>".$query;

						$query = "UPDATE sorder SET sorder_totalQuantity = (sorder_totalQuantity + ".($txtQty*$cur[2])."), sorder_taxable = (sorder_taxable + ".(($txtQty*$cur[2]) * (($txtSP*$cur[1]/100)/(1+$item_vat)) * $tax_flag)."), sorder_nonetaxable = (sorder_nonetaxable + ".(($txtQty*$cur[2]) * ($txtSP*$cur[1]/100) * $notax_flag)."), sorder_vat = (sorder_vat + ".(($txtQty*$cur[2]) * ($txtSP - ($txtSP/(1 + $item_vat))))."), sorder_discountamount = (sorder_discountamount + ".($txtDiscount * ($txtQty*$cur[2])).") WHERE sorder_id = ".$txtID."";
						updateIData($iconn, $query, false);
						//echo "<br><br>".$query;

						$query = "UPDATE sorder SET sorder_taxableBase1 = sorder_taxable * ".$rate_dt.", sorder_taxableBase2 = sorder_taxable / ".$parity_dt.", sorder_noneTaxableBase1 = sorder_nonetaxable * ".$rate_dt.", sorder_noneTaxableBase2 = sorder_nonetaxable / ".$parity_dt.", sorder_discountbase1 = sorder_discountamount * ".$rate_dt.", sorder_discountbase2 = sorder_discountamount / ".$parity_dt.", sorder_vatbase1 = sorder_vat * ".$rate_dt.", sorder_vatbase2 = sorder_vat / ".$parity_dt." WHERE sorder_id = ".$txtID."";
						updateIData($iconn, $query, false);
						//echo "<br><br>".$query;

						$message = $message . "<br>Item ".$cur[0]." Added";
					}else{
						$packed_qty = false;
						$message = $message . "<br>Item ".$cur[0]." COULD NOT be Added. Order Qty EXCEEDS Balance Qty";
					}
				//}else{
					//$message = $message . "<br>Item ".$cur[0]." ALREADY Exists. Please Delete and Re-Add the Item if Qty needs to be changed";
				//}
			}
		}else{
			$message = $message . "<br>Item ".$lstItem." COULD NOT be Added. Promo Qty/ Period Exhausted";
		}

		if ($packed_qty){
			mysqli_commit($iconn);
			$message = $message . "<br>Item ".$lstItem." Added";
		}else{
			$message = $message . "<br>Item ".$lstItem." COULD NOT be Added. Qty NOT Available for atleast ONE Child Item";
		}

		/*
		//Add Promo Item with Zero Price
		if ($lstItemType == "Promotion"){
			$query = "SELECT Item_CodePackDt, Packdt_CostPercentage, PackDt_Quantity FROM packdt WHERE Item_Code = '".$lstItem."' AND Packdt_promotion = 1 ";
			//echo "<br><br>".$query;
			$_result = mysql_query($query, $conn);
			while ($cur = mysql_fetch_row($_result)){
				//DO NOT Check Duplicate Item Existance	

				$query = "SELECT SUM(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered) FROM stktransaction WHERE item_code = '".$cur[0]."' AND warehouse_code = '".$lstWarehouse."'";
				//echo "<br><br>".$query;
				$_result_ = selectData($conn, $query);
				if ($_result_[0] >= $cur[2]){
					$query = "SELECT transactionsetup.Trans_directstkDbt, transactionsetup.Trans_directstkcrd, transactionsetup.Trans_directstkcur, transactionsetup.Trans_discountacc, transactionsetup.Trans_RMAcc from transactionsetup, items WHERE transactionsetup.Group_Code = items.Group_Code AND items.Item_Code = '".$cur[0]."'";
					$super_sub_result = selectData($conn, $query);
					//echo "<br><br>".$query;
					
					$query = "INSERT INTO sorderdt (sorderdt_id, sorder_id, sorderdt.item_code, sorderdt_quantity, sorderdt_quantityUsed, sorderdt_price, sorderdt_discount, warehouse_code, Item_Codepacked, Currency_Code, Item_Vat, sorderdt_priceTTC, Item_QtyPacked, sorderdt_posted, sorderdt_oqty, User_Account, Client_code, sorder_date, Project_code, sorderdt_directstkDbt, sorderdt_directstkcrd, sorderdt_directstkcur, sorderdt_ItemAccount, sorderdt_pricebase1, SroderDt_PriceBase2) VALUES (".$txt_ID.", ".$txtID.", '".$cur[0]."', '".$cur[2]."', '0', '".(($txtSP*$cur[1]/100)/(1+$item_vat))."', '".($txtDiscount*$cur[1]/100)."', '".$lstWarehouse."', '".$lstItem."', '".$lstCurrency."', '".($item_vat*100)."', '".(($txtSP)*$cur[1]/100)."', '".$cur[2]."', '0', '".$cur[2]."', '".$_SESSION['useraccount']."', '".$lstClient."', CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), '".$lstProject."', '".$super_sub_result[0]."', '".$super_sub_result[1]."', '".$super_sub_result[2]."', '".$super_sub_result[4]."', ".(($txtSP*$cur[1]/100)/(1+$item_vat))*$rate_dt.", ".(($txtSP*$cur[1]/100)/(1+$item_vat))/$parity_dt.")";
					updateIData($iconn, $query, false);
					//echo "<br><br>".$query;

					$query = "UPDATE sorder SET sorder_totalQuantity = (sorder_totalQuantity + ".$cur[2]."), sorder_taxable = (sorder_taxable + ".($cur[2] * (($txtSP*$cur[1]/100)/(1+$item_vat)) * $tax_flag)."), sorder_nonetaxable = (sorder_nonetaxable + ".($cur[2] * ($txtSP*$cur[1]/100) * $notax_flag)."), sorder_vat = (sorder_vat + ".($cur[2] * ($txtSP - ($txtSP/(1 + $item_vat))))."), sorder_discountamount = (sorder_discountamount + ".($txtDiscount * $cur[2]).") WHERE sorder_id = ".$txtID."";
					updateIData($iconn, $query, false);
					//echo "<br><br>".$query;

					$query = "UPDATE sorder SET sorder_taxableBase1 = sorder_taxable * ".$rate_dt.", sorder_taxableBase2 = sorder_taxable / ".$parity_dt.", sorder_noneTaxableBase1 = sorder_nonetaxable * ".$rate_dt.", sorder_noneTaxableBase2 = sorder_nonetaxable / ".$parity_dt.", sorder_discountbase1 = sorder_discountamount * ".$rate_dt.", sorder_discountbase2 = sorder_discountamount / ".$parity_dt.", sorder_vatbase1 = sorder_vat * ".$rate_dt.", sorder_vatbase2 = sorder_vat / ".$parity_dt." WHERE sorder_id = ".$txtID."";
					updateIData($iconn, $query, true);
					//echo "<br><br>".$query;

					$message = $message . "<br>Item ".$cur[0]." Added";
				}else{
					$message = $message . "<br>Item ".$cur[0]." COULD NOT be Added. Order Qty EXCEEDS Balance Qty";
				}
			}
		}
		*/
	}
	//echo "<br><br>".$query;	
}else if($act == "deleteItem"){
	//Check if Packed Item
	$query = "SELECT Item_Codepacked, sorder_id, sorderdt_price, sorderdt_pricettc, sorderdt_quantity, item_code, sorderdt_discount FROM sorderdt WHERE sorderdt_id = ".$_POST['txtDeleteItemCode'];
	$result = selectData($conn, $query);
	//echo "<br><br>".$query;
	if ($result[0] == ""){
		//Not Packed - Delete Row
		$query = "DELETE FROM sorderdt WHERE sorderdt_id = '".$_POST['txtDeleteItemCode']."'";
		updateIData($iconn, $query, false);
		//echo "<br><br>".$query;
	}else{
		//Packed - Delete Row
		$query = "DELETE FROM sorderdt WHERE sorder_id = ".$txtID." AND Item_Codepacked = '".$result[0]."'";
		updateIData($iconn, $query, false);
		//echo "<br><br>".$query;
	}
	$txtID = $result[1];
	$txtSP = $result[3];
	$txtQty = $result[4];
	$lstItem = $result[5];
	$txtDiscount = $result[6];

	$query = "SELECT curdt_rate FROM curdt WHERE Currency_Code = 'NGN' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = 'NGN' )";
	$result = selectData($conn, $query);
	$rate_dt = $result[0];

	$query = "SELECT curdt_parity FROM curdt WHERE Currency_Code = 'NGN' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = 'NGN' )";
	$result = selectData($conn, $query);
	$parity_dt = $result[0];

	$query = "SELECT Item_Vat FROM Items WHERE item_Code = '".$lstItem."'";
	$result = selectData($conn, $query);
	$item_vat = $result[0];
	$item_vat = $item_vat/100;
	$tax_flag = 0;
	$notax_flag = 1;
	if ($item_vat > 0){
		$tax_flag = 1;
		$notax_flag = 0;
	}
	
	$query = "UPDATE sorder SET sorder_taxable = (sorder_taxable - ".($txtQty * ($txtSP/(1 + $item_vat)) * $tax_flag)."), sorder_nonetaxable = (sorder_nonetaxable - ".($txtQty * $txtSP * $notax_flag)."), sorder_vat = (sorder_vat - ".($txtQty * ($txtSP - ($txtSP/(1 + $item_vat))))."), sorder_discountamount = (sorder_discountamount - ".($txtDiscount * $txtQty).") WHERE sorder_id = ".$txtID."";
	updateIData($iconn, $query, false);
	//echo "<br><br>".$query;

	$query = "UPDATE sorder SET sorder_totalQuantity = (SELECT SUM(sorderdt_Quantity) FROM sorderdt WHERE sorder_id = '".$txtID."'), sorder_taxableBase1 = sorder_taxable * ".$rate_dt.", sorder_taxableBase2 = sorder_taxable / ".$parity_dt.", sorder_noneTaxableBase1 = sorder_nonetaxable * ".$rate_dt.", sorder_noneTaxableBase2 = sorder_nonetaxable / ".$parity_dt.", sorder_discountbase1 = sorder_discountamount * ".$rate_dt.", sorder_discountbase2 = sorder_discountamount / ".$parity_dt.", sorder_vatbase1 = sorder_vat * ".$rate_dt.", sorder_vatbase2 = sorder_vat / ".$parity_dt." WHERE sorder_id = ".$txtID."";
	updateIData($iconn, $query, true);
	//echo "<br><br>".$query;

	$message = "Item Deleted";
}else if($act == "submitRecord"){
	//Get Ref
	$query = "SELECT sorder_reference+1 FROM sequence";
	$result = selectData($conn, $query);
	$txtRef = $result[0];
	$query = "UPDATE sequence SET sorder_reference = '".$txtRef."'";
	updateData($conn, $query, true);	
	//echo "<br><br>".$query;

	$query = "UPDATE sorderdt SET sorder_id = '".$txtID."', User_Account = '' WHERE User_Account = '".$_SESSION['useraccount']."'";
	updateIData($iconn, $query, false);	
	//echo "<br><br>".$query;

	$query = "SELECT curdt_rate FROM curdt WHERE Currency_Code = 'NGN' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = 'NGN' )";
	$result = selectData($conn, $query);
	$rate_dt = $result[0];

	$query = "SELECT curdt_parity FROM curdt WHERE Currency_Code = 'NGN' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = 'NGN' )";
	$result = selectData($conn, $query);
	$parity_dt = $result[0];

	$query = "SELECT Item_Vat FROM Items WHERE item_Code = '".$lstItem."'";
	$result = selectData($conn, $query);
	$item_vat = $result[0];
	$item_vat = $item_vat/100;
	$tax_flag = 0;
	$notax_flag = 1;
	if ($item_vat > 0){
		$tax_flag = 1;
		$notax_flag = 0;
	}

	$query = "UPDATE sorder SET sorder_totalQuantity = (SELECT SUM(sorderdt_Quantity) FROM sorderdt WHERE sorder_id = '".$txtID."'), sorder_date = CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), sorder_requestdate = CONCAT('".displayParadoxDate(insertDate($txtRequestDate))." ', RIGHT(NOW(), 8)), sorder_remark = '".$txtRemark."', sorder_Clientcontact = '".$txtIAddress."', Currency_Code = '".$lstCurrency."', sorder_DeliveryPlace = '".$txtDAddress."', Project_Code = '".$lstProject."', sorder_reference = '".$txtRef."', sorder_confirmed = 0 WHERE sorder_id = ".$txtID."";
	updateIData($iconn, $query, false);
	//echo "<br><br>".$query;

	$query = "UPDATE sorder SET sorder_taxableBase1 = sorder_taxable * ".$rate_dt.", sorder_taxableBase2 = sorder_taxable / ".$parity_dt.", sorder_noneTaxableBase1 = sorder_nonetaxable * ".$rate_dt.", sorder_noneTaxableBase2 = sorder_nonetaxable / ".$parity_dt.", sorder_discountbase1 = sorder_discountamount * ".$rate_dt.", sorder_discountbase2 = sorder_discountamount / ".$parity_dt.", sorder_vatbase1 = sorder_vat * ".$rate_dt.", sorder_vatbase2 = sorder_vat / ".$parity_dt." WHERE sorder_id = ".$txtID."";
	updateIData($iconn, $query, true);
	//echo "<br><br>".$query;

	$act = "viewRecord";
	$message = "Record Added";
}else if($act == "saveChanges"){
	$query = "UPDATE sorderdt SET sorder_id = '".$txtID."', User_Account = '' WHERE User_Account = '".$_SESSION['useraccount']."'";
	updateIData($iconn, $query, false);	
	//echo "<br><br>".$query;

	$query = "UPDATE sorder SET sorder_date = CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), sorder_requestdate = CONCAT('".displayParadoxDate(insertDate($txtRequestDate))." ', RIGHT(NOW(), 8)), sorder_remark = '".$txtRemark."', sorder_Clientcontact = '".$txtIAddress."', Currency_Code = '".$lstCurrency."', sorder_DeliveryPlace = '".$txtDAddress."', Project_Code = '".$lstProject."', sorder_reference = '".$txtRef."', sorder_confirmed = 0 WHERE sorder_id = ".$txtID."";
	updateIData($iconn, $query, false);
	//echo "<br><br>".$query;

	$query = "SELECT curdt_rate FROM curdt WHERE Currency_Code = 'NGN' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = 'NGN' )";
	$result = selectData($conn, $query);
	$rate_dt = $result[0];

	$query = "SELECT curdt_parity FROM curdt WHERE Currency_Code = 'NGN' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = 'NGN' )";
	$result = selectData($conn, $query);
	$parity_dt = $result[0];

	$query = "SELECT Item_Vat FROM Items WHERE item_Code = '".$lstItem."'";
	$result = selectData($conn, $query);
	$item_vat = $result[0];
	$item_vat = $item_vat/100;
	$tax_flag = 0;
	$notax_flag = 1;
	if ($item_vat > 0){
		$tax_flag = 1;
		$notax_flag = 0;
	}
	
	$query = "UPDATE sorder SET sorder_taxableBase1 = sorder_taxable * ".$rate_dt.", sorder_taxableBase2 = sorder_taxable / ".$parity_dt.", sorder_noneTaxableBase1 = sorder_nonetaxable * ".$rate_dt.", sorder_noneTaxableBase2 = sorder_nonetaxable / ".$parity_dt.", sorder_discountbase1 = sorder_discountamount * ".$rate_dt.", sorder_discountbase2 = sorder_discountamount / ".$parity_dt.", sorder_vatbase1 = sorder_vat * ".$rate_dt.", sorder_vatbase2 = sorder_vat / ".$parity_dt." WHERE sorder_id = ".$txtID."";
	updateIData($iconn, $query, true);
	//echo "<br><br>".$query;

	$act = "viewRecord";
	$message = "Record Updated";
}else if($act == "deleteRecord"){
	$query = "DELETE FROM sorderdt WHERE sorder_id = ".$txtID."";
	updateIData($iconn, $query, false);

	$query = "DELETE FROM sorder WHERE sorder_id = ".$txtID."";
	updateIData($iconn, $query, true);

	header("Location: ReceiptMaster.php?message=Record Deleted");
}else if($act == "confirmRecord"){
	$query = "UPDATE sorder SET sorder_confirmed = 1 WHERE sorder_id = ".$txtID."";
	updateIData($iconn, $query, true);
	
	$act = "viewRecord";
	$message = "Preparation Order Confirmed";
	//header("Location: ReceiptMaster.php?message=Preparation Order Confirmed");
}else if ($act == "clearPage"){
	$query = "DELETE FROM sorderdt WHERE User_Account = '".$_SESSION['useraccount']."'";
	updateData($conn, $query, true);

	$query = "DELETE FROM sorderdt WHERE User_Account = '".$_SESSION['useraccount']."' AND (sorder_reference IS NULL OR sorder_reference = '')";
	updateIData($iconn, $query, true);
}

if($act == "viewRecord"){
	$query = "SELECT sorder_id, sorder_date, sorder_requestdate, sorder_remark, Client_Code, sorder_Clientcontact, Currency_Code, Costcent_code, sorder_DeliveryPlace, Project_Code, sorder_totalQuantity, sorder_totalQuantityUsed, sorder_posted, sorder_taxable, sorder_vat, sorder_discountamount, sorder_type, sorder_confirmed, journal_type, User_Account, Salesman_code FROM sorder WHERE sorder_reference = ".$txtRef;
	//echo "<br><br>".$query;
	$result = selectData($conn, $query);
	$txtDate = displayDate(insertParadoxDate($result[1]));
	$txtRequestDate = displayDate(insertParadoxDate($result[2]));
	$txtRemark = $result[3];
	$txtIAddress = $result[5];
	$txtDAddress = $result[8];
	if ($txtDAddress == ""){$txtDAddress = $txtIAddress;}
	$lstClient = $result[4];
	$lstCurrency = $result[6];
	$lstCostCentre = $result[7];
	$lstProject = $result[9];
	$lstSalesman = $result[20];
	$txtConfirmed = $result[17];
	if ($txtConfirmed == "0"){
		$txtConfirmed = "No";
	}else{
		$txtConfirmed = "Yes";
	}
}

?>

<head>
<title>Preparation Order</title>
<link rel="stylesheet" href="default.css" type="text/css" />
<script type="text/javascript" language="javascript">

function deleteItem(a){
	x = document.frm1;
	if (confirm('Delete this Item')){
		x.act.value = 'deleteItem';
		x.txtDeleteItemCode.value = a;
		x.submit();
	}
}

function searchPage(){
	x = document.frm1;
	x.act.value = 'searchPage';	
	x.submit();
}

function openWindow(){ 
	x = document.frm1;
	if (x.lstClient.value == '' || x.lstProject.value == '' || x.lstSalesman.value == ''){
		alert('Please Select a Client, Project and Salesman');
		x.lstClient.focus();
	}else{
		win = window.open('Sales_Order_Child.php?txtID='+x.txtID.value+'&txtRef='+x.txtRef.value+'&txtDate='+x.txtDate.value+'&txtRequestDate='+x.txtRequestDate.value+'&txtRemark='+x.txtRemark.value+'&txtIAddress='+x.txtIAddress.value+'&txtDAddress='+x.txtDAddress.value+'&lstClient='+x.lstClient.value+'&lstCurrency='+x.lstCurrency.value+'&lstCostCentre='+x.lstCostCentre.value+'&lstProject='+x.lstProject.value+'&lstSalesman='+x.lstSalesman.value+'&user_level='+x.user_level.value+'&lstWarehouse='+x.lstWarehouse.value, 'Sales_Order_Child', 'toolbar=no,menubar=no,scrollbars=yes,resize=yes,maximize=no,location=no,height=250,width=800'); 
		win.creator = self;
		win.focus();
	}
}

function submitRecord(){
	x = document.frm1;
	if (x.lstClient.value == '' || x.lstCurrency.value == '' || x.lstProject.value == '' || x.lstSalesman.value == '' || check_valid_date(x.txtDate.value) == false || check_valid_date(x.txtRequestDate.value) == false){
		alert("Please ensure to select the Client, Currency, Project and Salesman. Please ensure Date Fields are in the Format DD/MM/YYYY");
		x.lstSalesman.focus();
	}else{
		x.act.value = 'submitRecord';
		//win = window.open('Sales_Order_Child.php', 'Sales_Order_Child', 'toolbar=no,menubar=no,scrollbars=yes,resize=yes,maximize=no,location=no,height=250,width=800'); 
		//win.close();
		x.submit();
	}
}

function saveChanges(){
	x = document.frm1;
	if (x.lstClient.value == '' || x.lstCurrency.value == '' || x.lstProject.value == '' || x.lstSalesman.value == '' || check_valid_date(x.txtDate.value) == false || check_valid_date(x.txtRequestDate.value) == false){
		alert("Please ensure to select the Client, Currency, Project and Salesman. Please ensure Date Fields are in the Format DD/MM/YYYY");
		x.lstSalesman.focus();
	}else{
		x.act.value = 'saveChanges';
		//win = window.open('Sales_Order_Child.php', 'Sales_Order_Child', 'toolbar=no,menubar=no,scrollbars=yes,resize=yes,maximize=no,location=no,height=250,width=800'); 
		//win.close();
		x.submit();
	}
}

function deleteRecord(){
	x = document.frm1;
	if (confirm('Delete this Record')){
		x.act.value = 'deleteRecord';
		x.submit();
	}
}

function confirmRecord(){
	x = document.frm1;
	if (confirm('Confirm Preparation Order')){
		x.act.value = 'confirmRecord';
		x.submit();
	}
}

function printPage(a, b){
	win = window.open('ReceiptMaster.php?prints=yes&act=viewRecord&txtID='+a+'&txtRef='+b, '', 'toolbar=no,menubar=no,scrollbars=yes,resize=yes,maximize=no,location=no,height=600,width=600');
}

function clearPage(){
	//win = window.open('Sales_Order_Child.php', 'Sales_Order_Child', 'toolbar=no,menubar=no,scrollbars=yes,resize=yes,maximize=no,location=no,height=600,width=600');
	//win.close();
	window.location.href = "ReceiptMaster.php?act=clearPage";
}
</script>

<style type="text/css">
<!--
.style1 {
	color: #000000;
	font-weight: bold;
	font-family: "Times New Roman", Times, serif;
}
body,td,th {
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 14px;
}
.style4 {color: #999999; font-size: 12px; }
.style5 {
	color: #333333;
	font-weight: bold;
	font-size: 13px;
}
.style12 {color: #666666; font-weight: bold; font-size: 12; }
.style13 {font-size: 12px}
body {
	margin-top: 0px;
}
.style14 {
	color: #FF0000;
	font-weight: bold;
}

#footer {position: absolute; bottom: 0; left: 0; width: 600px; height: 50px;} 
-->
</style>
</head>
<?php
	if ($prints == "yes"){
		print "<body onLoad='window.print();window.close();'>";
	}else{
		print "<body>";
	}
?>
<form id="frm1" name="frm1" method="post" action="ReceiptMaster.php">
	<input type='hidden' name='act'><input type='hidden' name='txtDeleteItemCode'>
 <table width="100%" border="0" align="center">
  <tr>
      <td bgcolor="#FFFFFF" width='100%' colspan='4'>
		<?php
			include_once("MenuBar.php");
		?>
	 </td>
    </tr>
    <tr>
      <td height="40" bgcolor="#FFFFFF" colspan='4'><span class="style1">PREPARATION ORDER</span></td>
    </tr>
	<tr>
		<?php
			print "<td bgcolor='#FFFFFF' colspan='4' align='center'><font size='1' color='#FF0000' face='Verdana'><b>".$message."</b></font></td>";
		?>
    </tr>
    <tr bgcolor="#F7F7F7">
		<?php
			print "<script>function check_valid_date(z){".				
				"if(z.length != 10 || z.substring(6,10)*1 < 1900 || z.substring(6,10)*1 > 2200){".
					"return false;".
				"}else{".
					"if (z.substring(0,2)*1 < 28 && z.substring(3,5)*1 < 13 && z.substring(2,3) == '/'  && z.substring(5,6) == '/'){".
						"return true;".
					"}else{".
						"if ((z.substring(3,5)*1 == 4 || z.substring(3,5)*1 == 6 || z.substring(3,5)*1 == 9 || z.substring(3,5)*1 == 11) && z.substring(0,2)*1 < 31){".
							"return true;".
						"}else if (z.substring(3,5)*1 == 2 && z.substring(6,10)*1 % 4 == 0 && z.substring(0,2)*1 < 30){".
							"return true;".
						"}else if (z.substring(3,5)*1 == 2 && z.substring(6,10)*1 % 4 != 0 && z.substring(0,2)*1 < 29){".
							"return true;".
						"}else if ((z.substring(3,5)*1 == 1 || z.substring(3,5)*1 == 3 || z.substring(3,5)*1 == 5 || z.substring(3,5)*1 == 7 || z.substring(3,5)*1 == 8 || z.substring(3,5)*1 == 10 || z.substring(3,5)*1 == 12) && z.substring(0,2)*1 < 32){".
							"return true;".
						"}else{".
							"return false;".
						"}".
					"}".
				"}".
			"}</script>";
			
			print "<input type='hidden' name='user_level' value='".$user_level."'>";
			print "<input type='hidden' name='lstWarehouse' value='".$lstWarehouse."'>";

			displayTextbox("txtRef", "Reference", $txtRef, "yes", "", "15%", "35%");
			print "<input type='hidden' name='txtID' value='".$txtID."'>";			
			displayTextbox("txtDate", "Date", $txtDate, "yes", "10", "15%", "35%");
		?>		
    </tr>
    <tr bgcolor="#F7F7F7">
		<?php
			$query = "SELECT Ledger_number, Ledger_name FROM Clients ORDER BY Ledger_name";
			if ($lstClient != "" && $txtID != ""){
				displayList("lstClient", "Client", $lstClient, "yes", $conn, $query, "onChange = document.frm1.submit()", "15%", "35%");
			}else{
				displayList("lstClient", "Client", $lstClient, $prints, $conn, $query, "onChange = document.frm1.submit()", "15%", "35%");
			}
			displayTextbox("txtRequestDate", "Request Date", $txtRequestDate, $prints, "10", "15%", "35%");
		?>		
	</tr>

    <tr bgcolor="#F7F7F7">
		<?php
			$query = "SELECT currency_code, currency_name FROM currency ORDER BY currency_code";
			if ($lstCurrency != ""){
				displayList("lstCurrency", "Currency", $lstCurrency, "yes", $conn, $query, "", "15%", "35%");
			}else{
				displayList("lstCurrency", "Currency", $lstCurrency, $prints, $conn, $query, "", "15%", "35%");
			}
			if ($lstClient != "" && ($txtCreditLimit == "" || $lstSalesman == "" || $txtIAddress == "")){
				$query = "SELECT Client_CreditLimit, Salesmen_Code, Client_Work, Client_Address FROM Clients WHERE Ledger_Number = '".$lstClient."'";
				$result = selectData($conn, $query);
				$txtCreditLimit = $result[0];
				if ($act != "viewRecord"){
					$lstSalesman = $result[1];
				}
				$txtIAddress = $result[3];
				//if ($txtCreditLimit == ""){$txtCreditLimit = $result[0];}
				if ($lstSalesman == ""){$lstSalesman = $_POST["lstSalesman"];}
				if ($lstSalesman == ""){$lstSalesman = $_GET["lstSalesman"];}
				if ($txtIAddress == ""){$txtIAddress = $_POST["txtIAddress"];}
				if ($txtDAddress == ""){$txtDAddress = $_POST["txtDAddress"];}
				if ($txtDAddress == ""){$txtDAddress = $txtIAddress;}
			}
			displayTextbox("txtCreditLimitDisplay", "Credit Limit", addComma($txtCreditLimit), "yes", "", "15%", "35%");
			print "<input type='hidden' name='txtCreditLimit' value='".$txtCreditLimit."'>";
		?>
	</tr>
    <tr bgcolor="#F7F7F7">
		<?php
			//$query = "SELECT costcent_code, costcent_name FROM costcent ORDER BY costcent_name";
			//displayList("lstCostCentre", "Cost Centre", $lstCostCentre, $prints, $conn, $query, "", "15%", "35%");
			print "<input type='hidden' name='lstCostCentre'>";
			if ($lstProject == "" && $defaultProject != ""){
				$lstProject = $defaultProject;
			}
			$query = "SELECT UPPER(project_code), project_name FROM project WHERE project_code is NOT NULL ".$projectQuery." ORDER BY project_name";
			if ($txtConfirmed == "Yes" || $act == "viewRecord"){				
				displayList("lstProject", "Project", $lstProject, "yes", $conn, $query, "", "15%", "35%");
			}else{
				displayList("lstProject", "Project", $lstProject, $prints, $conn, $query, "", "15%", "35%");
			}
			displayTextbox("txtRemark", "Remark", $txtRemark, $prints, "", "15%", "35%");
		?>
	</tr>    
	<tr bgcolor="#F7F7F7">
		<?php
			$query = "SELECT Ledger_number, Ledger_name FROM Salesmen ORDER BY Ledger_name";
			if ($lstSalesman != ""){
				displayList("lstSalesman", "Salesman", $lstSalesman, "yes", $conn, $query, "", "15%", "35%");
			}else{
				displayList("lstSalesman", "Salesman", $lstSalesman, $prints, $conn, $query, "", "15%", "35%");
			}
			if ($prints == "yes"){
				displayTextbox("txtConfirmed", "Order Confirmed", $txtConfirmed, "yes", "", "15%", "35%");
			}else{
				print "<td colspan='2'>&nbsp;</td>";
			}			
		?>
    </tr>
    <tr bgcolor="#F7F7F7">
		<?php
			displayTextarea("txtIAddress", "Invoice Address", $txtIAddress, "yes", 5, 40, "15%", "35%");
			displayTextarea("txtDAddress", "Delivery Address", $txtDAddress, $prints, 5, 40, "15%", "35%");
		?>
    </tr>
    <tr>
      <td colspan="4" valign="top" bgcolor="#FFFFFF" class="style4"><label></label>        <label></label>
      <label></label>        <label></label></td>
    </tr>
    <tr>
		<td bgcolor="#E0E0E0">&nbsp;</td>
		<td bgcolor="#E0E0E0" colspan='3'>
			<?php
				if ($prints != "yes" && (strpos($user_level, "-RE-") !== false || strpos($user_level, "-RA-") !== false)){
					print "<input name='additems' type='button' id='additems' onclick='javascript:openWindow()' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;' title='Add more items' value='Add Items'/>&nbsp;";				
					//print "<input name='clearPage' type='button' id='clearPage' onclick=javascript:window.location.href='ReceiptMaster.php' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;' title='Clear Page' value='Clear Page'/>&nbsp;";
				}
			?>
		</td>
	</tr>
</table>
<?php
$tot_qty = 0;
//$tot_discount = 0;
$tot_ttc = 0;
print "<table width='100%' border='1' cellspacing='-1' cellpadding='-1'>";
print "<tr><td class='style3' colspan='9'><b>Preparation Order Item List:</b></td> </tr>";
//print "<tr><td bgcolor='#E0E0E0' class='style3' colspan='9'><b>Preparation Order Item List:</b></td> </tr>";
//print "<tr><td bgcolor='#E0E0E0' class='style3'>&nbsp;</td> <td bgcolor='#E0E0E0' class='style3'>Item Code</td> <td bgcolor='#E0E0E0' class='style3'>Item Desc</td> <td bgcolor='#E0E0E0' class='style3'>Warehouse</td> <td bgcolor='#E0E0E0' class='style3'>Qty</td> <td bgcolor='#E0E0E0' class='style3'>Price</td> <td bgcolor='#E0E0E0' class='style3'>Discount</td> <td bgcolor='#E0E0E0' class='style3'>TTC</td> <td bgcolor='#E0E0E0' class='style3'>TTC Total</td> </tr>";
print "<tr><td bgcolor='#E0E0E0' class='style3'>&nbsp;</td> <td bgcolor='#E0E0E0' class='style3'>Item Code</td> <td bgcolor='#E0E0E0' class='style3'>Item Desc</td> <td bgcolor='#E0E0E0' class='style3'>Warehouse</td> <td bgcolor='#E0E0E0' class='style3'>Qty</td> <td bgcolor='#E0E0E0' class='style3'>Price</td> <td bgcolor='#E0E0E0' class='style3'>Discount</td> <td bgcolor='#E0E0E0' class='style3'>Total</td> </tr>";
if ($txtRef == ""){	
	$query = "SELECT sorderdt.sorderdt_id, sorderdt.sorder_id, sorderdt.item_code, sorderdt.sorderdt_quantity, sorderdt.sorderdt_quantityUsed, sorderdt.sorderdt_price, sorderdt.sorderdt_discount, sorderdt.warehouse_code, sorderdt.Currency_Code, sorderdt.Item_Vat, sorderdt.sorderdt_priceTTC, sorderdt.Item_QtyPacked, sorderdt.sorderdt_posted, sorderdt.sorderdt_oqty, items.item_description, warehouse.warehouse_name FROM sorderdt, items, warehouse WHERE sorderdt.item_code = items.item_code AND sorderdt.warehouse_code = warehouse.warehouse_code AND sorderdt.User_Account = '".$_SESSION['useraccount']."'";
}else{	
	$query = "SELECT sorderdt.sorderdt_id, sorderdt.sorder_id, sorderdt.item_code, sorderdt.sorderdt_quantity, sorderdt.sorderdt_quantityUsed, sorderdt.sorderdt_price, sorderdt.sorderdt_discount, sorderdt.warehouse_code, sorderdt.Currency_Code, sorderdt.Item_Vat, sorderdt.sorderdt_priceTTC, sorderdt.Item_QtyPacked, sorderdt.sorderdt_posted, sorderdt.sorderdt_oqty, items.item_description, warehouse.warehouse_name FROM sorderdt, items, warehouse, sorder WHERE sorderdt.sorder_id = sorder.sorder_id AND sorderdt.item_code = items.item_code AND sorderdt.warehouse_code = warehouse.warehouse_code AND (sorder.sorder_reference = '".$txtRef."' OR sorderdt.User_Account = '".$_SESSION['useraccount']."')";
}
//echo "<br><br>".$query;
$result = mysql_query($query, $conn);
while ($cur = mysql_fetch_row($result)){	
	print "<tr><td class='style4'>";
	if ($prints != "yes" && (strpos($user_level, "-RE-") !== false || (strpos($user_level, "-RA-") !== false && $txtRef == ""))){
		print "<a href='#' onClick='javascript:deleteItem(".$cur[0].")'>Delete</a>";
	}else{
		print "&nbsp;";
	}
	//print "</td> <td class='style4'>".$cur[2]."</td> <td class='style4'>".$cur[14]."</td> <td class='style4'>".$cur[15]."</td> <td class='style4'>".addComma($cur[3])."</td> <td class='style4'>".addComma($cur[5])."</td> <td class='style4'>".addComma($cur[6])."</td> <td class='style4'>".addComma($cur[10])."</td> <td class='style4'>".addComma($cur[10]*$cur[3])."</td></tr>";
	print "</td> <td class='style4'>".$cur[2]."</td> <td class='style4'>".$cur[14]."</td> <td class='style4'>".$cur[15]."</td> <td class='style4'>".addComma($cur[3])."</td> <td class='style4'>".addComma($cur[10])."</td> <td class='style4'>".addComma($cur[6])."</td> <td class='style4'>".addComma(($cur[10]-$cur[6])*$cur[3])."</td></tr>";
	$tot_qty = $tot_qty + $cur[3];
	//$tot_discount = $tot_discount + $cur[6];
	$tot_ttc = $tot_ttc + ($cur[10]*$cur[3]);
}
print "<tr><td bgcolor='#E0E0E0' class='style3'>&nbsp;</td> <td bgcolor='#E0E0E0' class='style3'>&nbsp;</td> <td bgcolor='#E0E0E0' class='style3'>&nbsp;</td> <td bgcolor='#E0E0E0' class='style3'>Totals</td> <td bgcolor='#E0E0E0' class='style3'>".addComma($tot_qty)."</td> <td bgcolor='#E0E0E0' class='style3'>&nbsp;</td> <td bgcolor='#E0E0E0' class='style3'>&nbsp;</td> <td bgcolor='#E0E0E0' class='style3'>".addComma($tot_ttc)."</td> </tr>";
print "</table>";

print "<table width='100%'>";
print "<tr>".
	"<td width='15%' bgcolor='#E0E0E0'>&nbsp;</td>".
	"<td width='85%' bgcolor='#E0E0E0' colspan='3'>";
		if ($txtRef == "" && $tot_qty > 0){
			if ($prints != "yes" && strpos($user_level, "-RA-") !== false){
				//New Record
				print "<input type='button' onclick='javascript:submitRecord()' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;' title='Post Record' value='Post Record'/>&nbsp;";
			}
		}else if ($txtRef != ""){
			if ($prints != "yes" && strpos($user_level, "-RE-") !== false && $txtConfirmed == "No"){
				print "<input type='button' onclick='javascript:saveChanges()' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;' title='Save Changes' value='Save Changes'/>&nbsp;";
			}
			if ($prints != "yes"){
				print "<input type='button' onclick='javascript:printPage(".$txtID.", ".$txtRef.")' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;' title='Print Preparation Order' value='Print'/>&nbsp;";
			}
			if ($prints != "yes" && strpos($user_level, "-SOC-") !== false && $txtConfirmed == "No"){
				//Check if Pending Record for this Preparation Order Exist
				$query = "SELECT sorderdt_id FROM sorderdt WHERE User_Account = '".$_SESSION['useraccount']."'";
				//echo "<br><br>".$query;
				$result = selectData($conn, $query);
				if (strlen($result[0]) == 0){	
					$confirm_flag = false;
					//Check if it is a Cash Client
					$query = "SELECT Client_CreditLimit, Client_PaymentTerms, Client_CashMode FROM Clients WHERE Ledger_Number = '".$lstClient."'";
					//echo "<br><br>".$query;
					$result = selectData($conn, $query);
					$c_cl = $result[0];
					$c_pt = $result[1];
					if ($result[2] == "1"){
						$confirm_flag = true;
					}else{
						//echo "<br><br>666".$confirm_flag;
						if (strpos($user_level, "-SOCPT-") !== false && strpos($user_level, "-SOCCL-") !== false){
							$confirm_flag = true;
						}else{
							if (strpos($user_level, "-SOCCL-") !== true){
								//echo "<br><br>670".$confirm_flag;
								//Check Client Credit Limit
								//Get Current Credit Value
								$query = "SELECT SUM(journaldt_amount1) FROM journaldt where journaldt_dbcd='C' and ledger_number = '".$lstClient."'";
								//echo "<br><br>".$query;
								$result = selectData($conn, $query);
								$q1 = $result[0];
								if (is_numeric($q1)){
									//Do Nothing
								}else{
									$q1 = 0;
								}
								$query = "SELECT SUM(journaldt_amount1) FROM journaldt WHERE journaldt_dbcd='D' and ledger_number = '".$lstClient."'";
								//echo "<br><br>".$query;
								$result = selectData($conn, $query);
								$q2 = $result[0];
								if (is_numeric($q2)){
									//Do Nothing
								}else{
									$q2 = 0;
								}
								$query = "SELECT sorder_taxableBase1 FROM sorder WHERE sorder_id = '".$txtID."'";
								//echo "<br><br>".$query;
								$result = selectData($conn, $query);
								$q3 = $result[0];
								if (is_numeric($q3)){
									//Do Nothing
								}else{
									$q3 = 0;
								}

								if ($c_cl >= ($q2 - $q1 + $q3)){
									$confirm_flag = true;
								}
							}
							
							if (strpos($user_level, "-SOCPT-") !== true){
								//echo "<br><br>711".$confirm_flag;
								//Check Client payment Term
								$query = "select InvoiceDays('".$lstClient."', '".displayParadoxDate(insertToday())."', 0)";
								//echo "<br><br>".$query;
								$result = selectData($conn, $query);
								//echo "<br><br>".$result[0];
								if ($c_pt > $result[0]){
									$confirm_flag = true;
								}
							}
							//726".$confirm_flag;
						}
					}

					if ($confirm_flag){
						print "<input type='button' onclick='javascript:confirmRecord()' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;' title='Confirm Record' value='Confirm Order'/>&nbsp;";
					}
				}
			}
			if ($prints != "yes" && strpos($user_level, "-RD-") !== false && $txtConfirmed == "No"){
				print "<input type='button' onclick='javascript:deleteRecord()' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;' title='Delete Record' value='Delete Record'/>&nbsp;";
			}
		}		
	print "</td>";
print "</tr>";
print "<tr>".
	"<td width='15%' bgcolor='#FFFFFF'>&nbsp;</td>".
	"<td width='85%' bgcolor='#FFFFFF' colspan='3'>";
		if ($prints != "yes"){
			print "<input name='searchPending' type='button' id='searchPending' onclick=javascript:window.location.href='ReceiptMaster.php?act=searchPending' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; width=220px' title='Search Pending Preparation Order' value='Search Pending Preparation Order'/>&nbsp;";			
			print "<input type='button' onclick='javascript:clearPage()' style='background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;' title='Clear Page' value='Clear Page'/>&nbsp;";
			print "&nbsp;&nbsp;&nbsp;&nbsp;<font face='Verdana' size='2'>Ref No:</font><input name='txtSearchRef' size='5' value='".$txtSearchRef."'><input type='button' onclick='javascript:searchPage()' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;' title='Search' value='Search'/>&nbsp;";
		}
	print "</td>";
print "</tr>";
print "</table>";

if ($act == "searchPending"  || $act == "searchPage"){
	$query = "DELETE FROM sorderdt WHERE User_Account = '".$_SESSION['useraccount']."'";
	updateData($conn, $query, true);

	$query = "DELETE FROM sorderdt WHERE User_Account = '".$_SESSION['useraccount']."' AND (sorder_reference IS NULL OR sorder_reference = '')";
	updateIData($iconn, $query, true);

	print "<table width='100%'>";
	if ($act == "searchPending"){
		print "<tr><td class='style3' colspan='6'><b>Pending Preparation Order List:</b></td> </tr>";
	}
	//print "<tr><td bgcolor='#E0E0E0' class='style3' colspan='7'><b>Pending Preparation Order List:</b></td> </tr>";
	print "<tr><td bgcolor='#E0E0E0' class='style3'>Ref No</td> <td bgcolor='#E0E0E0' class='style3'>Date</td> <td bgcolor='#E0E0E0' class='style3'>Client</td> <td bgcolor='#E0E0E0' class='style3'>Project</td> <td bgcolor='#E0E0E0' class='style3'>Salesman</td> <td bgcolor='#E0E0E0' class='style3'>Remark</td> <td bgcolor='#E0E0E0' class='style3'>Total TTC</td> </tr>";
	if ($act == "searchPending"){
		$query = "SELECT sorder.sorder_id, sorder.sorder_reference, sorder.sorder_date, Clients.Ledger_name, project.project_name, Salesmen.Ledger_name, sorder.sorder_remark, (sorder.sorder_taxable + sorder.sorder_vat) FROM sorder, Clients, Project, Salesmen WHERE sorder.Client_code = Clients.Ledger_number AND sorder.Project_code = project.Project_code AND sorder.Salesman_code = salesmen.Ledger_number AND sorder.sorder_confirmed = 0 AND LENGTH(sorder.sorder_reference) > 0 ".$projectQuery." ORDER BY sorder.sorder_date DESC, sorder.sorder_reference DESC";
	}else{
		$query = "SELECT sorder.sorder_id, sorder.sorder_reference, sorder.sorder_date, Clients.Ledger_name, project.project_name, Salesmen.Ledger_name, sorder.sorder_remark, (sorder.sorder_taxable + sorder.sorder_vat) FROM sorder, Clients, Project, Salesmen WHERE sorder.Client_code = Clients.Ledger_number AND sorder.Project_code = project.Project_code AND sorder.Salesman_code = salesmen.Ledger_number AND LENGTH(sorder.sorder_reference) > 0 ".$projectQuery." ";
		if ($txtSearchRef != ""){
			$query = $query . " AND sorder.sorder_reference = '".$txtSearchRef."' ";
		}
		if ($lstClient != ""){
			$query = $query . " AND Clients.Ledger_number = '".$lstClient."' ";
		}
		if ($lstProject != ""){
			$query = $query . " AND Project.Project_code = '".$lstProject."' ";
		}
		if ($lstSalesman != ""){
			$query = $query . " AND salesmen.Ledger_number = '".$lstSalesman."' ";
		}
		/*
		if ($txtDate != ""){
			$query = $query . " AND deliveries.delivery_date = '".displayParadoxDate(insertDate($txtDate))."' ";
		}
		*/
		if ($txtRemark != ""){
			$query = $query . " AND sorder.sorder_remark = '".$txtRemark."' ";
		}
		//$query = $query . " ORDER BY sorder.sorder_date DESC, sorder.sorder_reference DESC ";
		$query = $query . " ORDER BY sorder.sorder_reference DESC ";
	}
	//echo $query;
	$result = mysql_query($query, $conn);
	while ($cur = mysql_fetch_row($result)){
		print "<tr><td bgcolor='#E0E0E0' class='style4'><a href='ReceiptMaster.php?act=viewRecord&txtRef=".$cur[1]."&txtID=".$cur[0]."'>".$cur[1]."</a></td> <td bgcolor='#E0E0E0' class='style4'>".displayDate(insertParadoxDate($cur[2]))."</td> <td bgcolor='#E0E0E0' class='style4'>".$cur[3]."</td> <td bgcolor='#E0E0E0' class='style4'>".$cur[4]."</td> <td bgcolor='#E0E0E0' class='style4'>".$cur[5]."</td> <td bgcolor='#E0E0E0' class='style4'>".$cur[6]."</td> <td bgcolor='#E0E0E0' class='style4'>".addComma($cur[7])."</td> </tr>";		
	}	
	print "</table>";
}

if ($prints == "yes"){
	print "<div id='footer'>"; 
		footer("SO");
	print "</div>"; 
}
?>
</form>