<?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");
include("Forms_DataGrid_Manifest.php");



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

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

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

//Read From Module Table

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

$querySalesSetup="Select SalesTTC, TipsAccount, CashCur 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, Setup_Branch from setup";
$result= mysql_query($query_setup,$connection) or die( mysql_error());
while($rowsetup=mysql_fetch_array($result)){
	extract($rowsetup);
}




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

$message="";


if($vmode=='insertmanifest'){
	$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 "insert into manifest";
	$query="SELECT manifest_id,manifest_auto FROM manifest ORDER BY manifest_auto DESC LIMIT 1";
	$result  = mysql_query($query, $connection);
	if($row=mysql_fetch_array($result)){$manifest_id=$row[0];}
	

	$newmanifest_id =$manifest_id + 1;
		
	$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, declaredbyforwarder, manifest_emptyContainer, containeragent_code, 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).", ".$declaredbyforwarder.", ".$withEmptyContainer.", ".strformat($containeragent_code).",
			".$manifest_orderid.", ".strformat($otherRemark).");";

 	$result  = mysql_query($query, $connection);

	$lastid = mysql_insert_id($connection);
	$Manifest_Auto=$lastid;
		
}

if($mainmode=='insert'){
	// set amount and currency based on Offer Number 
	if ($offer_number != ''){
		$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];
		
		
	}
$query = " 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');";
 
$result  = mysql_query($query, $connection);

if ($vmode=='insertmanifest'){
echo $lastid;
echo "[BRK]";


ShowitemGrid($connection,'Manifest_Dtl',$Manifest_Auto,$_SESSION['gdl_parameters'],$_SESSION['gdl_arrayaccess'],'ManifestDt.DeliveryDt_ID');
echo "[BRK]";
Showtotalamount($connection,$Manifest_Auto);
echo "[BRK]";

exit;

}

else 
{
	//echo $query;
Showtotalamount($connection,$Manifest_Auto);
echo "[BRK]";
ShowitemGrid($connection,'Manifest_Dtl',$Manifest_Auto,$_SESSION['gdl_parameters'],$_SESSION['gdl_arrayaccess'],'ManifestDt.DeliveryDt_ID');
echo "[BRK]";


}
exit;



}

if($mainmode=='update'){
	// set amount and currency based on Offer Number 
	
	if ($offer_number != ''){
		$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];
		
		
	}
$query = " update ManifestDTL set tax_description='$itemcode', item_name='$itemname', tax_amount='$amount', quantity='$quantity', discount='$discount' ,DESCRIPTION=".strformat($description).", 
		vessel_name=".strformat($vessel_id).", Voyage_year=".strformat($voyage_year).", voyage_number=".strformat($voyage_number).", BOL_identification=".strformat($billoflading).",
		manifest_manifestauto='$Manifest_Auto', currencycode = '$txtcurr' where manifestdtl_id='$manifestdtl_id';";
 
 
$result  = mysql_query($query, $connection);

Showtotalamount($connection,$Manifest_Auto);
echo "[BRK]";
ShowitemGrid($connection,'Manifest_Dtl',$Manifest_Auto,$_SESSION['gdl_parameters'],$_SESSION['gdl_arrayaccess'],'ManifestDt.DeliveryDt_ID');

echo "[BRK]";
exit;


}
if($mainmode=='delete'){
	$querybill="select BOL_identification from ManifestDTL where  manifestdtl_id='$manifestdtl_id'";
	$result  = mysql_query($querybill, $connection);
	$row=mysql_fetch_row($result);
	$billoflading=$row[0];
	
	
$query="delete from  ManifestDTL  where manifestdtl_id='$manifestdtl_id';";
 
 
$result  = mysql_query($query, $connection);
Showtotalamount($connection,$Manifest_Auto);
echo "[BRK]";

ShowitemGrid($connection,'Manifest_Dtl',$Manifest_Auto,$_SESSION['gdl_parameters'],$_SESSION['gdl_arrayaccess'],'ManifestDt.DeliveryDt_ID');
echo "[BRK]";

}

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


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

 function strformat($str){
	if($str == '')
		$str = "NULL";
	else
		$str = "'".ereg_replace("'", "\'", $str)."'";
		
	return $str;	
}