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

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


$export = $_GET['export'];

if($export ==1){
	$filename = "Exp_SalesAnalysis" . date('Ymd') . ".xls";
	header("Content-Disposition: attachment; filename=\"$filename\"");
	header("Content-Type: application/vnd.ms-excel");
} 

if($export ==1){
}
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> Analysis 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 = 'Sales Analysis ';
 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 = '';
//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 height='5'><td colspan=8><h4></td></tr>
</table>
</td></tr>

<tr><td>
HERE;
 
$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  ";
 	
$sub_query6 = " Select RetailDt.Item_code, Items.Item_Description, Sum(ifNull(SaleDt_Quantity,0)) As SaleDtQuantity, ";


if($groupby==2)
	$Fieldgrouped = 'Retail.Project_Code';
else if($groupby==3)
	$Fieldgrouped = 'Retail.CostCenter_Code';
else if($groupby==7)
	$Fieldgrouped = 'Items.Group_Code';
else if($groupby==8)
	$Fieldgrouped = 'Items.SubGroup_Code';
else 
	$Fieldgrouped = 'RetailDt.Item_Code';

if($showdiscount == 1 )
	$sub_query6 = $sub_query6 . " 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 $sub_query6 = $sub_query6 . " 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 ";

$sub_query6 = $sub_query6 . "	, date_format(Retail.Sale_Date,'%b') MonthName, date_format(Retail.Sale_Date,'%Y') YearName	 ";
$sub_query6 = $sub_query6 . "	,Retail.Project_Code,Project.Project_Name,Retail.CostCenter_Code,Costcent.CostCent_Name, Items.Group_Code, Grouping.Group_Name,Items.SubGroup_Code, SubGroup.SubGroup_Name	 ";		 
$sub_query6 .= " From RetailDt  ".
			  " Inner Join Retail on RetailDt.Sale_Id = Retail.Sale_Id ";
	
$sub_query6 = $sub_query6." Inner Join Items on RetailDt.Item_code = Items.Item_code ".
				" Left Join Vendor on RetailDt.Vendor_Code = Vendor.Ledger_Number ";

$sub_query6 = $sub_query6." Left Join Grouping on Grouping.Group_code = Items.Group_code ".
				" Left Join Subgroup on Subgroup.Subgroup_Code = Items.Subgroup_Code ";


$sub_query6 = $sub_query6." Left Join Project on Project.Project_code = Retail.Project_code ".
				" Left Join Costcent on Retail.Costcenter_Code = Costcent.Costcent_Code ";


				
if ($projectexist > 0 && $FI_RepRestrictProject == 1)
			$sub_query6= $sub_query6.$QueryRestrictPrj." on Retail.Project_Code like concat(Q4.project_code,'%') ";
							 
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
			$sub_query6= $sub_query6.$QueryRestrictCst." on Retail.CostCenter_Code like concat(Q5.costcent_code,'%') ";
					
				// date_format( Retail.Sale_Date, '%Y-%m-%d %H:%i:%s')
$sub_query6 = $sub_query6. " Where 1 = 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'))  ";
$sub_query6= $sub_query6.	 " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
$sub_query6 = $sub_query6. " And Retail.User_Account = ifNull(".$fromuser.", Retail.User_Account) ".
		  " And Retail.CashRegister_Name = ifNull(".$fromcashreg.", Retail.CashRegister_Name) ".  
		  " 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')) ";
	

	
$sub_query7 = $sub_query6 . " Group By date_format(Retail.Sale_Date,'%Y%m') ";				 		 
$sub_query6 = $sub_query6 . " Group By date_format(Retail.Sale_Date,'%Y%m'),Retail.Currency_Code,RetailDt.Item_Code,".$Fieldgrouped."";	

					 
$sub_query6 = $sub_query6 . " Order by ".$Fieldgrouped.",RetailDt.Item_Code,Retail.Sale_Date,Retail.Sale_reference ";
$sub_query7 = $sub_query7 . " Order by Retail.Sale_Date";




// echo "<BR> 6 - ".$sub_query6;
 // echo "<BR> 7 - ".$sub_query7;
// exit;
 
echo "<table width='1000' border='0' align='left'  style='font-size:11px'>
			  ";
echo"<tr>";
echo"<th width=150>Item Code</th>";
echo"<th width=150>Desc</th>";

$sub_result7=mysql_query($sub_query7,$connection) or die(mysql_error());
while($sub_row7=mysql_fetch_array($sub_result7)){
extract($sub_row7);
$arr[] = $MonthName.$YearName;
echo"<th width=100 align=center>$MonthName $YearName<br>Qty</th>";
echo"<th width=100 align=center>$MonthName $YearName<br>Value</th>";

}

echo"<th width=100>Total Quantity</th>";
echo"<th width=100>Total Sales</th>";


echo"</tr>";
			    echo"<tr height='5'><td colspan=20><h4></td></tr>";


 $sub_result6=mysql_query($sub_query6,$connection) or die(mysql_error());
 $projectcode = '';
 $i=1;
	while($rows=mysql_fetch_array($sub_result6)){
	//	extract($sub_row6);
	
	
if($groupby==2) {
	//	$Field1 = $projectcode;
		$Field2 = $rows[9];
		$Field2Name = $rows[10];
		}
else if($groupby==3){
		//$Field1 = $projectcode;
		$Field2 = $rows[11];
		$Field2Name = $rows[12];
	}
else if($groupby==7){
		//$Field1 = $projectcode;
		$Field2 = $rows[13];
		$Field2Name = $rows[14];
	}
else if($groupby==8){
		//$Field1 = $projectcode;
		$Field2 = $rows[15];
		$Field2Name = $rows[16];
	}

	
	
	if($groupby	== 2 or $groupby	== 3 or $groupby	== 7 or $groupby	== 8){
	//echo $Field1.":".$Field2.":".$Project_Code."<br>";
	
	if($i!=1 and $Field1 != $Field2 ) {
			$arraysize = sizeof($arr);
			$arraysize = $arraysize +2;
			while($pos<$arraysize){
				echo"<td align=right>0</td>";
				echo"<td align=right>0</td>";
				$pos+=1;
			}
			echo"<td align=right width=100>".$totalqty."</td>";
			echo"<td  align=right width=100>".number_format($totalvalue, $DecimalBase)."</td>";
			echo"</tr>";
		$pos=0;	
		$totalqty=0;
		$totalvalue=0;

		}
		
		
		if($Field1 != $Field2 and $i!=1 ){
		
				 echo "<tr>";
				 echo"<td></tD>";
				 echo"<td><b><font size=2><i>Total $Field1</b></tD>";
				 
				$sub_result9=mysql_query($sub_query7,$connection) or die(mysql_error());
				while($sub_row7=mysql_fetch_array($sub_result9)){
				$indexname=$sub_row7[7].$sub_row7[8];
				echo"<td align=right><b><font size=2><i>".$subarra[$indexname]."</tD>";
				echo"<td align=right><b><font size=2><i>".number_format($subarra1[$indexname], $DecimalBase)."</tD>";
				$subtotal_totalqty +=$subarra[$indexname]; 
				$subtotal_totalsales +=$subarra1[$indexname]; 
				$subarra[$indexname]=0;
				$subarra1[$indexname]=0;
				}

				echo"<td align=right><b><b><font size=2><i>".$subtotal_totalqty."</b></tD>";
				echo"<td align=right><b><b><font size=2><i>".number_format($subtotal_totalsales, $DecimalBase)."</b></tD>";
				echo"</tr>";
				$subtotal_totalqty=0;
				$subtotal_totalsales =0; 
				 
		}
	
		if($Field1 != $Field2 ){
		
		if($groupby==2)
			$FieldName = 'Project';
		else if($groupby==3)
			$FieldName = 'CostCenter';
		else if($groupby==7)
			$FieldName = 'Group';
		else if($groupby==8)
			$FieldName = 'SubGroup';

	
				echo"<tr height=35><td><b><u><i><font size=2>$FieldName</u></b></td><td colspan=2><u><i><b><font size=2>$Field2 - $Field2Name</b></u></td></tr>";
				
				
				}
	
	}
	
	
	
	
	
	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];
				}	
			}
			


	if($itemcode!=$rows[0] ){
	
		if($i!=1 and $Field1 == $Field2 ) {
		$arraysize = sizeof($arr);
			$arraysize = $arraysize +2;
			while($pos<$arraysize){
				echo"<td align=right>0</td>";
				echo"<td align=right>0</td>";
				$pos+=1;
			}
			echo"<td align=right width=100>".$totalqty."</td>";
			echo"<td  align=right width=100>".number_format($totalvalue, $DecimalBase)."</td>";
			echo"</tr>";
		$pos=0	;
		$totalqty=0;
		$totalvalue=0;

		}

		
		echo"<tr>";
		$pos=1;
			echo"<td width=300>".$rows[0]."</td>";
			echo"<td width=200>".$rows[1]."</td>";
		$pos+=1;
	}
	
	
		/*$sub_result7=mysql_query($sub_query7,$connection) or die(mysql_error());
		while($sub_row7=mysql_fetch_array($sub_result7)){
		 
		
		IF($MonthName==$sub_row7[3] and $YearName==$sub_row7[4]){
			echo"<td width=100 align=right>".$rows[2]."</td>";
			echo"<td  width=150 align='right' valign='top'>".number_format($SaleDtAmount, $DecimalBase)."</td>";
		} else {
			echo"<td width=100 align=right>0</td>";
			echo"<td  width=150 align='right' valign='top'>".number_format(0, $DecimalBase)."</td>";
		}
	
		}
		foreach ($arr as $value) {
			echo $value."<br>";
		}

	*/
	
		$position = array_search($rows[7].$rows[8],$arr);
		$position+=2;
		while($pos < $position){
			echo"<td width=100 align=right>0</td>";
			echo"<td  width=150 align='right' valign='top'>".number_format(0, $DecimalBase)."</td>";
			$pos+=1;
		}
		$indexname=$rows[7].$rows[8];
		
		$arra[$indexname]+=$rows[2];
		$arra1[$indexname]+=$SaleDtAmount;
		
		$subarra[$indexname]+=$rows[2];
		$subarra1[$indexname]+=$SaleDtAmount;
		
		echo"<td width=100 align=right>".$rows[2]."</td>";
		echo"<td  width=150 align='right' valign='top'>".number_format($SaleDtAmount, $DecimalBase)."</td>";
		$pos+=1;
		
	$Field1 = $Field2;
	$totalqty+=$rows[2];
	$totalvalue+=$SaleDtAmount;
	$itemcode=$rows[0]; 
	$i+=1;
	}
	
	
	{
			$arraysize = sizeof($arr);
			$arraysize = $arraysize +2;
			while($pos<$arraysize){
				echo"<td align=right>0</td>";
				echo"<td align=right>0</td>";
				$pos+=1;
			}
			echo"<td align=right width=100>".$totalqty."</b></td>";
			echo"<td  align=right width=100>".number_format($totalvalue, $DecimalBase)."</b></td>";
			echo"</tr>";
		$pos=0;	
		$totalqty=0;
		$totalvalue=0;

		}
		
		 echo "<tr>";
				 echo"<td></tD>";
				 echo"<td><b><i><font size=2><i>Total $Field1</b></tD>";
				 
				$sub_result9=mysql_query($sub_query7,$connection) or die(mysql_error());
				while($sub_row7=mysql_fetch_array($sub_result9)){
				$indexname=$sub_row7[7].$sub_row7[8];
				echo"<td align=right><b><font size=2><i>".$subarra[$indexname]."</b></tD>";
				echo"<td align=right><b><font size=2><i>".number_format($subarra1[$indexname], $DecimalBase)."</b></tD>";
				$subtotal_totalqty +=$subarra[$indexname]; 
				$subtotal_totalsales +=$subarra1[$indexname]; 
				$subarra[$indexname]=0;
				$subarra1[$indexname]=0;
				}

				echo"<td align=right><font size=2><b><i>".$subtotal_totalqty."</b></tD>";
				echo"<td align=right><font size=2><b><i>".number_format($subtotal_totalsales, $DecimalBase)."</b></tD>";
				$subtotal_totalqty=0;
				$subtotal_totalsales =0; 
				echo"</tr>";		
 
 
 echo "<tr>";
 echo"<td colspan=20><hr></td>";
 echo "</tr>";
 echo "<tr>";
 echo"<td></tD>";
 echo"<td><b><i><font size=2>Total</b></tD>";
 
 $sub_result9=mysql_query($sub_query7,$connection) or die(mysql_error());
while($sub_row7=mysql_fetch_array($sub_result9)){
$indexname=$sub_row7[7].$sub_row7[8];
echo"<td align=right><font size=2><b><i>".$arra[$indexname]."</b></tD>";
echo"<td align=right><font size=2><b><i>".number_format($arra1[$indexname], $DecimalBase)."</b></tD>";
$total_totalqty +=$arra[$indexname]; 
$total_totalsales +=$arra1[$indexname]; 
}

echo"<td align=right><font size=2><b><i>".$total_totalqty."</b></tD>";
echo"<td align=right><font size=2><b><i>".number_format($total_totalsales, $DecimalBase)."</b></tD>";
 echo"</tr>";
 echo"</table>";
  
 
 
function current_server_time($connection){

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

  return $now;
}

function explodewordtime($date)
{

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

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

$trim = "$trim[2]"."-"."$trim[1]"."-"."$trim[0]";
return $trim;
}


if ($printaccess==1 && $_GET['print'] == 1)
print <<< HERE

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

 
 
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];

}
 
 
 ?>