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

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


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: 14px; 
                  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;
        }					  
				 
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);

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

$RepTitle = 'Daily Sales';
if ($showpending == 1) $RepTitle = 'Pending Daily Sales';



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




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='800' 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>$RepTitle</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;
$dispcashregister     = $fromcashreg;

$dispfromitem = $fromitem;
$disptoitem = $toitem;

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


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($fromdriver))  $fromdriver = 'null';
else  $fromdriver = "'".$fromdriver."'";   


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 = '';
if (empty($subgroupitem))  $subgroupitem = 0;
//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($fromcredit))  $fromcredit = 'null';
else  $fromcredit = "'".$fromcredit."'";    
if (empty($tocredit))  $tocredit = 'null';
else  $tocredit = "'".$tocredit."'";  
   
if (empty($showunpost))  $showunpost = 0;
if (empty($showpending)) $showpending = 0;
if (empty($custperitem)) $custperitem = 0;


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

<tr><td>
<table class='params' width='800' 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="18%">$dispfromuser</td>
  <td width="10%" valign='top'><b>CashRegister:</b></td>
  <td width="13%">$dispcashregister</td>
</tr>
<tr>
  <td width="12%" valign='top'><b>Group From/To</b></td>
  <td width="18%">$dispfromgroup - $disptogroup </td>
  <td width="8%" colspan=3 valign='top'><b>SubGroup From/To</b></td>
  <td width="36%">$dispfromsubgroup - $disptosubgroup </td>
  <td width="10%" valign='top'><b>TIN:</b></td>
  <td width="13%">21204511-0001</td>
</tr>  
<tr>
  <td width="10%" valign='top'><b>Item From/To</b></td>
  <td width="60%" colspan=4>$dispfromitem - $disptoitem </td>
</tr>
<tr height='5'><td colspan=8><h4></td></tr>
</table>
</td></tr>

<tr><td>
HERE;

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

if ($custperitem == 0) {
	if ($groupby == 2 || $groupby == 6) {
		echo "<table width='800' border='0' align='left' class='master' style='table-layout:fixed'>
			  <col width=120>
			  <col width=280>
			  <col width=80>
			  <col width=120>
			  <col width=120>
			  <tr>
				<th >Item Code </th>
				<th >Description</th>
				<th >Qty</th>
				<th >Selling Price </th>
				<th >Cost Price </th>
			  </tr>
			  <tr height='5'><td colspan=5><h4></td></tr>";
	} 
	else if ($groupby == 8) {
		echo "<table width='450' border='0' align='left' class='master' style='table-layout:fixed'>
			  <col width=120>
			  <col width=150>
			  <col width=150>
			  <tr>
				<th >Date</th>
				<th >Total $Base1</th>
				<th >Total $Base2</th>
			  </tr>
			  <tr height='5'><td colspan=3><h4></td></tr>";
	}
	else {
		echo "<table width='800' border='0' align='left' class=$masterclass style='table-layout:fixed'>
			  <col width=20>
			  <col width=70>
			  <col width=120>
			  <col width=200>
			  <col width=60>
			  <col width=80>
			  <col width=60>
			  <col width=110>
			  <tr>
				<th >&nbsp;</th>
				<th >Reference</th>
				<th >Date</th>
				<th >Remark</th>
				<th >User</th>
				<th >CashRegister</th>
				<th >Currency</th>
				<th >Amount </th>
			  </tr>";
			  
		if ($showdetail == 1) {
			echo"<tr height='5'><td colspan=8><h5></td></tr>";
			echo"<tr height='20'><td colspan='8'>";
			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=8><h4></td></tr>";

	}		 
} else {
	echo "<table width='800' border='0' align='left' class='master1' style='table-layout:fixed'>
		  <col width=120>
		  <col width=680>
		  <tr>
			<th align='left'>Item Code</th>
			<th align='left'>Description</th>
		  </tr>";
		  
	echo "<tr height='20'><td colspan='2'>
			<table width='800' border='0' align='left' class='detail' style='table-layout:fixed'>
			<col width=20>
			<col width=70>
			<col width=120>
			<col width=250>
			<col width=340>
			<tr>
				<th >&nbsp;</th>
				<th align='center'>Reference</th>
				<th align='center'>Date</th>
				<th align='left'>Customer</th>
				<th align='left'>Remark</th>
			</tr>";
	echo"	</table>";
	echo"</td></tr>";
	echo"<tr height='5'><td colspan=2><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 RetailDt.Item_code, Items.Item_Description, Sum(ifNull(SaleDt_Quantity,0)) As SaleDtQuantity, ";


if($showdiscount == 1 )
	$query = $query . " 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, ";
else $query = $query . " Round(Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))), ".$DecimalBase.") As SaleDtTotal, ".
		 " Round(Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0))), ".$DecimalBase.") As SaleDtTotalTTC, ".
		 " Round(Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceBase2,0))), ".$DecimalBase.") As SaleDtTotalBase2, ".
		 " Round(Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTCBase2,0))), ".$DecimalBase.") As SaleDtTotalTTCBase2, ";
		 
		 
$query = $query . "  if($groupby=6, ifNull(RetailDt.Vendor_Code,''), '') As MasterCode, if($groupby=6, ifNull(Vendor.Ledger_Name,''), '') As MasterDescription, ".
		 " ifNull(convertcurfunc(Items.Currency_Code, '".$Base1."', Retail.Sale_Date, 0, 0, '', '', ifNull(Items.Item_LastCostPrice,0)),0) as  LastCostPriceB1, ".
		 " ifNull(convertcurfunc(Items.Currency_Code, '".$Base2."', Retail.Sale_Date, 0, 0, '', '', ifNull(Items.Item_LastCostPrice,0)),0) as  LastCostPriceB2
		 ,if(RetailDt.SaleDt_ItemStatus=2,'Gift',if(RetailDt.SaleDt_ItemStatus=3,'Void','Waste')),Items.SubGroup_Code
		 ";
		 
if ($showpending != 1) {
	$query .= " From RetailDt  ".
			  " Inner Join Retail on RetailDt.Sale_Id = Retail.Sale_Id ";
} else {
	$query .= " From Temp_RetailDt As RetailDt  ".
			  " Inner Join Temp_Retail As Retail on RetailDt.Sale_Id = Retail.Sale_Id ";
}
			  
$query = $query." left 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,'%') ";
					

$query= $query.					
	     " Where Retail.User_Account = ifNull(".$fromuser.", Retail.User_Account) ";

$querystatus = 	$query;

//$query= $query.	 " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
$querystatus= $querystatus.	 " And IfNull(SaleDt_ItemStatus,0) In (1,2,3) ";

$query= $query.	 " 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(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(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)) " .
		"  And Items.Item_Code Between ifNull(".$fromitem.", Items.Item_Code) and ifNull(". $toitem.", Items.Item_Code) ";
		
$querystatus = $querystatus.	 " 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(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(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)) " .
		"  And Items.Item_Code Between ifNull(".$fromitem.", Items.Item_Code) and ifNull(". $toitem.", Items.Item_Code) ";

		
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']."')  ";
	$querystatus = $querystatus." And RetailDt.Warehouse_Code In (select distinct warehouse_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";
	
	}
	
if($subgroupitem == 1 && $groupby == 2)		 
	   $query= $query." Group By RetailDt.Item_code Order By Items.SubGroup_Code, RetailDt.Item_code ";
else   $query= $query." Group By MasterCode, RetailDt.Item_code Order By MasterCode, RetailDt.Item_code ";

$querystatus= $querystatus.
		 " Group By MasterCode, RetailDt.Item_code ".
	     " Order By RetailDt.SaleDt_ItemStatus, MasterCode, RetailDt.Item_code ";

///////////////////////////////////////////////////////////

$query1 = " Select Sale_ID, Sale_Reference, Sale_Date As SaleDate, Sale_Remark, ".
		  " Retail.Currency_code As CurrCode, Round(ifNull(Sale_NetTotal,0), ".$DecimalBase.") As  SaleNetTotal, ".
		  " Round(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,''), if($groupby=7, concat(ifNull(Retail.User_Account,''),'-',ifNull(Retail.CashRegister_Name,'')), if($groupby=10, ifNull(Retail.Driver_Code,''), if($groupby=11, ifNull(Retail.Sale_Type,''), '')))))) As MasterCode, ".
		  " if($groupby=3, ifNull(Users.User_Name,''), if($groupby=4, ifNull(Retail.CashRegister_Name,''), if($groupby=5, ifNull(Customer.Customer_Name,''), if($groupby=7, concat(ifNull(Retail.User_Account,''),'-',ifNull(Retail.CashRegister_Name,'')), if($groupby=10, ifNull(Driver.Ledger_Name,''), ''))))) As MasterDescription, ".
		  " Retail.User_Account, Retail.CashRegister_Name, if(ifNull(Sale_Posted,0)=1, 'P', 'U') As SalePosted, Customer_Address, ".
		  " if(Customer_Telephone1!='' and Customer_Telephone2!='', concat(Customer_Telephone1, '-', Customer_Telephone2), if(Customer_Telephone1!='', Customer_Telephone1, Customer_Telephone2)) as CustomerTelephone  ";
		  
if ($showpending != 1) {
	$query1 .= " From Retail  ";
} else {
	$query1 .= " From Temp_Retail As Retail  ";
}

$query1 = $query1." Left Join Customer on Retail.Customer_Code = Customer.Customer_Code ".
				  " Left Join Clients As Driver on Retail.Driver_Code = Driver.Ledger_Number And Upper(Client_Type) = 'DRIVER'  ".
				  " 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.Driver_Code,'-1') = ifNull(".$fromdriver.", ifNull(Retail.Driver_Code,'-1')) ".
		  " 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')) ";
		  
if ($showunpost == 1)
	$query1= $query1." And ifNull(Retail.Sale_Posted, 0) = 0 ";
	

if ($showpending != 1 and $showreturn == 1) {
	$query1 .= " And Exists (Select 1 from RetailDt as RetailDt1 where SaleDt_Quantity < 0 and RetailDt1.Sale_Id=Retail.Sale_Id) ";
} else if($showreturn == 1){
	$query1 .= " And Exists (Select 1 from Temp_RetailDt as RetailDt1 where SaleDt_Quantity < 0 and RetailDt1.Sale_Id=Retail.Sale_Id) ";
}


	
$query1= $query1." Order By MasterCode, Sale_Date, Sale_Reference  ";

		 
/////////////////////////////////////////////////////////////////////////

$query2 = " Select date_format(Retail.Sale_Date, '%d/%m/%Y') As SaleDate, ".
		  " Round(Sum(ifNull(Sale_NetTotalBase1,0)), ".$DecimalBase1.") As  SaleNetTotalBase1, ".
		  " Round(Sum(ifNull(Sale_NetTotalBase2,0)), ".$DecimalBase2.") As SaleNetTotalBase2 ";
		  
if ($showpending != 1) {
	$query2 .= " From Retail  ";
} else {
	$query2 .= " From Temp_Retail As Retail  ";
}
 
$query2 = $query2." Left Join Customer on Retail.Customer_Code = Customer.Customer_Code ";
		  
		if ($projectexist > 0 && $FI_RepRestrictProject == 1)
			$query2= $query2.$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,'%') ";

$query2= $query2.			
          " 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')) ";
		  
if ($showunpost == 1)
	$query2= $query2." And ifNull(Retail.Sale_Posted, 0) = 0 ";
	
$query2= $query2." Group By SaleDate  ".
				 " Order By SaleDate  ";

///////////////////////////////////////////////////////////////////////////


$query3 = " Select RetailDt.Item_Code, Items.Item_Description, Retail.Sale_ID, Retail.Sale_Reference, ".
	      " Retail.Sale_Date As SaleDate, Customer.Customer_Name, Retail.Sale_Information  ";
		  
if ($showpending != 1) {
	$query3 .= " From RetailDt  ".
			   " Inner Join Retail on RetailDt.Sale_Id = Retail.Sale_Id ";
} else {
	$query3 .= " From Temp_RetailDt As RetailDt  ".
			   " Inner Join Temp_Retail As Retail on RetailDt.Sale_Id = Retail.Sale_Id ";
}

$query3 = $query3." Inner Join Items on RetailDt.Item_code = Items.Item_code ".
				  " Left Join Customer on Retail.Customer_Code = Customer.Customer_Code ";
		 
		if ($projectexist > 0 && $FI_RepRestrictProject == 1)
			$query3 = $query3.$QueryRestrictPrj." on Retail.Project_Code like concat(Q4.project_code,'%') ";
							 
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
			$query3 = $query3.$QueryRestrictCst." on Retail.CostCenter_Code like concat(Q5.costcent_code,'%') ";
					

$query3 = $query3.					
	     " 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 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')) ".
		 " Order By RetailDt.Item_Code, Retail.Sale_Reference ";


///////////////////////////////////////////////////////////

$query4 = " Select Retail.Sale_ID, Retail.Sale_Reference, Retail.Sale_Date As SaleDate, Retail.Sale_Remark, Retail.Currency_code As CurrCode, ";

if ($CashRegisterTTC == 1) {
	$query4 .= " Round(Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0)*(1 - ifNull(SaleDt_DiscountPer,0)/100)) - ifNull(SaleDt_DiscountAmount,0)), ".$DecimalBase.") As  SaleNetTotal, ".
			   " Round(Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTCBase2,0)*(1 - ifNull(SaleDt_DiscountPer,0)/100)) - ifNull(SaleDt_DiscountBase2,0)), ".$DecimalBase2.") As  SaleNetTotalBase2, ";
} else {
	$query4 .= " Round(Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*(1 - ifNull(SaleDt_DiscountPer,0)/100)) - ifNull(SaleDt_DiscountAmount,0)), ".$DecimalBase.") As  SaleNetTotal, ".
			   " Round(Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceBase2,0)*(1 - ifNull(SaleDt_DiscountPer,0)/100)) - ifNull(SaleDt_DiscountBase2,0)), ".$DecimalBase2.") As  SaleNetTotalBase2, ";
}
		  
$query4 .= " ifNull(Items.SubGroup_Code,'') As MasterCode, ifNull(Items.SubGroup_Code,'') As MasterDescription, ".
		   " Retail.User_Account, Retail.CashRegister_Name, if(ifNull(Sale_Posted,0)=1, 'P', 'U') As SalePosted, ifNull(Items.SubGroup_Code,'') as ItemSubGroup, ".
		   " if(ifNull(Customer.Customer_Code,'')='', Retail.Sale_information, Customer.Customer_Name) as CustomerName ";
		  
if ($showpending != 1) {
	$query4 .= " From RetailDt  ".
			   " Inner Join Retail on RetailDt.Sale_Id = Retail.Sale_Id ";
} else {
	$query4 .= " From Temp_RetailDt As RetailDt  ".
			   " Inner Join Temp_Retail As Retail on RetailDt.Sale_Id = Retail.Sale_Id ";
}

$query4 = $query4." Inner Join Items on Items.Item_Code = RetailDt.Item_Code ".
				  " Left Join SubGroup on SubGroup.SubGroup_Code = Items.SubGroup_Code ".
				  " Left Join Customer on Retail.Customer_Code = Customer.Customer_Code ".
				  " Left Join ".$_SESSION['dbLabel'].".Users on Retail.User_Account = Users.User_Account ";
		  
		if ($projectexist > 0 && $FI_RepRestrictProject == 1)
			$query4= $query4.$QueryRestrictPrj." on Retail.Project_Code like concat(Q4.project_code,'%') ";
							 
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
			$query4= $query4.$QueryRestrictCst." on Retail.CostCenter_Code like concat(Q5.costcent_code,'%') ";

$query4= $query4.			
          " 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')) ";
		  
if ($showunpost == 1)
	$query4= $query4." And ifNull(Retail.Sale_Posted, 0) = 0 ";
	
$query4= $query4." Group By MasterCode, Retail.Sale_Date, Retail.Sale_Reference  ";
$query4= $query4." Order By MasterCode, CustomerName, Retail.Sale_Date, Retail.Sale_Reference  ";		 
///////////////////////////////////////////////////////////////////////////


//echo $query;
//exit;

$TotalQty	  = 0;
$TotalAmount  = 0;
$SaleDtAmount = 0;
$SaleAmount   = 0;
$SaleDtCost   = 0;

$TotalAmountB1 = 0;
$TotalAmountB2 = 0;

$SumQty	    = 0;
$SumAmount  = 0;

$GroupByCode  = '';
$GroupByLabel = '';

$MasterCode  = '';

$InvCounter  = 0;
$TotalInvoices  = 0;

if ($custperitem == 0) {
	if ($groupby == 2 || $groupby == 6)
		$result=mysql_query($query,$connection) or die(mysql_error());
	else if ($groupby == 8)
		$result=mysql_query($query2,$connection) or die(mysql_error());	
	else if ($groupby == 9)
		$result=mysql_query($query4,$connection) or die(mysql_error());	
	else 	
		$result=mysql_query($query1,$connection) or die(mysql_error());
} else {
	$result=mysql_query($query3,$connection) or die(mysql_error());
}
	
$TotalInvoices = mysql_num_rows($result);	
$tempsubgroup = '**';
while($rows=mysql_fetch_row($result)){

	if ($custperitem == 0) {
		if ($groupby == 2 || $groupby == 6) {
			if ($CashRegisterTTC == 1){
				if($curr == '' or $curr == $Base1) {
					$SaleDtAmount = $rows[4];
					$SaleDtCost = $rows[9];
				}	
				else {
					$SaleDtAmount = $rows[6];
					$SaleDtCost = $rows[10];
				}	
			} else {
				if($curr == '' or $curr == $Base1) {
					$SaleDtAmount = $rows[3];
					$SaleDtCost = $rows[9];
				}	
				else {
					$SaleDtAmount = $rows[5];
					$SaleDtCost = $rows[10];
				}	
			}
			
			$MasterCode  = $rows[7];
			if ($MasterCode == '') $MasterCode = 'None';
			
			if ($groupby == 6 && ($GroupByCode != ''  && $GroupByCode != $MasterCode)) 
			{
				$GroupByLabel = '';
				$GroupByLabel = 'Total by Vendor';
				
				echo "<tr height='5'><td colspan=5><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' >". number_format($SumAmount, $DecimalBase) ."</td>";
				echo "	<td align='right' valign='top' >&nbsp;</td>";
				echo "</tr>";
				
				$SumQty     = 0;
				$SumAmount  = 0;
				
			}
			
			if ($groupby == 6 && ($GroupByCode == '' || $GroupByCode != $MasterCode)) {
			  
				$GroupByLabel = '';
				$GroupByLabel = 'Group by Vendor';
				
				
				echo "<tr>"; 
				echo "<td colspan='5'><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($subgroupitem == 1 && $groupby == 2 && $tempsubgroup != $rows[12])	{
				echo "<tr>"; 
				echo "<td colspan='5'><table class='group' width='100%' border='0' align='center' style='table-layout:fixed' >";
				echo "<tr>";
				echo "   <td width='10%'> Subgroup</td>";
				echo "   <td width='47%' >". $rows[12] ."</td>";
				echo "</tr>"; 
				echo "<tr height='5'><td colspan='3'>&nbsp;</td></tr></table></td></tr>";

				$tempsubgroup = $rows[12];
			}	
			echo "<tr>"; 
			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($SaleDtAmount, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleDtCost, $DecimalBase)."</td>";
			echo "</tr>";
			
			
			$TotalQty    = $TotalQty    +  $rows[2];
			$TotalAmount = $TotalAmount +  $SaleDtAmount;
			
			$SumQty    = $SumQty    +  $rows[2];
			$SumAmount = $SumAmount +  $SaleDtAmount;
			
		} 
		else if ($groupby == 8) {
			echo "<tr>"; 
			echo "	<td align='left' valign='top' >". $rows[0] ."</td>";
			echo "	<td align='right' valign='top'>".number_format($rows[1], $DecimalBase1)."</td>";
			echo "	<td align='right' valign='top'>".number_format($rows[2], $DecimalBase2)."</td>";
			echo "</tr>";
			
			$TotalAmountB1 = $TotalAmountB1 + $rows[1];
			$TotalAmountB2 = $TotalAmountB2 + $rows[2];
		}
		else {
		
			$MasterCode  = $rows[7];
			if ($MasterCode == '') $MasterCode = 'None';
			
			if (($groupby == 5 || $groupby == 3 || $groupby == 4 || $groupby == 7 || $groupby == 9 || $groupby == 10 || $groupby == 11) && ($GroupByCode != ''  && $GroupByCode != $MasterCode)) 
			{
				$GroupByLabel = '';
				if ($groupby == 5)		 $GroupByLabel = 'Total by Customer';
				else if ($groupby == 3)  $GroupByLabel = 'Total by User';
				else if ($groupby == 4)  $GroupByLabel = 'Total by CashRegister';
				else if ($groupby == 7)  $GroupByLabel = 'Total by User/CashRegister';
				else if ($groupby == 9)  $GroupByLabel = 'Total by SubGroup';
				else if ($groupby == 10) $GroupByLabel = 'Total by Driver';
				else if ($groupby == 11) $GroupByLabel = 'Total by Order Type';
				
				echo "<tr height='5'><td colspan=8><h5></td></tr>"; 
				echo "<tr class='totals'>"; 
				echo "  <td align='left' colspan='4'>Count Invoices: ".$InvCounter."</td>";
				echo "  <td align='right' colspan='3'>$GroupByLabel</td>";
				echo "	<td align='right' valign='top' >". number_format($SumAmount, $DecimalBase) ."</td>";
				echo "</tr>";
				
				$SumAmount   = 0;
				$InvCounter  = 0;
				
			}
			
			if (($groupby == 5 || $groupby == 3 || $groupby == 4 || $groupby == 7 || $groupby == 9 || $groupby == 10 || $groupby == 11) && ($GroupByCode == '' || $GroupByCode != $MasterCode)) {
			  
				$GroupByLabel = '';
				if ($groupby == 5)		 $GroupByLabel = 'Group by Customer';
				else if ($groupby == 3)	 $GroupByLabel = 'Group by User';
				else if ($groupby == 4)	 $GroupByLabel = 'Group by CashRegister';
				else if ($groupby == 7)	 $GroupByLabel = 'Group by User/CashRegister';
				else if ($groupby == 9)	 $GroupByLabel = 'Group by SubGroup';
				else if ($groupby == 10) $GroupByLabel = 'Group by Driver';
				else if ($groupby == 11) $GroupByLabel = 'Group by Order Type';
				
				
				echo "<tr>"; 
				echo "<td colspan='8'><table class='group' width='100%' border='0' align='center' style='table-layout:fixed' >";
				
				if ($groupby != 9) {
					echo "<tr>";
					echo "   <td width='10%'> $GroupByLabel</td>";
					echo "   <td width='7%' >". $rows[7] ."</td>";
					echo "   <td width='40%'>". $rows[8] ."</td>";
					echo "</tr>"; 
					
					if ($groupby == 5) {
						echo "<tr>";
						echo "   <td align='left' colspan='2'>". $rows[13] ."</td>";
						echo "   <td align='left'>". $rows[12] ."</td>";
						echo "</tr>";
					}	
					echo "<tr height='5'><td colspan='3'>&nbsp;</td></tr></table></td></tr>";
				} else {
					echo "<tr>";
					echo "   <td width='10%'> $GroupByLabel</td>";
					echo "   <td width='47%'>". $rows[8] ."</td>";
					echo "</tr>"; 
					echo "<tr height='5'><td colspan='2'>&nbsp;</td></tr></table></td></tr>";
				}	
				

				$GroupByCode = $MasterCode;
			
			}
			
			if($curr == '' or $curr == $Base1) $SaleAmount = $rows[5];
			else $SaleAmount = $rows[6];
				
			echo "<tr>"; 
			echo "	<td align='left' valign='top' >". $rows[11] ."</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='left' valign='top' >". $rows[9] ."</td>";
			echo "	<td align='left' valign='top' >". $rows[10] ."</td>";
			echo "	<td align='center' valign='top' >". $curr ."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleAmount, $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 ";
				//echo $querydt;		   
				if ($showpending != 1) {
					$querydt = $querydt." From RetailDt  ";
				} else {
					$querydt = $querydt." From Temp_RetailDt As RetailDt ";
				}
				
				$querydt = $querydt." 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 ($groupby == 9) {
					$querydt = $querydt." And ifNull(Items.SubGroup_Code,'') = '".$rows[12]."' ";
				}
				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='8'>"; 
				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>";
			
			}
			
			$TotalAmount = $TotalAmount +  $SaleAmount;
			$SumAmount   = $SumAmount   +  $SaleAmount;
		
			$InvCounter  += 1;
		}
	} else {
		if ($GroupByCode == '' || $GroupByCode != $rows[0]) {
			  
			echo "<tr>";
			echo "   <td align='left'>". $rows[0] ."</td>";
			echo "   <td align='left'>". $rows[1] ."</td>";
			echo "</tr>"; 
			
			$GroupByCode = $rows[0];
		}
		  
		echo "<tr><td colspan='2'>
				<table width='800' border='0' cellspacing='0' align='left' class='detail' style='table-layout:fixed'>
				<col width=20>
				<col width=70>
				<col width=120>
				<col width=250>
				<col width=340>
				<tr>
					<td align='center'>&nbsp;</th>
					<td align='center'>".$rows[3]."</th>
					<td align='center'>".$rows[4]."</th>
					<td align='left'>".$rows[5]."</th>
					<td align='left'>".$rows[6]."</th>
				</tr>";
		echo"	</table>";
		echo"</td></tr>";	
	
	}
}



// Report Totals
if ($custperitem == 0) {
	if ($groupby == 2 || $groupby == 6) {
		if ($groupby == 6) 
		{
			$GroupByLabel = '';
			$GroupByLabel = 'Total by Vendor';
				
			echo "<tr height='5'><td colspan=5><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' >". number_format($SumAmount, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >&nbsp;</td>";
			echo "</tr>";
				
		}
			
		echo "<tr height='5'><td colspan=5><h4></td></tr>"; 
		echo "<tr height='10'><td colspan='5'>&nbsp;</td></tr>"; 
		echo "<tr class='totals'>"; 
		echo "  <td align='right' colspan='2'>Total </td>";
		echo "	<td align='right' valign='top' >". $TotalQty ."</td>";
		echo "	<td align='right' valign='top' >". number_format($TotalAmount, $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >&nbsp;</td>";
		echo "</tr>";
		
	} 
	else if ($groupby == 8) {
		echo "<tr height='5'><td colspan=3><h4></td></tr>"; 
		echo "<tr height='10'><td colspan='3'>&nbsp;</td></tr>"; 
		echo "<tr class='totals'>"; 
		echo "  <td align='left'>Total: </td>";
		echo "  <td align='right' valign='top'>". number_format($TotalAmountB1, $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top'>". number_format($TotalAmountB2, $DecimalBase) ."</td>";
		echo "</tr>";	
	}
	else {
		if ($groupby == 5 || $groupby == 3 || $groupby == 4 || $groupby == 7 || $groupby == 9 || $groupby == 10 || $groupby == 11) 
		{
			$GroupByLabel = '';
			if ($groupby == 5)		 $GroupByLabel = 'Total by Customer';
			else if ($groupby == 3)  $GroupByLabel = 'Total by User';
			else if ($groupby == 4)  $GroupByLabel = 'Total by CashRegister';
			else if ($groupby == 7)  $GroupByLabel = 'Total by User/CashRegister';
			else if ($groupby == 9)  $GroupByLabel = 'Total by SubGroup';
			else if ($groupby == 10) $GroupByLabel = 'Total by Driver';
			else if ($groupby == 11) $GroupByLabel = 'Total by Order Type';
				
			echo "<tr height='5'><td colspan=8><h5></td></tr>"; 	
			echo "<tr class='totals'>"; 
			echo "  <td align='left' colspan='4'>Count Invoices: ".$InvCounter."</td>";
			echo "  <td align='right' colspan='3'>$GroupByLabel</td>";
			echo "	<td align='right' valign='top' >". number_format($SumAmount, $DecimalBase) ."</td>";
			echo "</tr>";
			
		}

		echo "<tr height='5'><td colspan=8><h4></td></tr>"; 
		echo "<tr height='10'><td colspan='8'>&nbsp;</td></tr>"; 
		echo "<tr class='totals'>"; 
		echo "  <td align='left' colspan='4'>Total Invoices: $TotalInvoices </td>";
		echo "  <td align='right' colspan='3'>Total </td>";
		echo "	<td align='right' valign='top' >". number_format($TotalAmount, $DecimalBase) ."</td>";
		echo "</tr>";	
		
		if ($showdetail == 1) {
			echo "<tr class='totals'>"; 
			echo "  <td align='right' colspan='7'>Total Qty</td>";
			echo "	<td align='right' valign='top' >". $TotalQty ."</td>";
			echo "</tr>";
		}
	}
}









echo "<tr><td>&nbsp;</td></tr>";


if( ($groupby == 2 or $groupby == 6 ) and $varprintstatus == 1){

//echo $querystatus;
/// list items for gift and void
$itemstat = '';
$TotalQty='';
$result=mysql_query($querystatus,$connection) or die(mysql_error());
while($rows=mysql_fetch_row($result)){





if($itemstat != $rows[11] )	{
	
		
		if($TotalQty !=''){
			echo "<tr class='totals'>"; 
			echo "  <td align='right' colspan='2'>Total $itemstat</td>";
			echo "	<td align='right' valign='top' >". $TotalQty ."</td>";
			echo "	<td align='right' valign='top' >". number_format($TotalAmount, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >&nbsp;</td>";
			echo "</tr>";
		}
		echo "<tr height='5'><td colspan=5><h4></td></tr>"; 
		//echo "<tr height='10'><td colspan='5'>&nbsp;</td></tr>"; 
		
	echo "<tr height='5'><td colspan=5><b><u>".$rows[11]."</u></b></td></tr>";
	//echo "<tr height='5'><td colspan=5><h5></td></tr>";
	$TotalQty    = 0	;
	$TotalAmount = 0	;
	}
	
	
	if ($custperitem == 0) {
		if ($groupby == 2 || $groupby == 6) {
			if ($CashRegisterTTC == 1){
				if($curr == '' or $curr == $Base1) {
					$SaleDtAmount = $rows[4];
					$SaleDtCost = $rows[9];
				}	
				else {
					$SaleDtAmount = $rows[6];
					$SaleDtCost = $rows[10];
				}	
			} else {
				if($curr == '' or $curr == $Base1) {
					$SaleDtAmount = $rows[3];
					$SaleDtCost = $rows[9];
				}	
				else {
					$SaleDtAmount = $rows[5];
					$SaleDtCost = $rows[10];
				}	
			}
			
			$MasterCode  = $rows[7];
			if ($MasterCode == '') $MasterCode = 'None';
			
			if ($groupby == 6 && ($GroupByCode != ''  && $GroupByCode != $MasterCode)) 
			{
				$GroupByLabel = '';
				$GroupByLabel = 'Total by Vendor';
				
				echo "<tr height='5'><td colspan=5><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' >". number_format($SumAmount, $DecimalBase) ."</td>";
				echo "	<td align='right' valign='top' >&nbsp;</td>";
				echo "</tr>";
				
				$SumQty     = 0;
				$SumAmount  = 0;
				
			}
			
			if ($groupby == 6 && ($GroupByCode == '' || $GroupByCode != $MasterCode)) {
			  
				$GroupByLabel = '';
				$GroupByLabel = 'Group by Vendor';
				
				
				echo "<tr>"; 
				echo "<td colspan='5'><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;
			
			}
			
			echo "<tr>"; 
			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($SaleDtAmount, $DecimalBase)."</td>";
			echo "	<td align='right' valign='top'>".number_format($SaleDtCost, $DecimalBase)."</td>";
			echo "</tr>";
			
			
			$TotalQty    = $TotalQty    +  $rows[2];
			$TotalAmount = $TotalAmount +  $SaleDtAmount;
			
			$SumQty    = $SumQty    +  $rows[2];
			$SumAmount = $SumAmount +  $SaleDtAmount;
			
		} 
		
	} else {
		if ($GroupByCode == '' || $GroupByCode != $rows[0]) {
			  
			echo "<tr>";
			echo "   <td align='left'>". $rows[0] ."</td>";
			echo "   <td align='left'>". $rows[1] ."</td>";
			echo "</tr>"; 
			
			$GroupByCode = $rows[0];
		}
		  
		echo "<tr><td colspan='2'>
				<table width='800' border='0' cellspacing='0' align='left' class='detail' style='table-layout:fixed'>
				<col width=20>
				<col width=70>
				<col width=120>
				<col width=250>
				<col width=340>
				<tr>
					<td align='center'>&nbsp;</th>
					<td align='center'>".$rows[3]."</th>
					<td align='center'>".$rows[4]."</th>
					<td align='left'>".$rows[5]."</th>
					<td align='left'>".$rows[6]."</th>
				</tr>";
		echo"	</table>";
		echo"</td></tr>";	
	
	}
	
	
	$itemstat = $rows[11];
	
}
	if($TotalQty !=''){
			echo "<tr class='totals'>"; 
			echo "  <td align='right' colspan='2'>Total $itemstat</td>";
			echo "	<td align='right' valign='top' >". $TotalQty ."</td>";
			echo "	<td align='right' valign='top' >". number_format($TotalAmount, $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' >&nbsp;</td>";
			echo "</tr>";
		}
		echo "<tr height='5'><td colspan=5><h4></td></tr>"; 
		echo "<tr height='10'><td colspan='5'>&nbsp;</td></tr>"; 
		
	echo "<tr height='5'><td colspan=5><b>".$rows[11]."</b></td></tr>";
	
	$TotalQty    = 0	;
	$TotalAmount = 0	;
}


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

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;

?>