<?php
/*
File Name:		Sales_Order_Child.php

Started on:		07/08/2010
Last Modified:	20/01/2011

Change History:
23/08/2010 - Displaying Lower Qty (of Child) for Packed Item [Child Item can be sold alone (Without Bundling)]
24/08/2010 - Display Promo Items
14/09/2010 - IF ELSE Condition to updateIData - Change Session Variable
07/10/2010 - Read SalesOrder + Current Balance while Displaying Current Balance
23/10/2010 - Replace & by @@-@@-@@
23/10/2010 - Group NOT working for Packed/ Promo
23/10/2010 - Sales Order (Preparation Order) Qty for Packed/ Promo Items
10/11/2010 - Add sequence function
18/11/2010 - Nabil Mail - 11/11/2010
20/01/2011 - Item_Active
*/
ob_start('ob_gzhandler');
error_reporting(E_ERROR);
set_time_limit(0);
include("Functions_Sales.php");
include("function.inc.php");
if($_SESSION['dbName']==""){
	header("location:../logout5.php");
}
if (strpos($user_level_sales_order, "-SO-") !== false){
	//Do Nothing	
}else{
	header("location:../logout5.php");
}

$conn = openConnection();

//$iconn = new PDO('mysql:host=localhost;dbname=dajcom_acc2010', "root", "root", array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_AUTOCOMMIT => false));
//$iconn = serialize($_SESSION["iconn"]);

$user_account = $_SESSION['useraccount'];
$user_level_sales_order = $_SESSION['user_level_sales_order'];

$txtID = $_POST["txtID"]; if ($txtID == ""){$txtID = $_GET["txtID"];}
$txtRef = $_POST["txtRef"]; if ($txtRef == ""){$txtRef = $_GET["txtRef"];}
$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"];}
$lstGroup = $_POST['lstGroup']; if ($lstGroup == ""){$lstGroup = $_GET["lstGroup"];}
$lstItemType = $_POST['lstItemType']; if ($lstItemType == ""){$lstItemType = $_GET["lstItemType"];} if ($lstItemType == ""){$lstItemType = "Not Packed";}
$lstItemSort = $_POST['lstItemSort']; if ($lstItemSort == ""){$lstItemSort = $_GET["lstItemSort"];} if ($lstItemSort == ""){$lstItemSort = "Item Code";}
$lstItem = $_POST['lstItem']; if ($lstItem == ""){$lstItem = $_GET["lstItem"];}
$txtMaxQty = $_POST['txtMaxQty']; if ($txtMaxQty == ""){$txtMaxQty = $_GET["txtMaxQty"];}
$txtZeroValueFlag = $_POST['txtZeroValueFlag']; if ($txtZeroValueFlag == ""){$txtZeroValueFlag = $_GET["txtZeroValueFlag"];}
//$txtQty = $_POST['txtQty']; if ($txtQty == ""){$txtQty = $_GET["txtQty"];}

$txtRemark = str_replace("@@-@@-@@", "&", $txtRemark);
$txtIAddress = str_replace("@@-@@-@@", "&", $txtIAddress);
$txtDAddress = str_replace("@@-@@-@@", "&", $txtDAddress);
$lstClient = str_replace("@@-@@-@@", "&", $lstClient);
$lstCurrency = str_replace("@@-@@-@@", "&", $lstCurrency);
$lstCostCentre = str_replace("@@-@@-@@", "&", $lstCostCentre);
$lstProject = str_replace("@@-@@-@@", "&", $lstProject);
$lstSalesman = str_replace("@@-@@-@@", "&", $lstSalesman);
$lstWarehouse = str_replace("@@-@@-@@", "&", $lstWarehouse);
$lstGroup = str_replace("@@-@@-@@", "&", $lstGroup);

$warehouseQuery1 = $_SESSION['warehouseQuery1'];	
$warehouseQuery2 = $_SESSION['warehouseQuery2'];
$projectQuery = $_SESSION['projectQuery'];	
$defaultProject = $_SESSION['defaultProject'];
$defaultWarehouse = $_SESSION['defaultWarehouse'];

if($lstItemType == 'Packed' || $lstItemType == 'Promotion'){$lstItemSort = "Item Code";}

if ($txtID == ""){
	//Check IF Sorder IS ALREADY IN Process
	//$query = "SELECT sorder_id FROM sorder WHERE User_Account = '".$_SESSION['userSession']."'";
	//$result = selectData($conn, $query);
	//if (is_numeric($result[0])){
		//$txtID = $result[0];
	//}else{
		//$iconn->beginTransaction();
		/*
		$query = "SELECT sorder_id+1 FROM sequence";
		$result = selectData($conn, $query);
		$txtID = $result[0];
		$query = "UPDATE sequence SET sorder_id = ".$txtID;
		//echo "<br><br>".$query;
		updateData($conn, $query, true);
		*/
		$txtID = get_nextsequence("sorder_id" , "",$conn);
		
		//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)), '".ereg_replace("\'", "''", trim($txtRemark))."', '".ereg_replace("\'", "''", trim($lstClient))."', '".ereg_replace("\'", "''", trim($txtIAddress))."', '".$lstCurrency."', NULL, '".ereg_replace("\'", "''", trim($txtDAddress))."', '".ereg_replace("\'", "''", trim($lstProject))."', '0', '0', '0', '0', '0', '0', 'SO', '0', 'SO', '".$_SESSION['userSession']."', '".ereg_replace("\'", "''", trim($lstSalesman))."', NOW(), '0')";
		//$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['userSession']."', '".$lstSalesman."', NOW(), '0')";
		//$iconn->exec($query);
		updateData($conn, $query, true);
		//echo "<br><br>".$query;
	//}
}	

$message = $_GET["message"];
//$user_level_sales_order = $_POST['user_level_sales_order']; if ($user_level_sales_order == ""){$user_level_sales_order = $_GET["user_level_sales_order"];} 

print "<html><head><title>Sales Order - Add Items</title> <style>select{background-color:'#FFFFFF';font-family:'Verdana';font-size:'10';}</style> </head><body>";
	if ($message != ""){print "<center><font face='Verdana' size='1' color='#FF0000'><b>".$message."</b></font></center>";}
	print "<table width='100%' border='0'><form name='frm1' method='post' action='Sales_Order_Child.php'>";
	
	print "<input type='hidden' name='user_level_sales_order' value='".$user_level_sales_order."'>";
	print "<input type='hidden' name='txtID' value='".$txtID."'>";
	print "<input type='hidden' name='txtRef' value='".$txtRef."'>";
	print "<input type='hidden' name='txtDate' value='".$txtDate."'>";
	print "<input type='hidden' name='txtRequestDate' value='".$txtRequestDate."'>";
	print "<input type='hidden' name='txtRemark' value='".$txtRemark."'>";
	print "<input type='hidden' name='txtIAddress' value='".$txtIAddress."'>";
	print "<input type='hidden' name='txtDAddress' value='".$txtDAddress."'>";
	print "<input type='hidden' name='lstClient' value='".$lstClient."'>";
	print "<input type='hidden' name='lstCurrency' value='".$lstCurrency."'>";
	print "<input type='hidden' name='lstCostCentre' value='".$lstCostCentre."'>";
	print "<input type='hidden' name='lstProject' value='".$lstProject."'>";
	print "<input type='hidden' name='lstSalesman' value='".$lstSalesman."'>";

	print "<tr>";		
		$query = "SELECT warehouse_code, CONCAT(warehouse_code, ' - ', warehouse_name) FROM warehouse WHERE LENGTH(warehouse_code) > 0 ".$warehouseQuery1." ORDER BY warehouse_code ";
		//echo $query;
		if ($lstWarehouse == "" && $defaultWarehouse != ""){
			$lstWarehouse = $defaultWarehouse;
		}
		displayList("lstWarehouse", "Warehouse:", $lstWarehouse, $prints, $conn, $query, "onChange = 'javascript:document.frm1.submit()'", "12%", "88%");
	print "</tr><tr>";
		$query = "SELECT group_code, CONCAT(group_code, ' - ', group_name) FROM grouping WHERE LENGTH(group_code) > 0 ORDER BY group_code ";
		displayList("lstGroup", "Group:", $lstGroup, $prints, $conn, $query, "onChange = 'javascript:document.frm1.submit()'", "12%", "88%");
	print "</tr><tr>";
		print "<td align='right'><font face='Verdana' size='2' color='#A0A0A0'>Item Type:</font></td><td><select name='lstItemType' onChange = 'javascript:document.frm1.submit()'>";
		if ($lstItemType == "Packed"){
			print "<option selected value='Packed'>Packed</option>";
		}else{
			print "<option value='Packed'>Packed</option>";
		}
		if ($lstItemType == "Not Packed"){
			print "<option selected value='Not Packed'>Not Packed</option>";
		}else{
			print "<option value='Not Packed'>Not Packed</option>";
		}
		if ($lstItemType == "Promotion"){
			print "<option selected value='Promotion'>Promotion</option>";
		}else{
			print "<option value='Promotion'>Promotion</option>";
		}
		if ($lstItemType == "Single"){
			print "<option selected value='Single'>Single</option>";
		}else{
			print "<option value='Single'>Single</option>";
		}
		print "</select></td>";
	print "</tr><tr>";
		print "<td align='right'><font face='Verdana' size='2' color='#A0A0A0'>Sort By:</font></td><td><select name='lstItemSort' onChange = 'javascript:document.frm1.submit()'>";
		if ($lstItemSort == "Item Code"){
			print "<option selected value='Item Code'>Item Code</option>";
		}else{
			print "<option value='Item Code'>Item Code</option>";
		}
		if ($lstItemSort == "Item Desc"){
			print "<option selected value='Item Desc'>Item Desc</option>";
		}else{
			print "<option value='Item Desc'>Item Desc</option>";
		}
		print "</select></td>";
	print "</tr><tr>";
		$query = "";
		if($lstItemType == 'Packed'){
			if ($lstItemSort == "Item Code"){
				//$query="SELECT items.item_code, CONCAT(items.item_code, ' - ', items.item_description, ' - (', stktransaction.warehouse_code, ') - [', sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered)/2, ']') FROM stktransaction, items, packdt WHERE items.item_code = packdt.item_code AND items.item_pack = 1 AND packdt.Item_CodePackDt = stktransaction.Item_code ";
				//$query = "SELECT items.item_code, CONCAT(items.item_code, ' - ', items.item_description, ' - (', stktransaction.warehouse_code, ') - [', ROUND(sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered)/ (SELECT COUNT(packdt.item_code) FROM packdt WHERE packdt.item_Code = items.item_code)), ']') FROM stktransaction, items, packdt WHERE items.item_code = packdt.item_code AND items.item_pack = 1 AND packdt.Item_CodePackDt = stktransaction.Item_code ";
				//$query="SELECT stktransaction.item_code, Item_CodePacked, CONCAT(items.item_code, ' - ', items.item_description, ' - (', stktransaction.warehouse_code, ') - [', sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered), ']')  FROM stktransaction, items WHERE stktransaction.item_code = items.item_code AND stktransaction.item_code IN (SELECT packdt.Item_CodePackDt FROM packdt) ";
				$query="SELECT packdt.item_code, packdt.Item_CodePackDt, sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered), stktransaction.warehouse_code, PackDt_Quantity FROM stktransaction, packdt, items WHERE stktransaction.item_code = packdt.Item_CodePackDt AND stktransaction.item_code = items.Item_Code AND packdt.item_code IN (SELECT items.item_code FROM items where items.item_promotion = 0)  ";
			}else{
				//$query="SELECT items.item_code, CONCAT(items.item_description, ' - ', items.item_code, ' - (', stktransaction.warehouse_code, ') - [', sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered)/2, ']') FROM stktransaction, items, packdt WHERE items.item_code = packdt.item_code AND items.item_pack = 1 AND packdt.Item_CodePackDt = stktransaction.Item_code ";
				//$query = "SELECT items.item_code, CONCAT(items.item_description, ' - ', items.item_code, ' - (', stktransaction.warehouse_code, ') - [', ROUND(sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered)/ (SELECT COUNT(packdt.item_code) FROM packdt WHERE packdt.item_Code = items.item_code)), ']') FROM stktransaction, items, packdt WHERE items.item_code = packdt.item_code AND items.item_pack = 1 AND packdt.Item_CodePackDt = stktransaction.Item_code ";
				//$query="SELECT packdt.item_code, stktransaction.item_code, sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered), CONCAT(items.item_description, ' - ', stktransaction.item_code, ' - (', stktransaction.warehouse_code, ') - [', sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered), ']')  FROM stktransaction, packdt, items WHERE stktransaction.item_code = packdt.Item_CodePackDt AND stktransaction.item_code = items.Item_Code ";
			}
		}else if ($lstItemType == 'Promotion'){
				$query="SELECT packdt.item_code, packdt.Item_CodePackDt, sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered), stktransaction.warehouse_code, PackDt_Quantity FROM stktransaction, packdt, items WHERE stktransaction.item_code = packdt.Item_CodePackDt AND stktransaction.item_code = items.Item_Code AND packdt.Packdt_fromdate <= '".displayParadoxDate(insertToday())." 00:00:00' AND packdt.Packdt_todate >= '".displayParadoxDate(insertToday())." 00:00:00' AND packdt.item_code IN (SELECT items.item_code FROM items where items.item_promotion = 1) AND packdt.Packdt_fromdate IS NOT NULL AND packdt.Packdt_todate IS NOT NULL ";
		}else{
			if ($lstItemSort == "Item Code"){
				$query = "SELECT stktransaction.item_code, CONCAT(items.item_code, ' - ', items.item_description, ' - (', stktransaction.warehouse_code, ') - [', sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered), ']')  FROM stktransaction, items WHERE stktransaction.item_code = items.item_code AND items.Item_Pack = 0 ";				
			}else{
				$query = "SELECT stktransaction.item_code, CONCAT(items.item_description, ' - ', stktransaction.item_code, ' - (', stktransaction.warehouse_code, ') - [', sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered), ']')  FROM stktransaction, items WHERE stktransaction.item_code = items.item_code AND items.Item_Pack = 0 ";
			}

			if ($lstItemType == 'Single'){
				$query .= " AND (items.item_code NOT IN (SELECT packdt.Item_CodepackDt FROM packdt) OR items.item_code IN (SELECT packdt.Item_CodepackDt FROM packdt WHERE packdt.Item_Code IN (SELECT Item_Code FROM items WHERE item_promotion = 1)))";
			}
		}		
		if($lstWarehouse != ''){
			$query = $query . " AND stktransaction.warehouse_code='".$lstWarehouse."' ";
		}
		/*
		if($lstGroup != '' && ($lstItemType == 'Not Packed' || $lstItemType == 'Single')){
			$query = $query . " AND items.group_code='".$lstGroup."' ";
		}else if ($lstGroup != '' && ($lstItemType == 'Packed' || $lstItemType == 'Promotion')){
			$query = $query . " AND items.group_code='".$lstGroup."' ";
		}
		*/
		if($lstGroup != ''){
			$query = $query . " AND items.group_code='".$lstGroup."' ";
		}
		if($lstItemType == 'Packed' || $lstItemType == 'Promotion'){
			$query = $query . $warehouseQuery2 ." AND packdt.item_code IN (SELECT item_code FROM items WHERE items.item_active = 1) GROUP BY items.item_code, stktransaction.warehouse_code, packdt.item_code, PackDt_Quantity ORDER BY packdt.item_code, ";
		}else{
			$query = $query . $warehouseQuery2 ." AND items.item_active = 1 GROUP BY items.item_code, stktransaction.warehouse_code, items.item_description ORDER BY ";
			if ($lstItemSort == "Item Code"){
				$query = $query . " items.item_code, ";
			}else{
				$query = $query . " items.item_description, ";
			}
		}				
		$query = $query . " stktransaction.warehouse_code";
		//echo $query;
		if($lstItemType == 'Packed' || $lstItemType == 'Promotion'){
			print "<td align='right'><font size='2' face='Verdana' color='#A0A0A0'>Item:</font></td><td> <select name='lstItem' id='lstItem' onChange = 'javascript:getQtyAndWarehouse()'> <option value=''>---</option>";
			$qty = 9876543210;
			$code = "";
			$wh = "";
			$counter = 0;
			$sub_counter = 0;
			$promo_display = true;
			$promo_qty = 0;
			$result = mysql_query($query, $conn);
			//$rows = mysql_num_rows($result);
			while($cur = mysql_fetch_row($result)){
				//echo "<br><br>".$cur[2]."----".$code;
				if ($cur[2] == "" || $cur[2] == "NULL"){$cur[2] = 0;}
				if ($code != $cur[0]){
					if ($counter == 0){
						//First Record - Do Nothing
					}else{
						//Check if ANY Child Record is MISSING
						$sub_query = "SELECT Item_CodePackDt FROM packdt WHERE Item_Code = '".$code."'";
						$sub_result = mysql_query($sub_query, $conn);
						$sub_row_count = mysql_num_rows($sub_result);

						if ($sub_row_count != $sub_counter){
							$qty = "0";							
						}else{
							//Check Balance Promo Qty
							if($lstItemType == 'Promotion'){
								$sub_query = "SELECT Packdt_totalpromotion, PackDt_FromDate, PackDt_ToDate FROM packdt WHERE Item_Code = '".$code."'";
								$sub_result = selectData($conn, $sub_query);
								$total_qty = $sub_result[0];

								$sub_query = "SELECT sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered) FROM stktransaction WHERE Item_CodePacked = '".$code."' 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;
								}
							}
						}

						if ($promo_display){
							$sub_query = "SELECT item_description FROM items WHERE item_code = '".$code."'";
							$sub_result = selectData($conn, $sub_query);
							if ($code == $lstItem){
								print "<option selected value='".$code."'>".$code." - ".$sub_result[0]." - (".$wh.") - [".$qty."]</option>";
							}else{
								print "<option value='".$code."'>".$code." - ".$sub_result[0]." - (".$wh.") - [".$qty."]</option>";
							}
						}

						$qty = 9876543210;
						$promo_qty = 0;
						$promo_display = true;
						$sub_counter = 0;
					}					
				}
				
				if ($cur[2] < $qty){
					$qty = $cur[2];
				}
				
				$code = $cur[0];
				$wh = $cur[3];
				$promo_qty = $promo_qty + $cur[4];
				$counter++;
				$sub_counter++;
			}
			if ($counter > 0){
				$sub_query = "SELECT item_description FROM items WHERE item_code = '".$code."'";
				$sub_result = selectData($conn, $sub_query);
				if ($code == $lstItem){
					print "<option selected value='".$code."'>".$code." - ".$sub_result[0]." - (".$wh.") - [".$qty."]</option>";
				}else{
					print "<option value='".$code."'>".$code." - ".$sub_result[0]." - (".$wh.") - [".$qty."]</option>";
				}
			}
			print "</select></td>";
			//print $counter;
		}else{
			displayList("lstItem", "Item:", $lstItem, $prints, $conn, $query, " id='lstItem' onChange = 'javascript:getQtyAndWarehouse()'", "12%", "88%");
		}		
		print "<input type='hidden' name='txtMaxQty' value='".$txtMaxQty."'>";		
	print "</tr>";
	if($lstItem != ''){
		$min_packed_sorder_qty = 0;
		if($lstItemType == 'Packed' || $lstItemType == 'Promotion'){
			//$query = "SELECT IFNULL((SUM(sorderdt.sorderdt_quantity) - SUM(deliverydt.deliverydt_quantity)), 0), sorderdt.Item_code FROM sorderdt, deliverydt WHERE sorderdt.Item_CodePacked = deliverydt.Item_CodePacked AND sorderdt.warehouse_code = deliverydt.warehouse_code AND deliverydt.Journal_Type = 'DI' AND sorderdt.Item_CodePacked = '".$lstItem."' AND sorderdt.warehouse_code = '".$lstWarehouse."' AND length(deliverydt.user_account) = 0 AND (LENGTH(sorderdt.user_account) = 0 OR sorderdt.user_account LIKE '%".insertToday()."%') GROUP BY sorderdt.Item_code";
			$query = "SELECT Item_CodePackDt FROM packdt WHERE Item_Code = '".$lstItem."' AND PackDt_CostPercentage > 0";
			$result = mysql_query($query, $conn);			
			while($cur = mysql_fetch_row($result)){
				$query = "SELECT IFNULL(SUM(B.SorderDt_Quantity), 0) FROM SorderDt B Left Outer Join ( Select A.Delivery_id, A.Journal_Type, if(sum(A.DeliveryDt_Quantity) is null,0 ,sum(A.DeliveryDt_Quantity)) As SorderDt_QuantityUse, A.DeliveryDt_ID, RelatedDt_id from Deliverydt A, Deliveries Where Deliveries.Delivery_id = A.Delivery_id And A.Journal_Type = 'DI' Group by A.RelatedDt_id ) As Q on B.Sorderdt_id = Q.RelatedDt_id where B.item_code = '".$cur[0]."' and B.Warehouse_code = '".$lstWarehouse."' and ((B.Sorderdt_Quantity > if(0,Q.SorderDt_QuantityUse + ((B.SorderDt_Quantity*100)/100),Q.SorderDt_QuantityUse)) or Q.RelatedDt_ID is null) and (B.sorderdt_olddata=False or B.sorderdt_olddata is null) and B.sorder_id in (select sorder_id from sorder where sorder_type='SO')";
				//echo "<br><br>".$query;
				$sub_result = selectData($conn, $query);
				if ($sub_result[0] < 0){$sub_result[0] = 0;}
				if ($sub_result[0] > $min_packed_sorder_qty){
					$min_packed_sorder_qty = $sub_result[0];
				}
			}			
		}else{
			$query = "SELECT IFNULL(SUM(B.SorderDt_Quantity), 0) FROM SorderDt B Left Outer Join ( Select A.Delivery_id, A.Journal_Type, if(sum(A.DeliveryDt_Quantity) is null,0 ,sum(A.DeliveryDt_Quantity)) As SorderDt_QuantityUse, A.DeliveryDt_ID, RelatedDt_id from Deliverydt A, Deliveries Where Deliveries.Delivery_id = A.Delivery_id And A.Journal_Type = 'DI' Group by A.RelatedDt_id ) As Q on B.Sorderdt_id = Q.RelatedDt_id where B.item_code = '".$lstItem."' and B.Warehouse_code = '".$lstWarehouse."' and ((B.Sorderdt_Quantity > if(0,Q.SorderDt_QuantityUse + ((B.SorderDt_Quantity*100)/100),Q.SorderDt_QuantityUse)) or Q.RelatedDt_ID is null) and (B.sorderdt_olddata=False or B.sorderdt_olddata is null) and B.sorder_id in (select sorder_id from sorder where sorder_type='SO')";
			$result = selectData($conn, $query);
			if ($result[0] < 0){$result[0] = 0;}
			$min_packed_sorder_qty = $result[0];
		}
		//echo $query;
		print "<tr>";
			displayTextbox("txtSorderQty", "PO Qty:", $min_packed_sorder_qty, "yes", 10, "12%", "88%");
		print "</tr><tr>";

		$query = "SELECT Client_SellingPrice FROM Clients WHERE Ledger_Number = '".$lstClient."'";
		//echo "<br><br>".$query;
		$result = selectData($conn, $query);
		$c_sp = $result[0];

		$query = "SELECT Item_SellingPrice1, Item_SellingPrice2, Item_SellingPrice3, Item_SellingPrice4, Item_SellingPrice5, Item_SellingPrice6, item_zeroprice FROM items WHERE Item_Code = '".$lstItem."'";
		//echo "<br><br>".$query;
		$result = selectData($conn, $query);
		$i_sp = $result[0];
		
		switch ($c_sp){
			case "II":
				$i_sp = $result[1]; break;
			case "III":
				$i_sp = $result[2]; break;
			case "IV":
				$i_sp = $result[3]; break;
			case "V":
				$i_sp = $result[4]; break;
			case "VI":
				$i_sp = $result[5]; break;
		}		
		
		print "<tr>";
			displayTextbox("txtQty", "Qty:", $txtQty, "", 10, "12%", "88%");
		print "</tr><tr>";
			if (strpos($user_level_sales_order, "-SOMSP-") !== false){
				displayTextbox("txtSP", "Sales Price:", $i_sp, "yes", 10, "12%", "88%");
			}else{
				displayTextbox("txtSP", "Sales Price:", $i_sp, "", 10, "12%", "88%");
			}
		print "</tr><tr>";
			displayTextbox("txtDiscount", "Discount:", "0", "yes", 10, "12%", "88%");
		print "</tr>";
		print "<input type='hidden' name='txtZeroValueFlag' value='".$result[6]."'>";
		if (strpos($user_level_sales_order, "-SOE-") !== false || strpos($user_level_sales_order, "-SOA-") !== false){
			print "<tr>";
				print "<td>&nbsp;</td> <td><input type='button' onClick='javascript:changeLocation()' value='Submit Record' style='background-color:#4069A7; color:#FFFFFF;font-family:Verdana; font-size:11px;'> &nbsp;&nbsp;&nbsp;<input type='button' onClick='javascript:window.close()' value='Close Window' style='background-color:#4069A7; color:#FFFFFF;font-family:Verdana; font-size:11px;'>";
			print "</td></tr>";
		}
	}
	print "</form></table>";
?>
<script>
	function getQtyAndWarehouse(){
		x = document.frm1;
		y = x.lstItem[x.lstItem.selectedIndex].text;
		x.txtMaxQty.value = y.substring(y.lastIndexOf('[')+1, y.lastIndexOf(']'));
		x.lstWarehouse.value = y.substring(y.lastIndexOf('(')+1, y.lastIndexOf(')'));
		x.submit();
	}

	function changeLocation(){
		x = document.frm1;
		a = x.txtQty.value*1;
		b = x.txtSP.value; if (b == ''){b = 0;}
		c = x.txtDiscount.value; if (c == ''){c = 0;}
		d = x.txtSorderQty.value*1;
		e = x.txtMaxQty.value*1;
		f = x.txtZeroValueFlag.value*1;
		if (a == '' || a*1 != a/1 || a > (e - d) || a < 0){
			alert('Qty ('+a+') should be a NUMERIC value and NOT MORE than the [Available ('+e+') - PO ('+d+')] Qty: ['+(e*1 - d*1)+']');
			x.txtQty.focus();
			return false;
		}else if (b == '' || b*1 != b/1){
			alert('Sales Price should be a NUMERIC value');
			x.txtSP.focus();
			return false;
		}else if (f==0 && b <= 0){
			alert('Sales Price should MORE THAN Zero');
			x.txtSP.focus();
			return false;
		}else if (c == '' || c*1 != c/1){
			alert('Discount should be a NUMERIC value');
			x.txtDiscount.focus();
			return false;
		}else{			
			var loc = 'salesorder_form.php?act=addItem&txtRef='+x.txtRef.value+'&txtDate='+x.txtDate.value+'&txtRequestDate='+x.txtRequestDate.value+'&txtRemark='+x.txtRemark.value.replace('&', '@@-@@-@@')+'&txtIAddress='+x.txtIAddress.value.replace('&', '@@-@@-@@')+'&txtDAddress='+x.txtDAddress.value.replace('&', '@@-@@-@@')+'&lstClient='+x.lstClient.value.replace('&', '@@-@@-@@')+'&lstCurrency='+x.lstCurrency.value.replace('&', '@@-@@-@@')+'&lstCostCentre='+x.lstCostCentre.value.replace('&', '@@-@@-@@')+'&lstProject='+x.lstProject.value.replace('&', '@@-@@-@@')+'&lstSalesman='+x.lstSalesman.value.replace('&', '@@-@@-@@')+'&lstWarehouse='+x.lstWarehouse.value.replace('&', '@@-@@-@@')+'&lstItem='+x.lstItem.value.replace('&', '@@-@@-@@')+'&txtQty='+x.txtQty.value+'&txtSP='+x.txtSP.value+'&txtDiscount='+x.txtDiscount.value+'&txtID='+x.txtID.value+'&user_level_sales_order='+x.user_level_sales_order.value+'&lstItemType='+x.lstItemType.value;
			//alert("Else");			
			if (!opener){
				win.creator.location = loc;
			}else{
				opener.location = loc;
			}
			x.lstItem.value='';
			x.action = 'Sales_Order_Child.php?message=Item Added to Sales Order';
			x.submit();
		}
	}
</script>
<style>input{background-color:'#FDFDFD';font-family:'Verdana';font-size:'10';}</style>
<style>select{background-color:'#FDFDFD';font-family:'Verdana';font-size:'10';}</style>
</center></body></html>
