<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<?php
 
 
 
session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}

if($_SESSION['module']=="0")
  $title = 'List of Sales';
else {
  if ($transaction == 'SI' || $transaction == 'SR' )
    $title = 'List of Sales';
  else
    $title = 'List of Deliveries';  
}  

print <<< HERE
<HTML>
<HEAD>
<TITLE> $title </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">

<style type="text/css">
table.params td { font-size: 12px; 
                  font-family:Times-New-Roman;
                 }

table.master th { font-size: 14px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
                      }				 
table.master td { font-size: 12px; 
                  font-family:Times-New-Roman;
                 }
table.group td { font-size: 12px; 
                 font-weight: bold;
                 font-family:Times-New-Roman;
               }				 
				 
table.detail td { font-size: 10px; 
                  font-family:Times-New-Roman;
                 }				 
table.headerdetail td { font-size: 10px; 
                        font-weight: bold;
                        font-family:Times-New-Roman;
                      }				 
table.totals td { font-size: 12px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
                 }					  
				 

</style>


</HEAD>


HERE;

include("config.inc.php");

//Set Time Execution For the Report
ini_set('max_execution_time', $config['ReportTimeExecution']);

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

//maroun 30.03.2011
$querylog="SELECT print as printaccess, ifNull(FI_RepRestrictProject,0) As FI_RepRestrictProject, ifNull(FI_RepRestrictCostcenter,0) As FI_RepRestrictCostcenter
		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);
	}


if ($printaccess==0 or $printaccess=='')
echo'<BODY oncontextmenu="return false;">';
else
echo'<BODY>';



	
$querysetup="select DecimalBase, DecimalBase1, DecimalBase2, Base1, Base2, report_color1, report_color2, Company_Name As CompanyName from setup";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultsetup)){
  extract($rows);
}

/*$querysalessetup="select Salesttc from salessetup";
$resultsalessetup=mysql_query($querysalessetup,$connection) or die(mysql_error());
while($rowssalessetup=mysql_fetch_array($resultsalessetup)){
  extract($rowssalessetup);
}*/

//User Access
$querylog=" Select ifNull(FI_ShowCostPrice,0) As FI_ShowCostPrice ".
          " 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);
}


$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$_SESSION['dbLabel'].".loginstk on project.project_code like concat(ifnull(loginstk.project_code,project.project_code),'%') ".
			  " where user_account='".$_SESSION['useraccount']."' ".
			  " order by project.project_code";
$projectresult = mysql_query($queryproject,$connection) or die(mysql_error());
$projectexist   = mysql_num_rows($projectresult);

$querycostcent=" select distinct costcent.costcent_code, costcent_name ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on costcent.costcent_code like concat(ifnull(loginstk.costcent_code,costcent.costcent_code),'%')".
			   " where user_account='".$_SESSION['useraccount']."' ".
			   " and (loginstk.costcent_code is not null and loginstk.costcent_code != '') ".
			   " order by costcent.costcent_code";
$costcentresult = mysql_query($querycostcent,$connection) or die(mysql_error());
$costcentexist  = mysql_num_rows($costcentresult);	

$now=current_server_time($connection);
$dt=split(" ",$now[0]);
$printdate=split("-",$dt[0]);

print <<< HERE
<table width="100%" border="0" align="center">
<tr>
  <td width='30%'><b>$CompanyName</b></td>
  <td width='50%' align='center'><font size=4><b>$title</b></font></td>
  <td width='10%'><font size=1><b> Printed Date: </b> <br><b>Time: </b>
  <td width='10%'><font size=1>
HERE;

echo $printdate[2]."/".$printdate[1]."/".$printdate[0];
//echo DATE("d"."/"."m"."/"."Y");
echo "<br>".$dt[1]." ".$dt[2];

$dispfromref  = $fromref;
$disptoref = $toref;
$dispfromclient = $fromclient;
$disptoclient = $toclient;
$dispfromdate = $fromdate;
$disptodate = $todate;

if (empty($fromref))
  $fromref = 'null'; 
  
if (empty($toref))
  $toref = 'null';   
  
if ($cur == 'currency1'){
   $cur='null';  
   $displaycur = '';
}   
else {
   $displaycur = $cur;
   $cur="'".$cur."'";
}   

if (empty($fromclient))   
   $fromclient = 'null';
else
   $fromclient = "'".$fromclient."'";   

if (empty($fromsalesman))   
   $fromsalesman = 'null';
else
   $fromsalesman = "'".$fromsalesman."'";


if (empty($tosalesman))   
   $tosalesman = 'null';
else
   $tosalesman = "'".$tosalesman."'";

if (empty($fromcostcent))   
   $fromcostcent = 'null';
else
   $fromcostcent = "'".$fromcostcent."'";

 if (empty($fromgroup))   
   $fromgroup = 'null';
else
   $fromgroup = "'".$fromgroup."'";  
if (empty($togroup))   
   $togroup = 'null';
else
   $togroup = "'".$togroup."'";  

if (empty($fromitem))   
   $fromitem = 'null';
else
   $fromitem = "'".$fromitem."'";  
if (empty($toitem))   
   $toitem = 'null';
else
   $toitem = "'".$toitem."'";  


if (empty($fromwarehouse))   
   $fromwarehouse = 'null';
else
   $fromwarehouse = "'".$fromwarehouse."'"; 
if (empty($towarehouse))   
   $towarehouse = 'null';
else
   $towarehouse = "'".$towarehouse."'"; 



if (empty($fromsubgroup))   
   $fromsubgroup = 'null';
else
   $fromsubgroup = "'".$fromsubgroup."'";  
if (empty($tosubgroup))   
   $tosubgroup = 'null';
else
   $tosubgroup = "'".$tosubgroup."'";  

if (empty($fromcategory))   
   $fromcategory = 'null';
else
   $fromcategory = "'".$fromcategory."'";  
if (empty($tocategory))   
   $tocategory = 'null';
else
   $tocategory = "'".$tocategory."'";        
if (empty($toclient))   
   $toclient = 'null';
else
   $toclient = "'".$toclient."'";      

if (empty($fromproject))   
   $fromproject = 'null';
else
   $fromproject = "'".$fromproject."%'";    

if (!empty($fromdate))
   $fromdate = explodeword($fromdate);
if (!empty($todate))
   $todate = explodeword($todate);  

if (empty($fromdate))   
   $fromdate = 'null';
else
   $fromdate = "'".$fromdate."'"; 
   
if (empty($todate))   
   $todate = 'null';
else
   $todate = "'".$todate."'";


   
$SalesReport = 0;
$ShowTotals  = 0;
$ShowCost    = 0;

if($_SESSION['module']=="0"){
  $showboth = $salesboth;
  $SalesReport = 0;
  $ShowTotals  = 1;
  $ShowCost    = 0;
}
else {
  if ($transaction == 'SI' || $transaction == 'SR' ) {
    $showboth = $salesboth;
	$SalesReport = 1;
	$ShowTotals  = 1;
	$ShowCost    = 0;
  }		
  else	{
	$showboth = $deliveryboth;
	$SalesReport = 0;
	
	if ($FI_ShowCostPrice == 1) {	$ShowTotals = 1; $ShowCost = 1;  }
	else { $ShowTotals = 0; $ShowCost  = 0;  }
  }	
}

   
print <<<HERE
</font></td>
</tr>
<tr>
   <td colspan='4' width='100%'> <hr width='100%' color='black' size='1'> </td>
</tr>
</table>

HERE;


print <<<HERE
<table class="params" width="100%" border="0" align="center" >
<tr>
  <td width="10%" valign='top'><b>Client</b></td>
  <td width="5%"><b>From <br>To </b></td>
  <td width="35%">$dispfromclient <br> $disptoclient</td>
  <td width="10%" valign='top'><b>Reference</b></td>
  <td width="5%"><b>From <br>To </b></td>
  <td width="35%">$dispfromref <br> $disptoref </td>
</tr>
<tr>
	<td width="10%" valign='top'><b>Sales Man</b></td>
	<td width="40%">$salesmanname</td>
</tr>
<tr>
  <td width="10%"><b>Date From/To</b></td>
  <td width="40%" colspan='2'>$dispfromdate - $disptodate </td>
  <td width="10%"><b>Currency</b></td>
  <td width="40%" colspan='2'>$displaycur </td>
</tr>
</table>


<table width="100%" border="0" cellpadding='0' cellspacing='0' align="center" class='master' >
<tr>
    <th width="4%">Date</th>
    <th width="4%">Ref.</th>
	<th width="3%">Type </th>
	<!--start nabil 2011-01-20 -->
	<th width="4%">Sorder#</th>
	<!--end nabil 2011-01-20 -->
	
HERE;

if($SalesReport==1)	echo"<th width='4%'>Delivery#</th>";
else echo"<th width='4%'>&nbsp;</th>";

print <<<HERE
    <th width="5%">Client</th>
	<th width="15%">Description</th>
	<th width="5%">Project</th>
	
HERE;

if($showProjCostName == 1)
echo "<th width='5%'>Project Name</th>";
echo "<th width='5%'>Costcenter</th>";
if($showProjCostName == 1)
echo"<th width='5%'>Costcenter Name</th>"; 
echo"<th width='4%'>Cur.</th>
	<th width='7%'>Taxable</th>
	<th width='7%'>Non Taxable</th>
	<th width='7%'>Gross Total</th>";
	
echo "<th width='7%'>Discount</th>";
//if ($pricettc == 0)
	echo "<th width='7%'>VAT</th>";


if($ShowTotals == 1) {
	echo "<th width='7%'>Net Total $displaycur</th>";
} else {
	echo "<th width='7%'>&nbsp;</th>";
}
	
echo"</tr>";



    if ($showdetail == 1) {
		echo "<tr>";
		echo "  <td colspan='13'><table class='headerdetail' width='100%' border='0' align='center' ><tr> ";
		echo "  <td width='8%' align='center'> Item Code/Description/Reason </td>";
		echo "  <td width='19%'>&nbsp;</td>";
		echo "  <td width='5%'> Warehouse </td>";
		echo "  <td width='4%' align='right'> Qty. </td>";
		echo "  <td width='5%' align='center'> Unit Price </td>";
		echo "  <td width='4%' align='center'> Disc. % </td>";
		echo "  <td width='5%' align='center'> Total </td>";
		
		if ($ShowCost == 1)	echo "  <td width='5%' align='center'> T.MeanCost </td>";
		else echo "  <td width='5%' align='center'> &nbsp; </td>";
		
		echo " </tr></table></td>";
		echo " </tr>";
		
	}	
	
if($showProjCostName == 1)	
	$colspn = 18;
else $colspn = 16;
print <<<HERE
<tr>
    <td colspan='$colspn'><hr width='100%' color='black' size='2'></td>
</tr>
 
HERE;
 
   

//if ($pricettc == 0) {   
    //nabil 2011-01-20 adding sorder_reference at the end of the following string
	$querydelivery= " select date_format(deliveries.delivery_date,'%d/%m/%Y') delivery_date, delivery_reference, deliveries.journal_type, ".
					" deliveries.client_code, clients.ledger_name , deliveries.project_code, deliveries.costcent_code, deliveries.currency_code, ".
					" ifnull(if(upper($cur)='".$Base1."',delivery_taxablebase1,if(upper($cur)='".$Base2."',delivery_taxablebase2,delivery_taxable)),0), ".
					" deliveries.delivery_id, if('".$date."' = 'date', date_format(deliveries.delivery_date,'%Y-%m-%d'), delivery_reference) ord, project_name,sorder_reference, null as sale_relatedid, deliveries.Delivery_Remark, ".
					" ifnull(if(upper($cur)='".$Base1."',delivery_nonetaxablebase1,if(upper($cur)='".$Base2."',delivery_nonetaxablebase2,delivery_nonetaxable)),0), ".
					" ifnull(if(upper($cur)='".$Base1."',delivery_vatbase1,if(upper($cur)='".$Base2."',delivery_vatbase2,delivery_vat)),0), ".
					" ifnull(if(upper($cur)='".$Base1."',delivery_discountbase1,if(upper($cur)='".$Base2."',delivery_discountbase2,delivery_discountamount)),0), ".
					" costcent_name";
/*} else {
    //nabil 2011-01-20 adding sorder_reference at the end of the following string
	$querydelivery= " select date_format(deliveries.delivery_date,'%d/%m/%Y') deliveries.delivery_date, delivery_reference, deliveries.journal_type, ".
					" client_code, clients.ledger_name , deliveries.project_code, deliveries.costcent_code, deliveries.currency_code, ".
					" convertcurfunc(deliveries.currency_code,
					if(upper($cur)='".$Base1."', '".$Base1."',if(upper($cur)='".$Base2."','".$Base2."',deliveries.currency_code)),
					deliveries.delivery_date,
					0,
					0,
					'','',ifnull(delivery_taxableTTC,0)), ".
					" delivery_id,  if('".$date."' = 'date', date_format(deliveries.deliveries.delivery_date,'%Y-%m-%d'), delivery_reference) ord, project_name, sorder_reference, null as sale_relatedid, deliveries.Delivery_Remark, ".
					" ifnull(if(upper($cur)='".$Base1."',delivery_nonetaxablebase1,if(upper($cur)='".$Base2."',delivery_nonetaxablebase2,delivery_nonetaxable)),0), ".
					" convertcurfunc(deliveries.currency_code,if(upper($cur)='".$Base1."', '".$Base1."',if(upper($cur)='".$Base2."','".$Base2."',deliveries.currency_code)),deliveries.delivery_date,0,0,'','',ifnull(delivery_discountTTC,0))";
}*/

$querydelivery= $querydelivery."  from deliveries ".
							   " left join clients on deliveries.client_code = clients.ledger_number ".
							   " left join project on project.project_code = deliveries.project_code ".
							   " left join costcent on costcent.Costcent_code = deliveries.Costcent_code".
							   " left join deliverydt on deliverydt.delivery_id = deliveries.delivery_id".
							   " left join items on deliverydt.item_code = items.item_code ";
				
if ($projectexist >	0 && $FI_RepRestrictProject == 1)
  $querydelivery= $querydelivery." left join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
								 "			 where loginstk.user_account='".$_SESSION['useraccount']."'  ".
								 "           and (project_code is not null and project_code != '') ".
								 "			) Q1 on deliveries.project_code like concat(Q1.project_code,'%') ";
								 
if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1) 
		$querydelivery = $querydelivery." Inner join ( select distinct costcent_code from ".$_SESSION['dbLabel'].".loginstk ".
									  "			     where loginstk.user_account='".$_SESSION['useraccount']."' ".
									  "              and (costcent_code is not null and costcent_code != '') ".
								  	  "			 ) Q2 on deliveries.costcent_code like concat(Q2.Costcent_Code,'%')";								 

$querydelivery= $querydelivery.  				
				" where (($grpclient=1 and deliveries.client_code between ifNull(".$fromclient.",deliveries.client_code) and ifNull(". $toclient.",deliveries.client_code)) or ($grpclient=0 and 1 = 1)) ".
				" and delivery_reference between ifNull(". $fromref .",delivery_reference) and ifNull(". $toref.",delivery_reference) ".
				" and upper(ifNull(deliveries.project_code,-1)) like ifNull(upper(".$fromproject."), upper(ifNull(deliveries.project_code,-1))) ".
				" and date_format(deliveries.delivery_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(deliveries.delivery_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(deliveries.delivery_date,'%Y-%m-%d'))  ".
				" and (($showboth = 1 and 1 = 1) or ($showboth =0 and deliveries.journal_type='".$transaction."')) 
				and deliveries.client_code between ifNull(".$fromclient.",deliveries.client_code) and ifNull(". $toclient.",deliveries.client_code)".
				 //and deliveries.Salesman_Code between ifNull(".$fromsalesman.",deliveries.salesman_code) and ifNull(". $tosalesman.",deliveries.salesman_code)
				" AND ifnull( deliveries.Costcent_code , '-1' ) = ifnull( ".$fromcostcent.", '-1' )
				and deliverydt.item_Code between ifNull(".$fromitem.",deliverydt.item_code) and ifNull(". $toitem.",deliverydt.item_code)
				and items.group_Code between ifNull(".$fromgroup.",items.group_code) and ifNull(". $togroup.",items.group_code)
				and items.subgroup_Code between ifNull(".$fromsubgroup.",items.subgroup_code) and ifNull(". $tosubgroup.",items.subgroup_code)
				and deliverydt.warehouse_Code between ifNull(".$fromwarehouse.",deliverydt.warehouse_code) and ifNull(". $towarehouse.",deliverydt.warehouse_code)";	
				if($fromcategory!='' && $fromcategory!='null')
$querydelivery.=" and items.category_Code between ifNull(".$fromcategory.",items.category_code) and ifNull(". $tocategory.",items.category_code)";							
				
if ($_GET['salesman'] !='') {
	$querydelivery= $querydelivery."and salesman_code='$salesman'";
}

$querydelivery= $querydelivery.   '  group by delivery_reference ';
$querydelivery= $querydelivery.  
				" order by if($grpclient=1, deliveries.Client_code, if($grpproject=1, deliveries.project_code, null) ),ord, delivery_reference ";
				
//echo $querydelivery;exit;				
//if ($pricettc == 0) {   
    //nabil 2011-01-20 adding sorder_reference at the end of the following string
	$querysales= " select date_format(Sales.Sale_Date,'%d/%m/%Y') Sale_Date, Sale_Reference, sales.journal_type, ".
				 " Sales.client_code, clients.ledger_name , sales.project_code, sales.Costcenter_code, sales.currency_code, ".
				 " ifnull(if(upper($cur)='".$Base1."',sale_taxablebase1,if(upper($cur)='".$Base2."',sale_taxablebase2,sale_taxable)),0), ".
				 " Sales.sale_id, if('".$date."' = 'date', date_format(Sales.Sale_Date,'%Y-%m-%d'), Sale_Reference) ord, project_name, sorder_reference, sale_relatedid, sales.Sale_Remark,".
				 " ifnull(if(upper($cur)='".$Base1."',sale_nonetaxablebase1,if(upper($cur)='".$Base2."',sale_nonetaxablebase2,sale_nonetaxable)),0),".
				 " ifnull(if(upper($cur)='".$Base1."',sale_vatbase1,if(upper($cur)='".$Base2."',sale_vatbase2,sale_vat)),0),".
				 " ifnull(if(upper($cur)='".$Base1."',sale_discountbase1,if(upper($cur)='".$Base2."',sale_discountbase2,sale_discountamount)),0), ".
				 " costcent_name ";
/*} else {
    //nabil 2011-01-20 adding sorder_reference at the end of the following string
	$querysales= " select date_format(Sale_Date,'%d/%m/%Y') Sale_Date, Sale_Reference, sales.journal_type, ".
				 " client_code, clients.ledger_name , sales.project_code, sales.Costcenter_code, sales.currency_code, ".
				 " convertcurfunc(sales.currency_code,if(upper($cur)='".$Base1."', '".$Base1."',if(upper($cur)='".$Base2."','".$Base2."',sales.currency_code)),Sale_Date,0,0,'','',ifnull(sale_taxableTTC,0)), ".
				 " sale_id,  if('".$date."' = 'date', date_format(sales.Sale_Date,'%Y-%m-%d'), Sale_Reference) ord, project_name, sorder_reference, sale_relatedid, sales.Sale_Remark,".
				 " ifnull(if(upper($cur)='".$Base1."',sale_nonetaxablebase1,if(upper($cur)='".$Base2."',sale_nonetaxablebase2,sale_nonetaxable)),0),".
				 " convertcurfunc(sales.currency_code,if(upper($cur)='".$Base1."', '".$Base1."',if(upper($cur)='".$Base2."','".$Base2."',sales.currency_code)),Sale_Date,0,0,'','',ifnull(sale_discountTTC,0)) ";
}*/

$querysales= $querysales." from sales ".
				         " left join clients on sales.client_code = clients.ledger_number ".
						 " left join salesdt on sales.sale_id = salesdt.sale_id ".
						 " left join project on sales.project_code = project.project_code ".
						 " left join costcent on costcent.Costcent_code = sales.Costcenter_code".
						 " left join items on salesdt.item_code = items.item_code  ";
				
if ($projectexist >	0 && $FI_RepRestrictProject == 1)
  $querysales= $querysales." left join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
						   "			 where loginstk.user_account='".$_SESSION['useraccount']."'  ".
						   "             and (project_code is not null and project_code != '') ".
						   "			) Q1 on sales.project_code like concat(Q1.project_code,'%') ";
if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1) 
		$querysales = $querysales." Inner join ( select distinct costcent_code from ".$_SESSION['dbLabel'].".loginstk ".
						  "			     where loginstk.user_account='".$_SESSION['useraccount']."' ".
						  "              and (costcent_code is not null and costcent_code != '') ".
						  "			 ) Q2 on sales.costcenter_code like concat(Q2.Costcent_Code,'%')";			
						  
$querysales= $querysales.  				
				" where (($grpclient=1 and sales.client_code between ifNull(".$fromclient.",sales.client_code) and ifNull(". $toclient.",sales.client_code)) or ($grpclient=0 and 1 = 1)) ".
				" and Sale_Reference between ifNull(". $fromref .",Sale_Reference) and ifNull(". $toref.",Sale_Reference) ".
				" and upper(ifNull(sales.project_code,-1)) like ifNull(upper(".$fromproject."), upper(ifNull(sales.project_code,-1))) ".
				" and date_format(Sales.Sale_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(Sales.Sale_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(Sales.Sale_Date,'%Y-%m-%d'))  ".
				" and (($showboth = 1 and 1 = 1) or ($showboth =0 and sales.journal_type='".$transaction."')) ";

$querysales= $querysales.  '  group by sale_reference ';
$querysales= $querysales.  
				" order by if($grpclient=1, Sales.Client_code, if($grpproject=1, sales.project_code, null) ), ord, Sale_Reference ";

$SumTaxable     = 0;
$SumNonTaxable = 0;
$SumGrossTot    = 0;
$SumDisc        = 0;
$SumVat         = 0;
$SumNetTot      = 0;
$SumGroupNetTot = 0;

$masterproject  = '';
$masterclient = '';
	
//echo $querydelivery;
//exit;
if($SalesReport==1){
  //echo "<BR> querysales: ".$querysales;
  $resultdelivery=mysql_query($querysales,$connection) or die(mysql_error());}
else{

 // echo "<BR>querydelivery: ".$querydelivery;
  $resultdelivery=mysql_query($querydelivery,$connection) or die(mysql_error());
  }
  
$col=0; 

unset($_SESSION['delivery_id_sess']);
while($rowdelivery=mysql_fetch_row($resultdelivery)){
	
	
	$chksepareteinvoice = $_GET['chksepareteinvoice'];
	
	if (1==$chksepareteinvoice) // continue coding here ....
	{
		$_SESSION['delivery_id_sess'] .= $rowdelivery[9] .=";";
	   if( $SalesReport==0)
	   {
		   header("location:Form_DeliveryPreview.php?PLang=EN&chktip=0&printlogo=1&option_to_print=&option_to_print2=");
	   }
	   else
	   {
		   header("location:Form_SalesPreview.php?PLang=EN&chktip=0&printlogo=1&option_to_print=&option_to_print2=");
	   }
	 
	}
	else
	{
		
		
			if($col%2==0){
		$color = "style='background-color:".$report_color1."'";
	}else{
		$color = "style='background-color:".$report_color2."'";
	}
	
    //if ($pricettc == 0) {
		$querydeliverydt= " select deliverydt.item_code, items.item_description, deliverydt.warehouse_code, deliverydt_quantity, ".
						  " ifNull(if(upper($cur)='".$Base1."',deliverydt_pricebase1,if(upper($cur)='".$Base2."',deliverydt_pricebase2,deliverydt_price)),0), ".
						  " ifNull(deliverydt_discountper,0), ".
						  " ((ifNull(deliverydt_quantity,0) * ifNull(if(upper($cur)='".$Base1."',deliverydt_pricebase1,if(upper($cur)='".$Base2."',deliverydt_pricebase2,deliverydt_price)),0)) - ".
						  " ((ifNull(deliverydt_quantity,0) * ifNull(if(upper($cur)='".$Base1."',deliverydt_pricebase1,if(upper($cur)='".$Base2."',deliverydt_pricebase2,deliverydt_price)),0) * ifNull(deliverydt_discountper,0)) / 100) ) total, ".
						  " if(upper($cur)='".$Base1."', DeliveryDt_CostBase1, if(upper($cur)='".$Base2."', DeliveryDt_CostBase2, DeliveryDt_Cost))*ifNull(deliverydt_quantity,0) As MeanCostAmount, DeliveryDt_REason ";
						  
	/*} else 	{
		$querydeliverydt= " select deliverydt.item_code, items.item_description, deliverydt.warehouse_code, deliverydt_quantity, ".
						  " convertcurfunc(deliverydt.currency_code,if(upper($cur)='".$Base1."', '".$Base1."',if(upper($cur)='".$Base2."','".$Base2."',deliverydt.currency_code)),delivery_date,0,0,'','',ifnull(deliverydt_priceTTC,0)), ".
						  " ifNull(deliverydt_discountper,0), ".
						  " convertcurfunc(deliverydt.currency_code,if(upper($cur)='".$Base1."', '".$Base1."',if(upper($cur)='".$Base2."','".$Base2."',deliverydt.currency_code)),delivery_date,0,0,'','', ".
						  " ((ifNull(deliverydt_quantity,0) * ifNull(deliverydt_priceTTC,0)) - ".
						  " ((ifNull(deliverydt_quantity,0) * ifNull(deliverydt_priceTTC,0) * ifNull(deliverydt_discountper,0)) / 100) ) ) total, ".
						  " if(upper($cur)='".$Base1."', DeliveryDt_CostBase1, if(upper($cur)='".$Base2."', DeliveryDt_CostBase2, DeliveryDt_Cost))*ifNull(deliverydt_quantity,0) As MeanCostAmount, DeliveryDt_REason ";
						   
    }*/
	$querydeliverydt = $querydeliverydt." from deliverydt ".
										" left join items on deliverydt.item_code = items.item_code ".
										" where deliverydt.delivery_id = ". $rowdelivery[9]."
										and deliverydt.item_Code between ifNull(".$fromitem.",deliverydt.item_code) and ifNull(". $toitem.",deliverydt.item_code)
										and items.group_Code between ifNull(".$fromgroup.",items.group_code) and ifNull(". $togroup.",items.group_code)
										and items.subgroup_Code between ifNull(".$fromsubgroup.",items.subgroup_code) and ifNull(". $tosubgroup.",items.subgroup_code)
										and items.category_Code between ifNull(".$fromcategory.",items.category_code) and ifNull(". $tocategory.",items.category_code)
										and deliverydt.warehouse_Code between ifNull(".$fromwarehouse.",deliverydt.warehouse_code) and ifNull(". $towarehouse.",deliverydt.warehouse_code)";								
										
										
    //if ($pricettc == 0) {
		$querysalesdt= " select salesdt.item_code, items.item_description, salesdt.warehouse_code, saledt_quantity, ".
					   " ifNull(if(upper($cur)='".$Base1."',saledt_pricebase1,if(upper($cur)='".$Base2."',saledt_pricebase2,saledt_price)),0), ".
					   " ifNull(saledt_discountper,0), ".
					   " ((ifNull(saledt_quantity,0) * ifNull(if(upper($cur)='".$Base1."',saledt_pricebase1,if(upper($cur)='".$Base2."',saledt_pricebase2,saledt_price)),0)) - ".
					   " ((ifNull(saledt_quantity,0) * ifNull(if(upper($cur)='".$Base1."',saledt_pricebase1,if(upper($cur)='".$Base2."',saledt_pricebase2,saledt_price)),0) * ifNull(saledt_discountper,0)) / 100) ) total, ".
					   " 0 As MeanCostAmount, SaleDt_Reason ";
						  
	/*} else 	{
		$querysalesdt= " select salesdt.item_code, items.item_description, salesdt.warehouse_code, saledt_quantity, ".
					   " convertcurfunc(salesdt.currency_code,if(upper($cur)='".$Base1."', '".$Base1."',if(upper($cur)='".$Base2."','".$Base2."',salesdt.currency_code)),sale_date,0,0,'','',ifnull(saledt_priceTTC,0)), ".
					   " ifNull(saledt_discountper,0), ".
					   " convertcurfunc(salesdt.currency_code,if(upper($cur)='".$Base1."', '".$Base1."',if(upper($cur)='".$Base2."','".$Base2."',salesdt.currency_code)),sale_date,0,0,'','', ".
					   " ((ifNull(saledt_quantity,0) * ifNull(saledt_priceTTC,0)) - ".
					   " ((ifNull(saledt_quantity,0) * ifNull(saledt_priceTTC,0) * ifNull(saledt_discountper,0)) / 100) ) ) total, ".
					   " 0 As MeanCostAmount, SaleDt_Reason ";
						   
    }*/
	$querysalesdt = $querysalesdt." from salesdt ". 
					        	  " left join items on salesdt.item_code = items.item_code ".
							      " where salesdt.sale_id = ". $rowdelivery[9];													  
	
	//echo $querydeliverydt;
	
	if($_SESSION['module']=="1" && ($transaction == 'DI' || $transaction == 'DR' )){
		$sub_query= " select Sum(if(upper($cur)='".$Base1."', DeliveryDt_CostBase1, if(upper($cur)='".$Base2."', DeliveryDt_CostBase2, DeliveryDt_Cost))*ifNull(deliverydt_quantity,0)) As TotalCost ".
					" from deliverydt ".
					" where deliverydt.delivery_id = ". $rowdelivery[9];
								
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		$sub_row = mysql_fetch_row($sub_result);
		
	}										
	
	if (($grpproject == 1  && $grpclient == 0) && ($masterproject == '' || $masterproject!= $rowdelivery[5])) {
	  
	  echo "<tr>"; 
	  echo "<td colspan='13'><table class='group' width='100%' border='0' align='center' >";
	  
	  if (($cur != 'null') && ($masterproject != '' && $masterproject!= $rowdelivery[5]) && $ShowTotals == 1){
	    echo "   <tr>";
		echo "   <td colspan='2'>&nbsp;</td>";
	    echo "   <td align='right'> Total by group $displaycur  ".number_format($SumGroupNetTot, $DecimalBase)." </td>"; 
		echo "   </tr>";
		
		$SumGroupNetTot = 0;
	  }	
	
	  echo "<tr>";
	  echo "   <td width='10%'> Group by Project</td>";
	  echo "   <td width='7%'>". $rowdelivery[5] ."</td>";
	  echo "   <td width='38%'>". $rowdelivery[11] ."</td>";
	  echo "</tr>"; 
	  
	  
	  echo "<tr><td colspan='3'>&nbsp;</td></tr></table></td></tr>";
	  $masterproject= $rowdelivery[5];
	
	}
	
	if (($grpclient == 1) && ($masterclient == '' || $masterclient!= $rowdelivery[3])) {
	  
	  echo "<tr>"; 
	  echo "<td colspan='13'><table class='group' width='100%' border='0' align='center' >";
	  
	  if (($cur != 'null') && ($masterclient != '' && $masterclient!= $rowdelivery[3]) && $ShowTotals == 1){
	    echo "   <tr>";
		echo "   <td colspan='2'>&nbsp;</td>";
	    echo "   <td align='right'> Total by group $displaycur  ".number_format($SumGroupNetTot, $DecimalBase)." </td>"; 
		echo "   </tr>";
		
		$SumGroupNetTot = 0;
	  }	
	  
	  echo "<tr>";
	  echo "   <td width='10%'> Group by Client</td>";
	  echo "   <td width='7%'>". $rowdelivery[3] ."</td>";
	  echo "   <td width='38%'>". $rowdelivery[4] ."</td>";
	  echo "</tr>"; 
	  
	  
	  echo "<tr><td colspan='3'>&nbsp;</td></tr></table></td></tr>";
	  $masterclient= $rowdelivery[3];
	
	}
	
	if($_SESSION['module']=="1" && ($transaction == 'DI' || $transaction == 'DR' )){
		$NetTotal = $sub_row[0];
	}	
	else { 	
		$NetTotal = $rowdelivery[8] + $rowdelivery[15] - $rowdelivery[17];
		//if ($pricettc == 0)
			$NetTotal += $rowdelivery[16];
	}	
	
if($showdetail == 1){	
	echo "<tr>"; 
	echo "<td align='center' valign='top'>". $rowdelivery[0] ."</td>";
	echo "<td align='left'   valign='top' >". $rowdelivery[1] ."</td>";
	$col+=1;
	if($_SESSION['module']=="0"){
	  if ($rowdelivery[2] == 'DI')
	    echo "<td align='center' valign='top' > SI </td>";
	  else
	    echo "<td align='center' valign='top' > SR </td>";
	}
    else
      echo "<td align='center' valign='top' >". $rowdelivery[2] ."</td>"; 	
	//start nabil 2011-01-20
	echo "<td align='center' valign='top' >". $rowdelivery[12] ."</td>";
	//end nabil 2011-01-20
	if($rowdelivery[13])
		echo "<td align='center' valign='top' > ". $rowdelivery[13] ."</td>";
	else	
		echo "<td align='center' valign='top' > &nbsp;</td>";
		
	echo "<td align='center' valign='top'>". $rowdelivery[3] ."</td>";
	echo "<td align='left'   valign='top' >". $rowdelivery[4] ."</td>";
	if($rowdelivery[5]!='')
		echo "<td align='center' valign='top' >". $rowdelivery[5] ."</td>";
	else	
		echo "<td align='center' valign='top'>&nbsp;</td>";
	if($showProjCostName == 1)
		echo "<td align='center' valign='top' >". $rowdelivery[11] ."</td>";
	echo "<td align='center' valign='top' >". $rowdelivery[6] ."</td>";
	if($showProjCostName == 1)
		echo "<td align='center' valign='top' >". $rowdelivery[18] ."</td>";
	echo "<td align='center' valign='top' >". $rowdelivery[7] ."</td>";
	echo "<td align='center' valign='top' >". number_format($rowdelivery[8], $DecimalBase) ."</td>";
	echo "<td align='center' valign='top' >". number_format($rowdelivery[15], $DecimalBase) ."</td>";
	$GrossTot = $rowdelivery[15] + $rowdelivery[8];
	echo "<td align='center' valign='top' >". number_format($GrossTot, $DecimalBase) ."</td>";
	//if ($pricettc == 0){
		echo "<td align='center' valign='top' >". number_format($rowdelivery[17], $DecimalBase) ."</td>";
		echo "<td align='center' valign='top' >". number_format($rowdelivery[16], $DecimalBase) ."</td>";
	// }else
	// 	echo "<td align='center' valign='top' >". number_format($rowdelivery[16], $DecimalBase) ."</td>";
}else{
	echo "<tr $color>";
	echo "<td align='center' valign='top' style='border-right:1px solid black; '>". $rowdelivery[0] ."</td>";
	echo "<td align='left'   valign='top' style='border-right:1px solid black; padding-left:2px;'>". $rowdelivery[1] ."</td>";
	$col+=1;
	if($_SESSION['module']=="0"){
	  if ($rowdelivery[2] == 'DI')
	    echo "<td align='center' valign='top' style='border-right:1px solid black;'> SI </td>";
	  else
	    echo "<td align='center' valign='top' style='border-right:1px solid black; '> SR </td>";
	}
    else
      echo "<td align='center' valign='top' style='border-right:1px solid black; padding-left:2px;'>". $rowdelivery[2] ."</td>"; 	
	//start nabil 2011-01-20
	echo "<td align='center' valign='top' style='border-right:1px solid black; padding-left:2px;'>". $rowdelivery[12] ."</td>";
	//end nabil 2011-01-20
	if($rowdelivery[13])
		echo "<td align='center' valign='top' style='border-right:1px solid black; '> ". $rowdelivery[13] ."</td>";
	else	
		echo "<td align='center' valign='top' style='border-right:1px solid black; '> &nbsp;</td>";
		
	echo "<td align='center' valign='top' style='border-right:1px solid black; '>". $rowdelivery[3] ."</td>";
	echo "<td align='left'   valign='top' style='border-right:1px solid black; padding-left:2px;'>". $rowdelivery[4] ."</td>";
	if($rowdelivery[5]!='')
		echo "<td align='center' valign='top' style='border-right:1px solid black; '>". $rowdelivery[5] ."</td>";
	else	
		echo "<td align='center' valign='top' style='border-right:1px solid black; '>&nbsp;</td>";
	if($showProjCostName == 1)
		echo "<td align='center' valign='top' >". $rowdelivery[11] ."</td>";
	echo "<td align='center' valign='top' style='border-right:1px solid black; '>". $rowdelivery[6] ."</td>";
	if($showProjCostName == 1)
		echo "<td align='center' valign='top' >". $rowdelivery[18] ."</td>";
	echo "<td align='center' valign='top' style='border-right:1px solid black; '>". $rowdelivery[7] ."</td>";	
	echo "<td align='center' valign='top' style='border-right:1px solid black; '>". number_format($rowdelivery[8], $DecimalBase) ."</td>";	
	echo "<td align='center' valign='top' style='border-right:1px solid black; '>". number_format($rowdelivery[15], $DecimalBase) ."</td>";
	$GrossTot = $rowdelivery[15] + $rowdelivery[8];
	echo "<td align='center' valign='top' style='border-right:1px solid black; '>". number_format($GrossTot, $DecimalBase) ."</td>";
	//if ($pricettc == 0){	
		echo "<td align='center' valign='top' style='border-right:1px solid black; '>". number_format($rowdelivery[17], $DecimalBase) ."</td>";	
		echo "<td align='center' valign='top' style='border-right:1px solid black; '>". number_format($rowdelivery[16], $DecimalBase) ."</td>";	
	// }else{
	// 	echo "<td align='center' valign='top' style='border-right:1px solid black; '>". number_format($rowdelivery[16], $DecimalBase) ."</td>";	
	// }
}
	
	if($ShowTotals == 1) 
		echo "<td align='right' valign='top' >". number_format($NetTotal, $DecimalBase) ."</td>";
	else
		echo "<td align='right' valign='top'>&nbsp;</td>";
	
	echo "</tr>";
	
	if ($rowdelivery[14] != "") {
		echo "<tr>"; 
		echo "<td align='center'>&nbsp;</td>";
		echo "<td align='left' colspan='12'>". $rowdelivery[14] ."</td>";
		echo "</tr>";
	}
	
//exit;
	if ($rowdelivery[2] == 'SI' || $rowdelivery[2] == 'DI' || $showboth == 0) {
	  $SumNetTot       = $SumNetTot  + $NetTotal;
	  $SumGroupNetTot  = $SumGroupNetTot  + $NetTotal;
	} else {
	  $SumNetTot       = $SumNetTot  - $NetTotal;
	  $SumGroupNetTot  = $SumGroupNetTot  - $NetTotal;
	}

	
	if ($showdetail == 1) {
	    if($SalesReport==1)
		   $resultdeliverydt=mysql_query($querysalesdt,$connection) or die(mysql_error());
		else
           $resultdeliverydt=mysql_query($querydeliverydt,$connection) or die(mysql_error());
		   
		while($rowdeliverydt=mysql_fetch_row($resultdeliverydt)){
			if($col1%2==0){
				$color1 = "style='background-color:".$report_color1."'";
			}else{
				$color1 = "style='background-color:".$report_color2."'";
			}
			echo "<tr $color1>";
			echo "  <td colspan='13'><table class='detail' width='100%' border='0' align='center' cellpadding='0' cellspacing='0'><tr> ";
			echo "  <td width='2%'>&nbsp;</td>";
			echo "  <td width='6%' style='border-right:1px solid black;'>". $rowdeliverydt[0] ."</td>";
			echo "  <td width='19%' style='border-right:1px solid black; padding-left:2px;'>". $rowdeliverydt[1] ;
			if($_GET['show_reason'] == 1){
			echo "<br>Reason: ".$rowdeliverydt[8];
			}
			echo"</td>";
			//echo "  <td width='22%'>". $rowdeliverydt[14] ."</td>";
			echo "  <td width='5%' style='border-right:1px solid black; padding-left:2px;'>". $rowdeliverydt[2] ."</td>";
			
			echo "  <td width='4%' align='right' style='border-right:1px solid black; padding-right:2px;'> ". number_format($rowdeliverydt[3], $DecimalBase) ."</td>";
			echo "  <td width='5%' align='right' style='border-right:1px solid black; padding-right:2px;'> ". number_format($rowdeliverydt[4], $DecimalBase) ."</td>";
			echo "  <td width='4%' align='right' style='border-right:1px solid black; padding-right:2px;'> ". number_format($rowdeliverydt[5], $DecimalBase) ."%</td>";
			echo "  <td width='5%' align='right' style='border-right:1px solid black; padding-right:2px;'> ". number_format($rowdeliverydt[6], $DecimalBase) ."</td>";
			
			if ($ShowCost == 1)
				echo "  <td width='5%' align='right' style='border-right:1px solid black; padding-right:2px;'> ". number_format($rowdeliverydt[7], $DecimalBase) ."</td>";
			else 
				echo "  <td width='5%' align='right' style='border-right:1px solid black;'>&nbsp;</td>";
				
			echo " </tr></table></td></tr>";
			$col1+=1;
		}
	}	
		//exit;  
/*	echo "<tr height='8' >";
	echo "  <td colspan='13'><hr width='100%' color='black' size='1'></td>";
	echo "</tr>";
*/	
	$SumTaxable += $rowdelivery[8];
	$SumNonTaxable += $rowdelivery[15];
	$SumDisc += $rowdelivery[17];
	//if ($pricettc == 0)
		$SumVat += $rowdelivery[16];
	$SumGrossTot += $GrossTot;
	
	
	}


}
 
echo "<tr>";
echo "<td colspan='10'></td>";
echo "<td align='right'><b>Sum Taxable:</b><br> ".number_format($SumTaxable, $DecimalBase)."</td>";
echo "<td align='right'><b>Sum NonTaxable:</b><br> ".number_format($SumNonTaxable, $DecimalBase)."</td>";
echo "<td align='right'><b>Sum Gross Total:</b><br> ".number_format($SumGrossTot, $DecimalBase)."</td>";
echo "<td align='right'><b>Sum Discount:</b><br> ".number_format($SumDisc, $DecimalBase)."</td>";
//if ($pricettc == 0)
	echo "<td align='right'><b>Sum VAT:</b><br> ".number_format($SumVat, $DecimalBase)."</td>";


if (($grpproject == 1  && $grpclient == 0 ) && ($masterproject == '' || $masterproject!= $rowdelivery[5])) {
	  
    echo "<tr>"; 
    echo "<td colspan='40'><table class='group' width='100%' border='0' align='center' >";
	  
	if (($cur != 'null') && ($masterproject != '' ) && $ShowTotals == 1){
	   echo "   <tr>";
	   echo "   <td colspan='2'>&nbsp;</td>";
	   echo "   <td align='right'> Total by group $displaycur  ".number_format($SumGroupNetTot, $DecimalBase)." </td>"; 
	   echo "   </tr>";
		
	   $SumGroupNetTot = 0;
	}	
	  
  
     echo "<tr><td colspan='3'>&nbsp;</td></tr></table></td></tr>";
	
}

if (($grpclient == 1 ) && ($masterclient == '' || $masterclient!= $rowdelivery[3])) {
	  
    echo "<tr>"; 
    echo "<td colspan='40'><table class='group' width='100%' border='1' align='center' >";
	  
	if (($cur != 'null') && ($masterclient != '' ) && $ShowTotals == 1){
	   echo "   <tr>";
	   echo "   <td colspan='2'>&nbsp;</td>";
	   echo "   <td align='right'> Total by group $displaycur  ".number_format($SumGroupNetTot, $DecimalBase)." </td>"; 
	   echo "   </tr>";
		
	   $SumGroupNetTot = 0;
	}	
	  
  
     echo "<tr><td colspan='3'>&nbsp;</td></tr></table></td></tr>";
	
}
	
if ($cur != 'null' && $ShowTotals == 1){
	echo "<tr>";
	echo "  <td colspan='40'><table class='totals' width='100%' border='0' align='center' ><tr> ";
	echo "  <td width='80%' align='right'> Total $displaycur </td>";
	echo "  <td width='20%'  align='right'> ".number_format($SumNetTot, $DecimalBase)." </td>";
	echo " </tr></table></td>";
	echo "</tr>";
	
}

echo "</table>";

function current_server_time($connection){

  $string="Select date_format(NOW(),'%Y-%m-%d %h:%i %p') ";
  $result=mysql_query($string,$connection) or die(mysql_error());
  $now=mysql_fetch_row($result);

  return $now;
}

function explodeword($date)
{

$trim = explode('/',$date);
$trim = "$trim[2]"."-"."$trim[1]"."-"."$trim[0]";
return $trim;
}


if ($printaccess==1)
print <<< HERE

<script language=javascript>
if (typeof(window.print) != 'undefined')
{
    window.print();
}
</script>
</BODY>
</HTML>
HERE;

?>