<?php
header("Content-type: text/html; charset=windows-1256");

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

// var_dump($_GET);exit;
print <<< HERE
<html">
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<TITLE> List of Retail Report </TITLE>

<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: 13px; 
                  font-family:Times-New-Roman;
                 }
				 
table.master1 th { font-size: 14px; 
                   font-weight: bold;
                   font-family:Times-New-Roman;
                 }				 
table.master1 td { font-size: 13px; 
				   font-weight: bold;
                   font-family:Times-New-Roman;
                 }	
				 
table.group td { font-size: 14px; 
                 font-weight: bold;
				 font-style: italic;
                 font-family:Times-New-Roman;
               }	

table.detail th { font-size: 12px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
                 }				 			   
table.detail td { font-size: 12px; 
				  font-weight: normal;
                  font-family:Times-New-Roman;
                }		
table.detail td.sr  { font-size: 11px; 
					  font-style: italic; 
                      font-family:Times-New-Roman;
                    }				
				 
.totals { font-size: 12px; 
          font-weight: bold;
          font-family:Times-New-Roman;
        }	

table.summary th { font-size: 14px; 
                   font-weight: bold;
                   font-family:Times-New-Roman;
                 }				 		
table.summary td { font-size: 14px; 
                   font-weight: normal;
                   font-family:Times-New-Roman;
                 }				 
				 
h4 { border-top-style: solid; 
	 border-top-color: black; 
	 border-top-width: 2px;
   }
h5 { border-top-style: solid; 
	 border-top-color: black; 
	 border-top-width: 1px;
   }   
   
</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");

$querylog="SELECT print as printaccess 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);
}





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

//Read From CashRegister Table
/*$queryCashRegister=" Select ifNull(CashRegisterTTC,0) As CashRegisterTTC ".
				   " From CashRegister ".
				   " Where CashRegister_Name = '".$_SESSION['cashregister']."' ";*/

$queryCashRegister = " Select ifNull(CashRegisterTTC,0) As CashRegisterTTC, ifNull(retailserialno,0) As RetailSerialNo  ".
					 " From CashRegister Inner Join ".$_SESSION['dbLabel'].".logindt on logindt.Cash_Register = CashRegister.CashRegister_Name ".
					 " Where logindt.User_Account = '".$_SESSION['useraccount']."' ";
$resultCashRegister=mysql_query($queryCashRegister,$connection) or die(mysql_error());
while($rowCashRegister=mysql_fetch_array($resultCashRegister)){
	extract($rowCashRegister);
}

$querylog=" select ifNull(FI_RepRestrictProject,0) As FI_RepRestrictProject, ifNull(FI_RepRestrictCostcenter,0) As FI_RepRestrictCostcenter, ".
		  " ifNull(FI_RepRestrictWarehouse,0) As FI_RepRestrictWarehouse ".
          " from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."') ";
$resultlog=mysql_query($querylog) 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']."' ".
			  " and (loginstk.project_code is not null and loginstk.project_code != '') ".
			  " 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);		

$querywh=" select distinct warehouse.warehouse_code, warehouse_name ".
         " from warehouse where warehouse_code in ( select warehouse_code from ".$_SESSION['dbLabel'].".loginstk ".
		 "                                          where user_account='".$_SESSION['useraccount']."' ".
		 "                                          and (loginstk.warehouse_code is not null and loginstk.warehouse_code != '') ) ".
		 " order by warehouse.warehouse_code";
$resultwh = mysql_query($querywh,$connection) or die(mysql_error());
$whexist  = mysql_num_rows($resultwh);

$queryTax = "select 1, cashregister_TaxConsumptionpPer from cashregister where ifnull(cashregister_TaxConsumption,0) = 1 and ifnull(cashregister_TaxConsumptionpPer,0) > 0 limit 1";
$resTax = mysql_query($queryTax, $connection);
$rwTax = mysql_fetch_row($resTax);
$TaxConsumption = $rwTax[0];
$TaxConsumptionpPer = $rwTax[1];
if ($TaxConsumption == '') 		$TaxConsumption = 0;
if ($TaxConsumptionpPer == '') 	$TaxConsumptionpPer = 0;

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

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

print <<< HERE
<table width="100%" border="0" align="center">
<tr><td>
<table width='100%' border='0' align='left' style='table-layout:fixed'>
<tr>
  <td width='30%'><b>$CompanyName</b></td>
  <td width='50%' align='center'><font size=4><b>Daily Sales</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];

$dispfromdate = $fromdate;
$disptodate   = $todate;
$dispfromuser = $fromuser;
$dispcurr     = $curr;

  
$dispfromgroup = $fromgroup;
$disptogroup = $togroup;
$dispfromsubgroup = $fromsubgroup;
$disptosubgroup = $tosubgroup;


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

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

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


if (empty($curr))  $curr = '';
//else  $curr = "'".$curr."'";   



if(strlen($fromdate)==10 && $fromtime == '')
	$fromdate = $fromdate." 00:00:00";

if(strlen($todate)==10 && $totime == '')
	$todate = $todate." 23:59:59";

if (strlen($fromdate)==10 && $fromtime != '')   
   $fromdate = $fromdate." ".$fromtime.":00";
if (strlen($todate)==10 && $totime != '')   
   $todate = $todate." ".$totime.":59";

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

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

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

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

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

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


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

if (empty($fromcredit))  $fromcredit = 'null';
else  $fromcredit = "'".$fromcredit."'";    
if (empty($tocredit))  $tocredit = 'null';
else  $tocredit = "'".$tocredit."'";     
   
if(empty($showgroups)) $showgroups = 0;
if(empty($showcost)) $showcost = 0;
if(empty($costoption)) $costoption = 1;

print <<<HERE
</font></td>
</tr>
<tr height='5'><td colspan=4><h5></td></tr>
</table>
</td></tr>

<tr><td>
<table class='params' width='100%' border='0' align='left' style='table-layout:fixed' >
<tr>
  <td width="12%"><b>Date From/To:</b></td>
  <td width="18%">$dispfromdate - $disptodate </td>
  <td width="8%" valign='top'><b>Currency:</b></td>
  <td width="12%">$dispcurr</td>
  <td width="6%" valign='top'><b>User:</b></td>
  <td width="44%">$dispfromuser</td>
</tr>
<tr height='5'><td colspan=6><h4></td></tr>
</table>
</td></tr>

<tr><td>
HERE;

if ($showdetail == 1) $masterclass = 'master1';
else $masterclass = 'master';

if ($showcost == 1 && $groupby == 2) 
	$hr = 13;
else 
	$hr = 9;
if ($groupby == 2 || $groupby == 6) {
	echo "<table width='900' border='0' align='left' class='master' style='table-layout:fixed'>
		  <col width=120>
		  <col width=200>
		  <col width=60>
		  <col width=90>
		  <col width=90>
		  <col width=120>
		  <col width=100>
		  <col width=100>
		  <col width=75>";
	if ($TaxConsumption == 1){
		echo " <col width=80> <col width=80>";	
		$hr = $hr + 2;
	}
	if ($showcost == 1 && $groupby == 2) {
		echo"<col width=80>
			 <col width=100>
			 <col width=100>
			 <col width=80>";
	}		  
	
		  
	if ($showgroups == 1 && $groupby == 6) {	  
		echo"<tr>";
		echo"	<th align='left' colspan='2'>Vendor</th>
				<th >Qty</th>
				<th >Disc. Amount </th>
				<th >Total Amount </th>
				<th >Comm.(%)</th>
				<th colspan='3'>Comm. Amt </th>";
	} else {
		echo"<tr>
				<th colspan='6'>&nbsp;</th>
				<th colspan='3'>Inclusive in Price</th>
			 </tr>
		     <tr>";
		echo"	<th >Item Code</th>
				<th >Description</th>
				<th >Qty</th>
				<th >Unit Price </th>
				<th >Cost Price </th>
				<th >Total Amount </th>
				<th >Vat Amount </th>
				<th >Disc. Amount </th>
				<th >Disc(%) </th>";
		if ($TaxConsumption == 1)
			echo "<th >Tax Amount </th><th >Net Amount After Tax</th>";	
		if ($showcost == 1 && $groupby == 2) {
			echo"<th >Unit Cost</th>
				 <th >Total Cost</th>
				 <th >Profit Amount</th>
				 <th >Profit Margin (%)</th>";
		}		
	}
			 			 
			
	echo" </tr>";
	
	if ($showcost == 1 && $groupby == 2) 
		echo"<tr height='5'><td colspan='$hr'><h4></td></tr>";
	else
		echo"<tr height='5'><td colspan='$hr'><h4></td></tr>";
} else {
	$hr = 11;
	echo "<table width='970' border='0' align='left' class=$masterclass style='table-layout:fixed'>
		  <col width=20>
		  <col width=70>
		  <col width=110>
		  <col width=160>
		  <col width=60>
		  <col width=100>
		  <col width=90>
		  <col width=100>
		  <col width=50>
		  <col width=90>";
	if ($TaxConsumption == 1){	  
		echo "<col width=100><col width=90>"; 
		$hr = 13;
	}	
	echo "<col width=100>";
		  
	if (($groupby == 1 && $showgroups != 1) || ($groupby != 1 && 1 == 1)) {
	
		echo"<tr>";
			  
		if ($showgroups == 1) {
			echo"<th colspan='4' align='left'>Description</th>
				 <th >Currency</th>
				 <th >Disc. Amount </th>
				 <th >Net Amount </th>
				 <th colspan='4'>&nbsp;</th>";
		} else {
			echo"<th >&nbsp;</th>
				 <th >Reference</th>
				 <th >Date</th>
				 <th >Remark</th>
				 <th >Currency</th>
				 <th >Taxable Amount </th>
				 <th >NoneTaxable Amount </th>
				 <th >Disc. Amount </th>
				 <th >Disc(%) </th>
				 <th >Vat Amount </th>";
			if ($TaxConsumption == 1){
				echo "<th >Amount Before Tax</th><th >Tax Amount </th>";
			}	
			echo "<th >Net Amount </th>
			   </tr>";
		
			if ($showdetail == 1) {
				echo"<tr height='5'><td colspan='11'><h5></td></tr>";
				echo"<tr height='20'><td colspan='11'>";
				echo "<table width='780' border='0' align='left' class='detail' style='table-layout:fixed'>
						<col width=120>
						<col width=360>
						<col width=80>
						<col width=60>
						<col width=100>
						<tr>
							<th >Item Code</th>
							<th >Description</th>
							<th >Warehouse</th>
							<th >Qty</th>
							<th >Unit Price </th>
						</tr>";
					
				echo"</table>";
				echo"</td></tr>";		
			}
		}
		
		echo"<tr height='5'><td colspan='$hr'><h4></td></tr>";
	}
}		 


	

$query = '';

$QueryRestrictPrj = " Inner join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
					" 			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
					"              and (project_code is not null and project_code != '') ".
					"			 ) Q4  ";
					
$QueryRestrictCst = " 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 != '') ".
					"			 ) Q5  ";
					
					
$query = " Select ItemCode, ItemDescription, SaleDtQuantity, SaleDtTotal, SaleDtTotalTTC, SaleDtTotalBase2, SaleDtTotalTTCBase2, SaleDtDiscAmt, SaleDtDiscAmtTTC,  ".
		 " SaleDtDiscAmtBase2, SaleDtDiscAmtTTCBase2, SaleDtVatAmt, SaleDtVatAmtBase2, SaleDtDiscPer, MasterCode, MasterDescription, VendorCommission, ".
		 " ItemCost, (SaleDtQuantity*ItemCost) As TotalCost,  (SaleDtTotal - (SaleDtQuantity*ItemCost)) As ProfitAmount, ".
		 " if(SaleDtTotal=0, 0, (((SaleDtTotal - (SaleDtQuantity*ItemCost)) / (SaleDtTotal)) * 100)) As ProfitMargin, LastCostPriceB1, LastCostPriceB2, ".
		 " Round(if('$CashRegisterTTC'='1', saledtTotalTTc, saledtTotal)* $TaxConsumptionpPer/100, ".$DecimalBase.") as saledtTaxAmnt, ".
		 " Round(if('$CashRegisterTTC'='1', SaleDtTotalTTCBase2, SaleDtTotalBase2)*$TaxConsumptionpPer/100, ".$DecimalBase.") as saledtTaxAmntBase2  ".
		 " From ( ".
		 " Select if($showgroups!=1, RetailDt.Item_code, Null) As ItemCode, if($showgroups!=1, Items.Item_Description, Null) As ItemDescription, Sum(ifNull(SaleDt_Quantity,0)) As SaleDtQuantity, ".
	     " Round(Sum(((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100) - ifNull(SaleDt_DiscountAmount,0))), ".$DecimalBase.") As SaleDtTotal, ".
		 " Round(Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0)*ifNull(SaleDt_DiscountPer,0))/100) - (ifNull(SaleDt_DiscountAmount,0)*(1 + RetailDt.Item_Vat/100))), ".$DecimalBase.") As SaleDtTotalTTC, ".
		 " Round(Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceBase2,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceBase2,0)*ifNull(SaleDt_DiscountPer,0))/100) - ifNull(SaleDt_DiscountBase2,0)), ".$DecimalBase.") As SaleDtTotalBase2, ".
		 " Round(Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTCBase2,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTCBase2,0)*ifNull(SaleDt_DiscountPer,0))/100) - (ifNull(SaleDt_DiscountBase2,0)*(1 + RetailDt.Item_Vat/100))), ".$DecimalBase.") As SaleDtTotalTTCBase2, ".
		 " Round(Sum(((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100) + ifNull(SaleDt_DiscountAmount,0)), ".$DecimalBase.") As SaleDtDiscAmt, ".
		 " Round(Sum(((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0)*ifNull(SaleDt_DiscountPer,0))/100) + (ifNull(SaleDt_DiscountAmount,0)*(1 + RetailDt.Item_Vat/100))), ".$DecimalBase.") As SaleDtDiscAmtTTC, ".
		 " Round(Sum(((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceBase2,0)*ifNull(SaleDt_DiscountPer,0))/100) + ifNull(SaleDt_DiscountBase2,0)), ".$DecimalBase.") As SaleDtDiscAmtBase2, ".
		 " Round(Sum(((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTCBase2,0)*ifNull(SaleDt_DiscountPer,0))/100) + (ifNull(SaleDt_DiscountBase2,0)*(1 + RetailDt.Item_Vat/100))), ".$DecimalBase.") As SaleDtDiscAmtTTCBase2, ".
		 " Round(Sum(((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100) - ifNull(SaleDt_DiscountAmount,0))*ifNull(RetailDt.Item_Vat,0)/100), ".$DecimalBase.") As SaleDtVatAmt, ".
		 " Round(Sum(((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceBase2,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceBase2,0)*ifNull(SaleDt_DiscountPer,0))/100) - ifNull(SaleDt_DiscountBase2,0))*ifNull(RetailDt.Item_Vat,0)/100), ".$DecimalBase.") As SaleDtVatAmtBase2, ".
		 " ifnull(meancostcur(retaildt.item_code,Retail.Sale_Date,1,'',''),0) AS LastCostPriceB1, ".
		 " ifNull(convertcurfunc(Items.Currency_Code, '".$Base2."', Retail.Sale_Date, 0, 0, '', '', ifnull(meancostcur(retaildt.item_code,Retail.Sale_Date,1,'',''),0)),0) as  LastCostPriceB2, ".
		 " if($showgroups!=1, Round(Sum(((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100) + ifNull(SaleDt_DiscountAmount,0))*100/Sum(ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)), ".$DecimalBase."), Null) As SaleDtDiscPer, ".
		 " if($groupby=6, ifNull(RetailDt.Vendor_Code,''), '') As MasterCode, if($groupby=6, ifNull(Vendor.Ledger_Name,''), '') As MasterDescription, ifNull(Vendor.Vendor_Commission, 0) As VendorCommission,  ";

if ($showcost == 1 && $groupby == 2) {		 
	if ($costoption == 1)
		$query = $query." ifNull(MeanCostCur(RetailDt.Item_code, concat(".$todate.", ' 23:59:59'), if(upper('".$curr."')='".$Base1."', 1,if(upper('".$curr."')='".$Base2."',2, 1)), Retail.currency_code, if(upper('".$curr."')='".$Base1."', '',if(upper('".$curr."')='".$Base2."','',items.currency_code ))),0) as ItemCost ";
	else
		$query = $query." ifNull(ItemLifoCost(RetailDt.Item_code, concat(".$todate.", ' 23:59:59'), if(upper('".$curr."')='".$Base1."', 1,if(upper('".$curr."')='".$Base2."',2, 1)), Retail.currency_code, if(upper('".$curr."')='".$Base1."', '',if(upper('".$curr."')='".$Base2."','',items.currency_code ))),0) as ItemCost ";
} else {
	$query = $query." 0 as ItemCost ";				
}		


$query = $query.	
	     " From RetailDt  ".
		 " Inner Join Retail on RetailDt.Sale_Id = Retail.Sale_Id ".
		 " Inner Join Items on RetailDt.Item_code = Items.Item_code ".
		 " Left Join Vendor on RetailDt.Vendor_Code = Vendor.Ledger_Number ";
		 
		if ($projectexist > 0 && $FI_RepRestrictProject == 1)
			$query= $query.$QueryRestrictPrj." on Retail.Project_Code like concat(Q4.project_code,'%') ";
							 
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
			$query= $query.$QueryRestrictCst." on Retail.CostCenter_Code like concat(Q5.costcent_code,'%') ";
					
// var_dump($_GET);exit;
$query= $query.					
	     " Where Retail.User_Account = ifNull(".$fromuser.", Retail.User_Account) ".
		 " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ".
		 " And Retail.CashRegister_Name = ifNull(".$fromcashreg.", Retail.CashRegister_Name) ".
		 " And ifNull(Retail.Customer_Code,'-1') between ifNull(".$fromcustomer.",ifNull(Retail.Customer_Code,'-1')) and ifNull(". $tocustomer.",ifNull(Retail.Customer_Code,'-1')) ".
		 " And ifNull(Retail.sale_reference,'-1') between ifNull(".$fromref.",ifNull(Retail.sale_reference,'-1')) and ifNull(". $toref.",ifNull(Retail.sale_reference,'-1')) ".
		 " And Date_format(Retail.Sale_Date,'%Y-%m-%d %H:%i:%s') between ifNull(". $fromdate.",date_format(Retail.Sale_Date,'%Y-%m-%d %H:%i:%s')) and ifNull(". $todate.",date_format(Retail.Sale_Date,'%Y-%m-%d %H:%i:%s'))  ".
		 " And ifNull(Retail.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Retail.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Retail.Project_Code,'-1')) ".
		 " And ifNull(Retail.CostCenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Retail.CostCenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Retail.CostCenter_Code,'-1')) ".
		 " And ifNull(RetailDt.Warehouse_Code,'-1') = ifNull(". $fromwarehouse .", ifNull(RetailDt.Warehouse_Code,'-1')) ".
		 " And ifNull(Retail.Salesman_Code,'-1') = ifNull(".$fromsalesman.", ifNull(Retail.Salesman_Code,'-1')) ".
		 " And ifNull(Retail.Sales_creditacc,'-1') between ifNull(".$fromcredit.",ifNull(Retail.Sales_creditacc,'-1')) and ifNull(". $tocredit.",ifNull(Retail.Sales_creditacc,'-1')) ".
		 " And ifNull(RetailDt.Vendor_Code,'-1') between ifNull(".$fromvendor.",ifNull(RetailDt.Vendor_Code,'-1')) and ifNull(". $tovendor.",ifNull(RetailDt.Vendor_Code,'-1')) ".
		 " And ifNull(RetailDt.item_code,'-1') between ifNull(".$fromitem.",ifNull(RetailDt.item_code,'-1')) and ifNull(". $toitem.",ifNull(RetailDt.item_code,'-1')) ".
	   	 " And ifNull(Items.Group_Code,-1) between ifNull(". $fromgroup .", ifNull(Items.Group_Code,-1)) and ifNull(". $togroup.", ifNull(Items.Group_Code,-1)) ".
  	     " And ifNull(Items.SubGroup_Code,-1) between ifNull(". $fromsubgroup .", ifNull(Items.SubGroup_Code,-1)) and ifNull(". $tosubgroup.", ifNull(Items.SubGroup_Code,-1)) ";
		 if($paymentmethod != ''&& $paymentmethod != 'CASH' )$query.=" and Retail.Sales_creditacc = '$paymentmethod' ";
		 if($paymentmethod != ''&& $paymentmethod == 'CASH' )$query.=" and Retail.Sales_creditacc = ''  ";
if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
	$query = $query." And RetailDt.Warehouse_Code In (select distinct warehouse_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";
	
$query = $query." Group By MasterCode, ItemCode ".
				" Order By MasterCode, ItemCode ";
				
$query = $query." ) As Q1 Order By MasterCode, ItemCode ";
// echo $query;	 

$query1 = " Select if($showgroups!=1, Retail.Sale_ID, -1) As SaleID, if($showgroups!=1, Sale_Reference, Null) As SaleReference, if($showgroups!=1, Retail.Sale_Date, Null) As SaleDate, ".
		  " if($showgroups!=1, Sale_Remark, Null) As Sale_Remark, Retail.Currency_code As CurrCode, Round(Sum(ifNull(Sale_NetTotal,0)), ".$DecimalBase.") As  SaleNetTotal, ".
		  " Round(Sum(ifNull(Sale_NetTotalBase2,0)), ".$DecimalBase.") As SaleNetTotalBase2, ".
		  " if($groupby=3, ifNull(Retail.User_Account,''), if($groupby=4, ifNull(Retail.CashRegister_Name,''), if($groupby=5, ifNull(Retail.Customer_Code,''), ''))) As MasterCode, ".
		  " if($groupby=3, ifNull(Users.User_Name,''), if($groupby=4, ifNull(Retail.CashRegister_Name,''), if($groupby=5, ifNull(Customer.Customer_Name,''), ''))) As MasterDescription, ".
		  " Retail.User_Account, Retail.CashRegister_Name, ".
		  " Round(Sum(ifNull(Sale_Taxable,0)), ".$DecimalBase.") As  SaleTaxable, Round(Sum(ifNull(Sale_TaxableBase2,0)), ".$DecimalBase.") As  SaleTaxableBase2, ".
		  " Round(Sum(ifNull(Sale_NoneTaxable,0)), ".$DecimalBase.") As  SaleNoneTaxable, Round(Sum(ifNull(Sale_NoneTaxableBase2,0)), ".$DecimalBase.") As  SaleNoneTaxableBase2, ".
		  " Round(Sum(ifNull(Sale_DiscountAmount,0)), ".$DecimalBase.") As  SaleDiscountAmount, Round(Sum(ifNull(Sale_DiscountBase2,0)), ".$DecimalBase.") As  SaleDiscountBase2, ".
		  " Round(Sum(ifNull(Sale_VAT,0)), ".$DecimalBase.") As  SaleVAT, Round(Sum(ifNull(Sale_VATBase2,0)), ".$DecimalBase.") As  SaleVATBase2, ".
		  " if($showgroups!=1, ifNull(Sale_DiscountPer,0), Null) As SaleDiscountPer, Sum(ifNull(Sales_CashInBase1,0)) As SalesCashInBase1, Sum(ifNull(Sales_CashOutBase1,0)) As SalesCashOutBase1,  ".
		  " Sum(ifNull(Sales_CashInBase2,0)) As SalesCashInBase2, Sum(ifNull(Sales_CashOutBase2,0)) As SalesCashOutBase2, Sum(ifNull(Sale_CashBase1,0)) As SaleCheckBase1,  ".
		  " Sum(ifNull(Sale_CashBase2,0)) As SaleCheckBase2, Sum(ifNull(Sales_CreditAmountBase1,0)) As SalesCreditAmountBase1, Sum(ifNull(Sales_CreditAmountBase2,0)) As SalesCreditAmountBase2, ".
		  " Sum(ifNull(Sales_TipsBase1,0)) As SalesTipsBase1, if(ifNull(Sales_CreditAmountBase1,0) > 0, 'CR', '') As IsCredit, Sum(if(Sales_TipsBase1>0,1,0)) As SumofTips, ".
		  " Round(sum(sale_TaxConsumption),".$DecimalBase."), Round(sum(sale_TaxConsumptionB2),".$DecimalBase.") ".
  		  " From Retail ".
		  " Left Join Customer on Retail.Customer_Code = Customer.Customer_Code ";
 if($fromitem!='null')
 $query1= $query1.		  " Left Join RetailDt on Retail.sale_id = RetailDt.sale_id ";
 $query1= $query1." Left Join ".$_SESSION['dbLabel'].".Users on Retail.User_Account = Users.User_Account ";
		  
		if ($projectexist > 0 && $FI_RepRestrictProject == 1)
			$query1= $query1.$QueryRestrictPrj." on Retail.Project_Code like concat(Q4.project_code,'%') ";
							 
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
			$query1= $query1.$QueryRestrictCst." on Retail.CostCenter_Code like concat(Q5.costcent_code,'%') ";

$query1= $query1.			
          " Where Retail.User_Account = ifNull(".$fromuser.", Retail.User_Account) ".
		  " And Retail.CashRegister_Name = ifNull(".$fromcashreg.", Retail.CashRegister_Name) ".
		  " And ifNull(Retail.Customer_Code,'-1') between ifNull(".$fromcustomer.",ifNull(Retail.Customer_Code,'-1')) and ifNull(". $tocustomer.",ifNull(Retail.Customer_Code,'-1')) ".
		  " And ifNull(Retail.sale_reference,'-1') between ifNull(".$fromref.",ifNull(Retail.sale_reference,'-1')) and ifNull(". $toref.",ifNull(Retail.sale_reference,'-1')) ".
		  " And Date_format(Retail.Sale_Date,'%Y-%m-%d %H:%i:%s') between ifNull(". $fromdate.",date_format(Retail.Sale_Date,'%Y-%m-%d %H:%i:%s')) and ifNull(". $todate.",date_format(Retail.Sale_Date,'%Y-%m-%d %H:%i:%s'))  ";
 if($fromitem!='null')
 $query1= $query1.			
          " And ifNull(RetailDt.item_code,'-1') between ifNull(".$fromitem.",ifNull(RetailDt.item_code,'-1')) and ifNull(". $toitem.",ifNull(RetailDt.item_code,'-1')) ";
		  $query1= $query1.			
          " And ifNull(Retail.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Retail.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Retail.Project_Code,'-1')) ".
		  " And ifNull(Retail.CostCenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Retail.CostCenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Retail.CostCenter_Code,'-1')) ".
		  " And ifNull(Retail.Salesman_Code,'-1') = ifNull(".$fromsalesman.", ifNull(Retail.Salesman_Code,'-1')) ".
		  " And ifNull(Retail.Sales_creditacc,'-1') between ifNull(".$fromcredit.",ifNull(Retail.Sales_creditacc,'-1')) and ifNull(". $tocredit.",ifNull(Retail.Sales_creditacc,'-1')) ";
if ($paymentmethod != '')
	$query1= $query1."and if (upper('$paymentmethod')='CASH', ifnull(sales_creditacc,0) = '', if(upper('$paymentmethod')='CUSTOMER',sales_creditacc not in (select Payment_Account from PaymentMethods) and sales_creditacc !='' ,if(upper('$paymentmethod')='COUPON', coupon_id is not null ,sales_creditacc = '$paymentmethod')))";
// $query1= $query1." and if (upper('$paymentmethod')='CASH', ifnull(sales_creditacc,0) = '', if(upper('$paymentmethod')='CUSTOMER',
					// sales_creditacc not in (select Payment_Account from PaymentMethods) and sales_creditacc !='' 
					// ,sales_creditacc = '$paymentmethod')) ";	
$query1= $query1." Group By MasterCode, SaleID, SaleReference   ".
				 " Order By MasterCode, Retail.Sale_Date, SaleReference  ";

// echo $query1; //exit;

$SaleDtCost    		= 0;
$SaleDtAmount  		= 0;
$SaleDtDiscAmt 		= 0;
$SaleDtVatAmt	   	= 0;
$SaleDtTaxConsAmt  	= 0;
$SaleDtAfterTaxAmt 	= 0;

$TotalTaxable	  = 0;
$TotalNoneTaxable = 0;
$TotalDiscAmt	  = 0;
$TotalVatAmt	  = 0;
$TotalTaxConsAmt  = 0;
$TotalAfterTaxAmt = 0;
$TotalAmount 	  = 0;
$TotalQty	  	  = 0;
		
$SumTaxable	    = 0;
$SumNoneTaxable = 0;
$SumDiscAmt	    = 0;
$SumVatAmt	    = 0;
$SumTaxConsAmt	= 0;
$sumAfterTaxAmt = 0;
$SumAmount      = 0;
$SumQty	   		= 0;

$TotalCashInB1  = 0;
$TotalCashInB2  = 0;
$TotalCashOutB1 = 0;
$TotalCashOutB2 = 0;
$SubTotalCashB1 = 0;
$SubTotalCashB2 = 0;
$TotalCashB1    = 0;
$TotalCashB2    = 0;
$TotalChecksB1  = 0;
$TotalChecksB2  = 0;
$TotalCreditsB1 = 0;
$TotalCreditsB2 = 0;
$TotalCouponB1  = 0;
$TotalCouponB2  = 0;
$NetTotalB1     = 0;
$NetTotalB2	    = 0;
$NumofCash		= 0;
$NumofChecks	= 0;
$SumofTips		= 0;
$NumofCoupon	= 0;
$GroupByCode  = '';
$GroupByLabel = '';

$MasterCode  = '';
$InvCounter  = 0;
$TotalInvoices  = 0;


if ($groupby == 2 || $groupby == 6)
{
  // echo 'Query - '. $query;//exit;
		$result=mysql_query($query,$connection) or die(mysql_error());
}

else 	
{	 
   //  echo 'Query1 - '.$query1;
		$result=mysql_query($query1,$connection) or die(mysql_error());
}

	//echo "<BR>".$query; 
	// echo "<BR>".$query1;exit;
$TotalInvoices = mysql_num_rows($result);
while($rows=mysql_fetch_row($result)){

		
	if ($groupby == 2 || $groupby == 6) {
		if ($CashRegisterTTC == 1 && $showcost == 0){
			if($curr == '' or $curr == $Base1) {
				$SaleDtAmount  		= $rows[4];
				$SaleDtDiscAmt 		= $rows[8];
				$SaleDtVatAmt  		= $rows[11];
				$SaleDtCost    		= $rows[21];
				$SaleDtTaxConsAmt 	= $rows[23];
				if ($CashRegisterTTC == '1')
					$SaleDtAfterTaxAmt  = $SaleDtAmount + $SaleDtTaxConsAmt; 
				else 
					$SaleDtAfterTaxAmt  = $SaleDtAmount + $SaleDtTaxConsAmt + $SaleDtVatAmt; 
			}	
			else {
				$SaleDtAmount  		= $rows[6];
				$SaleDtDiscAmt 		= $rows[10];
				$SaleDtVatAmt  		= $rows[12];
				$SaleDtCost    		= $rows[22];
				$SaleDtTaxConsAmt 	= $rows[24];
				if ($CashRegisterTTC == '1')
					$SaleDtAfterTaxAmt  = $SaleDtAmount + $SaleDtTaxConsAmt; 
				else 
					$SaleDtAfterTaxAmt  = $SaleDtAmount + $SaleDtTaxConsAmt + $SaleDtVatAmt;
			}	
		} else {
			if($curr == '' or $curr == $Base1) {
				$SaleDtAmount  		= $rows[3];
				$SaleDtDiscAmt 		= $rows[7];
				$SaleDtVatAmt  		= $rows[11];
				$SaleDtCost    		= $rows[21];
				$SaleDtTaxConsAmt 	= $rows[23];
				if ($CashRegisterTTC == '1')
					$SaleDtAfterTaxAmt  = $SaleDtAmount + $SaleDtTaxConsAmt; 
				else 
					$SaleDtAfterTaxAmt  = $SaleDtAmount + $SaleDtTaxConsAmt + $SaleDtVatAmt;
			}	
			else {
				$SaleDtAmount  		= $rows[5];
				$SaleDtDiscAmt 		= $rows[9];
				$SaleDtVatAmt  		= $rows[12];
				$SaleDtCost    		= $rows[22];
				$SaleDtTaxConsAmt 	= $rows[24];
				if ($CashRegisterTTC == '1')
					$SaleDtAfterTaxAmt  = $SaleDtAmount + $SaleDtTaxConsAmt; 
				else 
					$SaleDtAfterTaxAmt  = $SaleDtAmount + $SaleDtTaxConsAmt + $SaleDtVatAmt;
			}	
		}
			
		$SaleDtUnitCost  = $rows[17]; 
		$SaleDtTotalCost = $rows[18];
		$SaleDtProfitAmt = ($SaleDtAmount - $SaleDtTotalCost);
		$SaleDtProfitMar = 0;
		
		if($SaleDtAmount != 0) $SaleDtProfitMar = (($SaleDtProfitAmt / $SaleDtAmount) * 100);
		
			
		$MasterCode  = $rows[14];
		if ($MasterCode == '') $MasterCode = 'None';
			
		if ($groupby == 6 && ($GroupByCode != ''  && $GroupByCode != $MasterCode) && $showgroups != 1) 
		{
			$GroupByLabel = '';
			$GroupByLabel = 'Total by Vendor';
				
			echo "<tr height='5'><td colspan='8'><h5></td></tr>"; 
			echo "<tr class='totals'>"; 
			echo "  <td align='right' colspan='2'>$GroupByLabel</td>";
			echo "	<td align='right' valign='top' >". $SumQty ."</td>";
			echo "	<td align='right' valign='top' >&nbsp;</td>";
			echo "	<td align='right' valign='top' >&nbsp;</td>";
			echo "	<td align='right' valign='top' >". number_format($SumAmount, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >". number_format($SumVatAmt, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >". number_format($SumDiscAmt, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >&nbsp;</td>";
			echo "</tr>";
			
			//echo "<tr height='5'><td colspan='8'><h5></td></tr>"; 
			echo "<tr class='totals'>"; 
			echo "  <td align='right' colspan='2'>Commission (".$VendotComission."%)</td>";
			echo "	<td align='right' colspan='3' valign='top' >&nbsp;</td>";
			echo "	<td align='right' valign='top' >". number_format(($SumAmount*$VendotComission/100), $DecimalBase) ."</td>";
			echo "	<td align='right' colspan='3' valign='top' >&nbsp;</td>";
			echo "</tr>";
			
			echo "<tr ><td colspan='9'>&nbsp;</td></tr>"; 
				
			$SumQty     = 0;
			$SumAmount  = 0;
			$SumDiscAmt = 0;
			$SumVatAmt  = 0;
			
			$VendotComission = 0;
			
		}
			
		if ($groupby == 6 && ($GroupByCode == '' || $GroupByCode != $MasterCode) && $showgroups != 1) {
		  
			$GroupByLabel = '';
			$GroupByLabel = 'Group by Vendor';
				
				
			echo "<tr>"; 
			echo "<td colspan='9'><table class='group' width='100%' border='0' align='center' style='table-layout:fixed' >";
			echo "<tr>";
			echo "   <td width='10%'> $GroupByLabel</td>";
			echo "   <td width='7%' >". $rows[14] ."</td>";
			echo "   <td width='40%'>". $rows[15] ."</td>";
			echo "</tr>"; 
			echo "<tr height='5'><td colspan='3'>&nbsp;</td></tr></table></td></tr>";

			$GroupByCode = $MasterCode;
			$VendotComission = $rows[16];
		}
			
		if ($rows[2] != 0)
			$SaleDtUnitPrice = $SaleDtAmount / $rows[2];
			
		if ($groupby == 6 && $showgroups == 1) {
			echo "	<td align='left' valign='top' colspan='2'>". $rows[14] ." - " . $rows[15] ."</td>";
			echo "	<td align='right' valign='top' >". $rows[2] ."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleDtDiscAmt, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleDtAmount, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($rows[16], $DecimalBase)."</td>";
			echo "	<td align='right' valign='top' colspan='2'>".number_format(($rows[16]*$SaleDtAmount/100), $DecimalBase)."</td>";
		} else {
			echo "	<td align='left' valign='top' >". $rows[0] ."</td>";
			echo "	<td align='left' valign='top' >". $rows[1] ."</td>";
			echo "	<td align='right' valign='top' >". $rows[2] ."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleDtUnitPrice, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleDtCost, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleDtAmount, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleDtVatAmt, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleDtDiscAmt, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($rows[13], $DecimalBase)."</td>";
			if ($TaxConsumption == 1){	
				echo "	<td align='right' valign='top'>".number_format($SaleDtTaxConsAmt, $DecimalBase)."</td>";
				echo "	<td align='right' valign='top'>".number_format($SaleDtAfterTaxAmt, $DecimalBase)."</td>";
			}
			if ($showcost == 1 && $groupby == 2) {
				echo "	<td align='right' valign='top'>".number_format($SaleDtUnitCost, $DecimalBase)."</td>";
				echo "	<td align='right' valign='top'>".number_format($SaleDtTotalCost, $DecimalBase)."</td>";
				echo "	<td align='right' valign='top'>".number_format($SaleDtProfitAmt, $DecimalBase)."</td>";
				echo "	<td align='right' valign='top'>".number_format($SaleDtProfitMar, $DecimalBase)."</td>";
			}
		}
		
		echo "</tr>";
			
			
		$TotalQty     = $TotalQty     +  $rows[2];
		$TotalAmount  = $TotalAmount  +  $SaleDtAmount;
		$TotalDiscAmt = $TotalDiscAmt +  $SaleDtDiscAmt;
		$TotalVatAmt  = $TotalVatAmt  +  $SaleDtVatAmt;
		$TotalTaxConsAmt  = $TotalTaxConsAmt + $SaleDtTaxConsAmt; 
		$TotalAfterTaxAmt = $TotalAfterTaxAmt + $SaleDtAfterTaxAmt;
		$TotalCost    = $TotalCost    +  $SaleDtTotalCost;
		$TotalProfit  = $TotalProfit  +  $SaleDtProfitAmt;
		if($TotalAmount != 0) $TotalProfitMar = (($TotalProfit / $TotalAmount) * 100);
			
		$SumQty     = $SumQty     +  $rows[2];
		$SumAmount  = $SumAmount  +  $SaleDtAmount;
		$SumDiscAmt = $SumDiscAmt +  $SaleDtDiscAmt;
		$SumVatAmt  = $SumVatAmt  +  $SaleDtVatAmt;
			
	} else if (($groupby == 1 && $showgroups != 1) || ($groupby != 1 && 1 == 1)) {
		
		$MasterCode  = $rows[7];
		if ($MasterCode == '') $MasterCode = 'None';
			
		if (($groupby == 5 || $groupby == 3 || $groupby == 4) && ($GroupByCode != ''  && $GroupByCode != $MasterCode) && $showgroups != 1) 
		{
			$GroupByLabel = '';
			if ($groupby == 5)		$GroupByLabel = 'Total by Customer';
			else if ($groupby == 3)	$GroupByLabel = 'Total by User';
			else if ($groupby == 4)	$GroupByLabel = 'Total by CashRegister';
				
			echo "<tr height='5'><td colspan='$hr'><h5></td></tr>"; 
			echo "<tr class='totals'>"; 
			echo "  <td align='left' colspan='3'>Count Invoices: ".$InvCounter."</td>";
			echo "  <td align='right' colspan='2'>$GroupByLabel</td>";
			echo "	<td align='right' valign='top' >". number_format($SumTaxable, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >". number_format($SumNoneTaxable, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >". number_format($SumDiscAmt, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >&nbsp;</td>";
			echo "	<td align='right' valign='top' >". number_format($SumVatAmt, $DecimalBase) ."</td>";
			if ($TaxConsumption == 1){
				echo "	<td align='right' valign='top' >". number_format($sumBefTaxAmt, $DecimalBase) ."</td>";
				echo "	<td align='right' valign='top' >". number_format($SumTaxConsAmt, $DecimalBase) ."</td>";
			}
			echo "	<td align='right' valign='top' >". number_format($SumAmount, $DecimalBase) ."</td>";
			echo "</tr>";
				
			$SumTaxable 	= 0;
			$SumNoneTaxable = 0;
			$SumDiscAmt	    = 0;
			$SumVatAmt 	    = 0;
			$SumAmount 	    = 0;
			$SumTaxConsAmt  = 0;
			$sumBefTaxAmt	= 0;
			$InvCounter     = 0;
				
		}
			
		if (($groupby == 5 || $groupby == 3 || $groupby == 4) && ($GroupByCode == '' || $GroupByCode != $MasterCode)  && $showgroups != 1) {
			  
			$GroupByLabel = '';
			if ($groupby == 5)		$GroupByLabel = 'Group by Customer';
			else if ($groupby == 3)	$GroupByLabel = 'Group by User';
			else if ($groupby == 4)	$GroupByLabel = 'Group by CashRegister';
				
				
			echo "<tr>"; 
			echo "<td colspan='11'><table class='group' width='100%' border='0' align='center' style='table-layout:fixed' >";
			echo "<tr>";
			echo "   <td width='10%'> $GroupByLabel</td>";
			echo "   <td width='7%' >". $rows[7] ."</td>";
			echo "   <td width='40%'>". $rows[8] ."</td>";
			echo "</tr>"; 
			echo "<tr height='5'><td colspan='3'>&nbsp;</td></tr></table></td></tr>";

			$GroupByCode = $MasterCode;
			
		}
			
		if($curr == '' or $curr == $Base1){
			$SaleNetAmount   	= $rows[5];
			$SaleTaxable     	= $rows[11];
			$SaleNoneTaxable 	= $rows[13];
			$SaleDiscAmt 	 	= $rows[15];
			$SaleVatAmt		 	= $rows[17];
			$SaleTaxAmt		 	= $rows[31];
			$saleBeforeTaxAmnt 	= $SaleNetAmount - $SaleTaxAmt;
		}	
		else {
			$SaleNetAmount 	 = $rows[6];
			$SaleTaxable     = $rows[12];
			$SaleNoneTaxable = $rows[14];
			$SaleDiscAmt 	 = $rows[16];
			$SaleVatAmt		 = $rows[18];
			$SaleTaxAmt		 = $rows[32];
			$saleBeforeTaxAmnt 	= $SaleNetAmount - $SaleTaxAmt;
		}	
				
		echo "<tr>"; 
		
		if ($showgroups == 1) {
			echo "	<td align='left' valign='top' colspan='4'>". $rows[7] . " - " . $rows[8] ."</td>";
			echo "	<td align='center' valign='top' >". $curr ."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleDiscAmt, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleNetAmount, $DecimalBase)."</td>";
			echo "	<td align='center' valign='top' colspan='4'>&nbsp;</td>";
		} else {
			echo "	<td align='center' valign='top' >". $rows[29] ."</td>";
			echo "	<td align='left' valign='top' >". $rows[1] ."</td>";
			echo "	<td align='left' valign='top' >". $rows[2] ."</td>";
			echo "	<td align='left' valign='top' >". $rows[3] ."</td>";
			echo "	<td align='center' valign='top' >". $curr ."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleTaxable, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleNoneTaxable, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleDiscAmt, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($rows[19], $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleVatAmt, $DecimalBase)."</td>";
			if ($TaxConsumption == 1){
				echo "	<td align='right' valign='top'>".number_format($saleBeforeTaxAmnt, $DecimalBase)."</td>";
				echo "	<td align='right' valign='top'>".number_format($SaleTaxAmt, $DecimalBase)."</td>";
			}
			echo "	<td align='right' valign='top'>".number_format($SaleNetAmount, $DecimalBase)."</td>";
			echo "</tr>";
			
			if ($showdetail == 1) {
				$querydt = " Select RetailDt.Item_code, Items.Item_Description, RetailDt.Warehouse_Code, ".
						   " ifNull(SaleDt_Quantity,0) As SaleDtQuantity, ".
						   " Round(ifNull(SaleDt_Price,0), ".$DecimalBase.") As SaleDtPrice, ".
						   " Round(ifNull(SaleDt_PriceTTC,0), ".$DecimalBase.") As SaleDtPriceTTC, ".
						   " Round(ifNull(SaleDt_PriceBase2,0), ".$DecimalBase.") As SaleDtPriceBase2, ".
						   " Round(ifNull(SaleDt_PriceTTCBase2,0), ".$DecimalBase.") As SaleDtPriceTTCBase2, ".
						   " RetailDt.SaleDt_ID ".
						   " From RetailDt  ".
						   " Inner Join Items on RetailDt.Item_code = Items.Item_code ".
						   " Where RetailDt.Sale_Id = '".$rows[0]."' ".
						   " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ".
						   " And ifNull(RetailDt.Warehouse_Code,'-1') = ifNull(". $fromwarehouse .", ifNull(RetailDt.Warehouse_Code,'-1')) ".
						   " And ifNull(RetailDt.Vendor_Code,'-1') between ifNull(".$fromvendor.",ifNull(RetailDt.Vendor_Code,'-1')) and ifNull(". $tovendor.",ifNull(RetailDt.Vendor_Code,'-1')) ";
							   
				if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
					$querydt = $querydt." And RetailDt.Warehouse_Code In (select distinct warehouse_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";
			
				$querydt = $querydt." Order By RetailDt.Item_code ";
					
					
				echo "<tr><td colspan='11'>"; 
				echo "<table width='780' border='0' align='left' class='detail' style='table-layout:fixed'>
					  <col width=20>
					  <col width=120>
					  <col width=360>
					  <col width=80>
					  <col width=60>
					  <col width=100>";
					
				$resultdt=mysql_query($querydt,$connection) or die(mysql_error());
				while($rowsdt=mysql_fetch_row($resultdt)){
						
					if ($CashRegisterTTC == 1){
						if($curr == '' or $curr == $Base1) $SaleDtAmount = $rowsdt[5];
						else $SaleDtAmount = $rowsdt[7];
					} else {
						if($curr == '' or $curr == $Base1) $SaleDtAmount = $rowsdt[4];
						else $SaleDtAmount = $rowsdt[6];
					}
						
						
					echo "<tr>"; 
					echo "	<td align='left' valign='top' >&nbsp;</td>";
					echo "	<td align='left' valign='top' >". $rowsdt[0] ."</td>";
					echo "	<td align='left' valign='top' >". $rowsdt[1] ."</td>";
					echo "	<td align='center' valign='top' >". $rowsdt[2] ."</td>";
					echo "	<td align='right' valign='top' >". $rowsdt[3] ."</td>";
					echo "	<td align='right' valign='top'>".number_format($SaleDtAmount, $DecimalBase)."</td>";
					echo "</tr>";
						
					$TotalQty    = $TotalQty    +  $rowsdt[3];
						
						
					if ($RetailSerialNo == 1) {
						$querysr = " SELECT SerialNo_Code ".
								   " FROM Purchasesserialno ".
								   " WHERE Purchasesserialno.RetailDt_Id = '".$rowsdt[8]."' ".
								   " AND Purchasesserialno.Journal_Type = 'DI' ";
							
						$resultsr=mysql_query($querysr,$connection) or die(mysql_error());
						$numsr=mysql_num_rows($resultsr);
							
						if ($numsr != 0)
						{
							$SerialCode='';
								
							while($rowsr=mysql_fetch_array($resultsr)){
								$SerialCode = $SerialCode." , ".$rowsr[0];
							}
								
							$SerialCode = substr($SerialCode,2);
							echo "<tr>";
							echo "	<td align='left' valign='top' >&nbsp;</td>";
							echo"   <td colspan='5' valign=top class='sr'>Serial No :".$SerialCode."</td>";
							echo "</tr>";
						}
					}
						
				}
					
					

				echo "</table>";	
				echo "</td></tr>";
				
			}
		}
		
		$TotalTaxable	  = $TotalTaxable     +  $SaleTaxable;
		$TotalNoneTaxable = $TotalNoneTaxable +  $SaleNoneTaxable;
		$TotalDiscAmt	  = $TotalDiscAmt	  +  $SaleDiscAmt;
		$TotalVatAmt	  = $TotalVatAmt 	  +  $SaleVatAmt;
		$TotalTaxAmt	  = $TotalTaxAmt 	  +  $SaleTaxAmt;
		$TotalBefTaxAmt	  = $TotalBefTaxAmt	  +  $saleBeforeTaxAmnt;
		$TotalAmount 	  = $TotalAmount	  +  $SaleNetAmount;
		
		$SumTaxable	    = $SumTaxable     +  $SaleTaxable;
		$SumNoneTaxable = $SumNoneTaxable +  $SaleNoneTaxable;
		$SumDiscAmt	    = $SumDiscAmt	  +  $SaleDiscAmt;
		$SumVatAmt	    = $SumVatAmt 	  +  $SaleVatAmt;
		$SumAmount      = $SumAmount 	  +  $SaleNetAmount;
		$SumTaxConsAmt	= $SumTaxConsAmt + $SaleTaxAmt; 
		$sumBefTaxAmt 	= $sumBefTaxAmt + $saleBeforeTaxAmnt;			
		$InvCounter  += 1;
	}

}



// Report Totals
if ($groupby == 2 || $groupby == 6) {
	if ($groupby == 6 && $showgroups != 1) 
	{
		$GroupByLabel = '';
		$GroupByLabel = 'Total by Vendor';
			
		echo "<tr height='5'><td colspan='$hr'><h5></td></tr>"; 
		echo "<tr class='totals'>"; 
		echo "  <td align='right' colspan='2'>$GroupByLabel</td>";
		echo "	<td align='right' valign='top' >". $SumQty ."</td>";
		echo "	<td align='right' valign='top' >&nbsp;</td>";
		echo "	<td align='right' valign='top' >&nbsp;</td>";
		echo "	<td align='right' valign='top' >". number_format($SumAmount, $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >". number_format($SumVatAmt, $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >". number_format($SumDiscAmt, $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >&nbsp;</td>";
		echo "</tr>";
		
		echo "<tr class='totals'>"; 
		echo "  <td align='right' colspan='2'>Commission (".$VendotComission."%)</td>";
		echo "	<td align='right' colspan='3' valign='top' >&nbsp;</td>";
		echo "	<td align='right' valign='top' >". number_format(($SumAmount*$VendotComission/100), $DecimalBase) ."</td>";
		echo "	<td align='right' colspan='3' valign='top' >&nbsp;</td>";
		echo "</tr>";
			
	}
	
	if ($showcost == 1 && $groupby == 2) {
		echo"<tr height='5'><td colspan='$hr'><h4></td></tr>";
		echo "<tr height='10'><td colspan='$hr'>&nbsp;</td></tr>"; 
	}	
	else {
		echo "<tr height='5'><td colspan='$hr'><h4></td></tr>"; 
		echo "<tr height='10'><td colspan='$hr'>&nbsp;</td></tr>"; 
	}	
		
	echo "<tr class='totals'>"; 
	
	if ($groupby == 6 && $showgroups == 1) {
		echo "  <td align='right' colspan='2'>Total </td>";
		echo "	<td align='right' valign='top' >". $TotalQty ."</td>";
		echo "	<td align='right' valign='top' >". number_format($TotalDiscAmt, $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >". number_format($TotalAmount, $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' colspan='3'>&nbsp;</td>";
	} else {
		echo "  <td align='right' colspan='2'>Total </td>";
		echo "	<td align='right' valign='top' >". $TotalQty ."</td>";
		echo "	<td align='right' valign='top' >&nbsp;</td>";
		echo "	<td align='right' valign='top' >&nbsp;</td>";
		echo "	<td align='right' valign='top' >". number_format($TotalAmount, $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >". number_format($TotalVatAmt, $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >". number_format($TotalDiscAmt, $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >&nbsp;</td>";
		if ($TaxConsumption == 1){
			echo "	<td align='right' valign='top' >". number_format($TotalTaxConsAmt, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >". number_format($TotalAfterTaxAmt, $DecimalBase) ."</td>";
		}
		 
		if ($showcost == 1 && $groupby == 2) {
			echo "	<td align='right' valign='top' >&nbsp;</td>";
			echo "	<td align='right' valign='top'>".number_format($TotalCost, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($TotalProfit, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($TotalProfitMar, $DecimalBase)."</td>";
		}
	}
	
		
	echo "</tr>";
	
} else {
	
	if (($groupby == 5 || $groupby == 3 || $groupby == 4) && $showgroups != 1)
	{
		$GroupByLabel = '';
		if ($groupby == 5)		$GroupByLabel = 'Total by Customer';
		else if ($groupby == 3)	$GroupByLabel = 'Total by User';
		else if ($groupby == 4)	$GroupByLabel = 'Total by CashRegister';
				
		echo "<tr height='5'><td colspan='$hr'><h5></td></tr>"; 	
		echo "<tr class='totals'>"; 
		echo "  <td align='left' colspan='3'>Count Invoices: ".$InvCounter."</td>";
		echo "  <td align='right' colspan='2'>$GroupByLabel</td>";  
		echo "	<td align='right' valign='top' >". number_format($SumTaxable, $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >". number_format($SumNoneTaxable, $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >". number_format($SumDiscAmt, $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >&nbsp;</td>";
		echo "	<td align='right' valign='top' >". number_format($SumVatAmt, $DecimalBase) ."</td>";
		if ($TaxConsumption == 1){
			echo "	<td align='right' valign='top' >". number_format($sumBefTaxAmt, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >". number_format($SumTaxConsAmt, $DecimalBase) ."</td>";
		}
		echo "	<td align='right' valign='top' >". number_format($SumAmount, $DecimalBase) ."</td>";
		echo "</tr>";
			
	}

	if (($groupby == 1 && $showgroups != 1) || ($groupby != 1 && 1 == 1)) {
		echo "<tr height='5'><td colspan='$hr'><h4></td></tr>"; 
		echo "<tr height='10'><td colspan='$hr'>&nbsp;</td></tr>"; 
		echo "<tr class='totals'>"; 
		echo "  <td align='left' colspan='3'>Total Invoices: $TotalInvoices </td>";
		echo "  <td align='right' colspan='2'>Total </td>";
		
		if ($showgroups != 1) {
			echo "	<td align='right' valign='top' >". number_format($TotalTaxable, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >". number_format($TotalNoneTaxable, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >". number_format($TotalDiscAmt, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >&nbsp;</td>";
			echo "	<td align='right' valign='top' >". number_format($TotalVatAmt, $DecimalBase) ."</td>";
			if ($TaxConsumption == 1){ 
				echo "	<td align='right' valign='top' >". number_format($TotalBefTaxAmt, $DecimalBase) ."</td>";
				echo "	<td align='right' valign='top' >". number_format($TotalTaxAmt, $DecimalBase) ."</td>";
			}
			echo "	<td align='right' valign='top' >". number_format($TotalAmount, $DecimalBase) ."</td>";
		} else {
			echo "	<td align='right' valign='top' >". number_format($TotalDiscAmt, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >". number_format($TotalAmount, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' colspan='4'>&nbsp;</td>";
		}
		
		echo "</tr>";	
			
		if ($showdetail == 1) {
			echo "<tr class='totals'>"; 
			echo "  <td align='right' colspan='6'>Total Qty</td>";
			echo "	<td align='right' valign='top' >". $TotalQty ."</td>";
			echo "</tr>";
		}
	}
	
	if ($showsummary == 1) {
		$query2 = " Select Sale_Bank As SaleBank, Sale_BankBranch As SaleBankBranch, Sale_CheckNo As SaleCheckNo, ".
				  " Date_Format(Sale_CheckDate,'%d/%m/%Y') As SaleCheckDate, Sale_CashCur As SaleCashCur, ".
				  " Round(ifNull(Sale_Cash,0), ".$DecimalBase.") As  SaleCash, Sale_Information As SaleInformation ".
				  " From Retail ";
		
		$query3 = " Select Sale_CashCur As CheckCurr, Round(Sum(ifNull(Sale_Cash,0)), ".$DecimalBase.") As CheckAmount ".
				  " From Retail ";

		$query4 = " Select Sales_creditacc As CreditCard, Clients.Ledger_Name As CreditDesc, ".
				  " Sales_creditacccur As CreditCur, Round(Sum(ifNull(Sales_CreditAmount,0)), ".$DecimalBase.") As  CreditAmount ,Count(*) As SumofRetails".
				  " From Retail ".
				  " Left Join Clients on Clients.Ledger_Number = Retail.Sales_creditacc ";
				  
		$query5 = " Select Sales_creditacccur As CreditCur, Round(Sum(ifNull(Sales_CreditAmount,0)), ".$DecimalBase.") As  CreditAmount ".
				  " From Retail ";
				  
		$query6 = " Select Round(Sum(ifNull(Sales_CashInBase1,0)),5) As SalesCashInBase1, Round(Sum(ifNull(Sales_CashOutBase1,0)),5) As SalesCashOutBase1,  ".
				  " Round(Sum(ifNull(Sales_CashInBase2,0)),5) As SalesCashInBase2, Round(Sum(ifNull(Sales_CashOutBase2,0)),2) As SalesCashOutBase2, ".
				  " Sum(ifNull(Sale_CashBase1,0)) As SaleCheckBase1, Sum(ifNull(Sale_CashBase2,0)) As SaleCheckBase2, ".
				  " Sum(ifNull(Sales_CreditAmountBase1,0)) As SalesCreditAmountBase1, Sum(ifNull(Sales_CreditAmountBase2,0)) As SalesCreditAmountBase2, ".
				  " Sum(ifNull(Sales_TipsBase1,0)) As SalesTipsBase1, ".
				  " Sum(ifNull(Coupon_AmountBase1,0)) As CouponAmountBase1, Sum(ifNull(Coupon_AmountBase2,0)) As CouponAmountBase2 ".
				  " ,Sum(if(Sales_CashInBase1>0,1,0)) as NumofCash, Sum(if(Sale_CashBase1>0,1,0)) as NumofChecks, Sum(if(Sales_CreditAmountBase1>0,1,0)) as NumofCredits, Sum(if(Coupon_AmountBase1>0,1,0)) as NumofCoupon".
				  " From Retail ";
				  
		$query7 = " Select Retail.Coupon_Id, Coupon.Coupon_Reference As CouponReference, Coupon.Coupon_Name As CouponName, Round(Sum(ifNull(Retail.Coupon_Amount,0)), ".$DecimalBase.") As CouponAmount, ".
				  " Round(Sum(abs(ifNull(Retail.Coupon_Amount,0)) - ifNull(convertcurfunc(Coupon.Currency_Code, Retail.Currency_code, Coupon_Date, 0, 0, '', '', ifNull(Coupon.Coupon_AmountConsum,0)),0)), ".$DecimalBase.") As CouponAmountRem ".
				  " From Retail ".
				  " Left Join Coupon on Retail.Coupon_Id =  Coupon.Coupon_Id ";
		
	$query8 = " Select Round(Sum(ifNull(Sales_CashInBase1,0)),5) As SalesCashInBase1, Round(Sum(ifNull(Sales_CashOutBase1,0)),5) As SalesCashOutBase1,  ".
				  " Round(Sum(ifNull(Sales_CashInBase2,0)),5) As SalesCashInBase2, Round(Sum(ifNull(Sales_CashOutBase2,0)),2) As SalesCashOutBase2, ".
				  " Sum(ifNull(Sale_CashBase1,0)) As SaleCheckBase1, Sum(ifNull(Sale_CashBase2,0)) As SaleCheckBase2, ".
				  " Sum(ifNull(Sales_CreditAmountBase1,0)) As SalesCreditAmountBase1, Sum(ifNull(Sales_CreditAmountBase2,0)) As SalesCreditAmountBase2, ".
				  " Sum(ifNull(Sales_TipsBase1,0)) As SalesTipsBase1, ".
				  " Sum(ifNull(Coupon_AmountBase1,0)) As CouponAmountBase1, Sum(ifNull(Coupon_AmountBase2,0)) As CouponAmountBase2 ".
				  " ,Sum(if(Sales_CashInBase1>0,1,0)) as NumofCash, Sum(if(Sale_CashBase1>0,1,0)) as NumofChecks, Sum(if(Sales_CreditAmountBase1>0,1,0)) as NumofCredits, Sum(if(Coupon_AmountBase1>0,1,0)) as NumofCoupon".
				  " , IfNull(PaymentMethods.payment_description,'Customers') as payment_description ".
				  " From Retail ";
				  
		if ($projectexist > 0 && $FI_RepRestrictProject == 1) {
			$query2= $query2.$QueryRestrictPrj." on Retail.Project_Code like concat(Q4.project_code,'%') ";
			$query3= $query3.$QueryRestrictPrj." on Retail.Project_Code like concat(Q4.project_code,'%') ";
			$query4= $query4.$QueryRestrictPrj." on Retail.Project_Code like concat(Q4.project_code,'%') ";
			$query5= $query5.$QueryRestrictPrj." on Retail.Project_Code like concat(Q4.project_code,'%') ";
			$query6= $query6.$QueryRestrictPrj." on Retail.Project_Code like concat(Q4.project_code,'%') ";
			$query7= $query7.$QueryRestrictPrj." on Retail.Project_Code like concat(Q4.project_code,'%') ";
			$query8= $query8.$QueryRestrictPrj." on Retail.Project_Code like concat(Q4.project_code,'%') ";
		}	
									 
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1) {
			$query2= $query2.$QueryRestrictCst." on Retail.CostCenter_Code like concat(Q5.costcent_code,'%') ";
			$query3= $query3.$QueryRestrictCst." on Retail.CostCenter_Code like concat(Q5.costcent_code,'%') ";
			$query4= $query4.$QueryRestrictCst." on Retail.CostCenter_Code like concat(Q5.costcent_code,'%') ";
			$query5= $query5.$QueryRestrictCst." on Retail.CostCenter_Code like concat(Q5.costcent_code,'%') ";
			$query6= $query6.$QueryRestrictCst." on Retail.CostCenter_Code like concat(Q5.costcent_code,'%') ";
			$query7= $query7.$QueryRestrictCst." on Retail.CostCenter_Code like concat(Q5.costcent_code,'%') ";
			$query8= $query8.$QueryRestrictCst." on Retail.CostCenter_Code like concat(Q5.costcent_code,'%') ";
		}	
		
				  
		$querycond= " Where Retail.User_Account = ifNull(".$fromuser.", Retail.User_Account) ".
				    " And Retail.CashRegister_Name = ifNull(".$fromcashreg.", Retail.CashRegister_Name) ".
				    " And ifNull(Retail.Customer_Code,'-1') between ifNull(".$fromcustomer.",ifNull(Retail.Customer_Code,'-1')) and ifNull(". $tocustomer.",ifNull(Retail.Customer_Code,'-1')) ".
				    " And Date_format(Retail.Sale_Date,'%Y-%m-%d %H:%i:%s') between ifNull(". $fromdate.",date_format(Retail.Sale_Date,'%Y-%m-%d %H:%i:%s')) and ifNull(". $todate.",date_format(Retail.Sale_Date,'%Y-%m-%d %H:%i:%s'))  ".
				    " And ifNull(Retail.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Retail.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Retail.Project_Code,'-1')) ".
				    " And ifNull(Retail.CostCenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Retail.CostCenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Retail.CostCenter_Code,'-1')) ".
				    " And ifNull(Retail.Salesman_Code,'-1') = ifNull(".$fromsalesman.", ifNull(Retail.Salesman_Code,'-1')) ".
					" And ifNull(Retail.Sales_creditacc,'-1') between ifNull(".$fromcredit.",ifNull(Retail.Sales_creditacc,'-1')) and ifNull(". $tocredit.",ifNull(Retail.Sales_creditacc,'-1')) ";
					
		$query2= $query2.$querycond." And Sale_CheckNo != '' And ifNull(Sale_Cash,0) != 0 Order By Sale_CheckNo  ";
		$query3= $query3.$querycond." And Sale_CheckNo != '' And ifNull(Sale_Cash,0) != 0 Group By CheckCurr ";
		$query4= $query4.$querycond." And Sales_creditacc != '' And ifNull(Sales_CreditAmount,0) != 0  ";
	if($paymentmethod != '' && $paymentmethod == 'CUSTOMER')
		$query4= $query4." and Sales_creditacc not in (select Payment_Account from PaymentMethods) ";
	if($paymentmethod != '' && $paymentmethod != 'CUSTOMER' && $paymentmethod != 'CASH')	
		$query4= $query4." and Sales_creditacc = '$paymentmethod' ";
		$query4= $query4." Group By CreditCard, CreditCur Order By CreditCard ";
		$query5= $query5.$querycond." And Sales_creditacc != '' And ifNull(Sales_CreditAmount,0) != 0 ";
	if($paymentmethod != '' && $paymentmethod != 'CUSTOMER' && $paymentmethod != 'CASH')	
		$query5= $query5." and Sales_creditacc = '$paymentmethod' ";
	if($paymentmethod != '' && $paymentmethod == 'CUSTOMER' )	
		$query5= $query5." and Sales_creditacc not in (select Payment_Account from PaymentMethods)  ";
		$query5= $query5." Group By CreditCur ";
		$query7= $query7.$querycond." And Retail.Coupon_Id != '' And Retail.Coupon_Id Is Not Null And ifNull(Retail.Coupon_Amount,0) != 0 Group By CouponReference Having CouponAmount != 0 ";
		
				  
		$query8=$query8;
		$query8= $query8." Left Join PaymentMethods on Retail.Payment_Description = PaymentMethods.Payment_Description ";
		
		$query6= $query6.$querycond;
	if($paymentmethod != '' && $paymentmethod != 'CASH' && $paymentmethod != 'CUSTOMER')
		$query6= $query6." and Sales_creditacc = '$paymentmethod' ";
	if($paymentmethod != '' && $paymentmethod == 'CUSTOMER')
		$query6= $query6." and Sales_creditacc not in (select Payment_Account from PaymentMethods)  ";
	
		$query8= $query8.$querycond;
		if($paymentmethod != '' && $paymentmethod != 'CASH' && $paymentmethod != 'CUSTOMER')
			$query8= $query8." and Sales_creditacc = '$paymentmethod' and ifnull(PaymentMethods.Payment_Description,'') !='' ";
		if($paymentmethod != '' && $paymentmethod == 'CUSTOMER')
			$query8= $query8." and Sales_creditacc not in (select Payment_Account from PaymentMethods) ";
		$query8= $query8."group by ifNull(PaymentMethods.Payment_Description,'-1') ";
		
		//echo$query6;
		$result6=mysql_query($query6,$connection) or die(mysql_error());
		while($rows6=mysql_fetch_array($result6)){
				extract($rows6);
		}		
		
		$TotalCashInB1  = $SalesCashInBase1;
		$TotalCashInB2  = $SalesCashInBase2;
		$TotalCashOutB1 = $SalesCashOutBase1;
		$TotalCashOutB2 = $SalesCashOutBase2;
		$TotalChecksB1  = $SaleCheckBase1;
		$TotalChecksB2  = $SaleCheckBase2;
		$TotalCreditsB1 = $SalesCreditAmountBase1;
		$TotalCreditsB2 = $SalesCreditAmountBase2;
		$TotalCouponB1  = $CouponAmountBase1;
		$TotalCouponB2  = $CouponAmountBase2;
		$TotalTipsB1 	= $SalesTipsBase1;
		
		$SubTotalCashB1 = $TotalCashInB1 - $TotalCashOutB1;
		$SubTotalCashB2 = $TotalCashInB2 - $TotalCashOutB2;
		
		$CurrDate = Date('Y-m-d h:i:s');
		$SubTotalCashB11 = ConvertCurrency($Base2, $Base1, $CurrDate, $SubTotalCashB2, $connection);
		$SubTotalCashB22 = ConvertCurrency($Base1, $Base2, $CurrDate, $SubTotalCashB1, $connection);
		
		$TotalCashB1 = $SubTotalCashB1 + $SubTotalCashB11;
		$TotalCashB2 = $SubTotalCashB2 + $SubTotalCashB22;
		
		 
		
		
		$TotalTipsB2 = ConvertCurrency($Base1, $Base2, $CurrDate, $TotalTipsB1, $connection);
		
		$NetTotalB1 = 0;
		$NetTotalB2 = 0;
	
	if($paymentmethod == '' || $paymentmethod == 'CASH')	
		$NetTotalB1	 = $NetTotalB1 + $TotalCashB1;
	if($paymentmethod == '')
		$NetTotalB1	 = $NetTotalB1 + $TotalChecksB1;
	if($paymentmethod == '' || $paymentmethod != 'CASH')
		$NetTotalB1	 = $NetTotalB1 + $TotalCreditsB1;
	if($paymentmethod == '')
		$NetTotalB1	 = $NetTotalB1 + $TotalCouponB1;
	if($paymentmethod == '')
		//$NetTotalB1	 = $NetTotalB1 + $TotalTipsB1;
	$NetTotalB1	 = $NetTotalB1 ;
	
	if($paymentmethod == '' || $paymentmethod == 'CASH')	
		$NetTotalB2	 = $NetTotalB2 + $TotalCashB2;
	if($paymentmethod == '' )
		$NetTotalB2	 = $NetTotalB2 + $TotalChecksB2;
	if($paymentmethod == '' || $paymentmethod != 'CASH')
		$NetTotalB2	 = $NetTotalB2 + $TotalCreditsB2;
	if($paymentmethod == '')
		$NetTotalB2	 = $NetTotalB2 + $TotalCouponB2;
	if($paymentmethod == '')
		$NetTotalB2	 = $NetTotalB2 + $TotalTipsB2;
		
	
	
		echo "<tr><td colspan='11' style='padding-top:50px;'>"; 
		echo "<table width='980' border='0' align='left' class='summary' style='table-layout:fixed'>
			  <col width=120>
			  <col width=150>
			  <col width=150>
			  <col width=150>
			  <col width=560>";
		if($paymentmethod == '' || $paymentmethod == 'CASH') {		  
		echo"	<tr><th align='left' style='border-bottom: 1px solid black;'>Cash</th><th align='center'>$Base1</th><th align='center'>$Base2</th><th align='center'>&nbsp;</th></tr>";
		//echo"	<tr><th align='left'>Cash In</th><td align='right'>". number_format($TotalCashInB1, $DecimalBase) ."</td><td align='right'>". number_format($TotalCashInB2, $DecimalBase) ."</td><td align='center'>&nbsp;</td></tr>";
		//echo"	<tr><th align='left'>Cash Out</th><td align='right'>". number_format($TotalCashOutB1, $DecimalBase) ."</td><td align='right'>". number_format($TotalCashOutB2, $DecimalBase) ."</td><td align='center'>&nbsp;</td></tr>";
	
		echo"	<tr><th align='left'>Total Cash</th><td align='right'>". number_format($SubTotalCashB1, $DecimalBase) ."</td><td align='right'>". number_format($SubTotalCashB2, $DecimalBase) ."</td><td align='center'>&nbsp;</td></tr>";
		echo "	<tr height='5'><td colspan='3'><h4></td><td align='center'>&nbsp;</td></tr>"; 
		}
		//Display Checks List
		$result2=mysql_query($query2,$connection) or die(mysql_error());
		$recordexists2 = mysql_num_rows($result2);
		
		if ($recordexists2 > 0 && $paymentmethod == '') {
			echo"<tr><td align='left' colspan='4' style='padding-top:10px;'>&nbsp;</td></tr>";
			echo"<tr><th align='left' valign='top'>Checks List</th>";
			echo"	<td colspan='3'>
					<table width='980' border='0' align='left' style='table-layout:fixed'>
						<col width=150>
						<col width=150>
						<col width=80>
						<col width=80>
						<col width=60>
						<col width=100>
						<col width=300>";
			echo"<tr>
					<th align='left'>Bank</th>
					<th align='left'>Location</th>
					<th align='left'>Check No</th>
					<th align='center'>Check Date</th>
					<th align='center'>Currency</th>
					<th align='center'>Amount</td>
					<th align='center'>Customer Name</th>
				</tr>";			
		
		
			while($rows2=mysql_fetch_array($result2)){
				extract($rows2);
				
				echo"<tr>
						<td align='left'>$SaleBank</td>
						<td align='left'>$SaleBankBranch</td>
						<td align='left'>$SaleCheckNo</td>
						<td align='center'>$SaleCheckDate</td>
						<td align='center'>$SaleCashCur</td>
						<td align='right'>". number_format($SaleCash, $DecimalBase) ."</td>
						<td align='center'>$Sale_Information</td>
					</tr>";
				
			}

			echo"	</table>";	
			echo"</td></tr>";
		}
		
		$result3=mysql_query($query3,$connection) or die(mysql_error());
		$recordexists3 = mysql_num_rows($result3);
		
		if ($recordexists3 > 0 && $paymentmethod == '') {
			echo"	<tr><td align='left' colspan='4' style='padding-top:15px;'>&nbsp;</td></tr>";
			echo"	<tr><th align='left' style='border-bottom: 1px solid black;'>Total Checks</th><th align='center'>Currency</th><th align='center'>Amount</th><th align='center'>&nbsp;</th></tr>";
			
			while($rows3=mysql_fetch_array($result3)){
				extract($rows3);
				
				echo"<tr><th align='left'>&nbsp;</th><td align='center'>$CheckCurr</td><td align='right'>". number_format($CheckAmount, $DecimalBase) ."</td><td align='center'>&nbsp;</td></tr>";
			}
			echo "	<tr height='5'><td colspan='3'><h4></td><td align='center'>&nbsp;</td></tr>"; 			
		}
		
		//echo $query4;
		//Display Credits List
		$result4=mysql_query($query4,$connection) or die(mysql_error());
		$recordexists4 = mysql_num_rows($result4);
		
		if ($recordexists4 > 0 && strtoupper($paymentmethod) != 'CASH') {
			
			echo"<tr><td align='left' colspan='4' style='padding-top:10px;'>&nbsp;</td></tr>";
			echo"<tr><th align='left' valign='top'>Credits List</th>";
			echo"	<td colspan='3'>
					<table width='730' border='0' align='left' style='table-layout:fixed'>
						<col width=150>
						<col width=300>
						<col width=80>
						<col width=120>
						<col width=80>
						";
			echo"<tr>
					<th align='left'>Credit</th>
					<th align='left'>Description</th>
					<th align='center'>Currency</th>
					<th align='center'>Amount</td>
					<th align='center'>Quantity</td>
				</tr>";			
		
		
			while($rows4=mysql_fetch_array($result4)){
				extract($rows4);
				
				echo"<tr>
						<td align='left'>$CreditCard</td>
						<td align='left'>$CreditDesc</td>
						<td align='center'>$CreditCur</td>
						<td align='right'>". number_format($CreditAmount, $DecimalBase) ."</td>
						<td align='right'>".$SumofRetails."</td>
					</tr>";
				
			}

			echo"	</table>";	
			echo"</td></tr>";
		}
		
		$result5=mysql_query($query5,$connection) or die(mysql_error());
		$recordexists5 = mysql_num_rows($result5);
		
		if ($recordexists5 > 0 && strtoupper($paymentmethod) != 'CASH') {
			echo"	<tr><td align='left' colspan='4' style='padding-top:15px;'>&nbsp;</td></tr>";
			echo"	<tr><th align='left' style='border-bottom: 1px solid black;'>Total Credits</th><th align='center'>Currency</th><th align='center'>Amount</th><th align='center'>&nbsp;</th></tr>";
			
			while($rows5=mysql_fetch_array($result5)){
				extract($rows5);
				
				echo"<tr><th align='left'>&nbsp;</th><td align='center'>$CreditCur</td><td align='right'>". number_format($CreditAmount, $DecimalBase) ."</td><td align='center'>&nbsp;</td></tr>";
			}
			echo "	<tr height='5'><td colspan='3'><h4></td><td align='center'>&nbsp;</td></tr>"; 			
		}
		
		//Display Coupon List
		$result7=mysql_query($query7,$connection) or die(mysql_error());
		$recordexists7 = mysql_num_rows($result7);
		
		if ($recordexists7 > 0 && $paymentmethod == '') {
			echo"<tr><td align='left' colspan='4' style='padding-top:10px;'>&nbsp;</td></tr>";
			echo"<tr><th align='left' valign='top'>Coupon List</th>";
			echo"	<td colspan='3'>
					<table width='650' border='0' align='left' style='table-layout:fixed'>
						<col width=120>
						<col width=290>
						<col width=120>
						<col width=120>";
			echo"<tr>
					<th align='left'>Reference</th>
					<th align='left'>Description</th>
					<th align='center'>Amount</th>
					<th align='center'>Remain Amount</td>
				</tr>";			
		
		
			while($rows7=mysql_fetch_array($result7)){
				extract($rows7);
				
				echo"<tr>
						<td align='left'>$CouponReference</td>
						<td align='left'>$CouponName</td>
						<td align='right'>". number_format($CouponAmount, $DecimalBase) ."</td>
						<td align='right'>". number_format($CouponAmountRem, $DecimalBase) ."</td>
					</tr>";
				
			}

			echo"	</table>";	
			echo"</td></tr>";
		}
		$TotalQty = 0;
		if($paymentmethod == '' || strtoupper($paymentmethod) == 'CASH')  $TotalQty = $TotalQty + $NumofCash;
		if($paymentmethod == '' ) 							  $TotalQty = $TotalQty + $NumofChecks;
		if($paymentmethod == '' || strtoupper($paymentmethod) != 'CASH')  $TotalQty = $TotalQty + $NumofCredits;
		if($paymentmethod == '' ) 							  $TotalQty = $TotalQty + $NumofCoupon;
		if($paymentmethod == '' ) 							  $TotalQty = $TotalQty + $SumofTips;
		echo"	<tr><td align='left' colspan='4' style='padding-top:15px;'>&nbsp;</td></tr>";
		echo"	<tr><th align='left' style='border-bottom: 1px solid black;'>Summary C/V</th><th align='center'>$Base1</th><th align='center'>$Base2</th><th align='left' style='border-bottom: 1px solid black;'>Quantity</th><th></th></tr>";
	
	if($paymentmethod == '' || strtoupper($paymentmethod) == 'CASH')
			echo"	<tr><th align='left'>Cash</th><td align='right'>". number_format($TotalCashB1, $DecimalBase) ."</td><td align='right'>". number_format($TotalCashB2, $DecimalBase) ."</td><td align='center'>$NumofCash</td><td align='center'>&nbsp;</td></tr>";
		
	if($paymentmethod == ''  )
		echo"	<tr><th align='left'>Checks111</th><td align='right'>". number_format($TotalChecksB1, $DecimalBase) ."</td><td align='right'>". number_format($TotalChecksB2, $DecimalBase) ."</td><td align='center'>$NumofChecks</td><td align='center'>&nbsp;</td></tr>";
		
	if($paymentmethod == '' || strtoupper($paymentmethod) != 'CASH') {
		
		$result8=mysql_query($query8,$connection) or die(mysql_error());
		while($rows8=mysql_fetch_array($result8)){
				extract($rows8);
				$TotalCreditsB1 = $SalesCreditAmountBase1;
				$TotalCreditsB2 = $SalesCreditAmountBase2;
				
				echo"	<tr><th align='left'>$payment_description</th><td align='right'>". number_format($TotalCreditsB1, $DecimalBase) ."</td><td align='right'>". number_format($TotalCreditsB2, $DecimalBase) ."</td><td align='center'>$NumofCredits</td><td align='center'>&nbsp;</td></tr>";
		}	
	}
		//echo"	<tr><th align='left'>Credits</th><td align='right'>". number_format($TotalCreditsB1, $DecimalBase) ."</td><td align='right'>". number_format($TotalCreditsB2, $DecimalBase) ."</td><td align='center'>$NumofCredits</td><td align='center'>&nbsp;</td></tr>";
	if($paymentmethod == ''  )
		echo"	<tr><th align='left'>Coupon</th><td align='right'>". number_format($TotalCouponB1, $DecimalBase) ."</td><td align='right'>". number_format($TotalCouponB2, $DecimalBase) ."</td><td align='center'>$NumofCoupon</td><td align='center'>&nbsp;</td></tr>";
	if($paymentmethod == ''  )	
		echo"	<tr><th align='left'>Tips</th><td align='right'>". number_format($TotalTipsB1, $DecimalBase) ."</td><td align='right'>". number_format($TotalTipsB2, $DecimalBase) ."</td><td align='center'>$SumofTips</td><td align='center'>&nbsp;</td></tr>";
		echo"	<tr><th align='left'>Net Total</th><td align='right'>". number_format($NetTotalB1, $DecimalBase) ."</td><td align='right'>". number_format($NetTotalB2, $DecimalBase) ."</td><td align='center'>$TotalQty</td><td align='center'>&nbsp;</td></tr>";
		echo "	<tr height='5'><td colspan='4'><h4></td><td align='center'>&nbsp;</td></tr>";
		echo"</table>";
		echo"</td></tr>";
		
	}
}

echo "</table></td></tr>";
echo "</table>";
echo "</td></tr></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;
}

function ConvertCurrency($FromCurr, $ToCurr, $FromDate, $Amount, $connection)
{
	$query = "SELECT ifNull(convertcurfunc('".$FromCurr."', '".$ToCurr."', '".$FromDate."', 0, 0, '', '', ifNull($Amount,0)),0) From Dual ";
	$result=mysql_query($query,$connection);
	$row=mysql_fetch_row($result);
	//echo $query;
	Return	$row[0];

}
function explodewordtime($date)
{

$trimtime = explode(' ',$date);
$date = $trimtime[0];
$time = $trimtime[1];

$trim = explode('/',$date);
$trim = "$trim[2]"."-"."$trim[1]"."-"."$trim[0]";
return $trim." ".$time;
}
if ($printaccess==1 && $_GET['print'] == 1)
print <<< HERE

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

?>