<?php

session_start();

include("config.inc.php");

header("Content-type: text/html; charset=".$_SESSION['encodingmode']);

if($_SESSION['dbName']==""){
header("location:../index.php");
}


echo "<html>";
echo "<head><title>Manifest Sorder Report</title>";
echo "<style>";
echo " #t1 td {
		font-size: 13px;
		}
		";
echo "</style></head>";


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

//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, Setup_vatno, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage, ".
			 " Company_Name_arabic, Company_NameF, Company_Memo, Company_MemoF, Company_Capital, Company_CapitalF, Header_color as HeaderColor, Background_Color as BackgroundColor ".
			 " from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}

if($checkprint == 1){
	$PRef 			= $_POST['PRef'];
	$manifeststatus = $_POST['manifeststatus'];
	$perpage 		= $_POST['perpage'];
	$startranger 	= $_POST['startranger'];
	
	if($PRef == '') $PRef = "NULL";
	else $PRef = "'".$PRef."'";
	
	$querysearch = " select manifest_auto, delivery_id from manifest ";

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

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

	if($manifeststatus != '')
		$querysearch=$querysearch." and ifnull(manifest_confirm,0) = '$manifeststatus' ";
	$querysearch=$querysearch." order by manifest_auto desc";
	$querysearch = $querysearch." limit ".$startranger.",".$perpage;
	
} else {
	$man_id 	= $_GET['man_id'];
	$querysearch 	= "select 1 ";

}
$rwcnt = 0;

$btop 	 = "border-top: 1px solid black;";
$bbottom = "border-bottom: 1px solid black;";
$bleft 	 = "border-left: 1px solid black;";
$bright	 = "border-right: 1px solid black;";

$btop2 	 = "border-top: 2px solid black;";
$bbottom2 = "border-bottom: 2px solid black;";
$bleft2 	 = "border-left: 2px solid black;";
$bright2	 = "border-right: 2px solid black;";

$resultSearch = mysql_query($querysearch, $connection);
while($rws = mysql_fetch_array($resultSearch)){
	
	if($man_id == '') $man_id = $rws[0];
	$chkval = 'chkval'.$man_id;
	
	if((($$chkval == 1 && $checkprint == 1) || ($checkprint == 0) ) && $man_id != ''){
		if($rwcnt > 0) echo "<div style='page-break-after: always;'></div>";
		
		//calculate tot
		$queryW = "select sum(ifnull(replace(Container_Weight,',',''),0))
					from manifestdt
					inner join manifestdesc on manifestdt.manifest_manifestauto=manifestdesc.manifest_manifestauto and  manifestdesc.detailsequence=manifestdt.detailsequence
					where manifestdt.manifest_manifestauto = $man_id  ";
		$resW = mysql_query($queryW, $connection);			
		$rw = mysql_fetch_row($resW);
		$totWeight = $rw[0];
		//check detail number
		$querydt = "select sum(Packages), count(manifestdt.auto), replace(packages, uExtractNumberFromString(packages), '')
					from manifestdt
					left join manifestdesc on manifestdt.manifest_manifestauto=manifestdesc.manifest_manifestauto and  manifestdesc.detailsequence=manifestdt.detailsequence
					where manifestdt.manifest_manifestauto = $man_id  
					group by manifestdt.manifest_manifestauto "; //echo $querydt;echo '<br>';
		$resdt = mysql_query($querydt, $connection);
		$rw = mysql_fetch_row($resdt);
		$tot = $rw[0];
		$rwnmr = $rw[1];
		$label = $rw[2];
		
		$queryTotCntr = "select count(1)
						from manifestdt
						left join container on container.cntr_code = manifestdt.Container
						where manifestdt.manifest_manifestauto = $man_id and (ifnull(detailtype,'') = 1 or container.cntr_code = manifestdt.Container) ";
		$resCntr = mysql_query($queryTotCntr, $connection);
		$rwCntr = mysql_fetch_row($resCntr);
		$tot = $rwCntr[0];	
		$label = "CONTAINERS";	
		$start = 0;
		$end = 32;
				
		
		$letter =  strtoupper(number_to_word($tot));
		$letter2 = strtoupper(number_to_word(round($totWeight,3)));
		$label2 = 'Kgs';
		while ($rwnmr > 0){
			//header
			showheader ($man_id, $connection);
			
			//detail
			showdetail ($man_id, $start, $end, $connection);
			
			$rwnmr = $rwnmr - 32;
			$start = $start + $end;
			$end = 32;
			$totWeight = number_format($totWeight,3);				
			echo "<table id='t1' cellpadding=0 cellspacing='0' width = '800px'>
				<col width='220px'><col width='80px'><col width='390px'><col width='110px'>";
			echo "<tr>
					<td align='center' valign='middle' style='$btop;$bbottom;$bleft;border-radius: 0px 0px 0px 8px;font-size:9px;'>ان سحب المستوعبات خاضع للشروط المدونة على البوليصة <br>
						le retrait des conteneurs est soumis aux conditions figurant sur le connaissement.</td>
					<td align='center' valign='middle' style='$btop2;$bbottom2;$bleft2;$bright2;'>$tot</td>
					<td align='center' style='$btop;$bbottom;font-size:9px;'><div style='float:right;'>.لا يؤخذ بعين الاعتبار اي كشف عوار يجري على البضاعة الا بحضور مندوبنا وبشرط ان يتم داخل مستودعات المرفأ وقبل فتح اي طرد </div><br>
						Aucune expertise n'est prise en considération que si elle est effectuée en présence de notre représentant, avant l'ouverture des colis et durant leur séjour dans les entrpots du port.</td>
					<td align='center' style='$btop2;$bbottom2;$bleft2;$bright2;border-radius: 0px 0px 8px 0px;'>$totWeight</td>
				</tr>";
			echo "<tr height='25px'><td align='left' colspan='4'></td></tr>";
			echo "<tr height='25px'><td align='left' colspan='4' ><div style='float:left;width:30px;'>Soit &nbsp;</div>
						<div style='float: left;width:730px;border-bottom:1px solid #0000004f;'>ONLY ".$letter." $label</div><div style='float:right;width:30px;'>اليكن</div>
					</td></tr>";
			echo "<tr height='25px'><td align='left' colspan='4' style='padding-left: 30px;border-bottom:1px solid #0000004f;'>ONLY ".$letter2." $label2</td></tr>";
			echo "<tr height='20px'><td align='left' colspan='4'></td></tr>";
			echo "</table>";
			echo "<table id='t1' cellpadding=1 cellspacing='0' width = '800px'>
					<col width='400px'><col width='400px'>";
			echo "<tr height='20px'><td style='$btop;$bleft;$bright;border-radius: 8px 0px 0px 0px;'></td><td style='$btop;$bright;border-radius: 0px 8px 0px 0px;'></td></tr>";		
			echo "<tr>
					<td style='padding-left:10px;padding-right:10px;$bleft;$bright;'>
						<div style='float:left; width:97px;'>Frêt payé d'avance</div>
						<div style='float: left;border-bottom:1px solid #0000004f;width: 185px;'>&nbsp;</div>
						<div style='float:right; width:93px;'>الناولون المدفوع مسبقاً</div>
					</td>
					<td style='$bright;'></td>
				 </tr>";
			echo "<tr>
					<td style='padding-left:10px;padding-right:10px;$bleft;$bright;'>
						<div style='float:left; width:85px;'>Ou frêt assigné</div>
						<div style='float: left;border-bottom:1px solid #0000004f;width: 205px;'>&nbsp;</div>
						<div style='float:right; width:78px;'>او الناولون المحوّل</div>
					</td>
					<td style='$bright;'></td>
				 </tr>";
			echo "<tr>
					<td style='padding-left:10px;padding-right:10px;$bleft;$bright;'>
						<div style='float:left; width:105px;'>Débarquement L.L.</div>
						<div style='float: left;border-bottom:1px solid #0000004f;width: 205px;'>&nbsp;</div>
						<div style='float:right; width:58px;'>رسوم التجريم</div>
					</td>
					<td style='padding-left:10px;padding-right:10px;$bright;'>
						<div style='float:left; width:80px;'>Beyrouth, le</div>
						<div style='float: left;border-bottom:1px solid #0000004f;width: 240px;'>&nbsp;</div>
						<div style='float:right; width:45px;'>بيروت في</div>
					</td>
				 </tr>";	 
			echo "<tr height='20px'><td style='$bbottom;$bleft;$bright;border-radius: 0px 0px 0px 8px;'></td><td style='$bbottom;$bright;border-radius: 0px 0px 8px 0px;'></td></tr>";		 
			echo "</table>";
			echo "<div style='page-break-after: always;'></div>";
			$rwcnt++;
		}
		
	} //end if
	$man_id = '';
} //end while

function showheader ($manifest_auto, $connection){
	$btop 	 = "border-top: 1px solid black;";
	$bbottom = "border-bottom: 1px solid black;";
	$bleft 	 = "border-left: 1px solid black;";
	$bright	 = "border-right: 1px solid black;";
	
	$queryComp = "select company_name_arabic from setup";
	$resComp = mysql_query($queryComp, $connection);
	$rwComp = mysql_fetch_row($resComp);
	$compname = $rwComp[0];
	
	$queryheader = "select vessel_id, voyage_number, date_format(received_date, '%d/%m/%Y'), Portofloading, BOL_identification, consignee1, manifest_orderid
					from manifest
					where manifest_auto = $manifest_auto ";
	$resheader = mysql_query($queryheader, $connection);
	$rwheader = mysql_fetch_row($resheader);	
	
	$vessel 	= $rwheader[0];
	$voy_nbr 	= $rwheader[1];
	$arr_date 	= $rwheader[2];
	$pol	 	= $rwheader[3];
	$bol	 	= $rwheader[4];
	$cosignee 	= $rwheader[5];
	$orderid 	= $rwheader[6];
	
	$queryvess = "select vessel_flag from vessel where vessel_description = '$rwheader[0]' ";
	$resvess = mysql_query($queryvess, $connection);
	$rwvess = mysql_fetch_row($resvess);
	
	echo "<table cellpadding=0 cellspacing='0' width = '800px'>
			<col width='570px'><col width='230px'>";
	echo "<tr><td></td><td align='center'><span style='font-size:18px;font-weight:bold;'>إذن تسليم</span></td></tr>";
	echo "<tr height=30px><td colspan='2'></td></tr>";
	echo "<tr><td><span style='font-size:18px;font-weight:bold;'>$compname</span></td><td align='center'><span style='font-size:18px;font-weight:bold;'>BON DE LIVRAISON</span></td></tr>";
	echo "<tr height=30px><td colspan='1'></td></tr>";
	echo "</table>";
	
	echo "<table id='t1' cellpadding=0 cellspacing='0' width = '800px'>
		<col width='570px'><col width='40px'><col width='150px'><col width='40px'>";
	echo "<tr height='30px'><td></td>
			<td align='center' valign='middle' style='$btop;$bbottom;$bleft;$bright;border-radius: 6px 0px 0px 6px;'>No.</td>
			<td align='center' valign='middle' style='$btop;$bbottom;'>$orderid</td>
			<td align='center' valign='middle' style='$btop;$bbottom;$bleft;$bright;border-radius: 0px 6px 6px 0px;'>رقم</td>
		 </tr>";
	echo "<tr height='30px'><td colspan='1'></td><td colspan='2'>FLAG:  $rwvess[0]</td></tr>";	 
	echo "</table>";
		
	echo "<table id='t1' cellpadding=3 cellspacing='0' width = '800px'>
		<col width='250px'><col width='80px'><col width='120px'><col width='180px'><col width='180px'>";
	echo "<tr height='10px'>
			<td align='center' style='$btop;$bbottom;$bleft;$bright;border-radius: 8px 0px 0px 0px;'><div style='float: left;'>Navire et Voyage</div><div style='float: right;'>الباخرة/سفرة رقم</div></td>
			<td align='center' style='$btop;$bbottom;$bright;'>Séquence</td>
			<td align='center' style='$btop;$bbottom;$bright;'><div style='float: left;'>Arrivé le</div><div style='float: right;'>الواصلة</div></td>
			<td align='center' style='$btop;$bbottom;'><div style='float: left;'>Provenance</div><div style='float: right;'>من الميناء</div></td>
			<td align='center' style='$btop;$bbottom;$bleft;$bright;border-radius: 0px 8px 0px 0px;'><div style='float: left;'>B/L No.</div><div style='float: right;'>البوليصة</div></td>
		</tr>";
	echo "<tr height='30px'>
			<td align='center' valign='middle' style='$bbottom;$bleft;$bright;border-radius: 0px 0px 0px 8px;'>$vessel $voy_nbr</td>
			<td align='center' valign='middle' style='$bbottom;$bright;'>$manifest_auto</td>
			<td align='center' valign='middle' style='$bbottom;$bright;'>$arr_date</td>
			<td align='center' valign='middle' style='$bbottom;'>$pol</td>
			<td align='center' valign='middle' style='$bbottom;$bleft;$bright;border-radius: 0px 0px 8px 0px;'>$bol</td>
		 </tr>";
	echo "</table>";
	
	echo "<table id='t1'  cellpadding=0 cellspacing='0' width = '800px'>
		<col width='500px'><col width='300px'>";
	echo "<tr height='20px'><td colspan='2'></td></tr>";	
	echo "<tr ><td align='left'>M. le chef du service de la Douane de Beyrouth</td><td align='right'>حضرة رئيس مصلحة مكتب جمرك بيروت المحترم</td></tr>";
	echo "<tr ><td><div style='float:left;width: 130px;'>Veuillez livrer à MM.</div><div>$cosignee</div></td><td align='right'>الرجاء تسليم السادة</td></tr>";
	echo "<tr><td>les colis ci-dessous spécifiés suivant déclaration de l'expéditeur</td><td align='right'>الطرود الموصوفة ادناه حسب تصريح الشاحن</td></tr>";
	echo "<tr height='30px'><td colspan='2'></td></tr>";
	echo "</table>";
	
	echo "<table id='t1' cellpadding=0 cellspacing='0' width = '800px'>
		<col width='220px'><col width='80px'><col width='100px'><col width='290px'><col width='110px'>";
	echo "<tr>
			<td align='center' valign='middle' style='$btop;$bbottom;$bleft;$bright;border-radius: 8px 0px 0px 0px; padding-left:8px; padding-right:8px;'><div style='float: left;'>Marques et Numéros</div><div style='float: right;'>الماركات والأرقام</div></td>
			<td align='center' valign='middle' style='$btop;$bbottom;$bright;'><div>العدد</div><div>Nombre</div></td>
			<td align='center' valign='middle' style='$btop;$bbottom;padding-left:15px; padding-right:15px;' colspan='2'><div style='float: left;'>Description</div><div style='float: right;'>مواصفات</div></td>
			<td align='center' valign='middle' style='$btop;$bbottom;$bleft;$bright;border-radius: 0px 8px 0px 0px;'><div>الوزن</div><div>Poids/kg</div></td>
		</tr>";
	echo "</table>";
	
}

function showdetail ($manifest_auto, $start, $end, $connection){
	
	$btop 	 = "border-top: 1px solid black;";
	$bbottom = "border-bottom: 1px solid black;";
	$bleft 	 = "border-left: 1px solid black;";
	$bright	 = "border-right: 1px solid black;";
	
	$querydt = "select Container, Packages,  descriptiongood, Container_Weight, if(ifnull(detailtype,'') = '', (select 1 from container where cntr_code= manifestdt.Container),detailtype)
				from manifestdt
				inner join manifestdesc on manifestdt.manifest_manifestauto=manifestdesc.manifest_manifestauto and  manifestdesc.detailsequence=manifestdt.detailsequence
				where manifestdt.manifest_manifestauto=$manifest_auto limit $start, $end  "; //echo $querydt;
	$resdt = mysql_query($querydt, $connection);
	echo "<table id='t1' cellpadding=0 cellspacing='0' width = '800px'>
			<col width='220px'><col width='80px'><col width='100px'><col width='290px'><col width='110px'>";
	$i = 1;
	while ($rwdt = mysql_fetch_array($resdt)) {
		if($rwdt[4] == 1)
			$isContainer = 1;
		else
			$isContainer = '';
		echo "<tr><td align='left' style='$bleft;$bright; padding-left: 10px;'>$rwdt[0]</td><td align='center' style='$bright;'>$isContainer</td>
					<td align='left' style = 'padding-left: 10px'>$rwdt[1]</td><td align='left' style='$bright;padding-left: 25px'>$rwdt[2]</td><td align='center' style='$bright;'>$rwdt[3]</td>
			 </tr>";
		$i++;
	}
	
	if($i != 32){
	for($j=32;$j>=$i; $j--)
		echo "<tr><td align='center' style='$bleft;$bright;'>&nbsp;</td>
				<td align='center' style='$bright;'>&nbsp;</td>
				<td align='center' style='$bright;' colspan='2'>&nbsp;</td>
				<td align='center' style='$bright;'>&nbsp;</td></tr>";
	}
	echo "</table>";
}



function number_to_word( $num = '' )
{
    $num    = ( string ) ( ( int ) $num );
   
    if( ( int ) ( $num ) )
    {
        $words  = array( );
       
        $num    = str_replace( array( ',' , ' ' ) , '' , trim( $num ) );
       
        $list1  = array('','one','two','three','four','five','six','seven',
            'eight','nine','ten','eleven','twelve','thirteen','fourteen',
            'fifteen','sixteen','seventeen','eighteen','nineteen');
       
        $list2  = array('','ten','twenty','thirty','forty','fifty','sixty',
            'seventy','eighty','ninety','hundred');
       
        $list3  = array('','thousand','million','billion','trillion',
            'quadrillion','quintillion','sextillion','septillion',
            'octillion','nonillion','decillion','undecillion',
            'duodecillion','tredecillion','quattuordecillion',
            'quindecillion','sexdecillion','septendecillion',
            'octodecillion','novemdecillion','vigintillion');
       
        $num_length = strlen( $num );
        $levels = ( int ) ( ( $num_length + 2 ) / 3 );
        $max_length = $levels * 3;
        $num    = substr( '00'.$num , -$max_length );
        $num_levels = str_split( $num , 3 );
       
        foreach( $num_levels as $num_part )
        {
            $levels--;
            $hundreds   = ( int ) ( $num_part / 100 );
            $hundreds   = ( $hundreds ? ' ' . $list1[$hundreds] . ' Hundred' . ( $hundreds == 1 ? '' : 's' ) . ' ' : '' );
            $tens       = ( int ) ( $num_part % 100 );
            $singles    = '';
           
            if( $tens < 20 )
            {
                $tens   = ( $tens ? ' ' . $list1[$tens] . ' ' : '' );
            }
            else
            {
                $tens   = ( int ) ( $tens / 10 );
                $tens   = ' ' . $list2[$tens] . ' ';
                $singles    = ( int ) ( $num_part % 10 );
                $singles    = ' ' . $list1[$singles] . ' ';
            }
            $words[]    = $hundreds . $tens . $singles . ( ( $levels && ( int ) ( $num_part ) ) ? ' ' . $list3[$levels] . ' ' : '' );
        }
       
        $commas = count( $words );
       
        if( $commas > 1 )
        {
            $commas = $commas - 1;
        }
       
        $words  = implode( ', ' , $words );
       
        //Some Finishing Touch
        //Replacing multiples of spaces with one space
        $words  = trim( str_replace( ' ,' , ',' , trim_all( ucwords( $words ) ) ) , ', ' );
        if( $commas )
        {
            $words  = str_replace_last( ',' , ' and' , $words );
        }
       
        return $words;
    }
    else if( ! ( ( int ) $num ) )
    {
        return 'Zero';
    }
    return '';
}

function trim_all( $str , $what = NULL , $with = ' ' )
{
    if( $what === NULL )
    {
        //  Character      Decimal      Use
        //  "\0"            0           Null Character
        //  "\t"            9           Tab
        //  "\n"           10           New line
        //  "\x0B"         11           Vertical Tab
        //  "\r"           13           New Line in Mac
        //  " "            32           Space
       
        $what   = "\\x00-\\x20";    //all white-spaces and control chars
    }
   
    return trim( preg_replace( "/[".$what."]+/" , $with , $str ) , $what );
}

function str_replace_last( $search , $replace , $str ) {
    if( ( $pos = strrpos( $str , $search ) ) !== false ) {
        $search_length  = strlen( $search );
        $str    = substr_replace( $str , $replace , $pos , $search_length );
    }
    return $str;
}


echo "
</body>
</html>";

print <<< HERE

<script language=javascript>

    window.print();

</script>
</BODY>
</HTML>
HERE;
?>