<?php

session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}

include("config.inc.php");
include("function.inc.php");
include("Functions_Synchro.php");




$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}

$perpage=$_POST['perpage'];
//User Access
$querylog=" select ifNull(login_belongstogrp,0) As FI_BelongsToGrp from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

//Read From Module Table

$querymodule=" Select ifnull(Module_AdditionalTaxes,0) as Module_AdditionalTaxes, ifNull(Module_Synchro,0) As Module_Synchro, ifnull(Module_RawMaterial,0) as Module_RawMaterial From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

$querySalesSetup="Select SalesTTC, TipsAccount, CashCur, ifnull(show_discountAmount,0) as show_discountAmount From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}
	

$query_setup=" Select base1 As base1, base2 as base2, Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage,
				Setup_Branch from setup";
$result= mysql_query($query_setup,$connection) or die( mysql_error());
while($rowsetup=mysql_fetch_array($result)){
	extract($rowsetup);
}


$querycostcent=" select costcent_applyvat ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on costcent.costcent_code like concat(loginstk.costcent_code,'%') ".
 			   " where user_account='".$_SESSION['useraccount']."' ".
 			   "";
			   
$costcentres = mysql_query($querycostcent,$connection) or die(mysql_error());
$rows=mysql_fetch_array($costcentres);
$costcent_applyvat = $rows[0];
if($costcent_applyvat=='')	$costcent_applyvat = 1;


$mode=$_GET['mode'];

	if($PRef == '') $PRef = "NULL";
	else $PRef = "'".$PRef."'";
	
if ($mode=='confirmallmanifests'){
	$ErrorExist = 0;
	
	$querysearch = " select manifest_auto, delivery_id	from manifest ";

	
	$querysearch=$querysearch." WHERE  ( (manifest_auto like Concat(ifNull($PRef, manifest_auto),'%')) or (Voyage_year like Concat(ifNull($PRef, Voyage_year),'%')) or
									(voyage_number like Concat(ifNull($PRef, voyage_number),'%')) or (BOL_identification like Concat(ifNull($PRef, BOL_identification),'%')) or
									(BOL_type like Concat(ifNull($PRef, BOL_type),'%')) or (Portofloading like Concat(ifNull($PRef, Portofloading),'%')) or
									(PortofDischarge like Concat(ifNull($PRef, PortofDischarge),'%'))
									) ";

	if ($PortRef != '') 	$querysearch=$querysearch." and Portofloading like '%".$PortRef."%' ";
	if ($LocalRef != '') 	$querysearch=$querysearch." and localagent_code like '%".$LocalRef."%' ";
	if ($BLRef != '') 	$querysearch=$querysearch." and BOL_type like '%".$BLRef."%' ";



	$querysearch=$querysearch." and ifnull(manifest_confirm,0) = 0 ";
	$querysearch=$querysearch." order by manifest_auto desc";
	$querysearch = $querysearch." limit ".$startranger.",".$perpage; 
	$resultsearch=mysql_query($querysearch,$connection) or die(mysql_error());		

	$selectedIds = array();
	
	while($rows=mysql_fetch_array($resultsearch)){
		$val = 'chkval'.$rows[0];
		if ( $$val == '1' ){
			array_push($selectedIds, $rows[0]);
		}
	}
		
	foreach ($selectedIds as $Manifest_Auto){	
		$queryselect="select client_code,received_date
					  from manifest 
					  where manifest_auto='$Manifest_Auto'";
		$resultsel  = mysql_query($queryselect, $connection);
		
		$row = mysql_fetch_row($resultsel);
		$clientcode = $row[0];
		$deliverydate = $row[1];
		
		if($clientcode == '' || $deliverydate == '')
			$chk_auto = $chk_auto.",".$Manifest_Auto;
	}
	if($chk_auto != ''){
		$ErrorExist = 1;
		$message = "Check For Client Code and Received Date for: ".$chk_auto;
	}	
	 
	if($ErrorExist == 0){
		foreach ($selectedIds as $Manifest_Auto){	
			$currArr = array();
			$querydt = "select 1, currencycode from manifestdtl where manifest_manifestauto='$Manifest_Auto' group by currencycode;";
			$resdt = mysql_query($querydt, $connection);
			$countdt = mysql_num_rows($resdt);
			while($rwdt = mysql_fetch_array($resdt)){
				if ($rwdt[1] != '')
					array_push($currArr, $rwdt[1]);
			}
	
			$queryselect="select client_code,received_date,manifest_confirm,tax1_amount,tax2_amount,tax3_amount,tax4_amount,tax5_amount,tax6_amount,currency, Manifest_sysdate
						  from manifest 
						  where manifest_auto='$Manifest_Auto'";
			$resultsel  = mysql_query($queryselect, $connection);
			//echo $queryselect;
			$row=mysql_fetch_row($resultsel);
			$clientcode=$row[0];
			$deliverydate=$row[1];
		
			$manifest_confirm=$row[2];
			
			$tax1_amount = $row[3];
			if($tax1_amount == '') $tax1_amount = 0;
			
			$tax2_amount = $row[4];
			if($tax2_amount == '') $tax2_amount = 0;		
			
			$tax3_amount = $row[5];
			if($tax3_amount == '') $tax3_amount = 0;
			
			$tax4_amount = $row[6];
			if($tax4_amount == '') $tax4_amount = 0;
			
			$tax5_amount = $row[7];
			if($tax5_amount == '') $tax5_amount = 0;
			
			$tax6_amount = $row[8];
			if($tax6_amount == '') $tax6_amount = 0;
			
			$currency=$row[9];
			$systdate = $row[10];
			
			if (!(in_array($currency, $currArr)))
				array_push($currArr, $currency);
		
			$countdt = $countdt + $tax1_amount + $tax2_amount + $tax3_amount + $tax4_amount + $tax5_amount + $tax6_amount;
			
	if($countdt > 0){
		foreach($currArr  as $currToUse){
			
			$sub_query = " Select ifNull(Client_VAT,0) From Clients Where Ledger_Number = '".$clientcode."'";			 
			$sub_result = selectData($connection, $sub_query);
			$PSaVatChkbx = $sub_result[0];
			if($costcent_applyvat==0) $PSaVatChkbx=0;
			//echo $PSaVatChkbx;exit;
			$PSaId 		= get_nextsequence('delivery_id','',$connection);
			$vSaRef 	= get_nextsequence('delivery_reference','',$connection);
			$manifestpr = "select vessel_id,voyage_number,Voyage_year,bol_type, BOL_identification, agent1  from manifest 
							left join agent on agent.code = localagent_code
							where manifest_auto=$Manifest_Auto";

			$resultprct  = mysql_query($manifestpr, $connection);
			//echo $queryselect;
			if($ctpr=mysql_fetch_array($resultprct)){
				$vessel_id		= $ctpr[0];
				$voyage_number	= $ctpr[1];
				$voyage_year	= $ctpr[2];
				$bol_type		= $ctpr[3];
				$bol_id			= $ctpr[4];
				$agentname		= $ctpr[5];
			}
			$querymandt = "select group_concat(concat (if(ifnull(container_type,'')='', ifnull(type_id,''),ifnull(container_type,'')),' ',container) separator ',')
							from manifestdt
							left join container on container.cntr_code = manifestdt.container
							where (ifnull(detailtype,'')=1 or container in (select cntr_code from container))
							and manifest_manifestauto = $Manifest_Auto ";
			$resmandt = mysql_query($querymandt, $connection);				
			$rwmandt = mysql_fetch_array($resmandt);
			$remarkman = $rwmandt[0];
			
			if($remarkman=='')
				$remarkman = "";
			else $remarkman = "'".$remarkman."'";
			$PSaCurr = $currToUse;
			if($PSaCurr == '') $PSaCurr = $base1;
			$project_name = $vessel_id.$voyage_number.$voyage_year;

			if ($bol_type=='I') $blt = 'Import';
			if ($bol_type=='E') $blt = 'Export';
			
				$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, if( ifNull(CreditCurdefault,0)=1, CreditCur, '".$PSaCurr."') As CreditCur, ".
							 " CreditAccount, TipsAccount, VatAccount, CreditAccountVAT, PromotionAccount, TransportAccount, BonusAccount ".
							 " FROM salessetup ";
				$Acc_Result = selectData($connection, $Acc_Query);
				
				$vSaVatAcc = $Acc_Result[8];
				$sub_queryVat = " SELECT GetVATAccount('".$clientcode."','".$vSaVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
					 
				$nontaxabalamount = 0;
				$taxableamount = 0;
				$vatamount = 0;
				$netamount = 0;			
				$discountamount = 0;	
				$nontaxabalamountbase1 = 0;
				$nontaxabalamountbase2 = 0;
				$taxableamountbase1 = 0;
				$taxableamountbase2 = 0;
				$discountamountbase1 = 0;
				$discountamountbase2 = 0;
				$vatamountbase1 = 0;
				$vatamountbase2 = 0;
				$netamountbase1 = 0;
				$netamountbase2 = 0;
			//#	JournalDt_ValueDate,
			$query = " INSERT INTO deliveries (Delivery_ID, Delivery_Reference, Delivery_Date,Client_code,  Currency_Code, Journaldt_valuedate, ".
					" Project_Code, Costcent_code, Delivery_Posted,Delivery_Edit,
					
					Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, 
					Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, 
					Delivery_DiscountAmount, "." Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer,
					Delivery_VAT,Delivery_VATBase1, Delivery_VATBase2, 
					Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2,
					Delivery_Confirmed, "." Delivery_Mode, 
					Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Acctax1, Delivery_Acctax2, 
					Delivery_Acctax3, Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, ".
					" Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc,
					Delivery_TransportAccount, Delivery_CREDITACCcur, Delivery_CREDITACC, Delivery_VatChkbx, 
					Delivery_BonusAccount,
					User_Account, Delivery_ClientDeliveryDate, manifest_auto, Delivery_Remark, Delivery_ShippedVia, Delivery_Marks, Delivery_ManualNo ) ".
					" VALUES ( ".$PSaId.", '$vSaRef', '".$deliverydate."',"."  '".$clientcode."', "."'".$PSaCurr."','".$deliverydate."',
					'$project_name', '$blt', 0, 0,
					'$taxableamount', '$taxableamountbase1', '$taxableamountbase2',
					'$nontaxabalamount','$nontaxabalamountbase1', '$nontaxabalamountbase2',
					'$discountamount', '$discountamountbase1', '$discountamountbase1', 0,
					'$vatamount', '$vatamountbase1', '$vatamountbase1',
					'$netamount', '$netamountbase1', '$netamountbase2', 
					 0, "." 0,
					'DI', Null, $FI_BelongsToGrp, '".$Acc_Result[0]."', '".$Acc_Result[1]."', '".$Acc_Result[2]."', '".$Acc_Result[3]."', '".$Acc_Result[4]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', '".$Acc_Result[7]."', ".
					"          '".$vSaVatAcc."', '".$Acc_Result[9]."', '".$Acc_Result[10]."', '".$Acc_Result[11]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', '$PSaVatChkbx', '".$Acc_Result[12]."',".
					"          '".$_SESSION['useraccount']."' , '".$deliverydate."', '$Manifest_Auto', ".strformat($remarkman).", '$vessel_id', ".strformat($agentname).", '".$bol_id."')";
						
							 
			//echo $query;exit;
			
			$lstWarehouse="NA";
			
			$ErrorExist = 0;
			 $result  = mysql_query($query, $connection);
			if(!$result){
				$ErrorExist = 1;
			}
			
			if($ErrorExist == 0){	
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PSaCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PSaCurr."' )";
				$result = selectData($connection, $query);
				$rate_dt = $result[0];
				
				
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
				$result = selectData($connection, $query);
				$rate_dt1 = $result[0];
				
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
				$result = selectData($connection, $query);
				$rate_dt2 = $result[0];
				
			
				$cntr=0;
				$selecttax="select tax1_desc,tax2_desc,tax3_desc,tax4_desc,tax5_desc,tax6_desc,
							tax1_amount,tax2_amount,tax3_amount,tax4_amount,tax5_amount,tax6_amount
							from manifest where manifest_auto='$Manifest_Auto' and currency = '$PSaCurr' ";
						//echo $selecttax;
				$result = selectData($connection, $selecttax);
					$tax1_desc 	      = $result[0];
					$tax2_desc        = $result[1];
					$tax3_desc 		  = $result[2];
					$tax4_desc        = $result[3];
					$tax5_desc        = $result[4];
					$tax6_desc        = $result[5];
					
					$tax1_amount      = $result[6];
					$tax2_amount      = $result[7];
					$tax3_amount      = $result[8];
					$tax4_amount      = $result[9];
					$tax5_amount      = $result[10];
					$tax6_amount      = $result[11];
							
					if ($tax1_desc!=''){
						$item_desc[$cntr]=$tax1_desc;
						$item_cost[$tax1_desc.$cntr]=$tax1_amount;
						$item_cur[$tax1_desc.$cntr] = $PSaCurr;
						$cntr++;
					}
						if ($tax2_desc!=''){
						$item_desc[$cntr]=$tax2_desc;
						$item_cost[$tax2_desc.$cntr]=$tax2_amount;
						$item_cur[$tax2_desc.$cntr] = $PSaCurr;
						$cntr++;
					}
						if ($tax3_desc!=''){
						$item_desc[$cntr]=$tax3_desc;
						$item_cost[$tax3_desc.$cntr]=$tax3_amount;
						$item_cur[$tax3_desc.$cntr] = $PSaCurr;
						$cntr++;
					}
						if ($tax4_desc!=''){
						$item_desc[$cntr]=$tax4_desc;
						$item_cost[$tax4_desc.$cntr]=$tax4_amount;
						$item_cur[$tax4_desc.$cntr] = $PSaCurr;
						$cntr++;
					}
						if ($tax5_desc!=''){
						$item_desc[$cntr]=$tax5_desc;
						$item_cost[$tax5_desc.$cntr]=$tax5_amount;
						$item_cur[$tax5_desc.$cntr] = $PSaCurr;
						$cntr++;
					}
						if ($tax6_desc!=''){
						$item_desc[$cntr]=$tax6_desc;
						$item_cost[$tax6_desc.$cntr]=$tax6_amount;
						$item_cur[$tax6_desc.$cntr] = $PSaCurr;
						$cntr++;
					}
					
				$queryitem = "select tax_description, ifnull(tax_amount,0), ifnull(discount,0), ifnull(quantity,0),currencycode
							from manifestdtl where manifest_manifestauto='$Manifest_Auto' and currencycode = '$PSaCurr';";	
				$resitem = mysql_query($queryitem, $connection);
				while($rwitem = mysql_fetch_array($resitem)){
					$item_desc[$cntr]					= $rwitem[0];
					$item_cost[$rwitem[0].$cntr]		= $rwitem[1];
					$item_discount[$rwitem[0].$cntr]	= $rwitem[2];
					$item_qty[$rwitem[0].$cntr]			= $rwitem[3];
					$item_cur[$rwitem[0].$cntr] 		= $rwitem[4];
					$cntr++;
				}

					foreach($item_desc as $itemcode){
						$itemcost 		= $item_cost[$itemcode.$cntr];
						$itemdiscount 	= $item_discount[$itemcode.$cntr];
						$txtSaDtQty 	= $item_qty[$itemcode.$cntr];
						$itemcurr 		= $item_cur[$itemcode.$cntr];
					
					if($itemdiscount == '') $itemdiscount = 0;	
					if($txtSaDtQty == '') $txtSaDtQty = 1;
					if($itemdiscount != 0) $itemdiscountper = ($itemdiscount*100/$itemcost);
					
					$itemcost 		= ConvertCurrency($itemcurr, $PSaCurr, $sysdate, $itemcost, $connection);
					$itemdiscount 	= ConvertCurrency($itemcurr, $PSaCurr, $sysdate, $itemdiscount, $connection);
					
					$querypack = "select ifnull(Item_Pack,0) from items where item_code = '$itemcode';";
					$respack = mysql_query($querypack, $connection);
					$rwpack = mysql_fetch_row($respack);
					$ItemPack = $rwpack[0];
					
					if ($ItemPack != 1) {
						//	echo "item".$itemcost."<br>";

						$query = "SELECT ifnull(Item_Vat,0), ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0) ".
								" FROM Items WHERE item_Code = '".$itemcode."'";	
						$result = selectData($connection, $query);
						//echo $query;
						$item_vat 	   = $result[0];
						$Item_MaxQty   = $result[1];
						$ItemGroupCode = $result[2];
						$ItemProd      = $result[3];
						$ItemTTCInc    = $result[4];
						$ItemUnit      = $result[5];
						$ItemPromo     = $result[6];
						$ItemNonStock  = $result[7];
						
						//$item_vat = $item_vat/100;
						$tax_flag = 0;
						$notax_flag = 1;
						if ($item_vat > 0){
							$tax_flag = 1;
							$notax_flag = 0;
						}	
								
						$vItemUnitCoef = 0;
						$vItemUnit2Qty = 0;
									
						// from salessetup => SalesTTC
						if ($SalesTTC == 1) {
							$vSaDtPriceTTC      = $itemcost;
							$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
							$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;
							
							if ($PSaVatChkbx == 1)	$vSaDtPrice = ($vSaDtPriceTTC / (1 + $item_vat/100));
							else $vSaDtPrice = $itemcost;			
											
							//$vSaDtPrice      = ($vSaDtPriceTTC / (1 + $item_vat/100));
							$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
							$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
									
						} else	{
							$vSaDtPrice      = $itemcost;
							$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
							$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
							
							$vSaDtPriceTTC      = 0;
							$vSaDtPriceTTCBase1 = 0;
							$vSaDtPriceTTCBase2 = 0;
									
						}	
						
						//get from module	
						if ($Module_AdditionalTaxes == 1) {
						
							// Calculation of Item Tax Amounts
							$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
									 " FROM Clients ".
									 " WHERE Ledger_number = '".$clientcode."'";
												 
							$result = selectData($connection, $query);
							$vCltTax1 = $result[0];
							$vCltTax2 = $result[1];
							$vCltTax3 = $result[2];
							$vCltTax4 = $result[3];
							$vCltTax5 = $result[4];
										
							$query = " SELECT ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
									 " FROM Items ".
									 " WHERE Item_Code = '".$itemcode."'";
											 
							$result = selectData($connection, $query);

							
							if ($vCltTax1 != 0)	$vSaDtTax1 = $result[0];
							if ($vCltTax2 != 0)	$vSaDtTax2 = $result[1];
							if ($vCltTax3 != 0)	$vSaDtTax3 = $result[2];
							if ($vCltTax4 != 0)	$vSaDtTax4 = $result[3];
							if ($vCltTax5 != 0)	$vSaDtTax5 = $result[4];
								
						}
											
										

									
									
							// Get DirectStock Accounts
							$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, PromotionAccount, TipsAccount,  ".
									 " CreditAccountNonStock, CreditAccountVatNonStock, VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS ".
									 " FROM salessetup ";
											 
							$result = selectData($connection, $query);
									
							$vSaStpDirectStkDbt = $result[0];
							$vSaStpDirectStkCrd = $result[1];
							$vSaStpDirectStkCur = $result[2];	
							$vSaStpDiscAcc      = $result[3];	
							$vSaStpCreditVatAcc = $result[4];	
							$vSaStpCreditAcc    = $result[5];	
							$vSaStpPromoAcc     = $result[6];
							$vSaStpTipsAcc      = $result[7];
							
							$vSaStpCreditNonStockAcc    = $result[8];
							$vSaStpCreditVatNonStockAcc = $result[9];
							$vSaStpVatAcc 		  	  	= $result[10];
							$vSaStpVatNonStockAcc 	  	= $result[11];
							$vSaStpVatAccCash	  	  	= $result[12];
							$vSaStpVatNonStockAccCash 	= $result[13];
									
							$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".$clientcode."' ";	
							$resexp = mysql_query($queryexp,$connection);
							$rwexp = mysql_fetch_row($resexp);
							$clientexp = $rwexp[0];
							
							$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
									 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc, Trans_TipsAcc, trans_export ".
									 " FROM transactionsetup ".
									 " WHERE Journal_type = 'SI' ".
									 " AND Group_code = '".$ItemGroupCode."'  ";
													
							$result = selectData($connection, $query);
									
							$vTranStpDirectStkDbt = $result[0];
							$vTranStpDirectStkCrd = $result[1];
							$vTranStpDirectStkCur = $result[2];
							$vTranStpVatAcc       = $result[3];
							$vTranStpNonRmVatAcc  = $result[4];
							$vTranStpRmVatAcc     = $result[5];
							$vTranStpNonRmTTCIncAcc  = $result[6];
							$vTranStpRmTTCIncAcc     = $result[7];
							$vTranStpNonRmAcc        = $result[8];
							$vTranStpRmAcc           = $result[9];
							$vTranStpDiscAcc         = $result[10];
							$vTranStpPromoAcc        = $result[11]; 
							$vTranStpTipsAcc         = $result[12]; 
									
							if ($Module_RawMaterial == 1) {
								$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
								$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
								$vSaDtDirectStkCur = $vTranStpDirectStkCur;
								$vSaDtVatAcc       = $vTranStpVatAcc;
								$vSaDtDiscAcc      = $vTranStpDiscAcc;
								$vSaDtPromoAcc     = $vTranStpPromoAcc;
								$vSaDtTipsAcc      = $vTranStpTipsAcc;
										
								if ($item_vat > 0 && $PSaVatChkbx == 1) {
									if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
								}
								else {
									if ($ItemProd == 1) {
										if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
									}	
									else {
										if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
									}
								}	
							} 
							else {
								$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
								$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
								$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
								//$vSaDtVatAcc       = $vSaStpVatAcc;
								$vSaDtDiscAcc      = $vSaStpDiscAcc;
								$vSaDtPromoAcc     = $vSaStpPromoAcc;
								$vSaDtTipsAcc      = $vSaStpTipsAcc;
										
								if ($item_vat > 0 && $PSaVatChkbx == 1) {
									if ($ItemNonStock == 1)
										$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
									else
										$vSaDtItemAcc = $vSaStpCreditVatAcc;
								} else {
									if ($ItemNonStock == 1)
										$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
									else	
										$vSaDtItemAcc = $vSaStpCreditAcc;
								}
									if ($ItemNonStock == 1)
										$vSaDtVatAcc = $vSaStpVatNonStockAcc;
									else	
										$vSaDtVatAcc = $vSaStpVatAcc;
								//}
								
												
							} 
							if($clientexp == 1) $vSaDtItemAcc = $result[13]; 
							
							$sub_queryVat = " SELECT GetVATAccount('".$clientcode."','".$vSaDtVatAcc."') from dual ";//echo $sub_queryVat;exit;
							$sub_resultVat = selectData($connection, $sub_queryVat);
							if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
							
							$query_cost = " select ifNull(MeanCostCur('".$itemcode."', '".$deliverydate."', 1, '', ''),0) MeanCostAmountB1 ,  ".
										  " ifNull(MeanCostCur('".$itemcode."', '".$deliverydate."', 2, '', ''),0) MeanCostAmountB2 from dual  ";//echo $query_cost;exit;
							$result_cost = selectData($connection, $query_cost);
							
							
							$vSaDtCostBase1  = $result_cost[0];
							$vSaDtCostBase2  = $result_cost[1];
							$vSaDtCost=ConvertCurrency($base1, $PSaCurr, $deliverydate, $vSaDtCostBase1, $connection);
							//$message = $vSaDtCost;
							if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
							if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
							
						
							$deliverydt_clientdiscount = 0;
							$deliverydt_itemdiscount = $itemdiscountper;

							// Calculation For Detail Discount Amount
							$vSaDtDiscAmt       = $itemdiscount;
							$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
							$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;

									
							fbegin();
							$txtSaDtId = get_nextsequence('deliverydt_id','',$connection);	
							fcommit();
					 
							fbegin();
							$project_name=$vessel_id.$voyage_number.$voyage_year;
							if ($voyage_type=='I')$blt='Import';
							if ($voyage_type=='E')$blt='Export';
							//echo "item".$itemcost."<br>";
							$query = " INSERT INTO deliverydt (Project_code, Costcent_code,DeliveryDt_id, Delivery_id, Currency_Code,Delivery_Date, Journal_Type, Client_Code, Warehouse_Code, ".
									 " Item_code, Item_CodePacked, DeliveryDt_Quantity, DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, ".
									 " DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
									 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, ".
									 " Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ".
									 " Deliverydt_BelongsToGroup, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, Item_UnitCoef, Item_Unit2Qty, ".
									 " Deliverydt_promotion, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2,  Deliverydt_cost, Deliverydt_costbase1, Deliverydt_costbase2, ".
									 " DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, deliverydt_clientdiscount,deliverydt_itemdiscount) ".
									 " VALUES ( '$project_name','$blt',".$txtSaDtId.", ".$PSaId.", '".$PSaCurr."', '".$deliverydate."', 'DI', '".$clientcode."', ".
									 " '".$lstWarehouse."', '".$itemcode."', Null, '$txtSaDtQty', $vSaDtPrice , $vSaDtPriceBase1, $vSaDtPriceBase2, ".
									 " '$itemdiscountper', '$vSaDtDiscAmt', '$vSaDtDiscAmtBase1', '$vSaDtDiscAmtBase2', '$item_vat', ".
									 " '$vSaDtPriceTTC', '$vSaDtPriceTTCBase1', '$vSaDtPriceTTCBase2', '".$vSaDtDirectStkDbt."', ".
									 " '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', '".$vSaDtPromoAcc."', ".
									 " '$FI_BelongsToGrp',  '$vSaDtTax1', '$vSaDtTax2', '$vSaDtTax3', '$vSaDtTax4','$vSaDtTax5', 0, 0, '$vItemUnitCoef', '$vItemUnit2Qty', '$chkSaDtPromo', ".
									 " '$vSaDtPrice', '$vSaDtPriceBase1',	 '$vSaDtPriceBase2' ,'$vSaDtCost', '$vSaDtCostBase2', ".
									 " '$vSaDtCostBase1'    ,  '".$vSaDtTipsAcc."', '".$vSaDtVatAcc."' , '".$_SESSION['useraccount']."','$deliverydt_clientdiscount', '$deliverydt_itemdiscount' ) ";
						
						$result=mysql_query($query,$connection);
					
						if ($result){
							fcommit();
						}else{
							$txtSaDtId = "";
							$ErrorExist = 1;
							$message  = mysql_error($connection); 
							frollback();
						}
							 
							
								
							}	// End Case Not Pack Item
							
			else {

				$QtyExistExceeded = 0;

					
				$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_Promotion,0), ifNull(Packdt_totalpromotion,0), PackDt_FromDate, PackDt_ToDate ".
							   " FROM PackDt ".
							   " WHERE Item_Code = '".$itemcode."'  ";
								//   echo $querypackdt."fg";
								   //exit;
				$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
				while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
					
					$vItemCodePacked = $rowspackdt[0];
					$vItemCode = $rowspackdt[1];
					$vPackDtQty = $rowspackdt[2];
					$vPackDtCostPer = $rowspackdt[3];
					$vPackDtPromo = $rowspackdt[4];
					$vPackDtPromoQty = $rowspackdt[5];
					
					

					$vSaDtQty = $txtSaDtQty*$vPackDtQty;
						
						
							
					$query = " SELECT ifnull(Item_Vat,0), ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_NonStock,0) ".
							 " FROM Items WHERE item_Code = '".$vItemCode."'";
					$result = selectData($connection, $query);
					$item_vat      = $result[0];
					$Item_MaxQty   = $result[1];
					$ItemGroupCode = $result[2];
					$ItemProd      = $result[3];
					$ItemTTCInc    = $result[4];
					$ItemUnit      = $result[5];
					$ItemNonStock  = $result[6];
					
					$tax_flag = 0;
					$notax_flag = 1;
					if ($item_vat > 0){
						$tax_flag = 1;
						$notax_flag = 0;
					}

					$vItemUnitCoef = 0;
					$vItemUnit2Qty = 0;
					if ($Module_DoubleUnit == 1) {
												
						$vItemUnitCoef = $ItemUnit;
						if ($Module_Unit1Method == 1)
							$vItemUnit2Qty = $vSaDtQty*$vItemUnitCoef;
						else	
							$vItemUnit2Qty = $vSaDtQty/$vItemUnitCoef;
					}	
									
					
							
						$vSaDtPriceTTC      = 0;
						$vSaDtPriceTTCBase1 = 0;
						$vSaDtPriceTTCBase2 = 0;					
						$vSaDtPrice   	    = 0;
						$vSaDtPriceBase1 	= 0;
						$vSaDtPriceBase2    = 0;
						$vSaDtCostBase1  	= 0;
						$vSaDtCostBase2  	= 0;
						$vSaDtDiscAmt       = 0;
						$vSaDtDiscAmtBase1  = 0;
						$vSaDtDiscAmtBase2  = 0;
								
						$vCltTax1 = 0;
						$vCltTax2 = 0;
						$vCltTax3 = 0;
						$vCltTax4 = 0;
						$vCltTax5 = 0;
						$vSaDtTax1 = 0;
						$vSaDtTax2 = 0;
						$vSaDtTax3 = 0;
						$vSaDtTax4 = 0;
						$vSaDtTax5 = 0;

							if ($SalesTTC == 1) {
								$vSaDtPriceTTC      = (($itemcost*$vPackDtCostPer/100)/$vPackDtQty);
								$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
								$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;	

								if ($PSaVatChkbx == 1)	$vSaDtPrice = ($vSaDtPriceTTC / (1 + $item_vat/100));
								else $vSaDtPrice = $itemcost;	
								
								$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
								$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
										
							} else	{
								$vSaDtPrice      = (($itemcost*$vPackDtCostPer/100)/$vPackDtQty);
								$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
								$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
										
								$vSaDtPriceTTC      = 0;
								$vSaDtPriceTTCBase1 = 0;
								$vSaDtPriceTTCBase2 = 0;
										
							}
									
								
							// Calculation For Detail Discount Amount
							$vSaDtDiscAmt       = 0;
							$vSaDtDiscAmtBase1  = 0;
							$vSaDtDiscAmtBase2  = 0;

							if ($Module_AdditionalTaxes == 1) {
								
								// Calculation of Item Tax Amounts
								$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
										 " FROM Clients ".
										 " WHERE Ledger_number = '".$clientcode."'";
														 
								$result = selectData($connection, $query);
								$vCltTax1 = $result[0];
								$vCltTax2 = $result[1];
								$vCltTax3 = $result[2];
								$vCltTax4 = $result[3];
								$vCltTax5 = $result[4];
												
								$query = " SELECT ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
										 " FROM Items ".
										 " WHERE Item_Code = '".$vItemCode."'";
														 
								$result = selectData($connection, $query);

									
								if ($vCltTax1 != 0)	$vSaDtTax1 = $result[0];
								if ($vCltTax2 != 0)	$vSaDtTax2 = $result[1];
								if ($vCltTax3 != 0)	$vSaDtTax3 = $result[2];
								if ($vCltTax4 != 0)	$vSaDtTax4 = $result[3];
								if ($vCltTax5 != 0)	$vSaDtTax5 = $result[4];
										
							}		
								
								
							
						
							
						// Get DirectStock Accounts
						$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, PromotionAccount, TipsAccount,  ".
								 " CreditAccountNonStock, CreditAccountVatNonStock, VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS ".
								 " FROM salessetup ";
										 
						$result = selectData($connection, $query);
									
						$vSaStpDirectStkDbt = $result[0];
						$vSaStpDirectStkCrd = $result[1];
						$vSaStpDirectStkCur = $result[2];	
						$vSaStpDiscAcc      = $result[3];	
						$vSaStpCreditVatAcc = $result[4];	
						$vSaStpCreditAcc    = $result[5];	
						$vSaStpPromoAcc     = $result[6];
						$vSaStpTipsAcc      = $result[7];
						
						$vSaStpCreditNonStockAcc    = $result[8];
						$vSaStpCreditVatNonStockAcc = $result[9];
						$vSaStpVatAcc 		  	  	= $result[10];
						$vSaStpVatNonStockAcc 	  	= $result[11];
						$vSaStpVatAccCash	  	  	= $result[12];
						$vSaStpVatNonStockAccCash 	= $result[13];
									
						$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".$clientcode."' ";	
						$resexp = mysql_query($queryexp,$connection);
						$rwexp = mysql_fetch_row($resexp);
						$clientexp = $rwexp[0];

						$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
								 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc, Trans_TipsAcc,trans_export ".
								 " FROM transactionsetup ".
								 " WHERE Journal_type = 'SI' ".
								 " AND Group_code = '".$ItemGroupCode."'  ";
											 
						$result = selectData($connection, $query);
									
						$vTranStpDirectStkDbt = $result[0];
						$vTranStpDirectStkCrd = $result[1];
						$vTranStpDirectStkCur = $result[2];
						$vTranStpVatAcc       = $result[3];
						$vTranStpNonRmVatAcc  = $result[4];
						$vTranStpRmVatAcc     = $result[5];
						$vTranStpNonRmTTCIncAcc  = $result[6];
						$vTranStpRmTTCIncAcc     = $result[7];
						$vTranStpNonRmAcc        = $result[8];
						$vTranStpRmAcc           = $result[9];
						$vTranStpDiscAcc         = $result[10];
						$vTranStpPromoAcc        = $result[11]; 
						$vTranStpTipsAcc         = $result[12];
									
						if ($Module_RawMaterial == 1) {
							$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
							$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
							$vSaDtDirectStkCur = $vTranStpDirectStkCur;
							$vSaDtVatAcc       = $vTranStpVatAcc;
							$vSaDtDiscAcc      = $vTranStpDiscAcc;
							$vSaDtPromoAcc     = $vTranStpPromoAcc;
							$vSaDtTipsAcc      = $vTranStpTipsAcc;
										
							if ($item_vat > 0 && $PSaVatChkbx == 1) {
								if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
							}
							else {
								if ($ItemProd == 1) {
									if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
								}	
								else {
									if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
								}
							}	
						} 
						else {
							$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
							$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
							$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
							//$vSaDtVatAcc       = $vSaStpVatAcc;
							$vSaDtDiscAcc      = $vSaStpDiscAcc;
							$vSaDtPromoAcc     = $vSaStpPromoAcc;
							$vSaDtTipsAcc      = $vSaStpTipsAcc;
								
							if ($item_vat > 0 && $PSaVatChkbx == 1) {
								if ($ItemNonStock == 1)
									$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
								else
									$vSaDtItemAcc = $vSaStpCreditVatAcc;
							} else {
								if ($ItemNonStock == 1)
									$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
								else	
									$vSaDtItemAcc = $vSaStpCreditAcc;
							}

							
								if ($ItemNonStock == 1)
									$vSaDtVatAcc = $vSaStpVatNonStockAcc;
								else	
									$vSaDtVatAcc = $vSaStpVatAcc;
							//}	
						}

						if($clientexp == 1) $vSaDtItemAcc = $result[13]; 
						
						$sub_queryVat = " SELECT GetVATAccount('".$clientcode."','".$vSaDtVatAcc."') from dual ";
						$sub_resultVat = selectData($connection, $sub_queryVat);
						if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				 
						$query_cost = " select ifNull(MeanCostCur('".$vItemCode."', '".$deliverydate."', 1, '', ''),0) MeanCostAmountB1 ,  ".
									  " ifNull(MeanCostCur('".$vItemCode."', '".$deliverydate."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
						$result_cost = selectData($connection, $query_cost);
						
						
						$deliverydt_clientdiscount = 0;
						$deliverydt_itemdiscount = $itemdiscountper;

						// Calculation For Detail Discount Amount
						$vSaDtDiscAmt       = $itemdiscount;
						$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
						$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;
						
						$vSaDtCostBase1  = $result_cost[0];
						$vSaDtCostBase2  = $result_cost[1];
						$vSaDtCost=ConvertCurrency($Base1, $deliverycurrency, $deliverydate, $vSaDtCostBase1, $connection);
						
						if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
						if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
						
						//$vSaDtCostBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $vSaDtCostBase1, $connection);
						
						fbegin();
						$vSaDtId = get_nextsequence('deliverydt_id','',$connection);
						fcommit();
								
						fbegin();		
						$query = " INSERT INTO deliverydt (Project_code, Costcent_code,DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Journal_Type, Client_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ".
								 " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
								 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ".
								 " Deliverydt_BelongsToGroup, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, Item_UnitCoef, Item_Unit2Qty, Deliverydt_promotion, 
							SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2,  Deliverydt_cost, Deliverydt_costbase1, Deliverydt_costbase2,  ".
								 " Item_QtyPacked, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account) ".
								 " VALUES ( '$project_name','$blt',".$vSaDtId.", ".$PSaId.", '".$PSaCurr."', '".$deliverydate."', 'DI', '".$clientcode."',  ".
								 "          , '".$lstWarehouse."', '".$vItemCode."', '".$vItemCodePacked."', '$vSaDtQty', '$vSaDtPrice', '$vSaDtPriceBase1', '$vSaDtPriceBase2', '$txtSaDtDiscount', '$vSaDtDiscAmt', '$vSaDtDiscAmtBase1', '$vSaDtDiscAmtBase2', '$item_vat' ".
								 "          '$vSaDtPriceTTC', '$vSaDtPriceTTCBase1', '$vSaDtPriceTTCBase2', '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', ".
								 "          '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', '".$vSaDtPromoAcc."',' $FI_BelongsToGrp',  '$vSaDtTax1', '$vSaDtTax2', '$vSaDtTax3', '$vSaDtTax4', '$vSaDtTax5', 0, 0, '$vItemUnitCoef', '$vItemUnit2Qty', '$vPackDtPromo',   ".
								 "         '$vSaDtPrice', '$vSaDtPriceBase1', '$vSaDtPriceBase2', '$vSaDtPrice', '$vSaDtPriceBase1', '$vSaDtPriceBase2',  '$vPackDtQty', '".$vSaDtTipsAcc."', 
								 '".$vSaDtVatAcc."', '".$_SESSION['useraccount']."' ) ";
					
						$result=mysql_query($query,$connection);
										
						
					
				} // End Loop Of Packdt
				
					
				if ($result){
					fcommit();
					
				}else{
					$txtSaDtId = "";
					$ErrorExist = 1;
					$message  = mysql_error(); 
					frollback();
				}
				
						
			} // End CasePack Item

			}
				if($ErrorExist == 0){
					
					$CalculateResult = Calculate_MasterAmounts($PSaId, $deliverydate, $PSaVatChkbx, 0, 0, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'I', $connection);
					
					$message = Create_DeliveryJv($PSaId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
					
					//$manifestdelivery="update manifest set delivery_id='$PSaId' where manifest_auto='$Manifest_Auto'";
				}
			
				//$resultdelmani=mysql_query($manifestdelivery,$connection);
			}
			
			
	}
			} // end count
		
		if($ErrorExist == 0){
			$query="update manifest set manifest_confirm=1,confirmed_user='".$_SESSION['useraccount']."' where manifest_auto='$Manifest_Auto'";
			$result  = mysql_query($query, $connection);
			if ($result)
				$messageconfirm="confirmed successfullly";
		}
		
		
	} // end foreach
		if ($message=='') $message = $messageconfirm;
		
	}
	header("Location: Form_ManifestsSearch.php?message=$message");
}

//echo $mode."is"."mode";

mysql_close($connection);

function Create_DeliveryJv($PSaId, $DbName, $DbLabel, $UserAccount, $UserName) {

	include("config.inc.php");
	
	$conn = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($DbName, $conn) or die("Could not find DB");

	fbegin();
	$resultvars = mysql_query("set @id :=0 ", $conn);

	$query = " call Create_DeliveryAutoJv(".$PSaId.", 0, '".$DbName."', '".$DbLabel."', '".$UserAccount."', '".$UserName."', 0, @id) ";
	//echo $query; 
	//exit;
	$result = mysql_query($query,$conn);
    $error = mysql_error();
	
	$query1 = " select @id from dual ";
	$result1 = mysql_query($query1,$conn) or die(mysql_error());
	$cur1 = mysql_fetch_row($result1);
	

	fcommit();
	
	
    if ($cur1[0] == -2)
	   $error = 'Error In Procedure Create_DeliveryAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_DeliveryJv: '.$error;

	Return $error;
	

}


function ConvertCurrency($FromCurr, $ToCurr, $FromDate, $Amount, $connection)
{
	$query = "SELECT ifNull(convertcurfunc('".$FromCurr."', '".$ToCurr."', '".$FromDate."', 0, 0, '', '', ifNull($Amount,0)),0) From Dual ";
	//echo "<br>".$query."<br>";
	
	
	$result = selectData($connection, $query);
	//echo $query;
	 Return	$result[0];

}

function insertMySQLDate($data){
		return substr($data, 6, 4) . substr($data, 3, 2) . substr($data, 0, 2);
	}

	
	function fbegin()
{
	mysql_query("START TRANSACTION");
}
function fcommit(){
	mysql_query("COMMIT");
}
function frollback()
{
	mysql_query("ROLLBACK");
}

function formatdatetime($dateval){
	if($dateval != ''){
	$ndate = explode(":", $dateval);
	
}
	return $ndate;
}


function formatdate($dateval){
	if($dateval != ''){
	$ndate = explode("-", $dateval);
	$dateval = $ndate[2]."-".$ndate[1]."-".$ndate[0];
}
	return $dateval;
}


function Calculate_MasterAmounts($PId, $PDate, $PVatChk, $PDiscPer, $PDiscAmt, $PTransportAmt, $PBonusAmt, $PRate, $PRate1, $PRate2, $PSetupVatStartDate, $PSetupVatPercentage, $PModuleAdditionalTaxes, $PSalesTTC, $PMode, $connection) {

	$vSaDtTotal = 0;
	$vItemVat    = 0;
	
	$vSaTaxable        = 0;
	$vSaTaxableTTC     = 0;
	$vSaNoneTaxable    = 0;
	$vSaGrossTotal     = 0;
	$vSaDiscountAmt    = 0;
	$vSaDiscountPer    = 0;
	$vSaDiscountAmtTTC = 0;
	$vSaTransportAmt   = 0;
	$vSaTransportAmtB1 = 0;
	$vSaTransportAmtB2 = 0;
	$vSaTransportAmtTTC = 0;
	$vSaBonusAmt   	    = 0;
	$vSaBonusAmtB1      = 0;
	$vSaBonusAmtB2      = 0;
	$vSaBonusAmtTTC     = 0;
	$vSaVat      = 0;
	$vSaVatBase1 = 0;
	$vSaVatBase2 = 0;
		
	$vSaTax1 = 0;
	$vSaTax2 = 0;
	$vSaTax3 = 0;
	$vSaTax4 = 0;
	$vSaTax5 = 0;
	$vSaTax1B1 = 0;
	$vSaTax2B1 = 0;
	$vSaTax3B1 = 0;
	$vSaTax4B1 = 0;
	$vSaTax5B1 = 0;
	$vSaTax1B2 = 0;
	$vSaTax2B2 = 0;
	$vSaTax3B2 = 0;
	$vSaTax4B2 = 0;
	$vSaTax5B2 = 0;
	
	$vSaTotalWeight = 0;

	$vSaDiscountPer = $PDiscPer;
	
	// In Case Not Save, Then Get The Vat CheckBox From Table Sorder
	if ($PMode != 'P') {
		$sub_query = "Select ifNull(Delivery_VatChkbx, 0) From Deliveries Where Delivery_ID = '".$PId."'";
		//echo "<br><br>".$sub_query;
		$sub_result = selectData($connection, $sub_query);
		$PVatChk    = $sub_result[0];
	
	}

	if ($PSalesTTC ==1 && $PVatChk == 0 && $PMode == 'P') {

		$query = " UPDATE DeliveryDt SET  ".
				 " DeliveryDt_Price = DeliveryDt_PriceTTC, ".
				 " DeliveryDt_PriceBase1 = DeliveryDt_PriceTTCBase1, ".
				 " DeliveryDt_PriceBase2 = DeliveryDt_PriceTTCBase2 ".
				 " Where Delivery_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}
	else if ($PSalesTTC ==1 && $PVatChk == 1 && $PMode == 'P') {

		$query = " UPDATE DeliveryDt SET  ".
				 " DeliveryDt_Price      = (DeliveryDt_PriceTTC / (1 + Item_Vat/100)), ".
				 " DeliveryDt_PriceBase1 = (DeliveryDt_PriceTTCBase1 / (1 + Item_Vat/100)), ".
				 " DeliveryDt_PriceBase2 = (DeliveryDt_PriceTTCBase2 / (1 + Item_Vat/100)) ".
				 " Where Delivery_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}	
	
	
	//Calculating Master Amounts
	$sub_query = " Select DeliveryDt.Item_Code, ((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0))-((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0)*ifNull(DeliveryDt_DiscountPer,0))/100)) As Total, ifNull(DeliveryDt.Item_Vat,0),
				   deliveryDt_Quantity, (ifNull(DeliveryDt_DiscountAmount,0) - ifNull(DeliveryDt_TransportAmount,0) - ifNull(DeliveryDt_BonusAmount,0)), ifNull(DeliveryDt.Item_Tax1,0), ifNull(DeliveryDt.Item_Tax2,0), ifNull(DeliveryDt.Item_Tax3,0), ifNull(DeliveryDt.Item_Tax4,0), ifNull(DeliveryDt.Item_Tax5,0),
				   ifNull(item_weight,0),ifNull(DeliveryDt_Quantity,0) ".
				 " From DeliveryDt ".
				 " left join items on items.item_code = DeliveryDt.Item_Code ".
				 " Where Delivery_ID = ".$PId;
										 
	//echo $sub_query;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

		$vSaDtTotal = $sub_rows[1];
		$vItemVat   = $sub_rows[2];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0 && $PVatChk == 1){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
							
		$vSaTaxable     = $vSaTaxable     + ($vSaDtTotal*$tax_flag);
		$vSaNoneTaxable = $vSaNoneTaxable + ($vSaDtTotal*$notax_flag);
		
		
		// Calculation of Vat Amount
		if ((($PDate > $PSetupVatStartDate && $vItemVat > 0) || ($PModuleAdditionalTaxes == 1))  && $PVatChk == 1 && $vSaDtTotal > 0)
			$vSaVat = $vSaVat + (($vSaDtTotal - $sub_rows[4])*$vItemVat/100);
						
		if ($PModuleAdditionalTaxes == 1 && $vSaDtTotal > 0) {
			if ($vItemVat > 0 && $sub_rows[5] != 0)
				$vSaTax1 = $vSaTax1 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[5]/100);
			if ($vItemVat > 0 && $sub_rows[6] != 0)
				$vSaTax2 = $vSaTax2 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[6]/100);
			if ($vItemVat > 0 && $sub_rows[7] != 0)
				$vSaTax3 = $vSaTax3 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[7]/100);
			if ($vItemVat > 0 && $sub_rows[8] != 0)
				$vSaTax4 = $vSaTax4 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[8]/100);
			if ($vItemVat > 0 && $sub_rows[9] != 0)
				$vSaTax5 = $vSaTax5 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[9]/100);	
		}
		$vSaTotalWeight = $vSaTotalWeight + ($sub_rows[10]*$sub_rows[11]);
					
	}			
					
				
	$vSaGrossTotal = $vSaTaxable + $vSaNoneTaxable;
					
	// Calculation of Discount Amount	
	if ($PSalesTTC == 1) {
		if ($PMode == 'P') {
			$vSaDiscountAmtTTC  = $PDiscAmt;					
			$vSaDiscountAmt     = ($vSaDiscountAmtTTC / (1 + $PSetupVatPercentage/100));
		} else {
			if ($vSaDiscountPer > 0) {
				$vSaDiscountAmt     = (($vSaGrossTotal * $vSaDiscountPer) / 100);
				$vSaDiscountAmtTTC  = ($vSaDiscountAmt * (1 + $PSetupVatPercentage/100));
			}	
		}
		
		$vSaTransportAmtTTC = $PTransportAmt;					
		$vSaTransportAmt    = ($vSaTransportAmtTTC / (1 + $PSetupVatPercentage/100));
		$vSaBonusAmtTTC 	= $PBonusAmt;					
		$vSaBonusAmt    	= ($vSaBonusAmtTTC / (1 + $PSetupVatPercentage/100));
		
		if ($PVatChk == 1)	$vSaTaxableTTC = ($vSaTaxable * (1 + $PSetupVatPercentage/100));
		else $vSaTaxableTTC = $vSaTaxable;
	} else	{
		if ($PMode == 'P') {
			$vSaDiscountAmt      = $PDiscAmt;					
		} else {
			if ($vSaDiscountPer > 0) {
				$vSaDiscountAmt     = (($vSaGrossTotal * $vSaDiscountPer) / 100);
			}	
		}
		
		$vSaTransportAmt    = $PTransportAmt;
		$vSaTransportAmtTTC = 0;
		$vSaBonusAmt    	= $PBonusAmt;
		$vSaBonusAmtTTC 	= 0;
		$vSaTaxableTTC 		= 0;
		$vSaDiscountAmtTTC  = 0;
	}
	
			
					
	$vSaNetTotal         = $vSaGrossTotal + $vSaVat - $vSaDiscountAmt;
	$vSaTaxableBase1     = ($vSaTaxable*$PRate)/$PRate1;
	$vSaTaxableBase2     = ($vSaTaxable*$PRate)/$PRate2;
	$vSaNoneTaxableBase1 = ($vSaNoneTaxable*$PRate)/$PRate1;
	$vSaNoneTaxableBase2 = ($vSaNoneTaxable*$PRate)/$PRate2;
	$vSaDiscountAmtBase1 = ($vSaDiscountAmt*$PRate)/$PRate1;
	$vSaDiscountAmtBase2 = ($vSaDiscountAmt*$PRate)/$PRate2;
	$vSaGrossTotalBase1  = ($vSaGrossTotal*$PRate)/$PRate1;
	$vSaGrossTotalBase2  = ($vSaGrossTotal*$PRate)/$PRate2;
	$vSaVatBase1 		 = ($vSaVat*$PRate)/$PRate1;
	$vSaVatBase2 		 = ($vSaVat*$PRate)/$PRate2;
	$vSaTransportAmtB1   = ($vSaTransportAmt*$PRate)/$PRate1;
	$vSaTransportAmtB2   = ($vSaTransportAmt*$PRate)/$PRate2;	
	$vSaBonusAmtB1 	     = ($vSaBonusAmt*$PRate)/$PRate1;
	$vSaBonusAmtB2	     = ($vSaBonusAmt*$PRate)/$PRate2;	
					

	$vSaTax1B1  = ($vSaTax1*$PRate)/$PRate1;
	$vSaTax1B2  = ($vSaTax1*$PRate)/$PRate2;		
	$vSaTax2B1  = ($vSaTax2*$PRate)/$PRate1;
	$vSaTax2B2  = ($vSaTax2*$PRate)/$PRate2;		
	$vSaTax3B1  = ($vSaTax3*$PRate)/$PRate1;
	$vSaTax3B2  = ($vSaTax3*$PRate)/$PRate2;		
	$vSaTax4B1  = ($vSaTax4*$PRate)/$PRate1;
	$vSaTax4B2  = ($vSaTax4*$PRate)/$PRate2;		
	$vSaTax5B1  = ($vSaTax5*$PRate)/$PRate1;
	$vSaTax5B2  = ($vSaTax5*$PRate)/$PRate2;	
	
	fbegin();
		
	//echo $delivery_date;exit;
	$sub_query1 = " UPDATE deliveries SET ".
				  " Delivery_Taxable = $vSaTaxable, Delivery_TaxableBase1 = $vSaTaxableBase1, Delivery_TaxableBase2 = $vSaTaxableBase2, ".
				  " Delivery_NoneTaxable = $vSaNoneTaxable, Delivery_NoneTaxableBase1 = $vSaNoneTaxableBase1, Delivery_NoneTaxableBase2 = $vSaNoneTaxableBase2, ".
				  " Delivery_DiscountAmount = $vSaDiscountAmt, Delivery_DiscountBase1 = $vSaDiscountAmtBase1, Delivery_DiscountBase2 = $vSaDiscountAmtBase2, ".
				  " Delivery_DiscountPer = $vSaDiscountPer, Delivery_VAT = $vSaVat, Delivery_VATBase1 = $vSaVatBase1, Delivery_VATBase2 = $vSaVatBase2, ".
				  " Delivery_VatChkbx = $PVatChk, ".
				  " Delivery_Total = $vSaGrossTotal, Delivery_TotalBase1 = $vSaGrossTotalBase1, Delivery_TotalBase2 = $vSaGrossTotalBase2, ".
				  " Delivery_TransportAmount = $vSaTransportAmt, Delivery_TransportAmountBase1 = $vSaTransportAmtB1, Delivery_TransportAmountBase2 = $vSaTransportAmtB2, Delivery_TransportTTC = $vSaTransportAmtTTC, ".
				  " Delivery_BonusAmount = $vSaBonusAmt, Delivery_BonusBase1 = $vSaBonusAmtB1, Delivery_BonusBase2 = $vSaBonusAmtB2, Delivery_BonusTTC = $vSaBonusAmtTTC, ".
				  " Delivery_DiscountTTC = $vSaDiscountAmtTTC, Delivery_TaxableTTC = $vSaTaxableTTC,  ".
				  " Delivery_Tax1 = $vSaTax1, Delivery_Tax1Base1 = $vSaTax1B1, Delivery_Tax1Base2 = $vSaTax1B2,  ".
				  " Delivery_Tax2 = $vSaTax2, Delivery_Tax2Base1 = $vSaTax2B1, Delivery_Tax2Base2 = $vSaTax2B2,  ".
				  " Delivery_Tax3 = $vSaTax3, Delivery_Tax3Base1 = $vSaTax3B1, Delivery_Tax3Base2 = $vSaTax3B2,  ".
				  " Delivery_Tax4 = $vSaTax4, Delivery_Tax4Base1 = $vSaTax4B1, Delivery_Tax4Base2 = $vSaTax4B2,  ".
				  " Delivery_Tax5 = $vSaTax5, Delivery_Tax5Base1 = $vSaTax5B1, Delivery_Tax5Base2 = $vSaTax5B2,  ".
				  " totalWeight = $vSaTotalWeight ".
				  " WHERE Delivery_ID = ".$PId;
		//echo $sub_query1."<br>";exit;
	$sub_result1=mysql_query($sub_query1,$connection);
	
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}
print <<<HERE
<html><head>
<script type="text/javascript" language="javascript">
//alert('ds');
function Dt(){
	//alert('ds');
}


</script>
</head>
 <body >";
HERE;
print <<<HERE

<form>
<input type='hidden' name='$mode' value='$mode'>
</form>


</body>

HERE;


?>
		           