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


include("config.inc.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");

$mode = $_GET['mode'];

$voy_year 			= $_POST['ark_voyyear'];
$voy_nbr	 		= $_POST['ark_voynb'];
$voy_dest			= $_POST['ark_voydest'];
$line_op 			= $_POST['ark_lineop'];

$portofLoading		= $_POST['ark_pol'];
$portofdischarge 	= $_POST['ark_pod'];
$received_date 		= $_POST['ark_rcvdate'];
$notify		 		= $_POST['ark_notify'];

$vessel				= $_POST['ark_vessel'];
$shipper 			= $_POST['ark_shipper'];
$cosignee			= $_POST['ark_cosignee'];


$path="select manifest_path from setup";
$res = mysql_query($path,$connection);
$rows = mysql_fetch_row($res);
$filepath = $rows[0];

$ErrorExists = 0;
$message = '';
if ($filepath == ''){
	$ErrorExists = 1;
	$message = "File Path in Setup is Empty!";
}


// import mode
if ($mode == 'import' && $ErrorExists == 0){
	$path = $filepath."/Arkas/Import/Arkas.txt";
	$tempBOL = '**';
	$tempBLtype = '**';
	
	if ($ark_rcvdate != ''){
		$ndate = explode('-', $ark_rcvdate);
		$ark_rcvdate = $ndate[2]."-".$ndate[1]."-".$ndate[0];
	}
	if (!(file_exists($path))){
		$ErrorExists = 1;
		$message = "File Path $path Not Found!";
	} 
	
	if ($ErrorExists == 0){
		$field = array();
		
		$query = "select fieldname1, rec_pos, fieldlength,  excludechar, tablename from arkas";
		$res = mysql_query($query, $connection);
		while($rw = mysql_fetch_array($res)){
			$fieldname   = $rw[0];
			$rec_pos	 = $rw[1]; 
			$fieldlength = $rw[2];  
			$excludechar = $rw[3];
			
			$field[$fieldname]['name'] = $fieldname;
			$field[$fieldname]['pos']  = $rec_pos;
			$field[$fieldname]['len']  = $fieldlength;
			$field[$fieldname]['excl'] = $excludechar;
		}
		
		
		
		$detailseqTemp = '';	
		//open file 
		$myfile = fopen($path, "r") or die("Unable to open file!");
		while(!feof($myfile)) {
			$line = fgets($myfile);
			//echo $line;echo "<br>";
			$query = "select upper(fieldname1), rec_pos, fieldlength,  excludechar, tablename from arkas";
			$res = mysql_query($query, $connection);
			while($rw = mysql_fetch_array($res)){
				$rec_pos = $rw[1] - 1;
				$excl = str_split($rw[3]);
				
				if ($rw[0] == 'BOL_TYPE'){
					$boltype = str_replace($excl,'',substr($line, $rec_pos, $rw[2]));
					//echo $boltype;echo "<br>";
				}
				
				if ($rw[0] == 'BOL_IDENTIFICATION'){
					$bolnumber = str_replace($excl,'',substr($line, $rec_pos, $rw[2]));
					$bolpnbr = substr(trim($bolnumber),-3);
					//echo $bolnumber;echo "<br>";
					//echo $bolpnbr;echo "<br>";
				}
				
				if ($rw[0] == 'DETAILSEQUENCE'){
					$detailseq = str_replace($excl,'',substr($line, $rec_pos, $rw[2]));
					$detailseq = addZeros(trim($detailseq));
					//echo $detailseq;echo "<br>";
				}
				
				if ($rw[0] == 'CONTAINER'){
					$container = str_replace($excl,'',substr($line, $rec_pos, $rw[2]));
					$container = trim($container);
					//echo $container;echo "<br>";
				}
				
				if ($rw[0] == 'PACKAGES'){
					$pckgs = str_replace($excl,'',substr($line, $rec_pos, $rw[2]));
					$pckgs = trim($pckgs);
					//echo $pckgs;echo "<br>";
				}
				
				if ($rw[0] == 'CONTAINER_WEIGHT'){
					$cntr_weight = str_replace($excl,'',substr($line, $rec_pos, $rw[2]));
					$cntr_weight = trim($cntr_weight);
					//echo $cntr_weight;echo "<br>";
				}
				
				if ($rw[0] == 'DESCRIPTIONGOOD'){
					$descgd = str_replace($excl,'',substr($line, $rec_pos, $rw[2]));
					if (trim($descgd!= '')) 
						$descArr = splitString($descgd);
					//var_dump($descArr);echo "<br><Br>";
					//echo $descgd;echo "<br>"; 
				}
			}
			
			if ($bolnumber != ''){
				// insert into manifest
				if ($bolnumber != $tempBOL){
					
					$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;
					
					$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];
					
					$queryManifest = "insert into manifest 
									(Manifest_date, Manifest_sysdate, Voyage_year, voyage_number, voyage_destination, voyage_BOLnumber, BOL_type, BOL_pagenumber, vessel_id, BOL_identification, Shipper1,
									consignee1, Notify1, Portofloading, PortofDischarge, No_of_tues, manifest_id, received_date, 
									year, month, day, hour, minutes, seconds, line_operator) 
									values 
								(now(), now(), '$ark_voyyear', '$ark_voynb', '$ark_voydest', '$bolpnbr', '$boltype', '01', ".strformat($ark_vessel).", '$bolnumber', ".strformat($ark_shipper).",
								".strformat($ark_cosignee).", ".strformat($ark_notify).", ".strformat($ark_pol).", ".strformat($ark_pod).", NULL, $newmanifest_id,  ".strformat($ark_rcvdate).",
								'$year', '$month', '$day', '$hour', '$minutes', '$second', ".strformat($ark_lineop)." ) ";
					//echo $queryManifest;echo "<br>";echo "<br>";
					$resultManifest = mysql_query($queryManifest, $connection);
					$manifest_auto = mysql_insert_id();
					//$manifest_auto = $manifest_auto+1;
					$detailseqTemp = '';
					
				}
				
				if ($detailseqTemp == '')
					$detailseqTemp = $detailseq;
				
				if ($manifest_auto != ''){
					// insert containers into manifestdt
					$queryManifestdt = "insert into manifestdt (Manifest_date, Manifest_sysdate, Voyage_year, voyage_number, voyage_destination, voyage_BOLnumber, voyage_descripiton, BOL_type, 
										BOL_pagenumber, vessel_id, BOL_identification, detailsequence, CTRFlag, Container, Packages, Container_Weight, year, month, day, hour, minutes, 
										seconds, manifest_manifestauto, detailtype)
										select Manifest_date, Manifest_sysdate, Voyage_year, voyage_number, voyage_destination, voyage_BOLnumber, voyage_descripiton, BOL_type,
										BOL_pagenumber, vessel_id, BOL_identification, '$detailseqTemp', NULL, '$container', '$pckgs', '$cntr_weight', year, month, day, hour, minutes, 
										seconds, $manifest_auto, 1
										from manifest where Manifest_auto = $manifest_auto ";
					//echo $queryManifestdt;echo "<br>";	
					$resultManifest = mysql_query($queryManifestdt, $connection);
					
					if (!empty($descArr)){
						$cnt = 0;var_dump($descArr);echo "<br><Br>";
						foreach($descArr as $desc){
							
								if ($cnt > 0){
									$queryManifestdt = "insert into manifestdt (Manifest_date, Manifest_sysdate, Voyage_year, voyage_number, voyage_destination, voyage_BOLnumber, voyage_descripiton, BOL_type, 
										BOL_pagenumber, vessel_id, BOL_identification, detailsequence, CTRFlag, Container, Packages, Container_Weight, year, month, day, hour, minutes, 
										seconds, manifest_manifestauto, detailtype)
										select Manifest_date, Manifest_sysdate, Voyage_year, voyage_number, voyage_destination, voyage_BOLnumber, voyage_descripiton, BOL_type,
										BOL_pagenumber, vessel_id, BOL_identification, '$detailseqTemp', '*', NULL, NULL, NULL, year, month, day, hour, minutes, 
										seconds, $manifest_auto, 5
										from manifest where Manifest_auto = $manifest_auto ";
									//echo $queryManifestdt;echo "<br>";	
									$resultManifest = mysql_query($queryManifestdt, $connection);
									
								}
								$queryManifestDesc = " insert into manifestdesc (Manifest_date, Manifest_sysdate, Voyage_year, voyage_number, voyage_destination, voyage_BOLnumber, voyage_descripiton, 
												BOL_type, BOL_pagenumber, vessel_id, BOL_identification, detailsequence, descriptiongood,  
												year, month, day, hour, minutes, seconds, manifest_manifestauto) 
												select Manifest_date, Manifest_sysdate, Voyage_year, voyage_number, voyage_destination, voyage_BOLnumber, voyage_descripiton,
												BOL_type, BOL_pagenumber, vessel_id, BOL_identification, '$detailseqTemp', ".strformat($desc).", 
												year, month, day, hour, minutes, seconds, $manifest_auto
												from manifest where Manifest_auto = $manifest_auto ;";//echo $queryManifestDesc."<br><br>";
								$resultManifestDesc = mysql_query($queryManifestDesc, $connection);
								$detailseqTemp = addZeros(($detailseqTemp+1));
								$cnt++;
						}						
					} else {
						$queryManifestDesc = " insert into manifestdesc (Manifest_date, Manifest_sysdate, Voyage_year, voyage_number, voyage_destination, voyage_BOLnumber, voyage_descripiton, 
											BOL_type, BOL_pagenumber, vessel_id, BOL_identification, detailsequence, descriptiongood,  
											year, month, day, hour, minutes, seconds, manifest_manifestauto) 
											select Manifest_date, Manifest_sysdate, Voyage_year, voyage_number, voyage_destination, voyage_BOLnumber, voyage_descripiton,
											BOL_type, BOL_pagenumber, vessel_id, BOL_identification, '$detailseqTemp', NULL, 
											year, month, day, hour, minutes, seconds, $manifest_auto
											from manifest where Manifest_auto = $manifest_auto ;";//echo $queryManifestDesc."<br>";
						$resultManifestDesc = mysql_query($queryManifestDesc, $connection);
						$detailseqTemp = addZeros(($detailseqTemp+1));
						
					}
					
					// update manifest
					$queryTues = "select sum(cntr_tues)
									from manifestdt
									inner join container on Container.cntr_code=manifestdt.container
									where  manifest_manifestauto='$manifest_auto';";
					$resultTues = mysql_query($queryTues, $connection);
					$rwTues = mysql_fetch_row($resultTues);
					$nbofteus  = $rwTues[0];
					
					$queryUpMan = "update manifest set No_of_tues = $nbofteus where Manifest_auto = $manifest_auto ";
					$resultUpMAn = mysql_query($queryUpMan, $connection);
							
				}
			
			}
			//echo "<hr>";
			$tempBOL = $bolnumber;
			$tempBLtype = $boltype;
		}
		fclose($myfile);
	}
	
} 

if ($message == '') $message = "Import Done!";

echo "<form name='returnImp' mtethod='POST' action=''>";
echo "<input type='text' name='mode' value=''>"; 
echo "<input type='text' name='message' value='$message'>"; 
echo "<input type='text' name='ark_voyyear' value='$voy_year'>"; 		
echo "<input type='text' name='ark_voynb' value='$voy_nbr'>"; 	
echo "<input type='text' name='ark_voydest' value='$voy_dest'>"; 	
echo "<input type='text' name='ark_pol' value='$portofLoading'>"; 	
echo "<input type='text' name='ark_lineop' value='$line_op'>"; 	
echo "<input type='text' name='ark_pod' value='$portofdischarge'>";
echo "<input type='text' name='ark_rcvdate' value='$received_date'>";
echo "<input type='text' name='ark_notify' value='$notify'>";
echo "<input type='text' name='ark_vessel' value='$vessel'>";
echo "<input type='text' name='ark_shipper' value='$shipper'>";
echo "<input type='text' name='ark_cosignee' value='$cosignee'>";
echo "</form>";
 echo " <script> ";
echo " document.returnImp.action = 'Form_ImpExp.php'; ";
echo " document.returnImp.submit(); ";

echo " </script> "; 
exit;
function strformat($str){
	if($str == '') $str = "NULL";
	else $str = "'".ereg_replace("'", "\'", trim($str))."'";
	return $str;
}

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 addZeros($nbr){
	$len = strlen($nbr);
	if ($len == 0)
		$nbr = "000".$nbr;
	else if ($len == 1)
		$nbr = "00".$nbr;
	else if ($len == 2)
		$nbr = "0".$nbr;
	else if ($len >= 2)
		$nbr = $nbr;
	
	return $nbr;
	
}

function splitString ($str){
	$arrStr = str_split($str);

$i = 1;
$newStr = array();
$t=0;

foreach($arrStr as $str){
	
	if ($i >= 58 && ($str == '' || $str == ' ')){
		$i=1;
		$t++;
	} else {
		$newStr[$t] = $newStr[$t].$str;	
		
	}
	$i++;
}
$t=0;
	foreach($newStr as $str){
		if (trim($str) != ''){
			$newStr1[$t] = $str;
			$t++;
		}
	}

	return $newStr1;
	
}


?>