<?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'];
$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;

//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);
}
if ($actionmode == 'getSize'){
	$containercode = $_GET['containercode'];
	$query = "select type_id from container where upper(cntr_code)=upper('$containercode')";
	$res = mysql_query($query, $connection);
	$row = mysql_fetch_row($res);
	$size = $row[0];
	echo "[BRK]";
	echo $size;
	exit;
}
if ($actionmode == 'changeOffer'){
	$desc1 		= $_GET['desc1'];
	$amount1 	= $_GET['amount1']; 
	$desc2 		= $_GET['desc2'];
	$amount2 	= $_GET['amount2'];
	$desc3 		= $_GET['desc3'];
	$amount3 	= $_GET['amount3'];
	
	$desc4 		= $_GET['desc4'];
	$amount4 	= $_GET['amount4'];
	$desc5 		= $_GET['desc5'];
	$amount5 	= $_GET['amount5'];
	$desc6 		= $_GET['desc6'];
	$amount6 	= $_GET['amount6'];
	
	$offer_number 	= $_GET['offer_number'];
	$currency 		= $_GET['currency'];
	$Manifest_Auto	= $_GET['Manifest_Auto'];
	
	if ($offer_number != ''){
		
		if ($Manifest_Auto != ''){
			$querydtl = "select manifestdtl_id, tax_description, tax_amount, currencycode from manifestdtl where manifest_manifestauto='$Manifest_Auto' "; 
			$resdtl = mysql_query($querydtl, $connection); 
			while ($rwdtl = mysql_fetch_array($resdtl)){
				$manifestdtl_id = $rwdtl[0];
				$itemcode 		= $rwdtl[1];
				$amount			= $rwdtl[2];
				$txtcurr		= $rwdtl[3];
				
				$queryItem = "select Item_SellingPrice1, Currency_code from items where item_code = '$itemcode'";
				$resItem = mysql_query($queryItem, $connection);
				$rowItem = mysql_fetch_row($resItem);
				
				$queryOffer = "select amount, currency_code from archivingofferdt
								inner join archivingoffer on archivingoffer.auto = archivingofferdt.offer_id
								where Offer_code = '$offer_number' and item_code = '$itemcode'";  
				$resOffer = mysql_query($queryOffer, $connection);
				$rowOffer = mysql_fetch_row($resOffer);
				if ($rowOffer[0] != '' && $rowOffer[0] != 0)
					$amount = $rowOffer[0];
				else if ($rowItem[0] != '' && $rowItem[0] != 0)
					$amount = $rowItem[0];
				
				if ($rowOffer[1] != '')
					$txtcurr = $rowOffer[1];
				else if ($rowItem[1] != '')
					$txtcurr = $rowItem[1];
				
				$updatedtl = "update manifestdtl set tax_amount = $amount, currencycode = '$txtcurr' where manifestdtl_id = $manifestdtl_id ";
				$resupdatedtl = mysql_query($updatedtl, $connection);
			}
			
			$amount1 = getOfferAmountPerItem ($Manifest_Auto, $desc1, $amount1, $offer_number, $currency, $connection);
			$amount2 = getOfferAmountPerItem ($Manifest_Auto, $desc2, $amount2, $offer_number, $currency, $connection);
			$amount3 = getOfferAmountPerItem ($Manifest_Auto, $desc3, $amount3, $offer_number, $currency, $connection);
			$amount4 = getOfferAmountPerItem ($Manifest_Auto, $desc4, $amount4, $offer_number, $currency, $connection);
			$amount5 = getOfferAmountPerItem ($Manifest_Auto, $desc5, $amount5, $offer_number, $currency, $connection);
			$amount6 = getOfferAmountPerItem ($Manifest_Auto, $desc6, $amount6, $offer_number, $currency, $connection);
			
			$update = "update manifest set tax1_amount = $amount1, tax2_amount = $amount2, tax3_amount = $amount3, 
						tax4_amount = $amount4, tax5_amount = $amount5, tax6_amount = $amount6,
						Offernumber = '$offer_number', currency = '$currency' 
						where Manifest_Auto = $Manifest_Auto";
			$resupdate = mysql_query($update, $connection);
			echo "[BRK]";
			echo 1;
			exit;
		}
		else {
			
			$amount1 = getOfferAmountPerItem ($Manifest_Auto, $desc1, $amount1, $offer_number, $currency, $connection);
			$amount2 = getOfferAmountPerItem ($Manifest_Auto, $desc2, $amount2, $offer_number, $currency, $connection);
			$amount3 = getOfferAmountPerItem ($Manifest_Auto, $desc3, $amount3, $offer_number, $currency, $connection);
			$amount4 = getOfferAmountPerItem ($Manifest_Auto, $desc4, $amount4, $offer_number, $currency, $connection);
			$amount5 = getOfferAmountPerItem ($Manifest_Auto, $desc5, $amount5, $offer_number, $currency, $connection);
			$amount6 = getOfferAmountPerItem ($Manifest_Auto, $desc6, $amount6, $offer_number, $currency, $connection);
			
			echo "[BRK]";
			echo 2;
			echo "[BRK]";
			echo $amount1;
			echo "[BRK]";
			echo $amount2;
			echo "[BRK]";
			echo $amount3;
			echo "[BRK]";
			echo $amount4;
			echo "[BRK]";
			echo $amount5;
			echo "[BRK]";
			echo $amount6;
			exit;
		}
	
	}
	
}
if ($actionmode == 'getAmount'){
	$descval 		= $_GET['descval'];
	$amountval 		= $_GET['amountval'];
	$offer_number 	= $_GET['offer_number'];
	$currency 		= $_GET['currency'];
	$Manifest_Auto	= $_GET['Manifest_Auto'];
	$changeAmnt = 0;
	
	
	if ($offer_number != ''){
		if ($Manifest_Auto != '')
			$queryman = "select manifest_sysdate from manifest where manifest_auto = $Manifest_Auto ";
		else 
			$queryman = "select now() ";
		
		$resman = mysql_query($queryman, $connection);
		$rwman = mysql_fetch_row($resman);	
		$sysdate = $rwman[0];
				
		$queryItem = "select Item_SellingPrice1, Currency_code from items where item_code = '$descval'";
		$resItem = mysql_query($queryItem, $connection);
		$rowItem = mysql_fetch_row($resItem);
		
		$queryOffer = "select amount, currency_code from archivingofferdt
						inner join archivingoffer on archivingoffer.auto = archivingofferdt.offer_id
						where Offer_code = '$offer_number' and item_code = '$descval'"; 
		$resOffer = mysql_query($queryOffer, $connection);
		$rowOffer = mysql_fetch_row($resOffer);
		if ($rowOffer[0] != '' && $rowOffer[0] != 0){
			$amountval = $rowOffer[0];
			if ($rowOffer[1] != '')
				$currency2 = $rowOffer[1];
			else 
				$currency2 = $currency;
			$amountval = ConvertCurrency($currency2, $currency, $sysdate, $amountval, $connection);
			$changeAmnt = 1;
		}
		else if ($rowItem[0] != '' && $rowItem[0] != 0){
			$amountval = $rowItem[0];
			if ($rowItem[1] != '')
				$currency2 = $rowItem[1];
			else 
				$currency2 = $currency;
			$amountval = ConvertCurrency($currency2, $currency, $sysdate, $amountval, $connection);
			$changeAmnt = 1;
		}
		
		
	}
	echo "[BRK]";
	echo $changeAmnt;
	echo "[BRK]";
	echo $amountval;
exit;
}
if ($actionmode == 'chk_deposit'){
	$clientcode = $_GET['clientcode'];
	$voyyear	= $_GET['voyyear'];
	
	$query = "select count(1)
			from Manifest_Deposit where voy_year = '$voyyear' and client_code = '$clientcode' group by client_code ";
	$res = mysql_query($query, $connection);
	$num = mysql_num_rows($res);
	
	echo "[BRK]";
	echo $num;
exit;
}

if ($actionmode == 'getSrcAgent'){
	$query = "select bl_code from agent inner join port on port_code = agent.code where port_name='$portlading';";
	$res = mysql_query($query, $connection);
	$rw = mysql_fetch_row($res);
	
	echo "[BRK]";
	echo $rw[0];
exit;
}
if ($actionmode == 'check_container'){
	$container = $_GET['container'];
	$query = "select 1 from container where cntr_code = '$container'";
	$res = mysql_query($query, $connection);
	$rw = mysql_fetch_row($res);
	
	echo "[BRK]";
	echo $rw[0];
	echo "[BRK]";
	exit;
}
if($actionmode == 'deleteDefault'){
	$auto_vessel = $_GET['auto_vessel'];
	$query = "delete from default_vessel where auto_vessel = $auto_vessel;";
	$result = mysql_query($query,$connection);
	if($result){
		header("Location: Form_ManifestDefaultVal.php");
	} else {
		$message = mysql_error($connection);
		header("Location: Form_ManifestDefaultVal.php?message=$message");
	}  
	exit;
}

if($actionmode == 'saveDefault'){
	$auto_vessel 		= $_POST['auto_vessel']; 			
	$chk_default		= $_POST['chk_default']; 			
	
	$voyage_year 		= $_POST['voyage_year']; 			
	$voyage_number 		= $_POST['voyage_number'];			
	$line_operator 		= $_POST['line_operator'];			
	
	$voyage_BOLnumber 	= $_POST['voyage_BOLnumber'];		
	$voyage_destination = $_POST['voyage_destination'];		
	$vessel_id 			= $_POST['vessel_id'];				
	
	$Portofloading 		= $_POST['Portofloading'];			
	$Freight_type 		= $_POST['Freight_type'];			
	$currency 			= $_POST['currency'];				
	
	$issued 			= $_POST['issued'];					
	$issued_date 		= $_POST['issued_date'];			
	$manifest_date 		= $_POST['manifest_date'];			
	$received_date 		= $_POST['received_date'];			
	
	$agent1_id 			= $_POST['agent1_id'];				
	$negotiable_BOL 	= $_POST['negotiable_BOL'];			
	$term_of_carriage 	= $_POST['term_of_carriage'];		
	$linear_meters 		= $_POST['linear_meters']; 			
	
	if($issued_date == '') $issued_date = "NULL";
	else $issued_date = "'".formatdate($issued_date)."'";
	
	if($manifest_date == '') $manifest_date = "NULL";
	else $manifest_date = "'".formatdate($manifest_date)."'";
	
	if($received_date == '') $received_date = "NULL";
	else $received_date = "'".formatdate($received_date)."'";
	
	if($chk_default == '') $chk_default = 0;
	
	if($chk_default == 1){
		$updatedefault = "update default_vessel set default_value = 0 where default_value = 1;";	
		$result = mysql_query($updatedefault, $connection);
	} 
	 
	if($auto_vessel == ''){
		$insert = " insert into default_vessel (default_value, Voyage_year, voyage_number, line_operator, voyage_BOLnumber, voyage_destination, vessel_id, ".
				  "  Portofloading, Freight_type, issued, issued_date, Manifest_date, received_date, ".
				  "  currency, Agent1_id, Negotiable_BOL, term_of_carriage, linear_meters) ".
				  " values ".
				  " ( ".$chk_default.", ".strformat($voyage_year).", ".strformat($voyage_number).", ".strformat($line_operator).", ".strformat($voyage_BOLnumber).", ".strformat($voyage_destination).", ".strformat($vessel_id).", ".
				  "  ".strformat($Portofloading).", ".strformat($Freight_type).", ".strformat($issued).", ".$issued_date.", ".$manifest_date.", ".$received_date.", ".
				  " ".strformat($currency).", ".strformat($agent1_id).", ".strformat($negotiable_BOL).", ".strformat($term_of_carriage).", ".strformat($linear_meters).");";
		
		$result = mysql_query($insert, $connection);
	} else {
		$update = " update default_vessel set ".
				  " default_value = ".$chk_default.",".
				  " Voyage_year = ".strformat($voyage_year).", voyage_number = ".strformat($voyage_number).", line_operator = ".strformat($line_operator).",".
				  " voyage_BOLnumber = ".strformat($voyage_BOLnumber).", voyage_destination = ".strformat($voyage_destination).", vessel_id = ".strformat($vessel_id).",".
				  " Portofloading = ".strformat($Portofloading).", Freight_type = ".strformat($Freight_type).", issued = ".strformat($issued).",".
				  " issued_date = ".$issued_date.", Manifest_date = ".$manifest_date.", received_date = ".$received_date.",".
				  " currency = ".strformat($currency).", Agent1_id = ".strformat($agent1_id).", Negotiable_BOL = ".strformat($negotiable_BOL).",".
				  " term_of_carriage = ".strformat($term_of_carriage).", linear_meters = ".strformat($linear_meters)." ".
				  " where auto_vessel = $auto_vessel ;";
		$result = mysql_query($update, $connection);		  
	} 
	if($result){
		header("Location: Form_ManifestDefaultVal.php");
	} else {
		$message = mysql_error($connection);
		header("Location: Form_ManifestDefaultVal.php?message=$message");
	}  
	exit;
}


$voyage_year 		= $_POST['voyage_year']; 		if($voyage_year == '') 			$voyage_year 		= $_GET['voyage_year'];
$voyage_number 		= $_POST['voyage_number'];		if($voyage_number == '')		$voyage_number 		= $_GET['voyage_number'];
$voyage_destination = $_POST['voyage_destination']; if($voyage_destination == '') 	$voyage_destination = $_GET['voyage_destination'];
$bol_number 		= $_POST['bol_number'];			if($bol_number == '') 			$bol_number 		= $_GET['bol_number'];
$voyage_type 		= $_POST['voyage_type'];		if($voyage_type == '') 			$voyage_type 		= $_GET['voyage_type'];
$voyage_pagenumber 	= $_POST['voyage_pagenumber'];	if($voyage_pagenumber == '') 	$voyage_pagenumber 	= $_GET['voyage_pagenumber'];
$billoflading 		= $_POST['billoflading'];		if($billoflading == '') $billoflading 	= $_GET['billoflading'];
$agent_code 		= $_POST['agent_code'];			if($agent_code == '') 	$agent_code 	= $_GET['agent_code'];
$shipper1 			= $_POST['shipper1'];			if($shipper1 == '') 	$shipper1 		= $_GET['shipper1'];
$shipper2 			= $_POST['shipper2'];			if($shipper2 == '') 	$shipper2 		= $_GET['shipper2'];
$shipper3 			= $_POST['shipper3'];			if($shipper3 == '') 	$shipper3 		= $_GET['shipper3'];
$shipper4 			= $_POST['shipper4'];			if($shipper4 == '') 	$shipper4 		= $_GET['shipper4'];
$consignee1 		= $_POST['consignee1'];			if($consignee1 == '') 	$consignee1 	= $_GET['consignee1'];
$consignee2 		= $_POST['consignee2'];			if($consignee2 == '') 	$consignee2 	= $_GET['consignee2'];
$consignee3 		= $_POST['consignee3'];			if($consignee3 == '') 	$consignee3 	= $_GET['consignee3'];
$consignee4 		= $_POST['consignee4'];			if($consignee4 == '') 	$consignee4 	= $_GET['consignee4'];
$notify1 			= $_POST['notify1'];			if($notify1 == '') 		$notify1 		= $_GET['notify1'];
$notify2 			= $_POST['notify2'];			if($notify2 == '') 		$notify2 		= $_GET['notify2'];
$notify3 			= $_POST['notify3'];			if($notify3 == '') 		$notify3 		= $_GET['notify3'];
$notify4 			= $_POST['notify4'];			if($notify4 == '') 		$notify4 		= $_GET['notify4'];
$amount1 			= $_POST['amount1'];			if($amount1 == '') 		$amount1 		= $_GET['amount1'];
$amount2 			= $_POST['amount2'];			if($amount2 == '') 		$amount2 		= $_GET['amount2'];
$amount3 			= $_POST['amount3'];			if($amount3 == '') 		$amount3 		= $_GET['amount3'];
$amount4 			= $_POST['amount4'];			if($amount4 == '') 		$amount4 		= $_GET['amount4'];
$amount5 			= $_POST['amount5'];			if($amount5 == '') 		$amount5 		= $_GET['amount5'];
$amount6 			= $_POST['amount6'];			if($amount6 == '')	 	$amount6 		= $_GET['amount6'];
$desc1 				= $_POST['desc1'];				if($desc1 == '') 		$desc1 			= $_GET['desc1'];
$desc2 				= $_POST['desc2'];				if($desc2 == '') 		$desc2 			= $_GET['desc2'];
$desc3	 			= $_POST['desc3'];				if($desc3 == '') 		$desc3 			= $_GET['desc3'];
$desc4 				= $_POST['desc4'];				if($desc4 == '') 		$desc4 			= $_GET['desc4'];
$desc5 				= $_POST['desc5'];				if($desc5 == '') 		$desc5 			= $_GET['desc5'];
$desc6 				= $_POST['desc6'];				if($desc6 == '') 		$desc6 			= $_GET['desc6'];
$evidence1 			= $_POST['evidence1'];			if($evidence1 == '') 	$evidence1 		= $_GET['evidence1'];
$evidence2 			= $_POST['evidence2'];			if($evidence2 == '') 	$evidence2 		= $_GET['evidence2'];
$evidence3			= $_POST['evidence3'];			if($evidence3 == '') 	$evidence3 		= $_GET['evidence3'];
$evidence4 			= $_POST['evidence4'];			if($evidence4 == '') 	$evidence4 		= $_GET['evidence4'];
$evidence5 			= $_POST['evidence5'];			if($evidence5 == '') 	$evidence5 		= $_GET['evidence5'];
$evidence6 			= $_POST['evidence6'];			if($evidence6 == '') 	$evidence6 		= $_GET['evidence6'];
$status 			= $_POST['status'];				if($status == '') 		$status 		= $_GET['status'];
$freight_type 		= $_POST['freight_type'];		if($freight_type == '') $freight_type 	= $_GET['freight_type'];
$freetimedays 		= $_POST['freetimedays'];		if($freetimedays == '') $freetimedays 	= $_GET['freetimedays'];
$offer_number 		= $_POST['offer_number'];		if($offer_number == '') $offer_number 	= $_GET['offer_number'];
$linearmeter 		= $_POST['linearmeter'];		if($linearmeter == '') 	$linearmeter 	= $_GET['linearmeter'];
$currency 			= $_POST['currency'];			if($currency == '') 	$currency 		= $_GET['currency'];
$nbofteus 			= $_POST['nbofteus'];			if($nbofteus == '') 	$nbofteus 		= $_GET['nbofteus'];
$precarriage 		= $_POST['precarriage'];		if($precarriage == '') 	$precarriage 	= $_GET['precarriage'];
$recieptplace 		= $_POST['recieptplace'];		if($recieptplace == '') $recieptplace 	= $_GET['recieptplace'];
$portlading 		= $_POST['portlading'];			if($portlading == '') 	$portlading 	= $_GET['portlading'];
$portdischarge 		= $_POST['portdischarge'];		if($portdischarge == '') $portdischarge = $_GET['portdischarge'];
$placedelivery 		= $_POST['placedelivery'];		if($placedelivery == '') $placedelivery = $_GET['placedelivery'];
$carriersign 		= $_POST['carriersign'];		if($carriersign == '') 	$carriersign 	= $_GET['carriersign'];
$nonegotiable 		= $_POST['nonegotiable'];		if($nonegotiable == '') $nonegotiable 	= $_GET['nonegotiable'];
$termcarriage 		= $_POST['termcarriage'];		if($termcarriage == '') $termcarriage 	= $_GET['termcarriage'];
$issuedon 			= $_POST['issuedon'];			if($issuedon == '') 	$issuedon 		= $_GET['issuedon'];
$issuedat			= $_POST['issuedat'];			if($issuedat == '')	 	$issuedat 		= $_GET['issuedat'];
$freight 			= $_POST['freight'];			if($freight == '')	 	$freight 		= $_GET['freight'];
$manifest_date 		= $_POST['manifest_date'];		if($manifest_date == '') $manifest_date = $_GET['manifest_date'];
$nonegotiable 		= $_POST['nonegotiable'];		if($nonegotiable == '') $nonegotiable 	= $_GET['nonegotiable'];
$file1 				= $_POST['file1'];				if($file1 == '') 		$file1 			= $_GET['file1'];
$otherRemark 		= $_POST['otherRemark'];		if($otherRemark == '') 	$otherRemark 	= $_GET['otherRemark'];

$localagent_code	 = $_POST['localagent_code'];		if($localagent_code == '') 			$localagent_code 	 = $_GET['localagent_code'];
$containeragent_code = $_POST['containeragent_code'];	if($containeragent_code == '') 		$containeragent_code = $_GET['containeragent_code'];
$declaredbyforwarder = $_POST['declaredbyforwarder'];	if($declaredbyforwarder == '') 		$declaredbyforwarder = $_GET['declaredbyforwarder'];
$withEmptyContainer  = $_POST['withEmptyContainer'];	if($withEmptyContainer == '') 		$withEmptyContainer  = $_GET['withEmptyContainer'];
$dateval= date("Y-m-d H:i:s");

$issuedon 				= formatdate($issuedon);
$manifest_date 			= formatdate($manifest_date);
$received_date 			= formatdate($received_date);

if ($received_date=='')
	$received_date = "NULL";
else $received_date = "'".$received_date."'";

if ($manifest_date == '') 
	$manifest_date = "NULL";
else $manifest_date = "'".$manifest_date."'";

if ($issuedon == '') 
	$issuedon = "NULL";
else $issuedon = "'".$issuedon."'";

if ($declaredbyforwarder == '') $declaredbyforwarder = 0;
if ($withEmptyContainer == '') $withEmptyContainer = 0;

if(($mode=='insert') || ($mode=='edit')){
	$project_name = $vessel_id.$voyage_number.$voyage_year;
	
	
	$query ="insert into project (Project_Code, Project_Name) values('$project_name','$project_name')";
	$result  = mysql_query($query, $connection);
	//echo $query;
	if ($voyage_type=='I') $blt='Import';
	if ($voyage_type=='E') $blt='Export';
	$query ="insert into costcent (Costcent_code, Costcent_name,  Costcent_CreationDate) values('$blt','$blt',now())";
	$result  = mysql_query($query, $connection);
	
}


$message="";
	$query="SELECT manifest_id,manifest_auto FROM manifest ORDER BY manifest_auto DESC LIMIT 1";
	$result  = mysql_query($query, $connection);
	$row=mysql_fetch_array($result);
	$manifest_id=$row[0];
	if($manifest_id == '') $manifest_id = 0;	
	$newmanifest_id =$manifest_id + 1;

	/*
if ($mode=='insertfromoffer' && $offer_number != ''){
	
	if ($Manifest_Auto == ''){
		$datesubs 	= formatdatetime(date('Y:m:d:H:i:s'));
		$year 		= $datesubs[0];
		$month 		= $datesubs[1];
		$day 		= $datesubs[2];
		$hour 		= $datesubs[3];
		$minutes 	= $datesubs[4];
		$second 	= $datesubs[5];

		
		$query = " 	insert into manifest(  Manifest_date, Manifest_sysdate, Voyage_year,voyage_number,voyage_destination,voyage_BOLnumber,
					BOL_type,BOL_pagenumber,vessel_id,
					BOL_identification, 
					Shipper1, shipper2, shipper3, shipper4, 
					consignee1, consignee2, consignee3, consignee4,
					Notify1, Notify2, Notify3, Notify4,
					agent_id,
					No_of_tues,currency,Precarriage, PlaceofReceipt, Portofloading, PortofDischarge, Placeofdelivery, 
					BOL_freight,Freight_type, issued, date, Negotiable_BOL, term_of_carriage, 
					manifest_id,
					Agent1_id, linear_meters, freetimedays, Offernumber,received_date,client_code,stamp1_id,stamp2_id,stamp3_id,stamp4_id,stamp5_id,stamp6_id,source_agentcode
					,year, month, day, hour, minutes, seconds,line_operator, localagent_code, declaredbyforwarder, manifest_emptyContainer)
					values
					($manifest_date,now(),".strformat($voyage_year).",".strformat($voyage_number).",".strformat($voyage_destination).",".strformat($bol_number).",
					".strformat($voyage_type).",".strformat($voyage_pagenumber).",".strformat($vessel_id).",
					".strformat($billoflading).",
					".strformat($shipper1).",".strformat($shipper2).",".strformat($shipper3).",".strformat($shipper4)."
					,".strformat($consignee1).",".strformat($consignee2).",".strformat($consignee3).",".strformat($consignee4).",
					".strformat($notify1).",".strformat($notify2).",".strformat($notify3).",".strformat($notify4).",
					".strformat($agent_id).",
					".strformat($nbofteus).",".strformat($currency).",
					".strformat($precarriage).",".strformat($recieptplace).",".strformat($portlading).",".strformat($portdischarge).",".strformat($placedelivery).",
					".strformat($freight).",".strformat($freight_type).",".strformat($issuedat).",".$issuedon.",".strformat($nonegotiable).",".strformat($termcarriage).",".strformat($newmanifest_id).",
					".strformat($carriersign).",".strformat($linearmeter).",".strformat($freetimedays).",".strformat($offer_number).",".$received_date.",".strformat($client_name).",".strformat($stamp1).",
					".strformat($stamp2).",".strformat($stamp3).",".strformat($stamp4).",".strformat($stamp5).",".strformat($stamp6).",".strformat($sourceagent)."
					,'$year','$month','$day','$hour','$minutes','$second',".strformat($lineoperator).", ".strformat($localagent_code).", ".$declaredbyforwarder.", ".$withEmptyContainer.");";
		  //echo $query;exit;
		 
		$result  = mysql_query($query, $connection);
		$Manifest_Auto = mysql_insert_id();
		if($result){
			if($offer_number != ''){
				$updateoffre = " update archivingoffer set confirmed = 1 where Offer_code = '$offer_number';";
				$resoffre = mysql_query($updateoffre,$connection);
			}
		}
	} else {
		$query = " update manifest set 
			Manifest_date = ".$manifest_date.", Voyage_year = ".strformat($voyage_year).",voyage_number = ".strformat($voyage_number).",
			voyage_destination = ".strformat($voyage_destination).",voyage_BOLnumber = ".strformat($bol_number).",
			BOL_type = ".strformat($voyage_type).",
			BOL_pagenumber = ".strformat($voyage_pagenumber).",vessel_id =".strformat($vessel_id).",
			BOL_identification=".strformat($billoflading).", 
			Shipper1=".strformat($shipper1).", shipper2=".strformat($shipper2).", shipper3=".strformat($shipper3).", shipper4=".strformat($shipper4).", 
			consignee1=".strformat($consignee1).", consignee2=".strformat($consignee2).", consignee3=".strformat($consignee3).", consignee4=".strformat($consignee4).",
			Notify1=".strformat($notify1).", Notify2=".strformat($notify2).", Notify3=".strformat($notify3).", Notify4=".strformat($notify4).",
			agent_id=".strformat($agent_id).",
			No_of_tues=".strformat($nbofteus).",currency=".strformat($currency).",				
			Precarriage=".strformat($precarriage).", PlaceofReceipt=".strformat($recieptplace).", Portofloading=".strformat($portlading).", 
			PortofDischarge=".strformat($portdischarge).", Placeofdelivery=".strformat($placedelivery).", 
			BOL_freight=".strformat($freight).",Freight_type=".strformat($freight_type).", issued=".strformat($issuedat).", date=".$issuedon.", 
			Negotiable_BOL=".strformat($nonegotiable).", term_of_carriage=".strformat($termcarriage).", 
			Agent1_id=".strformat($carriersign).", linear_meters=".strformat($linearmeter).", freetimedays=".strformat($freetimedays).", Offernumber=".strformat($offer_number).",
			client_code=".strformat($client_name).", received_date=$received_date,
			stamp1_id=".strformat($stamp1).", stamp2_id=".strformat($stamp2).", stamp3_id=".strformat($stamp3).", stamp4_id=".strformat($stamp4).", stamp5_id=".strformat($stamp5).", 
			stamp6_id=".strformat($stamp6).", source_agentcode=".strformat($sourceagent).", line_operator=".strformat($lineoperator).", localagent_code =".strformat($localagent_code).",
			declaredbyforwarder = ".$declaredbyforwarder.", manifest_emptyContainer = ".$withEmptyContainer."
			where manifest_auto='$Manifest_Auto'; ";
		 //echo $query;exit;
		 $result  = mysql_query($query, $connection);
		$manifestdtupdat="update manifestdt set
				 Voyage_year=".strformat($voyage_year).",voyage_number=".strformat($voyage_number).",
				 voyage_destination=".strformat($voyage_destination).",voyage_BOLnumber=".strformat($bol_number).",
				 BOL_type=".strformat($voyage_type).",
				 BOL_pagenumber=".strformat($voyage_pagenumber).",vessel_id=".strformat($vessel_id).",
				 BOL_identification=".strformat($billoflading)."	,source_agentcode=".strformat($sourceagent)."
				 where manifest_manifestauto='$Manifest_Auto';";
		  $result  = mysql_query($manifestdtupdat, $connection);
		  
		  $manifestdesc="update manifestdesc set
						 Voyage_year=".strformat($voyage_year).",voyage_number=".strformat($voyage_number).",
						 voyage_destination=".strformat($voyage_destination).",voyage_BOLnumber=".strformat($bol_number).",
						 BOL_type=".strformat($voyage_type).",
						 BOL_pagenumber=".strformat($voyage_pagenumber).",vessel_id=".strformat($vessel_id).",
						 BOL_identification=".strformat($billoflading).",source_agentcode=".strformat($sourceagent)."
						 where manifest_manifestauto='$Manifest_Auto';";
		  $result  = mysql_query($manifestdesc, $connection);
		  
		  $manifestdtl="update manifestdtl set
						vessel_name=".strformat($vessel_id).",
						Voyage_year=".strformat($voyage_year).",voyage_number=".strformat($voyage_number).",
						voyage_BOLnumber=".strformat($bol_number).",
						BOL_identification=".strformat($billoflading)."	
						where manifest_manifestauto='$Manifest_Auto';";
						
		  $result  = mysql_query($manifestdtl, $connection);
		
	}
	
	$queryman = "select Manifest_sysdate from manifest where  manifest_auto='$Manifest_Auto' ";
	$resman = mysql_query($queryman, $connection);
	$rwman = mysql_fetch_row($resman);
	$sysdate = $rwman[0];
	
	$i=1;
	$querytarros = "select archivingofferdt.item_code, description, amount, archivingofferdt.currency_code
					from archivingofferdt
					inner join archivingoffer on archivingoffer.auto = archivingofferdt.offer_id
					inner join items on items.item_code = archivingofferdt.item_code
					where offer_code='$offer_number' and SubGroup_code='TARROS' ";	
	$restarros = mysql_query ($querytarros, $connection);
	while($rwtarros = mysql_fetch_row($restarros)){
		if ($i == 1){
			$desc1 		= $rwtarros[0];
			$evidence1	= $rwtarros[1];
			$amount1 = ConvertCurrency($rwtarros[3], $currency, $sysdate, $rwtarros[2], $connection);
		}
		if ($i == 2){
			$desc2 		= $rwtarros[0];
			$evidence2	= $rwtarros[1];
			$amount2 = ConvertCurrency($rwtarros[3], $currency, $sysdate, $rwtarros[2], $connection);
		}
		if ($i == 3){
			$desc3 		= $rwtarros[0];
			$evidence3	= $rwtarros[1];
			$amount3 = ConvertCurrency($rwtarros[3], $currency, $sysdate, $rwtarros[2], $connection);
		}
		if ($i == 4){
			$desc4 		= $rwtarros[0];
			$evidence4	= $rwtarros[1];
			$amount4 = ConvertCurrency($rwtarros[3], $currency, $sysdate, $rwtarros[2], $connection);
		}
		if ($i == 5){
			$desc5 		= $rwtarros[0];
			$evidence5	= $rwtarros[1];
			$amount5 = ConvertCurrency($rwtarros[3], $currency, $sysdate, $rwtarros[2], $connection);
		}
		if ($i == 6){
			$desc6 		= $rwtarros[0];
			$evidence6	= $rwtarros[1];
			$amount6 = ConvertCurrency($rwtarros[3], $currency, $sysdate, $rwtarros[2], $connection);
		}
		$i++;
	}

	$upmanifest = "update manifest set tax1_desc=".strformat($desc1).",tax2_desc=".strformat($desc2).",tax3_desc=".strformat($desc3).",tax4_desc=".strformat($desc4).",tax5_desc=".strformat($desc5).",
						tax6_desc=".strformat($desc6).", 
						tax1_amount=".strformat($amount1).",tax2_amount=".strformat($amount2).", tax3_amount=".strformat($amount3).",tax4_amount=".strformat($amount4).",
						tax5_amount=".strformat($amount5).",tax6_amount=".strformat($amount6).",
						evidence1=".strformat($evidence1).",evidence2=".strformat($evidence2).",evidence3=".strformat($evidence3).",evidence4=".strformat($evidence4).",
						evidence5=".strformat($evidence5).",evidence6=".strformat($evidence6)."
					where  manifest_auto='$Manifest_Auto' ";
	$resupmanifest = mysql_query($upmanifest, $connection);
	
	$querydel = "delete from manifestdtl where manifest_manifestauto = $Manifest_Auto ";
	$resdel = mysql_query($querydel, $connection);
	
	$querynottarros = "select archivingofferdt.item_code, item_description, description, amount, qty, ifnull(discount,0), archivingofferdt.currency_code
					from archivingofferdt
					inner join archivingoffer on archivingoffer.auto = archivingofferdt.offer_id
					inner join items on items.item_code = archivingofferdt.item_code
					where offer_code='$offer_number' and SubGroup_code != 'TARROS' ";	
	$resno = mysql_query ($querynottarros, $connection);
	while($rwno = mysql_fetch_row($resno)){
		$itemcode 		= $rwno[0];
		$itemname 	 	= $rwno[1];
		$description 	= $rwno[2];
		$amount 		= $rwno[3];
		$quantity 		= $rwno[4];
		$discount 		= $rwno[5];
		$txtcurr 		= $rwno[6];
		
		$queryitemdt = " insert into ManifestDTL(tax_description, item_name,DESCRIPTION ,tax_amount, quantity, discount,vessel_name, Voyage_year, voyage_number, 
						BOL_identification,manifest_manifestauto, currencycode)
						values('$itemcode','$itemname',".strformat($description).",$amount,$quantity,$discount,".strformat($vessel_id).",".strformat($voyage_year).",".strformat($voyage_number).",
						".strformat($billoflading).",'$Manifest_Auto', '$txtcurr');";
		 
		$resitemdt  = mysql_query($queryitemdt, $connection);

		
	}
	
header("Location: Form_Manifest.php?Manifest_Auto=$Manifest_Auto");
exit;	

}
	
	*/
if($mode=='insert'){
	$datesubs 	= formatdatetime(date('Y:m:d:H:i:s'));
	$year 		= $datesubs[0];
	$month 		= $datesubs[1];
	$day 		= $datesubs[2];
	$hour 		= $datesubs[3];
	$minutes 	= $datesubs[4];
	$second 	= $datesubs[5];
	
	$manifest_orderid = get_nextsequence('manifest_orderid','',$connection);	//echo $manifest_orderid;exit;
	
$query = " 	insert into manifest(  Manifest_date, Manifest_sysdate, Voyage_year,voyage_number,voyage_destination,voyage_BOLnumber,
			BOL_type,BOL_pagenumber,vessel_id,
			BOL_identification, 
			Shipper1, shipper2, shipper3, shipper4, 
			consignee1, consignee2, consignee3, consignee4,
			Notify1, Notify2, Notify3, Notify4,
			agent_id,
			No_of_tues,currency,
			tax1_desc,tax2_desc,tax3_desc,tax4_desc,tax5_desc,tax6_desc,
			tax1_amount,tax2_amount, tax3_amount,tax4_amount,tax5_amount,tax6_amount,
			evidence1,evidence2,evidence3,evidence4,evidence5,evidence6,
			Precarriage, PlaceofReceipt, Portofloading, PortofDischarge, Placeofdelivery, 
			BOL_freight,Freight_type, issued, date, Negotiable_BOL, term_of_carriage, 
			manifest_id,
			Agent1_id, linear_meters, freetimedays, Offernumber,received_date,client_code,stamp1_id,stamp2_id,stamp3_id,stamp4_id,stamp5_id,stamp6_id,source_agentcode
			,year, month, day, hour, minutes, seconds,line_operator, localagent_code, containeragent_code, declaredbyforwarder, manifest_emptyContainer, manifest_orderid, other_remark)
			values
			($manifest_date,now(),".strformat($voyage_year).",".strformat($voyage_number).",".strformat($voyage_destination).",".strformat($bol_number).",
			".strformat($voyage_type).",".strformat($voyage_pagenumber).",".strformat($vessel_id).",
			".strformat($billoflading).",
			".strformat($shipper1).",".strformat($shipper2).",".strformat($shipper3).",".strformat($shipper4)."
			,".strformat($consignee1).",".strformat($consignee2).",".strformat($consignee3).",".strformat($consignee4).",
			".strformat($notify1).",".strformat($notify2).",".strformat($notify3).",".strformat($notify4).",
			".strformat($agent_id).",
			".strformat($nbofteus).",".strformat($currency).",
			".strformat($desc1).",".strformat($desc2).",".strformat($desc3).",".strformat($desc4).",".strformat($desc5).",".strformat($desc6).",
			".strformat($amount1)." ,".strformat($amount2)." ,".strformat($amount3)." ,".strformat($amount4)." ,".strformat($amount5).",".strformat($amount6).",
			".strformat($evidence1).",".strformat($evidence2).",".strformat($evidence3).",".strformat($evidence4).",".strformat($evidence5).",".strformat($evidence6)."
			,".strformat($precarriage).",".strformat($recieptplace).",".strformat($portlading).",".strformat($portdischarge).",".strformat($placedelivery).",
			".strformat($freight).",".strformat($freight_type).",".strformat($issuedat).",".$issuedon.",".strformat($nonegotiable).",".strformat($termcarriage).",".strformat($newmanifest_id).",
			".strformat($carriersign).",".strformat($linearmeter).",".strformat($freetimedays).",".strformat($offer_number).",".$received_date.",".strformat($client_name).",".strformat($stamp1).",
			".strformat($stamp2).",".strformat($stamp3).",".strformat($stamp4).",".strformat($stamp5).",".strformat($stamp6).",".strformat($sourceagent)."
			,'$year','$month','$day','$hour','$minutes','$second',".strformat($lineoperator).", ".strformat($localagent_code).", ".strformat($containeragent_code).", ".$declaredbyforwarder.", ".$withEmptyContainer.",
			".$manifest_orderid.", ".strformat($otherRemark).");";
 // echo $query;exit;
 
$result  = mysql_query($query, $connection);
$Manifest_Auto = mysql_insert_id();
if($result){
	if($offer_number != ''){
		$updateoffre = " update archivingoffer set confirmed = 1 where Offer_code = '$offer_number';";
		$resoffre = mysql_query($updateoffre,$connection);
	}
}
header("Location: Form_Manifest.php?Manifest_Auto=$Manifest_Auto");
exit;

}
else if ($mode=='delete'){
	$query="delete from manifest where manifest_auto='$Manifest_Auto'";
	$result  = mysql_query($query, $connection);
	$querymanifestdt="delete from manifestdt where manifest_manifestauto='$Manifest_Auto'";
	$result  = mysql_query($querymanifestdt, $connection);
	$querymanifestdesc="delete from manifestdesc where manifest_manifestauto='$Manifest_Auto'";
	$result  = mysql_query($querymanifestdesc, $connection);
	$querymanifestdtl="delete from manifestdtl where manifest_manifestauto='$Manifest_Auto'";
	$result  = mysql_query($querymanifestdtl, $connection);
	$querycontainerdt="delete from containerdt where manifest_manifestauto='$Manifest_Auto'";
	$result  = mysql_query($querycontainerdt, $connection);
	$querycontainertrace="delete from containertrace where manifest_manifestauto='$Manifest_Auto'";
	$result  = mysql_query($querycontainertrace, $connection);
	header('Location: ' . $_SERVER['HTTP_REFERER']);
	exit;
}
else if($mode=='edit'){
$query = " update manifest set 
			Manifest_date = ".$manifest_date.", Voyage_year = ".strformat($voyage_year).",voyage_number = ".strformat($voyage_number).",
			voyage_destination = ".strformat($voyage_destination).",voyage_BOLnumber = ".strformat($bol_number).",
			BOL_type = ".strformat($voyage_type).",
			BOL_pagenumber = ".strformat($voyage_pagenumber).",vessel_id =".strformat($vessel_id).",
			BOL_identification=".strformat($billoflading).", 
			Shipper1=".strformat($shipper1).", shipper2=".strformat($shipper2).", shipper3=".strformat($shipper3).", shipper4=".strformat($shipper4).", 
			consignee1=".strformat($consignee1).", consignee2=".strformat($consignee2).", consignee3=".strformat($consignee3).", consignee4=".strformat($consignee4).",
			Notify1=".strformat($notify1).", Notify2=".strformat($notify2).", Notify3=".strformat($notify3).", Notify4=".strformat($notify4).",
			agent_id=".strformat($agent_id).",
			No_of_tues=".strformat($nbofteus).",currency=".strformat($currency).",
			tax1_desc=".strformat($desc1).",tax2_desc=".strformat($desc2).",tax3_desc=".strformat($desc3).",tax4_desc=".strformat($desc4).",tax5_desc=".strformat($desc5).",
			tax6_desc=".strformat($desc6).",
			tax1_amount=".strformat($amount1).",tax2_amount=".strformat($amount2).", tax3_amount=".strformat($amount3).",tax4_amount=".strformat($amount4).",
			tax5_amount=".strformat($amount5).",tax6_amount=".strformat($amount6).",
			evidence1=".strformat($evidence1).",evidence2=".strformat($evidence2).",evidence3=".strformat($evidence3).",evidence4=".strformat($evidence4).",
			evidence5=".strformat($evidence5).",evidence6=".strformat($evidence6).",
			Precarriage=".strformat($precarriage).", PlaceofReceipt=".strformat($recieptplace).", Portofloading=".strformat($portlading).", 
			PortofDischarge=".strformat($portdischarge).", Placeofdelivery=".strformat($placedelivery).", 
			BOL_freight=".strformat($freight).",Freight_type=".strformat($freight_type).", issued=".strformat($issuedat).", date=".$issuedon.", 
			Negotiable_BOL=".strformat($nonegotiable).", term_of_carriage=".strformat($termcarriage).", 
			Agent1_id=".strformat($carriersign).", linear_meters=".strformat($linearmeter).", freetimedays=".strformat($freetimedays).", Offernumber=".strformat($offer_number).",
			client_code=".strformat($client_name).", received_date=$received_date,
			stamp1_id=".strformat($stamp1).", stamp2_id=".strformat($stamp2).", stamp3_id=".strformat($stamp3).", stamp4_id=".strformat($stamp4).", stamp5_id=".strformat($stamp5).", 
			stamp6_id=".strformat($stamp6).", source_agentcode=".strformat($sourceagent).", line_operator=".strformat($lineoperator).", localagent_code =".strformat($localagent_code).",
			containeragent_code =".strformat($containeragent_code).", declaredbyforwarder = ".$declaredbyforwarder.", manifest_emptyContainer = ".$withEmptyContainer.",
			other_remark = ".strformat($otherRemark)."
			where manifest_auto='$Manifest_Auto'; ";
 //echo $query;exit;
 $result  = mysql_query($query, $connection);
 
 $manifestdtupdat="update manifestdt set
				 Voyage_year=".strformat($voyage_year).",voyage_number=".strformat($voyage_number).",
				 voyage_destination=".strformat($voyage_destination).",voyage_BOLnumber=".strformat($bol_number).",
				 BOL_type=".strformat($voyage_type).",
				 BOL_pagenumber=".strformat($voyage_pagenumber).",vessel_id=".strformat($vessel_id).",
				 BOL_identification=".strformat($billoflading)."	,source_agentcode=".strformat($sourceagent)."
				 where manifest_manifestauto='$Manifest_Auto';";
  $result  = mysql_query($manifestdtupdat, $connection);
  
  $manifestdesc="update manifestdesc set
				 Voyage_year=".strformat($voyage_year).",voyage_number=".strformat($voyage_number).",
				 voyage_destination=".strformat($voyage_destination).",voyage_BOLnumber=".strformat($bol_number).",
				 BOL_type=".strformat($voyage_type).",
				 BOL_pagenumber=".strformat($voyage_pagenumber).",vessel_id=".strformat($vessel_id).",
				 BOL_identification=".strformat($billoflading).",source_agentcode=".strformat($sourceagent)."
				 where manifest_manifestauto='$Manifest_Auto';";
  $result  = mysql_query($manifestdesc, $connection);
  
  $manifestdtl="update manifestdtl set
				vessel_name=".strformat($vessel_id).",
				Voyage_year=".strformat($voyage_year).",voyage_number=".strformat($voyage_number).",
				voyage_BOLnumber=".strformat($bol_number).",
				BOL_identification=".strformat($billoflading)."	
				where manifest_manifestauto='$Manifest_Auto';";
				
  $result  = mysql_query($manifestdtl, $connection);
 
 $query = "select manifestdt.auto, Container, ctrflag,Marks, Packages,Container_Weight, CubeMeters,manifestdt.auto,descriptiongood,manifestdt.detailsequence, ifnull(detailtype,'') 
			from manifestdt
			inner join manifestdesc on  manifestdt.manifest_manifestauto=manifestdesc.manifest_manifestauto and manifestdesc.detailsequence=manifestdt.detailsequence
			where manifestdt.manifest_manifestauto='$Manifest_Auto'
			group by manifestdt.auto";
			//echo $query;
			$resultdes=mysql_query($query,$connection);
			$tempmanifest='';
			$i=0;
			
 while($row=mysql_fetch_array($resultdes)){
	 
	$i++;
	$manifestdt_auto= $row[0];
	$Container		= $row[1];
	$ctrflag		= $row[2];
	$freedaydiffs	= $freetimedays-1;
	$detailtype  	= $row[10];
	
 if($freedaydiffs<0){
	 //$departdate=$received_date;
	 $freedaydiffs=0;
 }
 
 

	 if ($ctrflag!='*' || $detailtype == '1')
	 {		$remark='';
 	
 $tempmanifest=$manifestdt_auto; 
 $selectcontainer="select * from containerdt where manifestdt_auto='$manifestdt_auto'";
 $container_result=mysql_query($selectcontainer,$connection);
 $num_rows = mysql_num_rows($container_result);
 if ($num_rows<1){

	$queryinsert= "insert into containerdt (  container_sysdate, container_BOL, Client_code, container_freeday, received_date,
					departure_date, Shipper, consigne, vessel_name, container_code, remark, Voyage_year, voyage_number, manifestdt_auto,manifest_manifestauto)
					values 
					(now(),".strformat($billoflading).",".strformat($client_name).",".strformat($freetimedays).",DATE_ADD($received_date, INTERVAL $freedaydiffs DAY),$received_date,
					".strformat($shipper1).",".strformat($consignee1).",".strformat($vessel_id).",".strformat($Container).",NULL,".strformat($voyage_year).",".strformat($voyage_number).",
					'$manifestdt_auto','$Manifest_Auto');";
	$resultinsert=mysql_query($queryinsert,$connection);
 }	 
 else {
	
		$queryupdate= "update containerdt set  	 
					container_BOL=".strformat($billoflading).", Client_code=".strformat($client_name).", container_freeday=".strformat($freetimedays).", received_date=$received_date,
					departure_date=DATE_ADD($received_date, INTERVAL $freedaydiffs DAY), Shipper=".strformat($shipper1).", consigne=".strformat($consignee1).", vessel_name=".strformat($vessel_id).",
					container_code=".strformat($Container).", Voyage_year=".strformat($voyage_year).", voyage_number=".strformat($voyage_number)."	 
					where manifestdt_auto='$manifestdt_auto';";
		$resultinsert=mysql_query($queryupdate,$connection);
	 
 }

 $selectcontainertr="select * from containertrace where manifestdt_auto='$manifestdt_auto'";
// echo $selectcontainertr;
 $containertr_result=mysql_query($selectcontainertr,$connection);
 $num_rowtr = mysql_num_rows($containertr_result);
 if($voyage_type=='E')$phase=4;
	 else $phase=1;
	 
	
 if ($num_rowtr<1){
	
	 $insertcontainertrace = " insert into containerTrace ( manifest_manifestauto,container_no, Manifest_auto,
				Voyage_year, voyage_number, BOL_identification, vessel_name,Manifestdt_auto,phase_id, freetimedays, bl_type,From_date,To_Date)
				values('$Manifest_Auto',".strformat($Container).",'$Manifest_Auto',".strformat($voyage_year).",".strformat($voyage_number).",".strformat($billoflading).",
				".strformat($vessel_id).",'$manifestdt_auto',".strformat($phase).",".strformat($freetimedays).",".strformat($voyage_type).",
				$received_date, DATE_ADD($received_date, INTERVAL $freedaydiffs DAY))";
	
	 	 $resultinsert=mysql_query($insertcontainertrace,$connection);
	
 }
 else {
	 
	$updatecontainertrace =" update  containerTrace set container_no=".strformat($Container).",phase_id=".strformat($phase)." ,freetimedays=".strformat($freetimedays).",
				Voyage_year=".strformat($voyage_year).", voyage_number=".strformat($voyage_number).", BOL_identification=".strformat($billoflading).", vessel_name=".strformat($vessel_id).",
				bl_type=".strformat($voyage_type).", From_date=$received_date, To_Date=DATE_ADD($received_date, INTERVAL $freedaydiffs DAY)
				where   manifestdt_auto='$manifestdt_auto'";
	 $resultinsert=mysql_query($updatecontainertrace,$connection);
 }
 
 }
	if ($ctrflag=='*'){
		
		$selectcontainer="select * from containerdt where manifestdt_auto='$tempmanifest'";
		$container_result=mysql_query($selectcontainer,$connection);
		
		$queryupdate = " update containerdt set remark =concat('$remark', ' seal: ','$Container'),
					container_BOL=".strformat($billoflading).", Client_code=".strformat($client_name).", container_freeday=".strformat($freetimedays).", received_date=$received_date,
					departure_date=DATE_ADD($received_date, INTERVAL $freedaydiffs DAY), Shipper=".strformat($shipper1).", consigne=".strformat($consignee1).", vessel_name=".strformat($vessel_id).", 
					Voyage_year=".strformat($voyage_year).", voyage_number=".strformat($voyage_number)."
					where manifestdt_auto='$tempmanifest'";
		//echo $queryupdate;
		$remark=$remark. ' seal: '.$Container;
	 $resultupdate=mysql_query($queryupdate,$connection);
	
	 }
	 
	
 }
 

 if ($offer_number != ''){
	$querydtl = "select manifestdtl_id, tax_description, tax_amount, currencycode from manifestdtl where manifest_manifestauto='$Manifest_Auto' "; 
	$resdtl = mysql_query($querydtl, $connection); 
	while ($rwdtl = mysql_fetch_array($resdtl)){
		$manifestdtl_id = $rwdtl[0];
		$itemcode 		= $rwdtl[1];
		$amount			= $rwdtl[2];
		$txtcurr		= $rwdtl[3];
		
		$queryItem = "select Item_SellingPrice1, Currency_code from items where item_code = '$itemcode'";
		$resItem = mysql_query($queryItem, $connection);
		$rowItem = mysql_fetch_row($resItem);
		
		$queryOffer = "select amount, currency_code from archivingofferdt
						inner join archivingoffer on archivingoffer.auto = archivingofferdt.offer_id
						where Offer_code = '$offer_number' and item_code = '$itemcode'";  
		$resOffer = mysql_query($queryOffer, $connection);
		$rowOffer = mysql_fetch_row($resOffer);
		if ($rowOffer[0] != '' && $rowOffer[0] != 0)
			$amount = $rowOffer[0];
		else if ($rowItem[0] != '' && $rowItem[0] != 0)
			$amount = $rowItem[0];
		
		if ($rowOffer[1] != '')
			$txtcurr = $rowOffer[1];
		else if ($rowItem[1] != '')
			$txtcurr = $rowItem[1];
		
		$updatedtl = "update manifestdtl set tax_amount = $amount, currencycode = '$txtcurr' where manifestdtl_id = $manifestdtl_id";
		$resupdatedtl = mysql_query($updatedtl, $connection);
	}
	 
 }
 /* $loc = '';
 if ($searchpol != '') 		$loc = "&searchpol=$searchpol";
 if ($searchlagent != '') 	$loc = "&searchlagent=$searchlagent";
 if ($searchtbl != '') 		$loc = "&searchtbl=$searchtbl"; */
  echo "<form id='manifestaction' name='manifestaction' method='post'>";
 echo "<input type='hidden' name='searchpol' id='searchpol' value='$searchpol'>
		<input type='hidden' name='searchlagent' id='searchlagent' value='$searchlagent'>
		<input type='hidden' name='searchtbl' id='searchtbl' value='$searchtbl'>
		<input type=hidden name='Manifest_Auto' value='$Manifest_Auto' id='Manifest_Auto'>";
 echo "</form>";
 
 echo "<script> ";
 echo " document.manifestaction.action='Form_Manifest.php?Manifest_Auto=$Manifest_Auto';";
 echo " document.manifestaction.submit(); "; 
 echo "</script>";
//header("Location: Form_Manifest.php?Manifest_Auto=$Manifest_Auto".$loc);
exit;
}



//ECHO $mode."mm";
$modestamp=$_GET['mode'];
if($modestamp=='updatestamp'){
	
 $query = " update manifest set stamp1_id=".strformat($stamp1).",stamp2_id=".strformat($stamp2).",stamp3_id=".strformat($stamp3).",
			stamp4_id=".strformat($stamp4).",stamp5_id=".strformat($stamp5).",stamp6_id=".strformat($stamp6)."
			where manifest_auto='$Manifest_Auto'";
 
 $result  = mysql_query($query, $connection);
 header('Location: Form_Manifest_stamp.php?Manifest_Auto='.$Manifest_Auto.'&selectstamp=1');
 exit;
 
}





if($modestamp=='updatemanifeststamp'){

 if ($stampdescstatus=='on'){$stampdescstatus=1;}
 else{$stampdescstatus=0;}
 $query="update manifest set stampdescstatus='$stampdescstatus' where manifest_auto='$Manifest_Auto'";
 $result  = mysql_query($query, $connection);

	
$query="select * from manifeststamp where manifest_manifestauto='$Manifest_Auto'";
$result  = mysql_query($query, $connection);


 $num_rows = mysql_num_rows($result);
 
 
  $selectmanifest = " select Voyage_year, voyage_number, voyage_destination, voyage_BOLnumber, BOL_type, BOL_pagenumber,source_agentcode, year, month, day, hour, minutes, seconds 
					from manifest where manifest_Auto='$Manifest_Auto'";
	$result  = mysql_query($selectmanifest, $connection);
	$row = mysql_fetch_row($result);
	$Voyage_year		= $row[0];
	$voyage_number		= $row[1];
	$voyage_destination	= $row[2];
	$voyage_BOLnumber	= $row[3];
	$BOL_type			= $row[4];
	$BOL_pagenumber		= $row[5];
	$source_agentcode	= $row[6];
	$year				= $row[7];
	$month				= $row[8];
	$day				= $row[9];
	$hour				= $row[10];
	$minutes			= $row[11];
	$second				= $row[12];
	
if($num_rows>=1){
	
	$updatestamp = " update manifeststamp set stampdesc1=".strformat($stampdesc1).", stampdesc2=".strformat($stampdesc2).", 
				stampdesc3=".strformat($stampdesc3).", stampdesc4=".strformat($stampdesc4).", stampdesc5=".strformat($stampdesc5).", 
				stampdesc6=".strformat($stampdesc6).", stampdesc7=".strformat($stampdesc7).", 
				stampdesc8=".strformat($stampdesc8).", stampdesc9=".strformat($stampdesc9).",
				stampdesc10=".strformat($stampdesc10).", stampdesc11=".strformat($stampdesc11).", stampdesc12=".strformat($stampdesc12).", 
				stampdesc13=".strformat($stampdesc13).", stampdesc14=".strformat($stampdesc14).", 
				stampdesc15=".strformat($stampdesc15).", stampdesc16=".strformat($stampdesc16).", stampdesc17=".strformat($stampdesc17).", stampdesc18=".strformat($stampdesc18).", 
				stampdesc19=".strformat($stampdesc19).",
				stampdesc20=".strformat($stampdesc20).", stampdesc21=".strformat($stampdesc21).", stampdesc22=".strformat($stampdesc22).",source_agentcode=".strformat($source_agentcode).",
				Voyage_year=".strformat($Voyage_year).", voyage_number=".strformat($voyage_number).", voyage_destination=".strformat($voyage_destination).", BOL_type=".strformat($BOL_type).", 
				voyage_BOLnumber=".strformat($voyage_BOLnumber).", BOL_pagenumber=".strformat($BOL_pagenumber)."
				where manifest_manifestauto='$Manifest_Auto'";
$result  = mysql_query($updatestamp, $connection);
//echo $updatestamp;
 }
 else{
	$query = " insert into manifeststamp (
			Voyage_year, voyage_number, voyage_destination, BOL_type, voyage_BOLnumber, BOL_pagenumber, stampdesc1, stampdesc2, 
			stampdesc3, stampdesc4, stampdesc5, stampdesc6, stampdesc7, stampdesc8, stampdesc9, stampdesc10, stampdesc11, stampdesc12, stampdesc13, stampdesc14, 
			stampdesc15, stampdesc16, stampdesc17, stampdesc18, stampdesc19, stampdesc20, stampdesc21, stampdesc22, source_agentcode, year, month, day, hour, minutes,
			seconds, manifest_manifestauto)
			values(".strformat($Voyage_year).",".strformat($voyage_number).",".strformat($voyage_destination).",".strformat($BOL_type).",".strformat($voyage_BOLnumber).",
			".strformat($BOL_pagenumber).", ".strformat($stampdesc1).",".strformat($stampdesc2).",
			".strformat($stampdesc3).",".strformat($stampdesc4).",".strformat($stampdesc5).",".strformat($stampdesc6).",".strformat($stampdesc7).",".strformat($stampdesc8).",
			".strformat($stampdesc9).",".strformat($stampdesc10).",".strformat($stampdesc11).",".strformat($stampdesc12).",
			".strformat($stampdesc13).",".strformat($stampdesc14).",".strformat($stampdesc15).",".strformat($stampdesc16).",".strformat($stampdesc17).",".strformat($stampdesc18).",
			".strformat($stampdesc19).",".strformat($stampdesc20).",
			".strformat($stampdesc21).",".strformat($stampdesc22).",".strformat($source_agentcode).",'$year','$month','$day','$hour','$minutes','$second','$Manifest_Auto' )";
	 $result  = mysql_query($query, $connection);
 
 //echo $query;
 }
 
 header("Location: Form_Manifest_close.php");
 
exit;

}

if ($confirm_mode=='confirm'){
	
	$Delivery_Taxable = 0;
	$Delivery_NonTaxable = 0;
	$Delivery_vat = 0;
	
	
	$queryselect="select client_code,received_date,manifest_confirm,currency
				  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];
	$currency=$row[3];
		
		
	
	if ($manifest_confirm==1){
		$message="this manifest already confirmed";
		header("Location: Form_ManifestsSearch.php?message=$message");
		exit;
	}
	else if (($clientcode=='') || ($deliverydate=='')){
		$message="you have to fill the client and the received date";
		header("Location: Form_ManifestsSearch.php?message=$message");
		exit;
	}
	else{
		
	$errorExists = 0;
	$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];
		$sysdate = $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;
		
		$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];
		}
		$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;
			$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];
			
						
		//#	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";
		
		$errorExists = 0;
		 $result  = mysql_query($query, $connection);
		if(!$result){
			$errorExists = 1;
		}
		 
		if($errorExists == 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 = '$currToUse' ";
					//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 = '$currToUse';";	
			$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++;
			}
			$cntr=0;
				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];
					$PSaVatChkbx = 0;
				
				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 Item_Vat, 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 = "";
						$ErrorExists = 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 Item_Vat, 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 = "";
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}
			
					
		} // End CasePack Item
			$cntr++;
		}
			if($ErrorExists == 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 foreach currArr
	} // end if count > 0
		
		if($errorExists == 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";
		}
		
		if ($message=='') $message = $messageconfirm;
		header("Location: Form_ManifestsSearch.php?message=$message");
	}
	
	
	
	
}

if ($mainmode=='setprvmanifest'){
	$voyage_year 	= $_GET['voyage_year'];
	$voyage_number 	= $_GET['voyage_number'];
	$searchpol 		= $_GET['searchpol'];
	$searchlagent 	= $_GET['searchlagent'];
	$searchtbl 		= $_GET['searchtbl'];
	
	$query="select manifest_auto from manifest where voyage_year='$voyage_year' and voyage_number='$voyage_number' ";
	if ($searchpol != '')	 $query .= " and Portofloading like '%".$searchpol."%' ";
	if ($searchlagent != '') $query .= " and localagent_code like '%".$searchlagent."%' ";
	if ($searchtbl != '') 	 $query .= " and BOL_type like '%".$searchtbl."%' ";
	
	$query .= " and manifest_auto<='$Manifest_Auto' order by manifest_auto desc limit 1 " ;
	
	//echo $query;
	$resultlog=mysql_query($query,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	$Manifest_Auto=$rows[0];
	echo $Manifest_Auto;
	echo "[BRK]";
	echo $query;
	echo "[BRK]";
	
}
exit;
}
if ($mainmode=='setnextmanifest'){
	$voyage_year 	= $_GET['voyage_year'];
	$voyage_number 	= $_GET['voyage_number'];
	$searchpol 		= $_GET['searchpol'];
	$searchlagent 	= $_GET['searchlagent'];
	$searchtbl 		= $_GET['searchtbl'];
	
	$query = " select manifest_auto from manifest where voyage_year = '$voyage_year'  and voyage_number = '$voyage_number'  ";
	
	if ($searchpol != '')	 $query .= " and Portofloading like '%".$searchpol."%' ";
	if ($searchlagent != '') $query .= " and localagent_code like '%".$searchlagent."%' ";
	if ($searchtbl != '') 	 $query .= " and BOL_type like '%".$searchtbl."%' ";
	
	$query .= " and manifest_auto>='$Manifest_Auto' order by manifest_auto  limit 1 " ;
	
	//echo $query;
	$resultlog=mysql_query($query,$connection) or die(mysql_error());
	$rows=mysql_fetch_row($resultlog);
	$Manifest_Auto=$rows[0];
	echo $Manifest_Auto;
	echo "[BRK]";
	echo $query;
	echo "[BRK]";

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

mysql_close($connection);

function getOfferAmountPerItem ($Manifest_Auto, $descval, $amountval, $offer_number, $currency, $connection){
	
		if ($Manifest_Auto != '')
			$queryman = "select manifest_sysdate from manifest where manifest_auto = $Manifest_Auto ";
		else 
			$queryman = "select now() ";
		
		$resman = mysql_query($queryman, $connection);
		$rwman = mysql_fetch_row($resman);	
		$sysdate = $rwman[0];
				
		$queryItem = "select Item_SellingPrice1, Currency_code from items where item_code = '$descval'";
		$resItem = mysql_query($queryItem, $connection);
		$rowItem = mysql_fetch_row($resItem);
		
		$queryOffer = "select amount, currency_code from archivingofferdt
						inner join archivingoffer on archivingoffer.auto = archivingofferdt.offer_id
						where Offer_code = '$offer_number' and item_code = '$descval'"; 
		$resOffer = mysql_query($queryOffer, $connection);
		$rowOffer = mysql_fetch_row($resOffer);
		if ($rowOffer[0] != '' && $rowOffer[0] != 0){
			$amountval = $rowOffer[0];
			if ($rowOffer[1] != '')
				$currency2 = $rowOffer[1];
			else 
				$currency2 = $currency;
			$amountval = ConvertCurrency($currency2, $currency, $sysdate, $amountval, $connection);
			
		}
		else if ($rowItem[0] != '' && $rowItem[0] != 0){
			$amountval = $rowItem[0];
			if ($rowItem[1] != '')
				$currency2 = $rowItem[1];
			else 
				$currency2 = $currency;
			$amountval = ConvertCurrency($currency2, $currency, $sysdate, $amountval, $connection);
			
		}
		
		if ($amountval == '') $amountval = 0;
		return $amountval;
	
}
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 strformat($str){
	if($str == '')
		$str = "NULL";
	else
		$str = "'".ereg_replace("'", "\'", $str)."'";
		
	return $str;	
} 
function getVAT($item_code, $connection){
	$query = "select ifnull(item_vat,0) from items where item_code='$item_code';";
	$res = mysql_query($query, $connection);
	$rw = mysql_fetch_row($res);
	$vat = $rw[0];
	if($vat == '') $vat = 0;
	return $vat;
}


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;


?>
		           