<?
//ob_start();
session_start();

function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}

if(isset($_SESSION['ses_name']))
{
$user=$_SESSION['ses_name'];
}else{
header("location:index.php");
}


$veh_num='';
$sdate_12 ='';
$page='1';
include("include/config.php");
require_once "include/Database_functions.php";
$sqlObj=new sqlclass();
$msg = '';
$client_namek ='';

if(isset($_REQUEST['del']) && $_REQUEST['del']=='delete')
{
	$id = $_REQUEST['sales_del'];
	//$client_id = $_REQUEST['clientids'];
	
	$sqlsaletab = mysql_query("select * from cf_sales where sales_id ='$id' ");
	$rwsaletab = mysql_fetch_array($sqlsaletab);
	$client_id =$rwsaletab['sales_clientid'];
	$saletot =$rwsaletab['sales_tot'];
	
	$salestype =$rwsaletab['sales_type'];
	
	
	$reclientres = mysql_query("select * from cf_ledger where ledgertype = 'clientledger' and empid = '$client_id'");
	$clientrw = mysql_fetch_array($reclientres);
	$ledgerids = $clientrw['ledgerid'];
	
	
	$sqlsale = mysql_query("select * from cf_sales_sub where sale_id ='$id' ");
	while($rwsale = mysql_fetch_array($sqlsale))
	{
		$packsale_box = $rwsale['sale_box'];
		$packsale_no_tin_kg = $rwsale['sale_no_tin_kg'];
		$productid = $rwsale['prd_id'];
		$sale_amount = $rwsale['sale_rate'];
		
		$damagereturn=$rwsale['sale_damage_qty'];
		$branchid = $rwsale['branch_id'];	
		$literid = $rwsale['liter_id'];
		/*$branchid = $rwpack['branch_id'];
		$literid = $rwpack['liter_id'];
		
		$sqlsku = mysql_query("select * from cf_sku_stock where brnd_id = '$branchid' and ltre_id = '$literid'");
		$rwsku = mysql_fetch_array($sqlsku);
		
		$skupackqty = $rwsku['packqty'];
		$skupackbox = $rwsku['packbox'];
		$updtpackqty = $skupackqty - $packqty;
		$updtpackbox = $skupackbox - $packbox;*/
		
		if($salestype=='tin'){
		$tin_sql=mysql_query("select * from cf_tin where status=1");
		  if($tin_sql && mysql_num_rows($tin_sql)>0)
		  {
		  while($tin_row=mysql_fetch_array($tin_sql))
		  {
		  $tin_jar_barrel_kg=$tin_row['kg_val'];
		  }
		  }
		  else
		  {
		  $tin_jar_barrel_kg=0;
		  }
		  
		  mysql_query("update cf_stock set `stock_tin`=`stock_tin`+$packsale_no_tin_kg");
		  
		}
		else if($salestype=='jar'){  
		  
		  $jar_sql=mysql_query("select * from cf_jar where status=1");
			  if($jar_sql && mysql_num_rows($jar_sql)>0)
			  {
			  while($jar_row=mysql_fetch_array($jar_sql))
			  {
			  $tin_jar_barrel_kg=$jar_row['jar_kg'];
			  }
			  }
			  else
			  {
			  $tin_jar_barrel_kg=0;
			  }
			  
			 mysql_query("update cf_stock set `stock_jar`=`stock_jar`+$packsale_no_tin_kg"); 
		}	
		else if($salestype=='barrel'){
		$barrel_sql=mysql_query("select * from cf_barrel where status=1");
				  if($barrel_sql && mysql_num_rows($barrel_sql)>0)
				  {
				  while($barrel_row=mysql_fetch_array($barrel_sql))
				  {
				  $tin_jar_barrel_kg=$barrel_row['barrel_kg'];
				  }
				  }
				  else
				  {
				  $tin_jar_barrel_kg=0;
				  }	
				  
			mysql_query("update cf_stock set `stock_barrel`=`stock_barrel`+$packsale_no_tin_kg");	  
		}
		else if($salestype=='box'){
		$box_sql=mysql_query("SELECT * FROM cf_liter_qty JOIN cf_liter ON cf_liter_qty.literids = cf_liter.liter_id JOIN cf_brand ON cf_liter_qty.brandid = cf_brand.brand_id
									WHERE brandid =  '$branchid' AND literids ='$literid'");
		
				  if($box_sql && mysql_num_rows($box_sql)>0)
				  {
				  while($box_row=mysql_fetch_array($box_sql))
				  {
				  $totkgs = $box_row['kgqty']*$box_row['liter_boxno'];
				  $tin_jar_barrel_kg = $totkgs*$packsale_no_tin_kg;
				  }
				  }
				  else
				  {
				  $tin_jar_barrel_kg=0;
				  }	
				  
			 
		}
		
			
		if($salestype=='barrel' || $salestype=='jar' || $salestype=='tin'){	  
		$tin_tot=$tin_jar_barrel_kg*($packsale_no_tin_kg+$damagereturn);
		}
		else if($salestype=='kg')
		{
		$tin_tot=$packsale_no_tin_kg;
		}
		else if($salestype=='box')
		{
		$tin_tot=$tin_jar_barrel_kg;
		}
		
	
		
		mysql_query("update cf_accountsreceivable set `receiveamount`=`receiveamount`-$saletot where clientid=$client_id"); 
		
	
		if($productid == 1)
		   		 {
		   			mysql_query("update cf_stock set `stock_palmoil`=`stock_palmoil`+$tin_tot");
		   		 }
				 else if($productid == 2)
				 {
				 	mysql_query("update cf_stock set `stock_coconutoil`=`stock_coconutoil`+$tin_tot");
				 }
				 
				 
				 
	 if($salestype == 'box'){

				$ven_client_id = 1005;					
						
				$acc_ref1=mysql_query("select account_reference from cf_purchase_account where ven_client_id = '$ven_client_id' and  purchaseid ='$id'");
				$acc_refrow1=mysql_fetch_array($acc_ref1);
				$acc_ref= $acc_refrow1['account_reference'];
				
				$sql=mysql_query("delete from cf_purchase_account where purchaseid='$id' and ven_client_id = '$ven_client_id' and account_type = 1 and account_reference = '$acc_ref' ");
				$sql=mysql_query("delete from cf_purchase_account where purchaseid='$id' and ven_client_id = '$ledgerids' and account_type = 2 and account_reference = '$acc_ref'");
			
			
				$sql=mysql_query("delete from cf_sales where sales_id='$id'");
				$sql2=mysql_query("delete from cf_sales_sub where sale_id='$id'");
		}
				 
				 
				 				 
	
	}


	if($salestype == 'tin')
	{
		$ven_client_id = 1006;
	}
	elseif($salestype == 'jar'){

		$ven_client_id = 1007;
	
	}
	elseif($salestype == 'kg'){
		$ven_client_id = 1008;
	
	}
	elseif($salestype == 'barrel'){

		$ven_client_id = 1009;
	}
	
	
	if($salestype != 'box'){
	$acc_ref1=mysql_query("select account_reference from cf_purchase_account where ven_client_id = '$ven_client_id' and  purchaseid ='$id'");
	$acc_refrow1=mysql_fetch_array($acc_ref1);
	$acc_ref= $acc_refrow1['account_reference'];
	
	$sql=mysql_query("delete from cf_purchase_account where purchaseid='$id' and ven_client_id = '$ven_client_id' and account_type = 1 and account_reference = '$acc_ref' ");
	$sql=mysql_query("delete from cf_purchase_account where purchaseid='$id' and ven_client_id = '$ledgerids' and account_type = 2 and account_reference = '$acc_ref'");


	$sql=mysql_query("delete from cf_sales where sales_id='$id'");
	$sql2=mysql_query("delete from cf_sales_sub where sale_id='$id'");
	//header("location:sales-list.php?msg=You Have Successfully Deleted");
	}
}

if(isset($_POST['damagesretrn']))
{

				if(isset($_POST['dmgcnt'])){
				$dmgcnt=addslashes($_POST['dmgcnt']);
				}
				else
				{$dmgcnt=0;
				}
				for($i=1;$i<$dmgcnt;$i++)
				{
					if(isset($_POST['brand_id'.$i])){
					$brand_id=addslashes($_POST['brand_id'.$i]);
					}else
					{$brand_id='';
					}
					if(isset($_POST['liter_id'.$i])){
					$liter_id=addslashes($_POST['liter_id'.$i]);
					}else
					{$liter_id='';
					}
					if(isset($_POST['damages'.$i])){
					$damages=addslashes($_POST['damages'.$i]);
					}else
					{$damages='';
					}
					if(isset($_POST['sub_id'.$i])){
					$sub_id=addslashes($_POST['sub_id'.$i]);
					}else
					{$sub_id='';
					}
					
					$result = mysql_query("select * from cf_liter where liter_id = '$liter_id' ");
					$rw = mysql_fetch_array($result);
					$liter_box = $rw['liter_boxno'];
					$chngqty=$liter_box*$damages;
					
					mysql_query("update cf_sales_sub set sale_damages='$damages' where sale_sub_id='$sub_id'");
					mysql_query("update cf_sku_stock set packbox=packbox+$damages,packqty=packqty+$chngqty where brnd_id='$brand_id' and ltre_id='$liter_id'");
				}

}
if(isset($_POST['damagesretrntin']))
{

				if(isset($_POST['dmgcnt'])){
				$dmgcnt=addslashes($_POST['dmgcnt']);
				}
				else
				{$dmgcnt=0;
				}
				$tin_sql=mysql_query("select * from cf_tin where status=1");
				  if($tin_sql && mysql_num_rows($tin_sql)>0)
				  {
				  while($tin_row=mysql_fetch_array($tin_sql))
				  {
				  $tin_kg=$tin_row['kg_val'];
				  }
				  }
				  else
				  {
				  $tin_kg=0;
				  }
				for($i=1;$i<$dmgcnt;$i++)
				{
					
					if(isset($_POST['damages'.$i])){
					$damages=addslashes($_POST['damages'.$i]);
					}else
					{$damages='';
					}
					if(isset($_POST['sub_id'.$i])){
					$sub_id=addslashes($_POST['sub_id'.$i]);
					}else
					{$sub_id='';
					}
					
					
					$chngqty=$tin_kg*$damages;
					
					mysql_query("update cf_sales_sub set sale_damages='$damages' where sale_sub_id='$sub_id'");
					mysql_query("update cf_stock set stock_oil=stock_oil+'$chngqty'");
				}

}

function print1($selectype,$saletype,$clientbox_id,$fromdate,$todate)
			{
				$dates = date('Y-m-d');
				$names = $selectype.$dates;
				$outstr = NULL;
				//header("Content-type: application/vnd.ms-word");
				//header("Content-Disposition: attachment;Filename=".$names.".xls");
			
					//set the directory to get image			
					// Query database to get data
				
				//print_r($_REQUEST);
				$cond='';
				
				$outstr .='<div id="header" >
					<table  border="0" cellspacing="0" cellpadding="0" class="tableList"  style="margin-left:20px; ">
  <tr class="heading">
    <td>No</td>    
    <td>Sales Code</td>
	<td>Product</td>
	<td>Quantity</td>
	<td>Sales Rate</td>	
	<td>Sales Type</td>		
	<td>Client</td>
	<td>Date</td>    
    <td>Total</td>    
   </tr>';
  
//print_r($_REQUEST);
$saletype ='';
$fromdate1='';
$todate1='';
$clientboxid='';

if(isset($_REQUEST['saletype'])){
$saletype=$_REQUEST['saletype'];
}

if(!empty($_REQUEST['from_date'])){
$fromdate=$_REQUEST['from_date'];
$fromdate1 = date('Y-m-d', strtotime($fromdate));
}

if(!empty($_REQUEST['to_date'])){
$todate=$_REQUEST['to_date'];
$todate1 = date('Y-m-d', strtotime($todate));
}

if(isset($_REQUEST['clientbox_id'])){
$clientboxid=$_REQUEST['clientbox_id'];
}

$i=1;
/*$sq_arr="select cf_sales.*,cf_sales_sub.sale_rate,cf_sales_sub.prd_id as prd_id,cf_sales_sub.sale_no_tin_kg from cf_sales join cf_client on cf_sales.sales_clientid = cf_client.client_id join cf_sales_sub on cf_sales.sales_id=
cf_sales_sub.sale_id where 1 ";*/

$i=1;
$saleTot =0; $saleAmountTot =0;
$sq_arr="select cf_sales.*,cf_sales_sub.sale_rate,cf_sales_sub.prd_id as prd_id,cf_sales_sub.sale_no_tin_kg from cf_sales join cf_sales_sub on cf_sales.sales_id=
cf_sales_sub.sale_id where 1";

if($saletype!=''){
$sq_arr.=" and cf_sales.sales_type = '".$saletype."' ";
}
echo $fromdate1;
if($fromdate1!="" && $todate1!=""){
$sq_arr.=" and cf_sales.sales_date between '$fromdate1' and '$todate1'";
}

if($clientboxid!=''){
$sq_arr.=" and cf_sales.sales_clientid = '".$clientbox_id."' ";
}
$sq_arr.=" order by cf_sales.sales_id desc ";
$query=$sq_arr;
//echo $query;

//calcutate total
$grandTot = 0;
$saleLists =mysql_query($sq_arr);
if($saleLists && mysql_num_rows($saleLists)>0){
while($val =mysql_fetch_array($saleLists))
{
	$grandTot += $val['sales_tot'];
}
}
$outstr .='<div style="margin-left:22px;margin-top:22px;"><strong >'.('Grand Total : '.$grandTot).'</strong></div>';
//////


$saleTot =0; $saleAmountTot =0;
$array=mysql_query($sq_arr);
if($array && mysql_num_rows($array)>0){
$pagecnt=1;
while($res=mysql_fetch_array($array))
{
$pagecnt++;

	$client_ids = $res['sales_clientid'];
	$reclientres1 = mysql_query("select * from cf_ledger where ledgerid = '$client_ids' ");
	$clientrw1 = mysql_fetch_array($reclientres1);
	$ledgername1 = $clientrw1['ledgername'];

 
  $outstr .='<tr>
    <td>'.$pagecnt.'</td>
    <td>SL- '.$res['sales_code'].'</td>';
	
	$sq_product=mysql_query("select * from cf_open_oil where open_stock_id = '".$res['prd_id']."'");
	$rws = mysql_fetch_array($sq_product);
	
	$outstr .='<td>'.$rws['item_name'].'</td>   	 
	<td>'.$res['sale_no_tin_kg'].'</td>    
	<td>'.$res['sale_rate'].'</td> 	
	<td>'.$res['sales_type'].'</td> 	
	
	<td>'.$ledgername1.'</td>     
    <td>'.date(('d-m-Y'),strtotime($res['sales_date'])).'</td>     
    <td>'.$res['sales_tot'].'</td>';   
   
	
	$saleTot +=$res['sale_no_tin_kg'];
	$saleAmountTot+=$res['sales_tot'];
  $outstr .='</tr>';
  
    }}else{
	 $outstr .='<tr>
    <td class="errorMessage"  style="border-right:0px;border-bottom:0px; "><font color="#FF0000">No Records Found</font></td></tr>';
	 }
  
  $outstr .='<tr>
  	<td><strong>Total</strong></td>
  	<td>&nbsp;</td>
  	<td>&nbsp;</td>
  	<td><strong>'.$saleTot.'</strong></td>
  	<td>&nbsp;</td>
  	<td>&nbsp;</td>
  	<td>&nbsp;</td>
  	<td>&nbsp;</td>
  	<td><strong>'.$saleAmountTot.'</strong></td>
  	<td>&nbsp;</td>
  </tr>
</table>
				

					</div>'; 
					
					
if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

             $ext = end(explode(".",$entry));
			if($ext=="xls" && startsWith($entry, "Export") === true)	
				
				unlink($entry);
        }
    }

    closedir($handle);
}

				$fname = "Export".time().".xls";
				  $file = fopen($fname,"w+");
				  fwrite($file,$outstr);
				  fclose($file);
				  header('Location:'.$fname);
					
									//echo $outstr;
				/*$fname = "Export".time().".xls";
				  $file = fopen($fname,"w+");
				  fwrite($file,$outstr);
				  fclose($file);
				  header('Content-Type: application/vnd.ms-excel');
				  header('Content-Disposition: attachment; filename="'.basename($fname).'"');
				  readfile($fname);
				  unlink($fname); 	*/
				exit;
			
				
			}
			
			
				
			if(isset($_POST['download']))
			{
				$selectype = "Sales List";
				$saletype = $_POST['saletype'];
				$clientbox_id = $_POST['clientbox_id'];
				$fromdate = $_POST['from_date'];
				$todate = $_POST['to_date'];
				
				
				print1($selectype,$saletype,$clientbox_id,$fromdate,$todate);
			}

?>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>OIL FILL</title>
<link href="css/styles.css" rel="stylesheet"  />
<link href="css/menu.css" rel="stylesheet" type="text/css" />
<link type="text/css" href="css_date/ui-lightness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script type='text/javascript' src="js/jquery.autocomplete.js"></script>
<link rel="stylesheet" type="text/css" href="js/jquery.autocomplete.css" />

<script type="text/javascript" src="scripts_date/jquery-calendar-1.7.2.js"></script>



<script src="js/popup_sales.js" type="text/javascript"></script>
<script>

$(document).ready(function(){
$('#from_date').datepicker({
showOn: 'both',
buttonImage: 'icons_date/calendar.gif',
buttonImageOnly: true,
changeMonth: true,
changeYear: true,
dateFormat: 'dd-mm-yy'
});
});

$(document).ready(function(){
$('#to_date').datepicker({
showOn: 'both',
buttonImage: 'icons_date/calendar.gif',
buttonImageOnly: true,
changeMonth: true,
changeYear: true,
dateFormat: 'dd-mm-yy'
});
});

</script>
<script language="javascript">
function getXMLHTTP()
	 { //fuction to return the xml http object
	var xmlhttp=false;	
		try
		{
		xmlhttp=new XMLHttpRequest();
		}
		catch(e)	
		{		
			try{			
				xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
				}
			catch(e)
			{
				try
				{
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch(e1)
				{
				xmlhttp=false;
				}
			}
		}
	return xmlhttp;
	}   


function Searchdate(page,val)
{ 
 	
	 var page=page;	
	 var saletype='';
	 var fromdate='';
	 var todate='';
	 var clientboxid='';
	 
	 if(document.sales_frm.saletype){
	 saletype= document.sales_frm.saletype.value;
	 } 
	 
	 if(document.sales_frm.from_date){
	 fromdate= document.sales_frm.from_date.value;
	 }
	 
	 if(document.sales_frm.to_date){
	 todate= document.sales_frm.to_date.value;
	 }
	 
	 if(document.sales_frm.clientbox_id){
	 clientboxid= document.sales_frm.clientbox_id.value;
	 }
	 
	 
	var strURL="ajax/sales_list_data.php?&page="+page;
		
		if(saletype!=''){
		strURL+="&saletype="+saletype;
		}
			
		if(fromdate!=''){
		strURL+="&fromdate="+fromdate;
		}
			
		if(todate!=''){
		strURL+="&todate="+todate;
		}
		
		if(clientboxid!=''){
		strURL+="&clientboxid="+clientboxid;
		}
	var req = getXMLHTTP();
   if (req)
   {
     req.onreadystatechange = function()
     {
		 
			if ((req.readyState == 0)||(req.readyState == 1)||(req.readyState == 2)||(req.readyState == 3))
      		{
			//document.getElementById('order').innerHTML='<div align="center"><img src="'+path+'images/ajax_loader.gif"/></div>';
			//document.getElementById('Cakeorder').innerHTML='<div align="center"><img src="'+path+'images/ajax_loader.gif"/></div>';
			}
		 
		 
      if (req.readyState == 4)
      {
	 // only if "OK"
	 	if (req.status == 200)
	 	{ 
	   document.getElementById('list').innerHTML=req.responseText;
	//	document.getElementById('Cakeorder').innerHTML=req.responseText;
	 	}
	  else 
	 	{
   	   alert("There was a problem while using XMLHTTP:\n" + req.statusText);

	 }
     }
     }
   req.open("GET", strURL, true);
   req.send(null);
   }
 
   
}
function showClientcodedropdown(str){
var xmlhttp;    
if (str=="")
  {
  document.getElementById("txtcodeshow").innerHTML="";
  Searchdate(1,str);
  return;
  }
  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
	   document.getElementById("txtcodeshow").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","clientajax_code_dropdown.php?str="+str,true);
xmlhttp.send();
}
</script>
</head>

<body>
<!------------------popup area (view, edit)--------------->

<div class="viewEmployeePopup login-popup"  id="login-box" style="width:800px;height:400px;">
<a href="#" class="close"><img src="images/close.png" class="btn_close" title="Close Window" alt="Close" /></a>
   <div id="popupid_sales"></div>
   
     
    </div>

<!---------------popup area ends------------------>
<div class="wrapper" >
   <div>
<?php 
	include("header.php");
?>
</div>
 
 <div class="tabbedArea" style="position:relative; margin-top:">

  
  <div class="tabBody">
   <h1>Sales List</h1>
   
   <form name="sales_frm" id="sales_frm" method="post"  >
   <div class="searchBox" style="width:93%; margin-right:0px;  padding:0px; ">
   <div style="padding:20px;">
    
    <div class="searchField" style="padding-left:20px;">
     <p class="input1">Sales Type</p>
     <select name="saletype" class="input1">
         <option value="">-Select Type-</option>
         <option value="box">Box</option>
         <option value="tin">Tin</option>
         <option value="kg">Kg</option>
		 <option value="jar">Jar</option>
		 <option value="barrel">Barrel</option>
     </select>
    </div>
	
	
	<div class="searchField" style="padding-left:20px;">
     <p class="input1">Client Name</p>
     <select class="input1 " name="clientbox_id" id="clientbox_id" >
                        <option value="">-Select Client-</option>
                        <?php 
                            $sq_client="select * from cf_client";
                            $arrclient=mysql_query($sq_client);
                            while($res1=mysql_fetch_array($arrclient))
                            {
                            ?>  <option value="<?=$res1['client_id']?>"><?=$res1['client_name']?></option>
                            <?php
                            }
                            ?>
                    </select>
    </div>
     
    <div class="searchField" style="padding-left:20px;">
     <p class="input1">From Date</p>
     <input type="text" name="from_date" id="from_date" style="width:75px;" maxlength="100" class="input1" />
    </div>
    
    <div class="searchField" style="padding-left:20px;">
     <p class="input1">To Date</p>
     <input type="text" name="to_date" id="to_date" style="width:75px;" maxlength="100" class="input1" />
    </div>
       
    <div class="searchField">
     <input name="button" type="button" class="input1" onClick="Searchdate(1);" value="search" />
    </div>
	
	<div class="searchField" style="padding-left:60px;margin-right: 20px;">
    <input name="download" type="submit" class="input1"  value="download" />
    </div>
  
   </div>
   </div>
   </form>
   
   <div class="searchBox" style="width:93%; margin-right:0px;  padding:0px;">
  
   
   <div id="list">
   <table  border="0" cellspacing="0" cellpadding="0" class="tableList"  style="margin-left:20px; ">
  <tr class="heading">
    <td>No</td>    
    <td>Sales Code</td>
	<td>Product</td>
	<td>Quantity</td>
	<td>Sales Rate</td>	
	<td>Sales Type</td>		
	<td>Client</td>
	<td>Date</td>    
    <td>Total</td>    
    <td align="center">Delete</td>
  </tr>
  
  <?php

$master = '';
$notification = '';
$trip = '';
$accounting = '';
$accpay = '';
$report = '';

$i=1;
$sq_arr="select cf_sales.*,cf_client.*,cf_sales_sub.sale_rate,cf_sales_sub.prd_id as prd_id,cf_sales_sub.sale_no_tin_kg from cf_sales join cf_client on cf_sales.sales_clientid = cf_client.client_id join cf_sales_sub on cf_sales.sales_id=
cf_sales_sub.sale_id where 1 ";
$sq_arr.=" group by cf_sales.sales_code order by cf_sales.sales_id desc ";
$query=$sq_arr;
//echo $query;

//calcutate total
$grandTot = 0;
$saleLists =mysql_query($sq_arr);
if($saleLists && mysql_num_rows($saleLists)>0){
while($val =mysql_fetch_array($saleLists))
{
	$grandTot += $val['sales_tot'];
}
}
echo '<div style="margin-left:22px;margin-top:22px;"><strong >'.('Grand Total : '.$grandTot).'</strong></div>';
//////

$function="Searchdate";
include("pagingserch.php");
$sq_arr.=" LIMIT $start, $limit";

if(isset($_REQUEST['page'])){
$page=$_REQUEST['page'];
}else{
$page=1;
}
$saleTot =0; $saleAmountTot =0;
$array=mysql_query($sq_arr);
if($array && mysql_num_rows($array)>0){
$pagecnt=$start;
while($res=mysql_fetch_array($array))
{
$pagecnt++;
  ?> 
  <tr>
    <td><?php echo $pagecnt;?></td>
    <td><a href="#login-box" class="login-window" data-id=<?php echo $res['sales_id'];?> data-chk=<?php echo $res['sales_type'];?> style="color:#AA2D58"><?php echo "SL-". $res['sales_code'];?></a></td>
	<?php 
	$sq_product=mysql_query("select * from cf_open_oil where open_stock_id = '".$res['prd_id']."'");
	$rws = mysql_fetch_array($sq_product);
	?>
	<td><?php echo $rws['item_name'];?></td>   	 
	<td><?php echo $res['sale_no_tin_kg']; $saleTot +=$res['sale_no_tin_kg'];?></td>    
	<td><?php echo $res['sale_rate'];?></td> 	
	<td><?php echo $res['sales_type'];?></td> 	
	
	<td><?php echo $res['client_name'];?></td>     
    <td><?php echo date(('d-m-Y'),strtotime($res['sales_date']));?></td>     
    <td><?php echo $res['sales_tot']; $saleAmountTot+=$res['sales_tot']; ?></td>   
    <td align="center" class="tr_td_r" ><a href="sales-list.php?sales_del=<?=$res['sales_id']?>&del=delete&clientids=<?=$res['sales_clientid']?>" onClick="return confirm('Do you really want to delete this field?');"><img src="images/delete.png" title="delete"></a></td>
  </tr>
  <?php 
    }}else{?>
	 <tr>
    <td class="errorMessage"  style="border-right:0px;border-bottom:0px; "><font color="#FF0000">No Records Found</font></td></tr>
	<? }
  ?>
  <tr>
  	<td><strong>Total</strong></td>
  	<td>&nbsp;</td>
  	<td>&nbsp;</td>
  	<td><strong><?php echo $saleTot;?></strong></td>
  	<td>&nbsp;</td>
  	<td>&nbsp;</td>
  	<td>&nbsp;</td>
  	<td>&nbsp;</td>
  	<td><strong><?php echo  $saleAmountTot;?></strong></td>
  	<td>&nbsp;</td>
  </tr>
</table>

  <div align="right" style="padding-top:10px;"><?=$pagination?></div> 
  </div>
  </div>
 </div>
 <div class="footer"><p>Powered by <a href="http://www.aadhocc.co.uk/" target="_blank">Aadhocc</a></p></div>
 
</div>
<div class="quicLInksCover">
 <?php 
	include("leftlink.php");
?>

</div>
</body>
</html>
