<?php
/*
23/12/2010 - Replaced convertcurfunc
*/
ob_start('ob_gzhandler');
error_reporting(E_ALL);
set_time_limit(0);

include("Functions_Sales.php");
include("function.inc.php");
if($_SESSION['dbName']==""){
	header("location:../logout5.php");
}

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

$txtID = $_POST["txtID"]; if ($txtID == ""){$txtID = $_GET["txtID"];}
$txtSID = $_POST["txtSID"]; if ($txtSID == ""){$txtSID = $_GET["txtSID"];}
$txtRef = $_POST["txtRef"]; if ($txtRef == ""){$txtRef = $_GET["txtRef"];}
$txtSRef = $_POST["txtSRef"]; if ($txtSRef == ""){$txtSRef = $_GET["txtSRef"];}
$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";}

$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);

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

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

//if ($user_level_sales == "" || strpos($_SESSION["userSession"], $_SESSION["useraccount"]) != 0){
if ($user_level_sales == ""){
	$query = "SELECT Fi_returnsalesmod, Fi_returnsalesdel, Fi_saleswithprice, 0, Unmodify_sellingprice, Fi_returnsalesapp, FI_returnSales FROM ".$_SESSION['dbLabel'].".login where user_account= '".$_SESSION['useraccount']."'";
	$result = selectData($aconn, $query);
	//$result = getUserAccess($_SESSION['dbLabel'], $_SESSION['useraccount']);
	if ($result[0] == "1"){$user_level_sales .= "-SOE-";}
	if ($result[1] == "1"){$user_level_sales .= "-SOD-";}
	if ($result[2] == "1"){$user_level_sales .= "-SOSP-";}
	if ($result[3] == "1"){$user_level_sales .= "-SOC-";}
	if ($result[4] == "0"){$user_level_sales .= "-SOMSP-";}	
	if ($result[5] == "1"){$user_level_sales .= "-SOA-";}	
	if ($result[6] == "1"){$user_level_sales .= "-SO-";}
	$_SESSION['user_level_sales'] = $user_level_sales;
	if($result[6] == "0"){
		header("location:../logout5.php");
	}

	$this_query = "SELECT Warehouse_code FROM ".$_SESSION['dbLabel'].".loginstk WHERE user_account = '".$_SESSION['useraccount']."' AND Warehouse_code IS NOT NULL ";
	$result = selectData($aconn, $this_query);
	if ($result[0] != "0" && $result[0] != "" && $result[0] != "NULL"){
		$warehouseQuery1 = " AND Warehouse_code IN (".$this_query.")";
		$warehouseQuery2 = " AND stktransaction.Warehouse_code IN (".$this_query.")";
	}
	$_SESSION['warehouseQuery1'] = $warehouseQuery1;	
	$_SESSION['warehouseQuery2'] = $warehouseQuery2;
		
	$this_query = "SELECT DISTINCT(Project_code) FROM ".$_SESSION['dbLabel'].".loginstk WHERE user_account = '".$_SESSION['useraccount']."' AND Project_code IS NOT NULL ";
	$result = selectData($aconn, $this_query);
	//echo "<br><br>".$this_query;
	if ($result[0] != "0" && $result[0] != "" && $result[0] != "NULL"){
		$projectQuery = " AND Project.Project_code IN (".$this_query.")";		
	}
	$_SESSION['projectQuery'] = $projectQuery;
	$pq_count = 0;
	$result = mysql_query($this_query, $conn);		
	while ($cur = mysql_fetch_row($result)){
		if (strlen($cur[0]) > 0){
			if ($pq_count == 0){
				$pq .= " AND (deliveries.Project_Code = '".$cur[0]."' ";
			}else{
				$pq .= " OR deliveries.Project_Code = '".$cur[0]."' ";
			}
			$pq_count++;
		}
	}
	if ($pq_count > 0){
		$pq .= " ) ";
	}
	$_SESSION['pq'] = $pq;

	$this_query = "SELECT Warehouse_code FROM ".$_SESSION['dbLabel'].".loginstk WHERE user_account = '".$_SESSION['useraccount']."' AND default_warehouse = 1 ";
	$result = selectData($aconn, $this_query);
	if ($result[0] != "0" && $result[0] != "" && $result[0] != "NULL"){
		$defaultWarehouse = $result[0];
	}
	$_SESSION['defaultWarehouse'] = $defaultWarehouse;
	
	$this_query = "SELECT Project_code FROM ".$_SESSION['dbLabel'].".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 "<br><br>".$this_query;
	$_SESSION["userSession"] = $_SESSION['useraccount'] . insertToday() . rand();
}

if ($lstProject == ""){$lstProject = $_SESSION['defaultProject'];}
//echo "<br>128: ".$_SESSION["userSession"];

if ($act == "viewSRecord" && $txtSID != ""){
	$queryFlag = true;
	if ($txtID == ""){
		//Check IF Sales IS ALREADY IN Process
		//Clear Page
		clearPage($iconn, $_SESSION['userSession'], "Sales");			
		$txtID = get_nextsequence("delivery_id" , "",$conn);			
		$query = "INSERT INTO deliveries (delivery_id, delivery_date, delivery_remark, Client_Code, Currency_Code, Costcent_code, Project_Code, delivery_totalQuantity,  delivery_posted, delivery_taxablettc, delivery_vat, delivery_discountamount, Journal_type, User_Account, Salesman_code, delivery_promotionacc, delivery_totalbase1, delivery_totalbase2, delivery_belongstogroup, delivery_rate, delivery_ratebase1, delivery_ratebase2, Delivery_taxable, delivery_vataccount, Delivery_nonetaxable, delivery_shippedto, delivery_returnref) SELECT ".$txtID.", delivery_date, delivery_remark, Client_Code, Currency_Code, Costcent_code, Project_Code, delivery_totalQuantity,  delivery_posted, delivery_taxablettc, delivery_vat, 0, 'DR', '".$_SESSION['userSession']."', Salesman_code, delivery_promotionacc, delivery_totalbase1, delivery_totalbase2, delivery_belongstogroup, delivery_rate, delivery_ratebase1, delivery_ratebase2, Delivery_taxable, delivery_vataccount, Delivery_nonetaxable, delivery_shippedto, Delivery_reference FROM Deliveries WHERE delivery_id = '".$txtSID."'";
		if (updateIData($iconn, $query, true)){
			//Do Nothing
		}else{
			$queryFlag = false;
		}
		//echo "<br><br>".$query;
	}
	
	if ($queryFlag){
		$query = "SELECT delivery_id, delivery_date, Client_Code, Currency_Code, Costcent_code,  Project_Code, Salesman_code, delivery_shippedto, delivery_discountamount FROM deliveries WHERE delivery_id = ".$txtID;
		$result = selectData($conn, $query);
		//echo "<br><br>".$query;
		$txtDate1 = $result[1];	
		$txtDate = displayDate(insertParadoxDate($result[1]));	
		$lstClient = $result[2];
		$lstCurrency = $result[3];
		$lstCostCentre = $result[4];
		$lstProject = $result[5];
		$lstSalesman = $result[6];	
		$txtDAddress = $result[7];	
		$txtDiscountTotal = $result[8];	
		
		$query = "SELECT deliverydt.item_code, IFNULL((deliverydt_quantity - DeliveryDt_QuantityReturn), 0), Saledt_price, Deliverydt_discountAmount, warehouse_code, Currency_Code, Item_Vat, DeliveryDt_PriceTTC, Item_Codepacked, Item_QtyPacked, DeliveryDt_id, Deliverydt_DiscountPer, deliverydt_priceTTCBase1, deliverydt_priceTTCBase2, Saledt_PriceBase1, Saledt_PriceBase2 FROM deliverydt WHERE Delivery_id = '".$txtSID."' AND (deliverydt.DeliveryDt_QuantityReturn IS NULL OR deliverydt.deliverydt_quantity <> deliverydt.DeliveryDt_QuantityReturn) ";
		//echo "<br><br>".$query;
		
		$result = mysql_query($query, $conn);	
		while ($cur = mysql_fetch_row($result)){	
			/*
			$query = "SELECT deliverydt_id+1 FROM sequence";
			$sub_result = selectData($conn, $query);	
			$query = "UPDATE sequence SET deliverydt_id = ".$sub_result[0];
			//echo "<br><br>".$query;
			updateData($conn, $query, true);	
			*/
			$sub_result[0] = get_nextsequence("deliverydt_id" , "",$conn);
					
			$query = "SELECT deliverydt_id FROM Deliverydt WHERE item_code = '".$cur[0]."' AND deliverydt_quantity = '".$cur[1]."' AND User_Account = '".$_SESSION['userSession']."' AND RelatedDt_Id = '".$cur[10]."'";
			$sub_sub_result = selectData($conn, $query);
			if ($sub_sub_result == "" && $sub_sub_result[0] == ""){			
				if ($cur[1] == "" || $cur[1] == "NULL"){$cur[1] = "0";}
				if ($cur[2] == "" || $cur[2] == "NULL"){$cur[2] = "0";}
				if ($cur[3] == "" || $cur[3] == "NULL"){$cur[3] = "0";}
				if ($cur[6] == "" || $cur[6] == "NULL"){$cur[6] = "0";}
				if ($cur[7] == "" || $cur[7] == "NULL"){$cur[7] = "0";}
				if ($cur[9] == "" || $cur[9] == "NULL"){$cur[9] = "0";}
				if ($cur[11] == "" || $cur[11] == "NULL"){$cur[11] = "0";}
				$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);

				$query = "INSERT INTO Deliverydt (deliverydt_id, delivery_id, item_code, DeliveryDt_QuantityReturn, Deliverydt_price, deliverydt_discountamount, warehouse_code, Currency_Code, Item_Vat, deliverydt_priceTTC, Item_Codepacked, Item_QtyPacked, User_Account, RelatedDt_Id, Client_code, delivery_date, Journal_type, Project_code, Deliverydt_directstkDbt, Deliverydt_directstkcrd, Deliverydt_directstkcur, Deliverydt_discountacc, Deliverydt_ItemAccount, deliverydt_quantity, Saledt_Price, deliverydt_discountper, deliverydt_priceTTCBase1, deliverydt_priceTTCBase2, Saledt_PriceBase1, Saledt_PriceBase2) VALUES ('".$sub_result[0]."', '".$txtID."', '".$cur[0]."', '".$cur[1]."', '".$cur[2]."', '".$cur[3]."', '".$cur[4]."', '".$cur[5]."', '".$cur[6]."', '".$cur[7]."', '".$cur[8]."', '".$cur[9]."', '".$_SESSION['userSession']."', '".$cur[10]."', '".$lstClient."', '".$txtDate1."', 'DR', '".$lstProject."', '".$super_sub_result[0]."', '".$super_sub_result[1]."', '".$super_sub_result[2]."', '".$super_sub_result[3]."', '".$super_sub_result[4]."', '0', '".$cur[2]."', '".$cur[11]."', '".$cur[12]."', '".$cur[13]."', '".$cur[14]."', '".$cur[15]."')";
				//echo "<br><br>".$query;
				if (updateIData($iconn, $query, false)){
					//Do Nothing
					//echo "<br>216";
				}else{
					//echo "<br>217";
					$queryFlag = false;
				}
			}		
		}
	}
	
	if ($queryFlag){
		$query = "UPDATE Deliverydt SET deliverydt_priceBase1 = convertcurfunc(deliverydt.currency_code, (select BASE1 from setup), Delivery_Date, 0, 0, '', '', ifNull(deliverydt_price,0)), deliverydt_pricebase2 = convertcurfunc(deliverydt.currency_code,(select BASE2 from setup),Delivery_Date,0,0,'','',ifNull(deliverydt_price,0)), saledt_priceBase1 = convertcurfunc(deliverydt.currency_code,(select BASE1 from setup),Delivery_Date,0,0,'','',ifNull(deliverydt_price,0)), saledt_pricebase2 = convertcurfunc(deliverydt.currency_code,(select BASE2 from setup),Delivery_Date,0,0,'','',ifNull(deliverydt_price,0)), deliverydt_discountbase1 = convertcurfunc(deliverydt.currency_code,(select BASE1 from setup),Delivery_Date,0,0,'','',ifNull(deliverydt_discountamount,0)), deliverydt_discountbase2 = convertcurfunc(deliverydt.currency_code,(select BASE2 from setup),Delivery_Date,0,0,'','',ifNull(deliverydt_discountamount,0)), deliverydt_priceTTCBase1 = convertcurfunc(deliverydt.currency_code,(select BASE1 from setup),Delivery_Date,0,0,'','',ifNull(deliverydt_priceTTC,0)), deliverydt_priceTTCBase2 = convertcurfunc(deliverydt.currency_code,(select BASE2 from setup),Delivery_Date,0,0,'','',ifNull(deliverydt_priceTTC,0)) WHERE delivery_id = ".$txtID."";
		//echo "<br><br>".$query;
		updateIData($iconn, $query, true);
		$message = "";
	}else{
		$message = "Sales Invoice COULD NOT be Loaded. Please ensure that ALL Items in the Invoice were NOT returned earlier";
	}	
}else if($act == "deleteItem"){
	$queryFlag = false;
	//Check if Packed Item
	$query = "SELECT Item_Codepacked, delivery_id, deliverydt_price, deliverydt_pricettc, deliverydt_quantity, item_code, deliverydt_discountamount FROM deliverydt WHERE deliverydt_id = ".$_POST['txtDeleteItemCode'];
	$result = selectData($conn, $query);
	$txtID = $result[1];
	$txtSP = $result[3];
	$txtQty = $result[4];
	$lstItem = $result[5];
	$txtDiscount = $result[6];
	//echo $query;
	$this_result = "";
	if ($result[0] == ""){
		//Not Packed - Delete Row
		$query = "DELETE FROM deliverydt WHERE deliverydt_id = ".$_POST['txtDeleteItemCode'];
		if (updateIData($iconn, $query, false)){
			$queryFlag = true;
		}
	}else{
		//Packed - Delete Row
		$query = "DELETE FROM deliverydt WHERE delivery_id = ".$txtID." AND Item_Codepacked = ".$result[0];
		if (updateIData($iconn, $query, false)){
			$queryFlag = true;
		}
	}
	
	if ($queryFlag){		
		//echo "<br>".$query;
		//$query = "DELETE FROM purchasesserialno WHERE RelatedSerial_ID IS NOT NULL AND DeliveryDt_id = '".$_POST['txtDeleteItemCode']."' AND UPPER(SerialNo_Code) = '".$txtSerial."'  AND purchasesserialno.Journal_Type = 'DI' ";
		$query = "DELETE FROM purchasesserialno WHERE RelatedSerial_ID IS NOT NULL AND DeliveryDt_id = '".$_POST['txtDeleteItemCode']."' AND SerialNo_Code = '".$txtSerial."'  AND purchasesserialno.Journal_Type = 'DR' ";
		//echo "<br><br>".$query;
		if (updateIData($iconn, $query, false)){
			//$query = "UPDATE purchasesserialno SET purchasesserialno.DeliveryDt_id = NULL, SerialNo_Used = 0 WHERE UPPER(SerialNo_Code) = '".$txtSerial."' AND (purchasesserialno.Journal_Type = 'PI' OR purchasesserialno.Journal_Type = 'AI' OR purchasesserialno.Journal_Type = 'TR') ";			
			//echo "<br><br>".$query;	
			//if (updateIData($iconn, $query, false)){
				$query = "UPDATE Deliveries SET Delivery_totalQuantity = IFNULL((SELECT SUM(deliverydt_quantity) FROM deliverydt WHERE Delivery_id = '".$txtID."'), 0), Delivery_taxable = IFNULL((SELECT SUM(deliverydt_quantity * ((deliverydt_priceTTC*(1-deliverydt_discountPer/100))/ (1 + Item_Vat/100))) FROM deliverydt WHERE Delivery_id = '".$txtID."' AND Item_Vat > 0), 0), Delivery_taxableTTC = IFNULL((SELECT SUM(deliverydt_quantity * (deliverydt_priceTTC*(1-deliverydt_discountPer/100))) FROM deliverydt WHERE Delivery_id = '".$txtID."' AND Item_Vat > 0), 0), Delivery_nonetaxable = IFNULL((SELECT SUM(deliverydt_quantity * (deliverydt_priceTTC*(1-deliverydt_discountPer/100))) FROM deliverydt WHERE Delivery_id = '".$txtID."' AND Item_Vat = 0), 0), Delivery_vat = IFNULL((SELECT SUM(deliverydt_quantity * ((deliverydt_priceTTC*(1-deliverydt_discountPer/100)) - ((deliverydt_priceTTC*(1-deliverydt_discountPer/100))/ (1 + Item_Vat/100)))) FROM deliverydt WHERE Delivery_id = '".$txtID."'), 0), Delivery_discountamount = IFNULL((SELECT SUM(deliverydt_quantity * DeliveryDt_DiscountAmount) FROM deliverydt WHERE Delivery_id = '".$txtID."'), 0) WHERE Delivery_id = ".$txtID."";
				//echo "<br>".$query;
				if (updateIData($iconn, $query, false)){
					//$query = "UPDATE deliveries SET delivery_taxablettcBase1 = IFNULL(delivery_taxablettc * ".$rate_dt.", 0), delivery_taxablettcBase2 = IFNULL(delivery_taxablettc / ".$parity_dt.", 0), delivery_taxableBase1 = IFNULL(delivery_taxable * ".$rate_dt.", 0), delivery_taxableBase2 = IFNULL(delivery_taxable / ".$parity_dt.", 0), delivery_discountBase1 = IFNULL(delivery_discountamount * ".$rate_dt.", 0), delivery_discountBase2 = IFNULL(delivery_discountamount / ".$parity_dt.", 0), delivery_vatBase1 = IFNULL(delivery_vat * ".$rate_dt.", 0), delivery_vatBase2 = IFNULL(delivery_vat / ".$parity_dt.", 0), delivery_total = IFNULL((delivery_taxable + Delivery_nonetaxable), 0), delivery_totalBase1 = IFNULL((delivery_taxableBase1 + Delivery_NoneTaxableBase1), 0), delivery_totalBase2 =  IFNULL((delivery_taxableBase2 + Delivery_NoneTaxableBase2), 0), Delivery_NoneTaxableBase1 = IFNULL(Delivery_NoneTaxable * ".$rate_dt.", 0), Delivery_NoneTaxableBase2 = IFNULL(Delivery_NoneTaxable / ".$parity_dt.", 0) WHERE delivery_id = ".$txtID."";
					$query = "UPDATE deliveries SET delivery_taxablettcBase1 = convertcurfunc(deliveries.currency_code, (select BASE1 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_taxablettc,0)), delivery_taxablettcBase2 = convertcurfunc(deliveries.currency_code, (select BASE2 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_taxablettc,0)), delivery_taxableBase1 = convertcurfunc(deliveries.currency_code, (select BASE1 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_taxable,0)), delivery_taxableBase2 = convertcurfunc(deliveries.currency_code, (select BASE2 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_taxable,0)), delivery_discountBase1 = convertcurfunc(deliveries.currency_code, (select BASE1 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_discountamount,0)), delivery_discountBase2 = convertcurfunc(deliveries.currency_code, (select BASE2 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_discountamount,0)), delivery_vatBase1 = convertcurfunc(deliveries.currency_code, (select BASE1 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_vat,0)), delivery_vatBase2 = convertcurfunc(deliveries.currency_code, (select BASE2 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_vat,0)), delivery_total = IFNULL((delivery_taxable + Delivery_nonetaxable), 0), delivery_totalBase1 = IFNULL((delivery_taxableBase1 + Delivery_NoneTaxableBase1), 0), delivery_totalBase2 =  IFNULL((delivery_taxableBase2 + Delivery_NoneTaxableBase2), 0), Delivery_NoneTaxableBase1 = convertcurfunc(deliveries.currency_code, (select BASE1 from setup), Delivery_Date, 0, 0, '', '', ifNull(Delivery_NoneTaxable,0)), Delivery_NoneTaxableBase2 = convertcurfunc(deliveries.currency_code, (select BASE2 from setup), Delivery_Date, 0, 0, '', '', ifNull(Delivery_NoneTaxable,0)) WHERE delivery_id = ".$txtID;
					//echo "<br><br>".$query;
					if (updateIData($iconn, $query, true)){
						$message = "Item Deleted";
					}else{
						$message = "Item COULD NOT be Deleted";
					}
				}else{
					$message = "Item COULD NOT be Deleted";
				}
			//}else{
				//$message = "Item COULD NOT be Deleted";
			//}
		}else{
			$message = "Item COULD NOT be Deleted";
		}
	}else{
		$message = "Item COULD NOT be Deleted";
	}
}else if($act == "submitRecord" && $txtID != ""){
	//Get Ref
	$query = "DELETE FROM deliverydt WHERE delivery_id = '".$txtID."' AND deliverydt_quantity = 0";
	//echo "<br><br>".$query;
	if (updateIData($iconn, $query, false)){
		$query = "UPDATE deliverydt SET User_Account = '', Delivery_Date = CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)) WHERE User_Account = '".$_SESSION['userSession']."' AND delivery_id = '".$txtID."' ";
		//echo "<br><br>".$query;
		if (updateIData($iconn, $query, false)){
			//$txtRef = get_nextsequence("Dreturn_Reference" , "",$conn); - Getting Reference at End and updating later
			$query = "UPDATE deliveries SET delivery_date = CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), delivery_remark = '".ereg_replace("\'", "''", trim($txtRemark))."', Currency_Code = '".$lstCurrency."', Project_Code = '".$lstProject."', User_Account = '".$_SESSION["useraccount"]."' WHERE delivery_id = ".$txtID."";
			//echo "<br><br>".$query;
			if (updateIData($iconn, $query, false)){
				$query = "UPDATE deliverydt SET deliverydt.DeliveryDt_QuantityReturn = (deliverydt.DeliveryDt_QuantityReturn + deliverydt.deliverydt_quantity) WHERE deliverydt.delivery_id = '".$txtID."'";
				//echo "<br><br>".$query;
				if (updateIData($iconn, $query, false)){
					$query = "UPDATE Deliveries SET Delivery_totalQuantity = (SELECT SUM(deliverydt_quantity) FROM deliverydt WHERE Delivery_id = '".$txtID."'), Delivery_taxable = IFNULL((SELECT SUM(deliverydt_quantity * ((deliverydt_priceTTC*(1-deliverydt_discountPer/100))/ (1 + Item_Vat/100))) FROM deliverydt WHERE Delivery_id = '".$txtID."' AND Item_Vat > 0), 0), Delivery_taxableTTC = IFNULL((SELECT SUM(deliverydt_quantity * (deliverydt_priceTTC*(1-deliverydt_discountPer/100))) FROM deliverydt WHERE Delivery_id = '".$txtID."' AND Item_Vat > 0), 0), Delivery_nonetaxable = IFNULL((SELECT SUM(deliverydt_quantity * (deliverydt_priceTTC*(1-deliverydt_discountPer/100))) FROM deliverydt WHERE Delivery_id = '".$txtID."' AND Item_Vat = 0), 0), Delivery_vat = IFNULL((SELECT SUM(deliverydt_quantity * ((deliverydt_priceTTC*(1-deliverydt_discountPer/100)) - ((deliverydt_priceTTC*(1-deliverydt_discountPer/100))/ (1 + Item_Vat/100)))) FROM deliverydt WHERE Delivery_id = '".$txtID."'), 0), Delivery_discountamount = IFNULL((SELECT SUM(deliverydt_quantity * DeliveryDt_DiscountAmount) FROM deliverydt WHERE Delivery_id = '".$txtID."'), 0) WHERE Delivery_id = ".$txtID."";
					//echo "<br><br>".$query;
					if (updateIData($iconn, $query, false)){
						$j_id = get_nextsequence("journal_id" , "",$conn);

						//Get Records from salesetup table
						$query = "SELECT VAtaccount, creditcur, cashaccount, cashcur, tipsaccount, CreditAccount FROM salessetup";
						$salessetup_result = selectData($conn, $query);

						$query = "SELECT Client_CashMode, Client_PaymentTerms FROM clients WHERE Ledger_Number = '".$lstClient."'";
						$clients_result = selectData($conn, $query);
						$next = strtotime(substr(insertDate($txtDate), 0, 4)."-".substr(insertDate($txtDate), 4, 2)."-".substr(insertDate($txtDate), 6, 2)." + ".$clients_result[1]." Day");
						$a = getDate($next);		
						$y = $a["year"];		
						$m = $a["mon"];
						if ($m < 10){$m = "0" . $m;}
						$d = $a["mday"];
						if ($d < 10){$d = "0" . $d;}
						$clients_result[1] = $y ."-". $m ."-". $d;
						
						//$query = "UPDATE deliveries SET delivery_taxableBase1 = convertcurfunc(deliveries.currency_code, (select BASE1 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_taxable,0)), delivery_taxableBase2 = convertcurfunc(deliveries.currency_code, (select BASE2 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_taxable,0)), delivery_discountBase1 = convertcurfunc(deliveries.currency_code, (select BASE1 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_discountamount,0)), delivery_discountBase2 = convertcurfunc(deliveries.currency_code, (select BASE2 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_discountamount,0)), delivery_vatBase1 = convertcurfunc(deliveries.currency_code, (select BASE1 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_vat,0)), delivery_vatBase2 = convertcurfunc(deliveries.currency_code, (select BASE2 from setup), Delivery_Date, 0, 0, '', '', ifNull(delivery_vat,0)), delivery_total = IFNULL((delivery_taxable + Delivery_nonetaxable), 0), delivery_totalBase1 = IFNULL((delivery_taxableBase1 + Delivery_NoneTaxableBase1), 0), delivery_totalBase2 =  IFNULL((delivery_taxableBase2 + Delivery_NoneTaxableBase2), 0), Delivery_NoneTaxableBase1 = convertcurfunc(deliveries.currency_code, (select BASE1 from setup), Delivery_Date, 0, 0, '', '', ifNull(Delivery_NoneTaxable,0)), Delivery_NoneTaxableBase2 = convertcurfunc(deliveries.currency_code, (select BASE2 from setup), Delivery_Date, 0, 0, '', '', ifNull(Delivery_NoneTaxable,0)), delivery_mode = '0', delivery_cashaccount = '".$salessetup_result[2]."', delivery_cashcur = '".$salessetup_result[3]."', delivery_tipsaccount = '".$salessetup_result[4]."', JournalDt_ValueDate = CONCAT('".$clients_result[1]." ', RIGHT(NOW(), 8)), Delivery_Cash = IFNULL((delivery_total + Delivery_vat), 0), Delivery_CashBase1 = IFNULL((delivery_totalBase1 + delivery_vatBase1), 0), Delivery_CashBase2 = IFNULL((delivery_totalBase2 + delivery_vatBase2), 0),  Delivery_CashInBase1 = IFNULL(delivery_totalBase1, 0), Delivery_CashInBase2 = IFNULL(delivery_totalBase2, 0), Journal_id = '".$j_id."' WHERE delivery_id = ".$txtID;
						$query = "UPDATE deliveries SET delivery_taxableBase1 = ROUND((IFNULL(delivery_taxable, 0) / ".getBase12($conn, 1, $lstCurrency, insertMySQLDate($txtDate))."), 2), delivery_taxableBase2 = ROUND((IFNULL(delivery_taxable, 0) / ".getBase12($conn, 2, $lstCurrency, insertMySQLDate($txtDate))."), 2), delivery_discountBase1 = ROUND((IFNULL(delivery_discountamount, 0) / ".getBase12($conn, 1, $lstCurrency, insertMySQLDate($txtDate))."), 2), delivery_discountBase2 = ROUND((IFNULL(delivery_discountamount, 0) / ".getBase12($conn, 2, $lstCurrency, insertMySQLDate($txtDate))."), 2), delivery_vatBase1 = ROUND((IFNULL(delivery_vat, 0) / ".getBase12($conn, 1, $lstCurrency, insertMySQLDate($txtDate))."), 2), delivery_vatBase2 = ROUND((IFNULL(delivery_vat, 0) / ".getBase12($conn, 2, $lstCurrency, insertMySQLDate($txtDate))."), 2), Delivery_NoneTaxableBase1 = ROUND((IFNULL(Delivery_NoneTaxable, 0) / ".getBase12($conn, 1, $lstCurrency, insertMySQLDate($txtDate))."), 2), Delivery_NoneTaxableBase2 = ROUND((IFNULL(Delivery_NoneTaxable, 0) / ".getBase12($conn, 2, $lstCurrency, insertMySQLDate($txtDate))."), 2), delivery_total = IFNULL((delivery_taxable + Delivery_nonetaxable), 0), delivery_totalBase1 = IFNULL((delivery_taxableBase1 + Delivery_NoneTaxableBase1), 0), delivery_totalBase2 =  IFNULL((delivery_taxableBase2 + Delivery_NoneTaxableBase2), 0), delivery_mode = '0', delivery_creditcur = '".$lstCurrency."', delivery_cashaccount = '".$salessetup_result[2]."', delivery_cashcur = '".$salessetup_result[3]."', delivery_tipsaccount = '".$salessetup_result[4]."', JournalDt_ValueDate = CONCAT('".$clients_result[1]." ', RIGHT(NOW(), 8)), Delivery_Cash = IFNULL((delivery_total + Delivery_vat), 0), Delivery_CashBase1 = IFNULL((delivery_totalBase1 + delivery_vatBase1), 0), Delivery_CashBase2 = IFNULL((delivery_totalBase2 + delivery_vatBase2), 0),  Delivery_CashInBase1 = IFNULL(delivery_totalBase1, 0), Delivery_CashInBase2 = IFNULL(delivery_totalBase2, 0), Journal_id = '".$j_id."' WHERE delivery_id = ".$txtID;
						//echo "<br><br>".$query;
						if (updateIData($iconn, $query, false)){
							//Add JV							
							$query = "INSERT INTO journal (journal_id, journal_refgovernment, journal_folio, journal_type, journal_flag, User_account, User_Name, Journal_Date, Journal_SysDate, Journal_Time, Project_Code, Journal_dtincr, Journal_typeref, Amnt1_db, Amnt1_cd, Amnt2_db, Amnt2_cd) VALUES (".$j_id.", ".get_nextsequence("journal_refgovernment" , "",$conn).", '".jFolio($conn)."', 'SR', 'N', '".$_SESSION["useraccount"]."', '', CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), '".$lstProject."', 3, 'SI".addZero(get_nextsequence("SReturn_TypeRef" , "",$conn), 8)."', convertcurfunc('".$lstCurrency."', (select BASE1 from setup), CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), 0, 0, '', '', ifNull((SELECT SUM(deliverydt_quantity * (deliverydt_priceTTC*(1-deliverydt_discountPer/100))) FROM deliverydt WHERE Delivery_id = '".$txtID."' AND Item_Vat > 0),0)), Amnt1_db, convertcurfunc('".$lstCurrency."', (select BASE2 from setup), CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), 0, 0, '', '', ifNull((SELECT SUM(deliverydt_quantity * (deliverydt_priceTTC*(1-deliverydt_discountPer/100))) FROM deliverydt WHERE Delivery_id = '".$txtID."' AND Item_Vat > 0),0)), Amnt2_db)";
							//echo "<br><br>".$query;
							if (updateIData($iconn, $query, false)){
								//Add JV - Client
								$query = "INSERT INTO journaldt (journaldt_id, journal_id, Ledger_Number, Document, Currency_Code, Journaldt_DBCD, Journaldt_dbcdAra, Journaldt_Desc, Journal_date, Journaldt_valuedate, Journaldt_Amount, Journaldt_Amount1, Journaldt_Amount2) VALUES (".(($j_id*1000000)+1).", ".$j_id.", '".$lstClient."', '".$lstClient."', '".$lstCurrency."', 'C', '?', 'Return Sale:".$txtRef." ".ereg_replace("\'", "''", trim($txtRemark))."', CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), Journal_date, IFNULL((SELECT SUM(deliverydt_quantity * (deliverydt_priceTTC*(1-deliverydt_discountPer/100))) FROM deliverydt WHERE Delivery_id = '".$txtID."'), 0), convertcurfunc(Currency_Code, (select BASE1 from setup), Journal_date, 0, 0, '', '', Journaldt_Amount), convertcurfunc(Currency_Code, (select BASE2 from setup), Journal_date, 0, 0, '', '', Journaldt_Amount))";
								//echo "<br><br>".$query;
								if (updateIData($iconn, $query, false)){
									//Add JV - Sales
									$query = "INSERT INTO journaldt (journaldt_id, journal_id, Ledger_Number, Document, Currency_Code, Journaldt_DBCD, Journaldt_dbcdAra, Journaldt_Desc, Journal_date, Journaldt_valuedate, Journaldt_Amount, Journaldt_Amount1, Journaldt_Amount2) VALUES (".(($j_id*1000000)+2).", ".$j_id.", '".$salessetup_result[5]."', '".$salessetup_result[5]."', '".$lstCurrency."', 'D', '?', 'Return Sale:".$txtRef." ".ereg_replace("\'", "''", trim($txtRemark))."', CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), Journal_date, IFNULL((SELECT SUM(deliverydt_quantity * (deliverydt_price*(1-deliverydt_discountPer/100))) FROM deliverydt WHERE Delivery_id = '".$txtID."'), 0), convertcurfunc(Currency_Code, (select BASE1 from setup), Journal_date, 0, 0, '', '', Journaldt_Amount), convertcurfunc(Currency_Code, (select BASE2 from setup), Journal_date, 0, 0, '', '', Journaldt_Amount))";
									//echo "<br><br>".$query;
									if (updateIData($iconn, $query, false)){
										//Add JV - VAT
										$query = "INSERT INTO journaldt (journaldt_id, journal_id, Ledger_Number, Document, Currency_Code, Journaldt_DBCD, Journaldt_dbcdAra, Journaldt_Desc, Journal_date, Journaldt_valuedate, Journaldt_Amount, Journaldt_Amount1, Journaldt_Amount2) VALUES (".(($j_id*1000000)+3).", ".$j_id.", '".$salessetup_result[0]."', '".$salessetup_result[0]."', '".$lstCurrency."', 'D', '?', 'Return Sale:".$txtRef." ".ereg_replace("\'", "''", trim($txtRemark))."', CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), Journal_date, IFNULL((SELECT SUM(deliverydt_quantity * ((deliverydt_priceTTC*(1-deliverydt_discountPer/100)) - (deliverydt_price*(1-deliverydt_discountPer/100)))) FROM deliverydt WHERE Delivery_id = '".$txtID."'), 0), convertcurfunc(Currency_Code, (select BASE1 from setup), Journal_date, 0, 0, '', '', Journaldt_Amount), convertcurfunc(Currency_Code, (select BASE2 from setup), Journal_date, 0, 0, '', '', Journaldt_Amount))";
										//echo "<br><br>".$query;
										if (updateIData($iconn, $query, false)){
											$query = "INSERT INTO cstjour (Project_code, Cstjour_prcnt, CstJour_Amount, CstJour_Amount1, CstJour_Amount2, journaldt_id) VALUES ('".$lstProject."', '100', IFNULL((SELECT SUM(deliverydt_quantity * (deliverydt_priceTTC*(1-deliverydt_discountPer/100))) FROM deliverydt WHERE Delivery_id = '".$txtID."'), 0), convertcurfunc('".$lstCurrency."', (select BASE1 from setup), CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), 0, 0, '', '', CstJour_Amount), convertcurfunc('".$lstCurrency."', (select BASE2 from setup), CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), 0, 0, '', '', CstJour_Amount), '".(($j_id*1000000)+1)."')";
											if (updateIData($iconn, $query, false)){
												$query = "INSERT INTO cstjour (Project_code, Cstjour_prcnt, CstJour_Amount, CstJour_Amount1, CstJour_Amount2, journaldt_id) VALUES ('".$lstProject."', '100', IFNULL((SELECT SUM(deliverydt_quantity * (deliverydt_price*(1-deliverydt_discountPer/100))) FROM deliverydt WHERE Delivery_id = '".$txtID."'), 0), convertcurfunc('".$lstCurrency."', (select BASE1 from setup), CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), 0, 0, '', '', CstJour_Amount), convertcurfunc('".$lstCurrency."', (select BASE2 from setup), CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), 0, 0, '', '', CstJour_Amount), '".(($j_id*1000000)+2)."')";
												if (updateIData($iconn, $query, false)){
													$query = "INSERT INTO cstjour (Project_code, Cstjour_prcnt, CstJour_Amount, CstJour_Amount1, CstJour_Amount2, journaldt_id) VALUES ('".$lstProject."', '100', IFNULL((SELECT SUM(deliverydt_quantity * ((deliverydt_priceTTC*(1-deliverydt_discountPer/100)) - (deliverydt_price*(1-deliverydt_discountPer/100)))) FROM deliverydt WHERE Delivery_id = '".$txtID."'), 0), convertcurfunc('".$lstCurrency."', (select BASE1 from setup), CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), 0, 0, '', '', CstJour_Amount), convertcurfunc('".$lstCurrency."', (select BASE2 from setup), CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), 0, 0, '', '', CstJour_Amount), '".(($j_id*1000000)+3)."')";
													if (updateIData($iconn, $query, false)){
														//Delete JV with Zero Value
														$query = "DELETE FROM journaldt WHERE Journaldt_Amount = 0 AND journal_id = '".$j_id."'";
														if (updateIData($iconn, $query, false)){
															$query = "DELETE FROM journal WHERE Amnt1_db = 0 AND journal_id = '".$j_id."'";
															if (updateIData($iconn, $query, false)){
																$commit_flag = true;
																$query = "SELECT Serial_Id FROM purchasesserialno WHERE journal_type='DI' and serialno_code IN (SELECT serialno_code FROM purchasesserialno WHERE journal_type='DR' AND PurchaseDt_ID IN (SELECT deliverydt_id FROM deliverydt WHERE delivery_id IN (SELECT delivery_id FROM deliveries WHERE journal_type='DR' AND delivery_id='".$txtID."'))) ";
																$result = mysql_query($query, $conn);
																while ($cur = mysql_fetch_row($result)){
																	$query = "UPDATE purchasesserialno SET flagunique = Serial_Id WHERE Serial_Id = '".$cur[0]."'";
																	if (updateIData($iconn, $query, false)){
																		//Do Nothing
																	}else{
																		$commit_flag = false;
																	}
																}						
																if ($commit_flag){
																	$txtRef = get_nextsequence("Dreturn_Reference" , "",$conn);
																	$query = "UPDATE journaldt SET Journaldt_Desc = 'Return Sale:- ".$txtRef." ".ereg_replace("\'", "''", trim($txtRemark))."' WHERE journaldt_id = '".(($j_id*1000000)+1)."' OR journaldt_id = '".(($j_id*1000000)+2)."' OR journaldt_id = '".(($j_id*1000000)+3)."' ";
																	if (updateIData($iconn, $query, false)){
																		$query = "UPDATE deliveries SET delivery_reference = '".$txtRef."' WHERE Delivery_id = '".$txtID."' ";
																		if (updateIData($iconn, $query, false)){																		
																			mysqli_commit($iconn);
																			$act = "viewRecord";
																			$message = "Record Added";
																			header("Location: salesreturn_form.php?act=viewRecord&message=".$message."&txtRef=".$txtRef."&txtID=".$txtID);
																		}else{
																			$commit_flag = false;
																			$message = "Record COULD NOT be Added [Waybill Reference No NOT Updated]";
																		}
																	}else{
																		$commit_flag = false;
																		$message = "Record COULD NOT be Added [Waybill Reference No NOT Updated on Journals]";
																	}																	
																}else{
																	$message = "Record COULD NOT be Added [FlagUnique NOT Updated]";
																}
															}else{
																$message = "Record COULD NOT be Added [JV with ZERO value NOT Deleted]";
															}
														}else{
															$message = "Record COULD NOT be Added [JV with ZERO value NOT Deleted]";															
														}
													}else{
														$message = "Record COULD NOT be Added [VAT CSTJOUR NOT Created]";
													}
												}else{
													$message = "Record COULD NOT be Added [Sales CSTJOUR NOT Created]";
												}
											}else{
												$message = "Record COULD NOT be Added [Client CSTJOUR NOT Created]";
											}											
										}else{
											$message = "Record COULD NOT be Added [VAT JV NOT Created]";
										}
									}else{
										$message = "Record COULD NOT be Added [Sales JV NOT Created]";
									}
								}else{
									$message = "Record COULD NOT be Added [Client JV NOT Created]";
								}
							}else{
								$message = "Record COULD NOT be Added [JV NOT Created]";
							}		
						}else{
							$message = "Record COULD NOT be Added [Delivery Accounts NOT Updated]";
						}
					}else{
						$message = "Record COULD NOT be Added [Delivery Amounts NOT Updated]";
					}
				}else{
					$message = "Record COULD NOT be Added [Sales Order NOT Updated]";
				}
			}else{
				$message = "Record COULD NOT be Added [Delivery Remarks NOT Updated]";
			}
		}else{
			$message = "Record COULD NOT be Added";
		}
	}else{
		$message = "Record COULD NOT be Added";
	}						
}else if ($act == "clearPage"){
	clearPage($iconn, $_SESSION['userSession'], "Sales");	
}

if($act == "viewRecord"){
	$query = "SELECT delivery_id, delivery_date, delivery_remark, Client_Code,  Currency_Code, Costcent_code, Project_Code, Salesman_code, delivery_returnref, Delivery_Marks, Delivery_ShippedVia, delivery_shippedto, delivery_discountamount FROM deliveries WHERE delivery_id = ".$txtID;	
	//echo $query;
	$result = selectData($conn, $query);
	$txtDate = displayDate(insertParadoxDate($result[1]));	
	$txtRemark = $result[2];
	$lstClient = $result[3];
	$lstCurrency = $result[4];
	$lstCostCentre = $result[5];
	$lstProject = $result[6];
	$lstSalesman = $result[7];
	$txtSRef = $result[8];
	//$txtVehicleNumber = $result[9];
	//$txtDriverName = $result[10];	
	$txtDAddress = $result[11];
	$txtDiscountTotal = $result[12];
}

?>

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

function focusOnSerial(){
	if (document.getElementById("txtSearchSerialNumber")){
		document.getElementById("txtSearchSerialNumber").focus();
	}
}

function deleteItem(a){
	x = document.frm1;
	if (confirm('Delete this Item')){
		x.act.value = 'deleteItem';
		x.txtDeleteItemCode.value = a;
		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{
		window.open('Return_Sales_Child.php?txtID='+x.txtID.value+'&txtSRef='+x.txtSRef.value+'&txtRef='+x.txtRef.value+'&user_level_sales='+x.user_level_sales.value, 'Sales_Child', 'toolbar=no,location=no,status=no,menu bar=no,scrollbars=yes,resizable=yes,width='+screen.availWidth+ ',height='+screen.availHeight+',left='+screen.availLeft+',top='+screen.availLeft);		
		win.creator = self;
		win.focus();		
		win.onunload = function() {
			window.location.href = 'salesreturn_form.php?act=viewRecord&txtSID='+x.txtSID.value+'&txtSRef='+x.txtSRef.value+'&txtID='+x.txtID.value+'&txtRef='+x.txtRef.value+'&user_level_sales='+x.user_level_sales.value;
		}
		
	}
}

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';
		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';
		x.submit();
		//win = window.open('Return_Sales_Child.php?txtID='+x.txtID.value+'&txtSRef='+x.txtSRef.value+'&txtRef='+x.txtRef.value+'&user_level_sales='+x.user_level_sales.value, 'Sales_Child', 'toolbar=no,menubar=no,scrollbars=yes,resize=yes,maximize=no,location=no,height=600,width=800');
		//win.close();
	}
}

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 searchPage(){
	x = document.frm1;
	if (x.lstClient.value == "" && x.txtSearchRef.value == "" && x.lstProject.value == "" && x.lstSalesman.value == ""){
		alert('Please Select Client/Project/Salesman OR Enter Ref No');
		x.txtSearchRef.focus();
	}else{
		x.act.value = 'searchPage';
		x.txtRef.value = '';
		x.submit();
	}
}

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

function searchRPage(){
	x = document.frm1;
	if (x.lstClient.value == "" && x.txtSearchRef.value == "" && x.lstProject.value == "" && x.lstSalesman.value == ""){
		alert('Please Select Client/Project/Salesman OR Enter Ref No');
		x.txtSearchRef.focus();
	}else{
		x.act.value = 'searchRPage';
		x.txtRef.value = '';
		x.submit();
	}
}

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

function printWPage(a, b){
	//win = window.open('Return_Sales_Child.php?prints=yes&act=viewRecord&txtID='+a+'&txtRef='+b, '', 'toolbar=no,menubar=no,scrollbars=yes,resize=yes,maximize=yes,location=no,height=768,width=1024'); 
	window.open('Return_Sales_Child.php?prints=yes&act=viewRecord&txtID='+a+'&txtRef='+b);
}
</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();'>";
		print "<body onLoad='window.print();'>";
	}else{
		print "<body onLoad='javascipt:focusOnSerial()'>";
	}
?>
<form id="frm1" name="frm1" method="post" action="salesreturn_form.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'><font size="4">
	  <?php
		if ($prints == "yes"){
			print "RETURN INVOICE# ".$txtRef;
		}else{
			print "RETURN INVOICE";
		}
	  ?>	  
	  </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>    
		<?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>";
			
			if ($prints != "yes"){
				print "<tr bgcolor='#F7F7F7'>";
				print "<input type='hidden' name='user_level_sales' value='".$user_level_sales."'>";			
				displayTextbox("txtRef", "Return Invoice Reference", $txtRef, "yes", "", "15%", "35%");
				print "<input type='hidden' name='txtID' value='".$txtID."'>";	
				displayTextbox("txtSRef", "Invoice/Waybill Ref", $txtSRef, "yes", "", "15%", "35%");
				print "<input type='hidden' name='txtSID' value='".$txtSID."'>";
				print "</tr>";
			}
		?>    
    <tr bgcolor="#F7F7F7">
		<?php
			$query = "SELECT Ledger_number, CONCAT(Ledger_name, ' - ', Ledger_number) FROM Clients ORDER BY Ledger_name";
			if ($lstClient != "" && $txtID != "" && $act != "searchPage"){
				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%");
			print "<input type='hidden' name='txtRequestDate' value='".$txtRequestDate."'>";
			if ($lstClient != "" && ($txtCreditLimit == "" || $lstSalesman == "" || $txtIAddress == "" || $txtDAddress == "")){
				$query = "SELECT Client_CreditLimit, Salesmen_Code, Client_Address FROM Clients WHERE Ledger_Number = '".$lstClient."'";
				$result = selectData($conn, $query);
				if ($txtCreditLimit == ""){$txtCreditLimit = $result[0];}
				if ($lstSalesman == ""){$lstSalesman = $result[1];}
				if ($txtIAddress == ""){$txtIAddress = $result[2];}
				if ($txtDAddress == ""){$txtDAddress = $txtIAddress;}
			}
			displayTextbox("txtDate", "Date", $txtDate, $prints, "10", "15%", "35%");
		?>		
	</tr>
    <tr bgcolor="#F7F7F7">
		<?php
			if ($prints != "yes"){
				$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%");
				}
				
				displayTextbox("txtCreditLimitDisplay", "Credit Limit", addComma($txtCreditLimit), "yes", "", "15%", "35%");				
				print "<input type='hidden' name='txtCreditLimit' value='".$txtCreditLimit."'>";
			}				
		?>
	</tr>
	<?php
		if ($prints != "yes"){
			print "<tr bgcolor='#F7F7F7'>";			
			//$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'>";
			$query = "SELECT ".$_SESSION['defaultdb'].".project.project_code, CONCAT(".$_SESSION['defaultdb'].".project.project_name, ' - ', ".$_SESSION['defaultdb'].".project.project_code) FROM ".$_SESSION['defaultdb'].".project WHERE ".$_SESSION['defaultdb'].".project.project_code is NOT NULL ".$projectQuery." ORDER BY ".$_SESSION['defaultdb'].".project.project_name";
			//echo $query;
			if ($lstProject != "" && $act != "searchPage" && $act != ""){
				displayList("lstProject", "Project", $lstProject, "yes", $conn, $query, "", "15%", "35%");
			}else{
				displayList("lstProject", "Project", $lstProject, $prints, $conn, $query, "", "15%", "35%");
			}
			if ($prints != "yes"){
				//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 delivery_taxableBase1 FROM deliveries WHERE delivery_id = '".$txtID."'";
				//echo "<br><br>".$query;
				$result = selectData($conn, $query);
				$q3 = $result[0];
				if (is_numeric($q3)){
					//Do Nothing
				}else{
					$q3 = 0;
				}
				print "<td colspan='2'><span class='style4'>&nbsp;</span></td>";
				//displayTextbox("txtCurBal", "Current Bal", addComma($txtCreditLimit*1 - $q2 - $q1 + $q3), "yes", "", "15%", "35%");				
			}else{
				print "<td colspan='2'><span class='style4'>&nbsp;</span></td>";
			}
			print "</tr>";
		}
	?>	
	<tr bgcolor="#F7F7F7">
		<?php
			displayTextbox("txtRemark", "Remark", $txtRemark, $prints, "", "15%", "35%");
			$query = "SELECT Ledger_number, CONCAT(Ledger_name, ' - ', Ledger_number) FROM Salesmen ORDER BY Ledger_name";
			if (($lstSalesman != "" || $txtRef != "") && $act != "searchPage"){
				displayList("lstSalesman", "Salesman", $lstSalesman, "yes", $conn, $query, "", "15%", "35%");
			}else{
				displayList("lstSalesman", "Salesman", $lstSalesman, $prints, $conn, $query, "", "15%", "35%");
			}			
		?>	
    </tr>	
    <tr bgcolor="#F7F7F7">
		<?php
			displayTextarea("txtIAddress", "Invoice Address", $txtIAddress, "yes", 5, 40, "15%", "35%");
			displayTextarea("txtDAddress", "Delivery Address", $txtDAddress, "yes", 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>
	<?php
		if ($prints != "yes" && (strpos($user_level_sales, "-SOE-") !== false || strpos($user_level_sales, "-SOA-") !== false) && $txtRef == "" && $txtID != ""){
			print "<tr> <td bgcolor='#E0E0E0'>&nbsp;</td> <td bgcolor='#E0E0E0' colspan='3'>";
			print "<input type='button' onclick='javascript:openWindow()' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; width=100px;' title='Add Serial Nos' value='Add Serial Nos'/>&nbsp;";				
			//print "<input name='clearPage' type='button' id='clearPage' onclick=javascript:window.location.href='salesreturn_form.php' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;' title='Clear Page' value='Clear Page'/>&nbsp;";
			print "</td>	</tr>";
		}
	?>		
</table>
<?php
$tot_qty = 0;
$order_qty = 0;
//$tot_discount = 0;
$tot_ttc = 0;
$tot_price = 0;
$sno_flag = true;
if ($txtID != ""){
	$query = "SELECT Client_SellingPrice FROM Clients WHERE Ledger_Number = '".$lstClient."'";
	//echo "<br><br>".$query;
	$result = selectData($conn, $query);
	$c_sp = $result[0];

	print "<table width='100%' border='1' cellspacing='-1' cellpadding='-1'>";
	if ($prints != "yes"){
		print "<tr><td class='style3' colspan='8'><b>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>";
	}else{
		print "<tr><td class='style3' colspan='7'><b>Item List:</b></td> </tr>";
		print "<tr><td bgcolor='#E0E0E0' class='style3'>&nbsp;</td> <td bgcolor='#E0E0E0' class='style3'>Item Code - Desc</td>";
	}	
	print "<td bgcolor='#E0E0E0' class='style3'>Warehouse</td>";
	if ($prints != "yes"){
		//print "<td bgcolor='#E0E0E0' class='style3'>Order Qty</td>";
		print "<td bgcolor='#E0E0E0' class='style3'>Return Qty</td>";
	}else{
		print "<td bgcolor='#E0E0E0' class='style3'>Return Qty</td>";
	}
	print "<td bgcolor='#E0E0E0' class='style3'>TTC</td> <td bgcolor='#E0E0E0' class='style3'>Discount</td> <td bgcolor='#E0E0E0' class='style3'>TTC Total</td> </tr>";
	if ($txtRef == ""){	
		$query = "SELECT deliverydt.deliverydt_id, deliverydt.delivery_id, deliverydt.item_code, deliverydt.deliverydt_quantity, '', deliverydt.deliverydt_price, deliverydt.deliverydt_discountamount, deliverydt.warehouse_code, deliverydt.Currency_Code, deliverydt.Item_Vat, deliverydt.deliverydt_priceTTC, deliverydt.Item_QtyPacked, deliverydt.deliverydt_posted, '', items.item_description, warehouse.warehouse_name, DeliveryDt_QuantityReturn, deliverydt.DeliveryDt_DiscountPer FROM deliverydt, items, warehouse WHERE deliverydt.item_code = items.item_code AND deliverydt.warehouse_code = warehouse.warehouse_code AND User_Account = '".$_SESSION['userSession']."' AND deliverydt.journal_type = 'DR' ";
	}else{	
		$query = "SELECT deliverydt.deliverydt_id, deliverydt.delivery_id, deliverydt.item_code, deliverydt.deliverydt_quantity, '', deliverydt.deliverydt_price, deliverydt.deliverydt_discountamount, deliverydt.warehouse_code, deliverydt.Currency_Code, deliverydt.Item_Vat, deliverydt.deliverydt_priceTTC, deliverydt.Item_QtyPacked, deliverydt.deliverydt_posted, '', items.item_description, warehouse.warehouse_name, DeliveryDt_QuantityReturn, deliverydt.DeliveryDt_DiscountPer, DeliveryDt_Price FROM deliverydt, items, warehouse, deliveries WHERE deliverydt.delivery_id = deliveries.delivery_id AND deliverydt.item_code = items.item_code AND deliverydt.warehouse_code = warehouse.warehouse_code AND deliveries.delivery_reference = '".$txtRef."' AND deliveries.journal_type = 'DR' ";
	}
	//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_sales, "-SOE-") !== false && $txtRef == ""){
			print "<a href='#' onClick='javascript:deleteItem(".$cur[0].")'>Delete</a>";
		}else{
			print "&nbsp;";
		}
		if ($prints == "yes"){
			print "</td> <td class='style4'>".$cur[2]." - ".$cur[14]."</td> <td class='style4'>".str_replace("WAREHOUSE", "", $cur[15])."</td>";
		}else{
			print "</td> <td class='style4'>".$cur[2]."</td> <td class='style4'>".$cur[14]."</td> <td class='style4'>".str_replace("WAREHOUSE", "", $cur[15])."</td>";
		}
		/*
		if ($prints != "yes"){
			print "<td class='style4'>".addComma($cur[16])."</td>";
		}
		*/
		print "<td class='style4'>".addComma($cur[3])."</td>";
		print "<td class='style4'>".addComma($cur[10])."</td> <td class='style4'>".addComma($cur[17])."%</td> <td class='style4'>".addComma(($cur[10] - ($cur[10]*$cur[17]/100)) * $cur[3])."</td>";
		/*
		if ($c_sp == "II"){
			print "<td class='style4'>".addComma($cur[18] - $cur[6] - ($cur[18]*$cur[17]/100))."</td> <td class='style4'>".addComma(($cur[18] - $cur[6] - ($cur[18]*$cur[17]/100)) * $cur[3])."</td>";
		}else{
			print "<td class='style4'>".addComma($cur[10] - $cur[6] - ($cur[10]*$cur[17]/100))."</td> <td class='style4'>".addComma(($cur[10] - $cur[6] - ($cur[10]*$cur[17]/100)) * $cur[3])."</td>";			
		}
		*/
		print "</tr>";
		$order_qty = $order_qty + $cur[16];
		$tot_qty = $tot_qty + $cur[3];
		//$tot_price = $tot_price + (($cur[18] - $cur[6] - ($cur[18]*$cur[17]/100)) *$cur[3]);
		//$tot_ttc = $tot_ttc + (($cur[10] - $cur[6] - ($cur[10]*$cur[17]/100)) *$cur[3]);
		$tot_ttc = $tot_ttc + (($cur[10] - ($cur[10]*$cur[17]/100)) *$cur[3]);
		$tot_price = $tot_ttc;
		//$tot_discount = $tot_discount + $cur[6];		
		//$sno_flag = getSNoFlag($conn, $sno_flag, $cur[0], $cur[3]);
		$sno_flag = getQtyFlag($conn, $sno_flag, $cur[0], $cur[3]);
	}
	if ($c_sp == "II"){
		print "<tr><td bgcolor='#FFFFFF' class='style3'>&nbsp;</td>";
		if ($prints != "yes"){
			print "<td bgcolor='#FFFFFF' class='style3'>&nbsp;</td>";
		}
		print "<td bgcolor='#FFFFFF' class='style3'>&nbsp;</td> <td bgcolor='#FFFFFF' class='style3'>&nbsp;</td>";
		if ($prints != "yes"){
			print "<td bgcolor='#FFFFFF' class='style3'>&nbsp;</td>";
		}
		print "<td bgcolor='#FFFFFF' class='style3'>&nbsp;</td> <td bgcolor='#E0E0E0' class='style3'>VAT</td> <td bgcolor='#E0E0E0' class='style3'>";
		if (($tot_ttc - $tot_price - $txtDiscountTotal) > 0){
			print addComma($tot_ttc - $tot_price - $txtDiscountTotal);
		}else{
			print addComma($tot_ttc);
		}
		print "</td> </tr>";
	}
	print "<tr><td bgcolor='#E0E0E0' class='style3'>&nbsp;</td>";
	if ($prints != "yes"){
		print "<td bgcolor='#E0E0E0' class='style3'>&nbsp;</td>";
	}
	print "<td bgcolor='#E0E0E0' class='style3'>&nbsp;</td> <td bgcolor='#E0E0E0' class='style3'>Totals</td>";
	/*
	if ($prints != "yes"){
		print "<td bgcolor='#E0E0E0' class='style3'>".addComma($order_qty)."</td>";
	}
	*/
	print "<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'>";
	print addComma($tot_ttc);
	/*
	if (($tot_ttc - $txtDiscountTotal) > 0){
		print addComma($tot_ttc - $txtDiscountTotal);
	}else{
		print addComma($tot_ttc);
	}
	*/
	print "</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_sales, "-SOA-") !== false){
				//echo "########".$tot_qty;
				//New Record
				//if ($sno_flag){
					print "<input type='button' onclick='javascript:submitRecord()' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; width=90px;' title='Post Record' value='Post Record'/>&nbsp;";
				//}else{
					//print "<input type='button' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;' title='Incomplete Serial Numbers. Cannot Post Record' value='Incomplete SNo' disabled/>&nbsp;";
				//}
			}
		}else if ($txtRef != ""){
			//if ($prints != "yes" && strpos($user_level_sales, "-SOE-") !== false){
				//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" && strpos($user_level_sales, "-SOC-") !== false){
				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_sales, "-SOD-") !== false){
				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;";
			}
			*/
		}
		if ($prints != "yes"){
			if ($txtRef != ""){
				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; width=140px;' title='Print Return Invoice' value='Print Return Invoice'/>&nbsp;";
				print "<input type='button' onclick='javascript:printWPage(".$txtID.", ".$txtRef.")' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; width=150px;' title='Print Waybill' value='Print Return Waybill'/>&nbsp;";
			}
			print "<input name='clearPage' type='button' id='clearPage' onclick=javascript:window.location.href='salesreturn_form.php?act=clearPage' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; width:80px;' title='Clear Page' value='Clear Page'/>&nbsp;";
			
			if ($act == "searchPage" || $act == "searchRPage" || $act == "clearPage" || $act == ""){
				print "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font face='Verdana' size='2'>Ref No:</font><input name='txtSearchRef' size='5' value='".$txtSearchRef."'>&nbsp;&nbsp;<input type='button' onclick='javascript:searchPage()' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;width=120px;' title='Search Invoice' value='Search Invoice'/>&nbsp;&nbsp;<input type='button' onclick='javascript:searchRPage()' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;width=150px;' title='Search Return Invoice' value='Search Return Invoice'/>&nbsp;";
			}
		}
	print "</td>";
print "</tr>";
print "<tr>".
	"<td width='15%' bgcolor='#E0E0E0'>&nbsp;</td>".
	"<td width='85%' bgcolor='#E0E0E0' colspan='3'>";		
		if ($act == "searchPage" || $act == "searchRPage" || $act == "clearPage" || $act == ""){
			print "<font face='Verdana' size='2'>Serial No:</font><input id='txtSearchSerialNumber' name='txtSearchSerialNumber' size='30' value='".$txtSearchSerialNumber."'>&nbsp;&nbsp;<input type='submit' onclick='javascript:searchSerialNumber()' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;width=150px;' title='Search Serial Number' value='Search Serial Number'/>";
		}
	print "</td>";
print "</tr>";
print "</table>";

if ($act == "searchSerialNumber" && $_POST["txtSearchSerialNumber"] != ""){
	clearPage($iconn, $_SESSION['userSession'], "Sales");	
	$query = "SELECT deliveries.Delivery_Id, deliveries.Delivery_Reference FROM purchasesserialno, deliveries, deliverydt WHERE purchasesserialno.SerialNo_Code = '".$_POST["txtSearchSerialNumber"]."' AND purchasesserialno.Journal_Type = 'DI' AND purchasesserialno.flagunique = 0 AND purchasesserialno.PurchaseDt_ID = deliverydt.deliverydt_id AND deliveries.delivery_id = deliverydt.delivery_id ORDER BY purchasesserialno.Serial_ID DESC ";
	$result = selectData($conn, $query);
	//echo $query;
	if ($result[1] != ""){
		header("Location: salesreturn_form.php?act=viewSRecord&txtSRef=".$result[1]."&txtSID=".$result[0]);
	}else{
		header("Location: salesreturn_form.php?message=Serial Number NOT Found");
	}	
}else if ($act == "searchPage" || $act == "searchRPage"){	
	clearPage($iconn, $_SESSION['userSession'], "Sales");	
	if ($act == "searchPage"){
		print "Invoice List";
	}else{
		print "Return Invoice List";
	}
	print "<table width='100%'>";	
		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</td> </tr>";
		$query = "SELECT ".$_SESSION['defaultdb'].".deliveries.delivery_id, ".$_SESSION['defaultdb'].".deliveries.delivery_reference, ".$_SESSION['defaultdb'].".deliveries.delivery_date, ".$_SESSION['defaultdb'].".Clients.Ledger_name, ".$_SESSION['defaultdb'].".project.project_name, ".$_SESSION['defaultdb'].".Salesmen.Ledger_name, ".$_SESSION['defaultdb'].".deliveries.delivery_remark, ".$_SESSION['defaultdb'].".deliveries.Delivery_Total FROM ".$_SESSION['defaultdb'].".deliveries, ".$_SESSION['defaultdb'].".Clients, ".$_SESSION['defaultdb'].".Project, ".$_SESSION['defaultdb'].".Salesmen WHERE ".$_SESSION['defaultdb'].".deliveries.Client_code = ".$_SESSION['defaultdb'].".Clients.Ledger_number AND ".$_SESSION['defaultdb'].".deliveries.Project_code = ".$_SESSION['defaultdb'].".project.Project_code AND ".$_SESSION['defaultdb'].".deliveries.Salesman_code = ".$_SESSION['defaultdb'].".salesmen.Ledger_number AND LENGTH(".$_SESSION['defaultdb'].".deliveries.delivery_reference) > 0 ".$projectQuery." ";
		if ($act == "searchPage"){
			$query .= " AND ".$_SESSION['defaultdb'].".deliveries.Journal_Type = 'DI' ";
		}if ($act == "searchRPage"){
			$query .= " AND ".$_SESSION['defaultdb'].".deliveries.Journal_Type = 'DR' ";
		}
		if ($txtSearchRef != ""){
			$query = $query . " AND ".$_SESSION['defaultdb'].".deliveries.delivery_reference = '".$txtSearchRef."' ";
		}
		if ($lstClient != ""){
			$query = $query . " AND ".$_SESSION['defaultdb'].".Clients.Ledger_number = '".$lstClient."' ";
		}
		if ($lstProject != ""){
			$query = $query . " AND ".$_SESSION['defaultdb'].".Project.Project_code = '".$lstProject."' ";
		}
		if ($lstSalesman != ""){
			$query = $query . " AND ".$_SESSION['defaultdb'].".salesmen.Ledger_number = '".$lstSalesman."' ";
		}
		/*
		if ($txtDate != ""){
			$query = $query . " AND deliveries.delivery_date = '".displayParadoxDate(insertDate($txtDate))."' ";
		}
		*/
		if ($txtRemark != ""){
			$query = $query . " AND ".$_SESSION['defaultdb'].".deliveries.delivery_remark = '".$txtRemark."' ";
		}
		//$query = $query . " ORDER BY deliveries.delivery_date DESC, deliveries.delivery_reference DESC ";
		$query = $query . " ORDER BY ".$_SESSION['defaultdb'].".deliveries.delivery_reference DESC ";
	
	//echo $query;
	$result = mysql_query($query, $conn);
	$sid = "";
	while ($cur = mysql_fetch_row($result)){
		if ($sid != $cur[0]){
			if ($act == "searchPage"){
				//$sub_query = "SELECT SUM(deliverydt_quantity) FROM deliverydt WHERE deliverydt.RelatedDt_Id = '".$cur[9]."'";
				//$sub_query = "SELECT SUM(deliverydt_quantity) FROM deliverydt, deliveries WHERE deliveries.delivery_id = deliverydt.delivery_id AND deliveries.delivery_returnref = '".$cur[1]."'";
				//$sub_result = selectData($conn, $sub_query);
				//echo "<br><br>".$sub_query;				
				//if ($sub_result[0] == "" || $sub_result[0]*1 < $cur[8]*1){
				//if (is_numeric($cur[9]) && $cur[8]*1 > $cur[9]*1){
					print "<tr><td bgcolor='#E0E0E0' class='style4'><a href='salesreturn_form.php?act=viewSRecord&txtSRef=".$cur[1]."&txtSID=".$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>";
				//}
			}else{
				print "<tr><td bgcolor='#E0E0E0' class='style4'><a href='salesreturn_form.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>";	
			}
		}
		$sid = $cur[0];
	}
	print "</table>";
}

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