<?php
//This code is copyright (c) ViciSoft SL, all rights reserved.
//The contents of this file are protected under law as the intellectual property 
//of ViciSoft SL. Any use, reproduction, disclosure or copying of any kind 
//without the express and written permission of ViciSoft SL is forbidden.
//Author: Vince Reid, vincereid@gmail.com
if(@$storesessionvalue=="") $storesessionvalue="virtualstore".time();
if(@$_SESSION['loggedon']!=$storesessionvalue||@$GLOBALS['disallowlogin']||!@$GLOBALS['incfunctionsdefined']) exit;
$success=TRUE;
$admindatestr="Y-m-d";
if(@$admindateformat=="") $admindateformat=0;
if($admindateformat==1)
	$admindatestr="m/d/Y";
elseif($admindateformat==2)
	$admindatestr="d/m/Y";
$alreadygotadmin=getadminsettings();
$fromdate=getpost('fromdate');
$todate=getpost('todate');
$hasfromdate=FALSE;
$hastodate=FALSE;
if(strtolower($adminencoding)=='iso-8859-1') $raquo='»'; else $raquo='>';
set_time_limit(300);
function writemenulevel($id,$itlevel){
	global $allcatsa,$numcats,$thecat,$raquo;
	if($itlevel<10){
		for($wmlindex=0; $wmlindex < $numcats; $wmlindex++){
			if($allcatsa[$wmlindex]['topSection']==$id){
				print "<option value='" . $allcatsa[$wmlindex]['sectionID'] . "'";
				if(is_array($thecat)){
					foreach($thecat as $catid){
						if($catid==$allcatsa[$wmlindex]['sectionID']) print '  selected';
					}
				}
				print '>';
				for($index=0; $index < $itlevel-1; $index++)
					print $raquo . ' ';
				print $allcatsa[$wmlindex]['sectionWorkingName'] . "</option>\n";
				if($allcatsa[$wmlindex]['rootSection']==0) writemenulevel($allcatsa[$wmlindex]['sectionID'],$itlevel+1);
			}
		}
	}
}
function getdatesql($datecol){
	global $hasfromdate, $hastodate, $thefromdate, $thetodate;
	$datesql='';
	if(! ($hasfromdate || $hastodate))
		; // nothing
	elseif($hasfromdate && $hastodate)
		$datesql=' AND '.$datecol." BETWEEN '" . date('Y-m-d', $thefromdate) . "' AND '" . date('Y-m-d H:i:s', $thetodate-1) . "'";
	elseif($hasfromdate)
		$datesql=' AND '.$datecol." BETWEEN '" . date('Y-m-d', $thefromdate) . "' AND '" . date('Y-m-d H:i:s', $thefromdate+86399) . "'";
	return($datesql);
}
function displayemptyresults(){
	global $hasresults;
	print '<div class="stattblrow">' .
			'<div style="margin:30px;text-align:center;padding:50px">Empty Result Set</div>' .
		'</div>';
	$hasresults=FALSE;
}
if($fromdate!=''){
	$hasfromdate=TRUE;
	if(is_numeric($fromdate))
		$thefromdate=time()-($fromdate*60*60*24);
	else
		$thefromdate=parsedate($fromdate);
	$hastodate=TRUE;
	if($todate=='')
		$hastodate=FALSE;
	elseif(is_numeric($todate))
		$thetodate=time()-($todate*60*60*24);
	else
		$thetodate=parsedate($todate);
	if($hasfromdate && $hastodate){
		if($thefromdate > $thetodate){
			$tmpdate=$thetodate;
			$thetodate=$thefromdate;
			$thefromdate=$tmpdate;
		}
		$thetodate+=86400;
	}
}else{
	$thefromdate=time()-(60*60*24*365);
	$thetodate=time();
}
$numstatus=0;
$sSQL="SELECT statID,statPrivate FROM orderstatus WHERE statPrivate<>'' ORDER BY statID";
$result=ect_query($sSQL) or ect_error();
while($rs=ect_fetch_assoc($result)){
	$allstatus[$numstatus++]=$rs;
}
ect_free_result($result);
$themask='yyyy-mm-dd';
if($admindateformat==1)
	$themask='mm/dd/yyyy';
elseif($admindateformat==2)
	$themask='dd/mm/yyyy';
$ordstate=@$_POST['ordstate'];
$ordcountry=@$_POST['ordcountry'];
$ordstatus=@$_POST['ordstatus'];
$orddiscount=@$_POST['orddiscount'];
$thecat=@$_POST['scat'];
$payprovider=@$_POST['payprovider'];
$stext=getpost('stext');
$stsearch=@$_POST['stsearch'];
?>
<script src="popcalendar.js"></script>
<script>try{languagetext('<?php print @$adminlang?>');}catch(err){}</script>
<h2><?php print $yySalRep?></h2>
		  <form method="post" action="adminorders.php" name="psearchform">
			<div class="orderssearch">
			  <div class="orderssearchrow">
                <div style="text-align:right;width:25%"><input type="button" onclick="popUpCalendar(this, document.forms.psearchform.fromdate, '<?php print $themask?>', 0)" value="<?php print $yyOrdFro?>" /></div>
				<div style="width:25%"><div style="position:relative;display:inline"><input type="text" class="orddatesel" size="14" name="fromdate" value="<?php print $fromdate?>" style="vertical-align:middle" /> <input type="button" onclick="document.forms.psearchform.fromdate.value='<?php print date($admindatestr,time()+($GLOBALS['dateadjust']*60*60))?>'" value="<?php print $yyToday?>" /></div></div>
				<div style="text-align:right;width:25%"><input type="button" onclick="popUpCalendar(this, document.forms.psearchform.todate, '<?php print $themask?>', -205)" value="<?php print $yyOrdTil?>" /></div>
				<div style="width:25%"><div style="position:relative;display:inline"><input type="text" class="orddatesel" size="14" name="todate" value="<?php print $todate?>" style="vertical-align:middle" /> <input type="button" onclick="document.forms.psearchform.todate.value='<?php print date($admindatestr,time()+($GLOBALS['dateadjust']*60*60))?>'" value="<?php print $yyToday?>" /></div></div>
			  </div>
			  <div class="orderssearchrow">
				<div style="text-align:center"><input type="checkbox" name="notsection" value="ON" title="<?php print $yyNot?>" style="vertical-align:middle" <?php if(getpost('notsection')=='ON') print 'checked="checked" '?>/> <?php print $yySection?></div>
				<div style="text-align:center"><input type="checkbox" name="notstatus" value="ON" title="<?php print $yyNot?>" style="vertical-align:middle" <?php if(getpost('notstatus')=='ON') print 'checked="checked" '?>/> <?php print $yyOrdSta?></div>
				<div style="text-align:center"><input type="checkbox" name="notstate" value="ON" title="<?php print $yyNot?>" style="vertical-align:middle" <?php if(getpost('notstate')=='ON') print 'checked="checked" '?>/> <?php print $yyState?></div>
				<div style="text-align:center"><input type="checkbox" name="notcountry" value="ON" title="<?php print $yyNot?>" style="vertical-align:middle" <?php if(getpost('notcountry')=='ON') print 'checked="checked" '?>/> <?php print $yyCountry?></div>
			  </div>
			  <div class="orderssearchrow">
				<div style="text-align:center"><select name="scat[]" size="5" multiple="multiple" style="max-width:200px"><?php
						$sSQL="SELECT sectionID,sectionWorkingName,topSection,rootSection FROM sections " . (@$adminonlysubcats==TRUE ? "WHERE rootSection=1 ORDER BY sectionWorkingName" : "ORDER BY sectionOrder");
						$allcats=ect_query($sSQL) or ect_error();
						$lasttsid=-1;
						$numcats=0;
						while($row=ect_fetch_assoc($allcats))
							$allcatsa[$numcats++]=$row;
						ect_free_result($allcats);
						if($numcats > 0){
							if(@$adminonlysubcats==TRUE){
								for($index=0;$index<$numcats;$index++){
									print '<option value="' . $allcatsa[$index]['sectionID'] . '"';
									if(is_array($thecat)){
										foreach($thecat as $catid){
											if($allcatsa[$index]['sectionID']==$catid) print '  selected';
										}
									}
									print '>' . $allcatsa[$index]['sectionWorkingName'] . "</option>\n";
								}
							}else
								writemenulevel(0,1);
						} ?>
					  </select></div>
				<div style="text-align:center"><select name="ordstatus[]" size="5" multiple="multiple" style="max-width:200px"><?php
						$numstatus=0;
						$sSQL="SELECT statID,statPrivate FROM orderstatus WHERE statPrivate<>'' ORDER BY statID";
						$result=ect_query($sSQL) or ect_error();
						while($rs=ect_fetch_assoc($result)){
							print '<option value="' . $rs['statID'] . '"';
							if(is_array($ordstatus)){
								foreach($ordstatus as $objValue)
									if($objValue==$rs['statID']) print '  selected';
							}
							print ">" . $rs["statPrivate"] . "</option>";
						}
						ect_free_result($result); ?></select></div>
				<div style="text-align:center"><select name="ordstate[]" size="5" multiple="multiple" style="max-width:200px"><?php
						$sSQL='SELECT stateID,stateName,stateAbbrev FROM states WHERE stateCountryID=' . $origCountryID . ' AND stateEnabled=1 ORDER BY stateName';
						$result=ect_query($sSQL) or ect_error();
						while($rs=ect_fetch_assoc($result)){
							print '<option value="' . htmlspecials(@$usestateabbrev==TRUE?$rs['stateAbbrev']:$rs['stateName']) . '"';
							if(is_array($ordstate)){
								foreach($ordstate as $objValue){
									if($objValue==(@$usestateabbrev==TRUE?$rs['stateAbbrev']:$rs['stateName'])) print '  selected';
								}
							}
							print '>' . $rs['stateName'] . "</option>\n";
						}
						ect_free_result($result); ?></select></div>
				<div style="text-align:center"><select name="ordcountry[]" size="5" multiple="multiple" style="max-width:200px"><?php
						$sSQL="SELECT countryID,countryName FROM countries WHERE countryEnabled=1 ORDER BY countryOrder DESC, countryName";
						$result=ect_query($sSQL) or ect_error();
						while($rs=ect_fetch_assoc($result)){
							print '<option value="' . htmlspecials($rs["countryName"]) . '"';
							if(is_array($ordcountry)){
								foreach($ordcountry as $objValue){
									if($objValue==$rs['countryName']) print '  selected';
								}
							}
							print '>' . $rs['countryName'] . "</option>\n";
						}
						ect_free_result($result); ?></select></div>
			  </div>
			  <div class="orderssearchrow">
				<div style="text-align:center;vertical-align:middle">
						<div style="border-bottom:1px solid #D2DDEE;padding:2px">
							<div style="text-align:center"><input type="checkbox" name="notpayprov" value="ON" title="<?php $yyNot?>" style="vertical-align:middle" <?php if(getpost('notpayprov')=='ON') print 'checked="checked" '?>/> <?php print $yyPayMet?>:</div>
						</div>
						<div style="padding:2px">
							<div style="text-align:center"><select name="payprovider[]" size="5" multiple="multiple" style="max-width:200px"><?php
						$sSQL="SELECT payProvID,payProvName FROM payprovider WHERE payProvEnabled=1 ORDER BY payProvOrder";
						$result=ect_query($sSQL) or ect_error();
						while($rs=ect_fetch_assoc($result)){
							print '<option value="' . $rs['payProvID'] . '"';
							if(is_array($payprovider)){
								foreach($payprovider as $objValue){
									if($objValue==$rs['payProvID']) print '  selected';
								}
							}
							print '>' . $rs['payProvName'] . '</option>';
						}
						ect_free_result($result); ?></select></div>
						</div>
				</div>
				<div style="text-align:center;vertical-align:middle">
						<div style="border-bottom:1px solid #D2DDEE;padding:2px">
							<div style="text-align:center"><input type="checkbox" name="notdiscount" value="ON" title="<?php $yyNot?>" style="vertical-align:middle" <?php if(getpost('notdiscount')=='ON') print 'checked="checked" '?>/> <?php print $yyDisco?>:</div>
						</div>
						<div style="padding:2px">
							<div style="text-align:center"><select name="orddiscount[]" size="5" multiple="multiple" style="max-width:200px"><?php
						$sSQL="SELECT cpnID,cpnWorkingName FROM coupons ORDER BY cpnWorkingName";
						$result=ect_query($sSQL) or ect_error();
						while($rs=ect_fetch_assoc($result)){
							print '<option value="' . $rs['cpnID'] . '"';
							if(is_array($orddiscount)){
								foreach($orddiscount as $objValue){
									if($objValue==$rs['cpnID']) print '  selected';
								}
							}
							print '>' . $rs['cpnWorkingName'] . '</option>';
						}
						ect_free_result($result); ?></select></div>
						</div>
				</div>
				<div style="text-align:center;vertical-align:middle">
					<div style="text-align:center;padding:5px"><input type="text" style="width:180px" name="stext" value="<?php print htmlspecials($stext)?>" placeholder="<?php print $yySeaTxt?>" /></div>
					<div style="text-align:center;padding:5px"><select name="stype" size="1" style="width:190px">
						<option value=""><?php print $yySearch.' '.$yySrchAl?></option>
						<option value="any"<?php if(getrequest("stype")=="any") print ' selected'?>><?php print $yySearch.' '.$yySrchAn?></option>
						<option value="exact"<?php if(getrequest("stype")=="exact") print ' selected'?>><?php print $yySearch.' '.$yySrchEx?></option>
						</select></div> 
					<div style="text-align:center;padding:5px">
				<input type="checkbox" name="stsearch[]" value="cartprodid" title="<?php print $yyPrId?>" <?php if(is_array($stsearch) && in_array('cartprodid', $stsearch)!==FALSE) print 'checked="checked" '?>/> <?php print $yyID?> 
				<input type="checkbox" name="stsearch[]" value="cartprodname" title="<?php print $yyPrName?>" <?php if(is_array($stsearch) && in_array('cartprodname', $stsearch)!==FALSE) print 'checked="checked" '?>/> <?php print $yyPrNam?> 
				<input type="checkbox" name="stsearch[]" value="ordaffiliate" title="<?php print $yyAffili?>" <?php if(is_array($stsearch) && in_array('ordaffiliate', $stsearch)!==FALSE) print 'checked="checked" '?>/> <?php print $yyAffili?>
					</div>
				</div>
				<div style="text-align:center;vertical-align:middle">
					<div style="text-align:center;padding:5px">
						<select name="numresults" id="numresults" size="1" style="vertical-align:middle">
						<option value="">Display Top 100 Sales</option>
						<option value="200"<?php if(getpost('numresults')=='200') print ' selected'?>>Display Top 200 Sales</option>
						<option value="300"<?php if(getpost('numresults')=='300') print ' selected'?>>Display Top 300 Sales</option>
						<option value="400"<?php if(getpost('numresults')=='400') print ' selected'?>>Display Top 400 Sales</option>
						<option value="500"<?php if(getpost('numresults')=='500') print ' selected'?>>Display Top 500 Sales</option>
						<option value="all"<?php if(getpost('numresults')=='all') print ' selected'?>>Display All Sales</option></select>
					</div>
					<div style="text-align:center;padding:5px;font-weight:bold">Generate Results</div>
					<div style="text-align:center;padding:5px">
						<select name="grouping" size="1" style="vertical-align:middle" onchange="document.getElementById('numresults').disabled=this.selectedIndex!=0&&this.selectedIndex!=1&&this.selectedIndex!=2&&this.selectedIndex!=3">
						<option value="4">Totals</option>
						<option value="6"<?php if(getpost("grouping")=='6') print ' selected'?>>Category Totals</option>
						<option value="7"<?php if(getpost("grouping")=='7') print ' selected'?>>Stock Totals</option>
						<option value="8"<?php if(getpost("grouping")=='8') print ' selected'?>>Repeat Customers</option>
						<option value="5"<?php if(getpost('grouping')=='5') print ' selected'?>><?php print 'Graph By Day'?></option>
						<option value="1"<?php if(getpost('grouping')=='1') print ' selected'?>><?php print $yyGrByWk?></option>
						<option value="2"<?php if(getpost('grouping')=='2') print ' selected'?>><?php print $yyGrByMo?></option>
						<option value="3"<?php if(getpost('grouping')=='3') print ' selected'?>><?php print $yyGrByYr?></option></select>
						<input type="button" value="Stats" onclick="document.forms.psearchform.action='adminstats.php';document.forms.psearchform.submit();" />
					</div>
				</div>
			  </div>
			</div>
		  </form>
<?php
$hascategory=FALSE;
$whereclause='WHERE cartCompleted=1 ';
if(is_array($ordstatus)) $whereclause.='AND ' . (getpost('notstatus')=='ON' ? 'NOT ' : '') . "(ordStatus IN (" . implode(',', $ordstatus) . ")) "; else $whereclause.='AND ordStatus<>0 AND ordStatus<>1 ';
if(is_array($payprovider)) $whereclause.='AND ' . (getpost('notpayprov')=='ON' ? 'NOT ' : '') . "(ordPayProvider IN (" . implode(',', $payprovider) . ")) ";
if(is_array($ordstate)) $whereclause.='AND ' . (getpost('notstate')=='ON' ? 'NOT ' : '') . "(ordState IN ('" . implode("','", $ordstate) . "')) ";
if(is_array($ordcountry)) $whereclause.='AND ' . (getpost('notcountry')=='ON' ? 'NOT ' : '') . "(ordCountry IN ('" . implode("','",$ordcountry) . "')) ";
if(is_array($orddiscount)) $whereclause.='AND ' . (getpost('notdiscount')=='ON' ? 'NOT ' : '') . "(cpaCpnID IN (" . implode(',', $orddiscount) . ")) ";
$orderclause=str_replace('cartCompleted=1 AND ', '', $whereclause);
if(getpost('stext')!='' && is_array(@$_POST['stsearch'])){
	$sText=escape_string($stext);
	$aText=explode(' ', $sText);
	$aFields=$stsearch;
	if(getpost('stype')=='exact'){
		$whereclause.='AND (';
		$rowcounter=0;
		$arrelms=count($aFields);
		foreach($aFields as $thefield){
			if(is_array($thefield))$thefield=$thefield[0];
			$whereclause.=$thefield . " LIKE '%" . $sText . "%' ";
			if($thefield=='ordaffiliate') $orderclause.=' AND ' . $thefield . " LIKE '%" . $sText . "%' ";
			if(++$rowcounter < $arrelms) $whereclause.='OR ';
		}
		$whereclause.=') ';
	}else{
		$sJoin='AND ';
		if(getpost('stype')=='any') $sJoin='OR ';
		$whereclause.='AND (';
		$whereand=' AND ';
		$index=0;
		$numFields=count($aFields);
		foreach($aFields as $thefield){
			if(is_array($thefield))$thefield=$thefield[0];
			$whereclause.='(';
			$rowcounter=0;
			$arrelms=count($aText);
			foreach($aText as $theopt){
				if(is_array($theopt))$theopt=$theopt[0];
				$whereclause.=$thefield . " LIKE '%".$theopt."%' ";
				if($thefield=='ordaffiliate') $orderclause.=' AND ' . $thefield . " LIKE '%" . $sText . "%' ";
				if(++$rowcounter < $arrelms) $whereclause.=$sJoin;
			}
			$whereclause.=') ';
			if(++$index < $numFields) $whereclause.='OR ';
		}
		$whereclause.=') ';
	}
}
if(is_array($thecat)){
	$catlist=$addcomma='';
	foreach($thecat as $catid){
		$catlist.=$addcomma . $catid;
		$addcomma=',';
	}
	$sectionids=getsectionids($catlist, TRUE);
	if($sectionids!='') $whereclause.='AND ' . (getpost('notsection')=='ON' ? 'NOT ' : '') . "(products.pSection IN (" . $sectionids . ")) ";
	$hascategory=TRUE;
}
if(getpost('grouping')=='1' || getpost('grouping')=='2' || getpost('grouping')=='3' || getpost('grouping')=='5'){
	$success=TRUE;
	$dateSQL='SELECT ordDate FROM products INNER JOIN cart ON products.pID=cart.cartProdID INNER JOIN orders ON cart.cartOrderID=orders.ordID ' . ($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'');
	$dateSQL.=$whereclause;
	$result=ect_query($dateSQL . 'ORDER BY ordDate LIMIT 0,1') or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$minfromdate=strtotime($rs['ordDate']);
		if(! $hasfromdate || $minfromdate > $thefromdate){
			$thefromdate=$minfromdate;
			$hasfromdate=TRUE;
		}
	}else
		$success=FALSE;
	ect_free_result($result);
	$result=ect_query($dateSQL . 'ORDER BY ordDate DESC LIMIT 0,1') or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$maxtodate=strtotime($rs['ordDate']);
		if(! $hastodate || $maxtodate < $thetodate){
			$thetodate=$maxtodate;
			$hastodate=TRUE;
		}
	}else
		$success=FALSE;
	ect_free_result($result);
	// print "Dates: " . date("Y-m-d", $thefromdate) . ", " . date("Y-m-d", $thetodate) . "<br>";
	if($success){
		if(getpost('grouping')=='1'){ // week
			$dotw=(int)date('w',$thefromdate);
			if($dotw==0) $dotw=7;
			$thefromdate -= ($dotw-1)*86400;
		}elseif(getpost('grouping')=='2'){ // month
			$thefromdate=mktime(0,0,0,date('m',$thefromdate),1,date('Y',$thefromdate));
		}elseif(getpost('grouping')=='5'){ // day
			$thefromdate=mktime(0,0,0,date('m',$thefromdate),date('d',$thefromdate),date('Y',$thefromdate));
		}else{
			$thefromdate=mktime(0,0,0,1,1,date('Y',$thefromdate));
		}
		$thetodate=$thetodate+86400;
	}
	// print "Dates: " . date("Y-m-d", $thefromdate) . ", " . date("Y-m-d", $thetodate) . "<br>";
	if($thefromdate > $thetodate) $success=FALSE;
	print '<div style="margin:30px"><h2>'.$yySalGra.'</h2></div>';
	if(! $success){
		print '<div style="margin:30px;text-align:center">Empty Result Set</div>';
	}else{
		$maxtotal=$maxorders=0;
		$rowcounter=0;
		// $sSQL="SELECT SUM(cartQuantity) AS numorders,SUM(cartProdPrice*cartQuantity) AS theordtot,SUM(ordHandling) AS tothandling,SUM(ordStateTax) AS totstatetax,SUM(ordCountryTax) AS totcountrytax,SUM(ordHSTTax) AS tothsttax,SUM(ordDiscount) AS totdiscount, SUM(ordShipping) AS totshipping ";
		$sSQL="SELECT SUM(cartQuantity) AS numorders,SUM(cartProdPrice*cartQuantity) AS theordtot ";
		$sSQL.="FROM products RIGHT JOIN cart ON products.pID=cart.cartProdID INNER JOIN orders ON cart.cartOrderID=orders.ordID " . ($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'');
		$sSQL.=$whereclause;
		
		$sSQLopts='SELECT SUM(coPriceDiff*cartQuantity) AS theordtot ';
		$sSQLopts.='FROM cartoptions INNER JOIN (cart LEFT OUTER JOIN products ON cart.cartProdId=products.pID) ON cartoptions.coCartID=cart.cartID INNER JOIN orders ON cart.cartOrderID=orders.ordID ' . ($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'');
		$sSQLopts.=$whereclause;
		// print '<div>' . $sSQL . '<br />' . $sSQLopts . '</div>';
		$themaxdate=$thetodate;
		while($thefromdate<$themaxdate){
			if(getpost('grouping')=='1') // week
				$thetodate=$thefromdate + (86400 * 7);
			elseif(getpost('grouping')=='2') // month
				$thetodate=mktime(0,0,0,date('m',$thefromdate)+1,date('d',$thefromdate),date('Y',$thefromdate));
			elseif(getpost('grouping')=='5') // day
				$thetodate=mktime(0,0,0,date('m',$thefromdate),date('d',$thefromdate)+1,date('Y',$thefromdate));
			else
				$thetodate=mktime(0,0,0,date('m',$thefromdate),date('d',$thefromdate),date('Y',$thefromdate)+1);
			$result=ect_query($sSQL . getdatesql('cartDateAdded')) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if($rs['numorders']==0){
					$outputvals[$rowcounter][0]=$thefromdate;
					$outputvals[$rowcounter][1]=0;
					$outputvals[$rowcounter][2]=0;
				}else{
					// $thetot=($rs['theordtot']+$rs['totshipping']+$rs['tothandling']+$rs['totstatetax']+$rs['totcountrytax']+$rs['tothsttax'])-$rs['totdiscount'];
					$thetot=$rs['theordtot'];
					$outputvals[$rowcounter][0]=$thefromdate;
					$outputvals[$rowcounter][1]=$rs['numorders'];
					$outputvals[$rowcounter][2]=$thetot;
				}
			}
			ect_free_result($result);
		
			$result=ect_query($sSQLopts . getdatesql('cartDateAdded')) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if($rs['theordtot']==0){
				}else{
					$thetot=$rs['theordtot'];
					$outputvals[$rowcounter][2]+=$thetot;
				}
			}
			ect_free_result($result);
			if($outputvals[$rowcounter][1] > $maxorders) $maxorders=$outputvals[$rowcounter][1];
			if($outputvals[$rowcounter][2] > $maxtotal) $maxtotal=$outputvals[$rowcounter][2];
			$thefromdate=$thetodate;
			$rowcounter++;
		}
		$statdateformat='M j, Y';
		if(getpost('grouping')=='2'){
			$timediv='Monthly';
			$statdateformat='M Y';
		}elseif(getpost('grouping')=='1')
			$timediv='Weekly';
		elseif(getpost('grouping')=='5')
			$timediv='Daily';
		else{
			$timediv='Yearly';
			$statdateformat='Y';
		}
?>
			<div style="padding-top:20px">
<?php
	$origmax=$maxtotal;
	$divisor=1;
	if($maxtotal>0){
		while($maxtotal/$divisor>10){
			$divisor*=10;
		}
	}
	if($maxtotal!=(int)($maxtotal/$divisor)*$divisor) $maxtotal=(int)(($maxtotal/$divisor)+1)*$divisor;
	if($maxtotal/$divisor<3) $divisor/=2;
	while($maxtotal-$divisor>$origmax) $maxtotal-=$divisor;
	if($maxtotal/$divisor<3) $divisor/=2;
?>
<svg id="svgelement" style="margin:auto;display:block;font-family:Arial,Helvetica,sans-serif;font-size:12px;width:90%;height:400px" viewBox="0 0 100 100" preserveAspectRatio="none">
	<text x="10" y="5" style="display:none;font-size:0.4em"><?php print $timediv." Sales: " . date($statdateformat,$outputvals[0][0]) . ' to ' . date($statdateformat,$outputvals[$rowcounter-1][0])?></text>
	<text x="10" y="95" style="display:none;font-size:0.2em;text-anchor:middle"><?php print date($statdateformat,$outputvals[0][0])?></text>
	<text x="90" y="95" style="display:none;font-size:0.2em;text-anchor:middle"><?php print date($statdateformat,$outputvals[$rowcounter-1][0])?></text>
<?php
	$tempdivisor=$divisor;
	while($tempdivisor<=$maxtotal){
		$thisy=10+(int)(($tempdivisor / $maxtotal) * 80);
		print '<text x="8.5" y="'.(101-$thisy).'" style="display:none;font-size:0.2em;text-anchor:end">'.FormatCurrencyZeroDP($tempdivisor)."</text>\r\n";
		$tempdivisor+=$divisor;
	}
?>
	<g transform="translate(0,100) scale(1,-1)">
		<rect stroke="#c0c8d0" fill="none" x="10" y="10" width="80" height="80" vector-effect="non-scaling-stroke" />
<?php	$markers='';
		print '<polygon style="fill:#506070" points="10,10 ';
		$onlyyears=$rowcounter>100;
		for($index=0; $index < $rowcounter; $index++){
			$pixelcolor='c0c8d0';
			$isyear=FALSE;
			if($rowcounter==1) $thisx=10; else $thisx=round(10+(($index/($rowcounter-1))*80),2);
			if(getpost('grouping')=='1'){ // week
				if(date('W', $outputvals[$index][0])=='1'){ $pixelcolor='FF6070'; $isyear=TRUE; }
			}elseif(getpost('grouping')=='2'){ // month
				if(date('m', $outputvals[$index][0])=='1'){ $pixelcolor='FF6070'; $isyear=TRUE; }
			}
			print $thisx.','.(10+(int)(($outputvals[$index][2] / $maxtotal) * 80)).' ';
			if($index!=0 && $index!=$rowcounter-1){
				if($isyear || $onlyyears=FALSE) $markers.='<path style="stroke:#'.$pixelcolor.';vector-effect:non-scaling-stroke" d="M'.$thisx.',8 L'.$thisx.',10" />'."\r\n";
			}
		}
		if($rowcounter==1) print '90,'.(10+(int)(($outputvals[0][2] / $maxtotal) * 80)).' 90'; else print round(10+((($index-1)/($rowcounter-1))*80),2);
		print ',10" />' . "\r\n";
		print $markers;
		$tempdivisor=$divisor;
		while($tempdivisor<=$maxtotal){
			$thisy=10+(int)(($tempdivisor / $maxtotal) * 80);
			print '<path style="stroke:#c0c8d0;vector-effect:non-scaling-stroke" d="M9,'.$thisy.' L10,'.$thisy.'" />'."\r\n";
			$tempdivisor+=$divisor;
		}
?>
	</g>
</svg>
			</div>
			
			<div style="padding-top:20px">
<?php
	$origmax=$maxorders;
	$divisor=1;
	if($maxorders>0){
		while($maxorders/$divisor>10){
			$divisor*=10;
		}
	}
	if($maxorders!=(int)($maxorders/$divisor)*$divisor) $maxorders=(int)(($maxorders/$divisor)+1)*$divisor;
	if($maxorders/$divisor<3) $divisor/=2;
	while($maxorders-$divisor>$origmax) $maxorders-=$divisor;
	if($maxtotal/$divisor<3) $divisor/=2;
?>
<svg id="svgelementorders" style="margin:auto;display:block;font-family:Arial,Helvetica,sans-serif;font-size:12px;width:90%;height:400px" viewBox="0 0 100 100" preserveAspectRatio="none">
	<text x="10" y="5" style="display:none;font-size:0.4em"><?php print $timediv.' Orders: ' . date($statdateformat,$outputvals[0][0]) . ' to ' . date($statdateformat,$outputvals[$rowcounter-1][0])?></text>
	<text x="10" y="95" style="display:none;font-size:0.2em;text-anchor:middle"><?php print date($statdateformat,$outputvals[0][0])?></text>
	<text x="90" y="95" style="display:none;font-size:0.2em;text-anchor:middle"><?php print date($statdateformat,$outputvals[$rowcounter-1][0])?></text>
<?php
	$tempdivisor=$divisor;
	while($tempdivisor<=$maxorders){
		$thisy=10+(int)(($tempdivisor / $maxorders) * 80);
		print '<text x="8.5" y="'.(101-$thisy).'" style="display:none;font-size:0.2em;text-anchor:end">'.$tempdivisor."</text>\r\n";
		$tempdivisor+=$divisor;
	}
?>
	<g transform="translate(0,100) scale(1,-1)">
		<rect stroke="#c0c8d0" fill="none" x="10" y="10" width="80" height="80" vector-effect="non-scaling-stroke" />
<?php	$markers='';
		print '<polygon style="fill:#506070" points="10,10 ';
		$onlyyears=$rowcounter>100;
		for($index=0; $index < $rowcounter; $index++){
			$pixelcolor='c0c8d0';
			$isyear=FALSE;
			if($rowcounter==1) $thisx=10; else $thisx=round(10+(($index/($rowcounter-1))*80),2);
			if(getpost('grouping')=='1'){ // week
				if(date('W', $outputvals[$index][0])=='1'){ $pixelcolor='FF6070'; $isyear=TRUE; }
			}elseif(getpost('grouping')=='2'){ // month
				if(date('m', $outputvals[$index][0])=='1'){ $pixelcolor='FF6070'; $isyear=TRUE; }
			}
			print $thisx.','.(10+(int)(($outputvals[$index][1] / $maxorders) * 80)).' ';
			if($index!=0 && $index!=$rowcounter-1){
				if($isyear || $onlyyears=FALSE) $markers.='<path style="stroke:#'.$pixelcolor.';vector-effect:non-scaling-stroke" d="M'.$thisx.',8 L'.$thisx.',10" />'."\r\n";
			}
		}
		if($rowcounter==1) print '90,'.(10+(int)(($outputvals[0][1] / $maxorders) * 80)).' 90'; else print round(10+((($index-1)/($rowcounter-1))*80),2);
		print ',10" />' . "\r\n";
		print $markers;
		$tempdivisor=$divisor;
		while($tempdivisor<=$maxorders){
			$thisy=10+(int)(($tempdivisor / $maxorders) * 80);
			print '<path style="stroke:#c0c8d0;vector-effect:non-scaling-stroke" d="M9,'.$thisy.' L10,'.$thisy.'" />'."\r\n";
			$tempdivisor+=$divisor;
		}
?>
	</g>
</svg>
			</div>
			
<script>
window.onresize = svgresized;
function svgresized(){
	var svgelem=document.getElementById("svgelement");
    var boundingwidth=svgelem.getBoundingClientRect().width;
	var boundingheight=svgelem.getBoundingClientRect().height;
	var xscale=400.0 / boundingwidth;
	var textelems=svgelem.getElementsByTagName("text");
	for (var svgi=0; svgi<textelems.length; svgi++) {
		var txtxpos=textelems[svgi].getAttribute('x');
		textelems[svgi].setAttribute('transform',"scale("+xscale+",1) translate("+(txtxpos*((1/xscale)-1))+",0)");
		textelems[svgi].style.display='';
	}
	
	var svgelem=document.getElementById("svgelementorders");
    var boundingwidth=svgelem.getBoundingClientRect().width;
	var boundingheight=svgelem.getBoundingClientRect().height;
	var xscale=400.0 / boundingwidth;
	var textelems=svgelem.getElementsByTagName("text");
	for (var svgi=0; svgi<textelems.length; svgi++) {
		var txtxpos=textelems[svgi].getAttribute('x');
		textelems[svgi].setAttribute('transform',"scale("+xscale+",1) translate("+(txtxpos*((1/xscale)-1))+",0)");
		textelems[svgi].style.display='';
	}
}
svgresized();
</script>
<?php
	}
}elseif(getpost("grouping")=="4"){
	$hasresults=TRUE;
	$whereclause.=getdatesql('cartDateAdded');
	$orderclause.=getdatesql('ordDate');
?>
			<div style="padding-top:20px">
			  <h2>Order Results (Not limited by product / section)</h2>
<?php
	$sSQL="SELECT COUNT(ordID) AS numorders,SUM(ordTotal) AS theordtot,SUM(ordHandling) AS tothandling,SUM(ordStateTax) AS totstatetax,SUM(ordCountryTax) AS totcountrytax,SUM(ordHSTTax) AS tothsttax,SUM(ordDiscount) AS totdiscount, SUM(ordShipping) AS totshipping ";
	$sSQL.="FROM orders " . ($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'');
	$sSQL.=$orderclause;
	// print '<div>' . $sSQL . '</div>';
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		print '<div class="stattbl">';
		if($rs['numorders']==0){
			$hasresults=FALSE;
			displayemptyresults();
		}else{
			print '<div class="stattblrow">' .
					'<div>'.$yyTotOrd.'</div><div>'.$xxOrdTot.'</div><div>'.$xxShippg.'</div><div>'.$xxHndlg.'</div><div>'.$xxDscnts.'</div><div>'.$xxStaTax.'</div>' . ($origCountryID==2?'<div>'.$xxHST.'</div>':'') . '<div>'.$xxCntTax.'</div><div>'.$xxGndTot.'</div>' .
				'</div>';
			print '<div class="stattblrow">' .
					'<div>' . $rs['numorders'] . '</div><div>' . FormatEuroCurrency($rs['theordtot']) . '</div><div>' . FormatEuroCurrency($rs['totshipping']) . '</div><div>' . FormatEuroCurrency($rs['tothandling']) . '</div><div style="color:red">' . FormatEuroCurrency($rs['totdiscount']) . '</div><div>' . FormatEuroCurrency($rs['totstatetax']) . '</div>' . ($origCountryID==2?'<div>' . FormatEuroCurrency($rs['tothsttax']) . '</div>':'') . '<div>' . FormatEuroCurrency($rs['totcountrytax']) . '</div><div>' . FormatEuroCurrency(($rs['theordtot']+$rs['totshipping']+$rs['tothandling']+$rs['totstatetax']+$rs['totcountrytax']+$rs['tothsttax'])-$rs['totdiscount']) . '</div>' .
				'</div>';
		}
		print '</div>'; ?>
		<div style="margin-top:10px">
			<a download="ectorderresults.csv" href="data:application/octet-stream,<?php
				print $yyTotOrd.'%2C'.$xxOrdTot.'%2C'.$xxShippg.'%2C'.$xxHndlg.'%2C'.$xxDscnts.'%2C'.$xxStaTax. ($origCountryID==2?'%2C'.$xxHST:'') .'%2C'.$xxCntTax.'%2C'.$xxGndTot.'%0A';
				print $rs['numorders'] .'%2C'. round($rs['theordtot'],2) .'%2C'. round($rs['totshipping'],2) .'%2C'. round($rs['tothandling'],2) .'%2C'. round($rs['totdiscount'],2) .'%2C'. round($rs['totstatetax'],2) . ($origCountryID==2?'%2C' . round($rs['tothsttax'],2):'') .'%2C'. round($rs['totcountrytax'],2) .'%2C'. round(($rs['theordtot']+$rs['totshipping']+$rs['tothandling']+$rs['totstatetax']+$rs['totcountrytax']+$rs['tothsttax'])-$rs['totdiscount'],2);
			?>">Click Here For CSV Download</a>
		</div>
<?php
	}else
		$hasresults=FALSE;
	ect_free_result($result);
?>
			</div>
<?php
	flush();
	$sSQLopts='SELECT SUM(coPriceDiff*cartQuantity) AS theordtot ';
	if($hascategory)
		$sSQLopts.='FROM cartoptions INNER JOIN cart ON cartoptions.coCartID=cart.cartID LEFT OUTER JOIN products ON cart.cartProdId=products.pID INNER JOIN orders ON cart.cartOrderID=orders.ordID ' . ($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'');
	else
		$sSQLopts.='FROM cartoptions INNER JOIN cart ON cartoptions.coCartID=cart.cartID INNER JOIN orders ON cart.cartOrderID=orders.ordID ' . ($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'');
	$sSQLopts.=$whereclause;
	$totopts=0;
	$result=ect_query($sSQLopts) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		if(is_numeric($rs['theordtot'])) $totopts=$rs['theordtot'];
	}
	ect_free_result($result);
	
	$sSQL="SELECT SUM(cartQuantity) AS numorders,SUM(cartProdPrice*cartQuantity) AS theordtot ";
	if($hascategory)
		$sSQL.="FROM products INNER JOIN cart ON products.pID=cart.cartProdID INNER JOIN orders ON cart.cartOrderID=orders.ordID " . ($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'');
	else
		$sSQL.="FROM cart INNER JOIN orders ON cart.cartOrderID=orders.ordID " . ($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'');
	$sSQL.=$whereclause;
	// print '<div>' . $sSQL . '</div>';
	if($hasresults){
?>
			<div style="padding-top:20px">
			  <h2><?php print $yySalRes?></h2>
<?php
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			print '<div class="stattbl">';
			if($rs['numorders']==0)
				displayemptyresults();
			else{
				print '<div class="stattblrow"><div>'.$yyTotItm.'</div><div>'.$yyItmTot.'</div></div>';
				print '<div class="stattblrow"><div>' . $rs['numorders'] . '</div><div>' . FormatEuroCurrency($rs['theordtot']+$totopts) . '</div></div>';
			}
			print '</div>';
?>
			<div style="margin-top:10px">
				<a download="ectsalesresults.csv" href="data:application/octet-stream,<?php
					print $yyTotItm.'%2C'.$yyItmTot.'%0A';
					print $rs['numorders'] .'%2C'. round($rs['theordtot']+$totopts,2);
				?>">Click Here For CSV Download</a>
			</div>
<?php	}
		ect_free_result($result);
?>
			</div>
<?php
	flush();
	}
	if($hasresults){
		print '<div style="overflow:auto">';
		for($index2=1; $index2<=2; $index2++){
			$sSQL="SELECT SUM(cartQuantity) AS thecount,SUM((cartProdPrice+IFNULL((SELECT SUM(coPriceDiff) FROM cartoptions WHERE coCartID=cartID),0))*cartQuantity) AS theordtot,cartProdID ";
			if($hascategory)
				$sSQL.="FROM products INNER JOIN cart ON products.pID=cart.cartProdID INNER JOIN orders ON cart.cartOrderID=orders.ordID " . ($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'');
			else
				$sSQL.="FROM cart INNER JOIN orders ON cart.cartOrderID=orders.ordID " . ($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'');
			$sSQL.=$whereclause . ' GROUP BY cartProdID ';
			if($index2==1)
				$sSQL.='ORDER BY thecount DESC';
			else
				$sSQL.='ORDER BY theordtot DESC';
			if(getpost("numresults")!="all") $sSQL.=" LIMIT 0,".(getpost("numresults")==""?100:getpost("numresults"));
			// print '<div>' . $sSQL . '</div>';
?>
			<div style="padding-top:20px;width:49%;min-width:800px;float:left;margin-right:1%">
			  <h2><?php
					print (getpost("numresults")!="all"?replace($yyTopSal,"100",getpost("numresults")):replace($yyTopSal,"100",""));
					if($index2==1) print ' By Quantity'; else print ' By Amount'; ?></h2>
<?php
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0){
			print '<div class="stattbl">';
			print '<div class="stattblrow"><div>'.$yyPrId.'</div><div>'.$yyPrName.'</div><div>'.replace($yyTotSal,' ','&nbsp;').'</div><div>'.$yyAmount.'</div></div>';
			$dldata='';
			while($rs=ect_fetch_assoc($result)){
				$prodname='';
				$sSQL="SELECT pName FROM products WHERE pID='" . escape_string($rs['cartProdID']) . "'";
				$result2=ect_query($sSQL) or ect_error();
				if($rs2=ect_fetch_assoc($result2)) $prodname=$rs2['pName'];
				if($prodname==''){
					$sSQL="SELECT cartProdName FROM cart WHERE cartProdID='" . escape_string($rs['cartProdID']) . "' ORDER BY cartID DESC LIMIT 0,1";
					$result2=ect_query($sSQL) or ect_error();
					if($rs2=ect_fetch_assoc($result2)) $prodname=$rs2['cartProdName'];
				}
				print '<div class="stattblrow"><div>' . $rs['cartProdID'] . '</div><div>' . $prodname . '</div><div>' . $rs['thecount'] . '</div><div style="text-align:right">' . number_format($rs['theordtot'], $GLOBALS['currDecimals'],'.','') . '</div></div>';
				$dldata.=$rs['cartProdID'] . '%2C' . rawurlencode('"' . str_replace('"','""',$prodname) . '"') . '%2C' . $rs['thecount'] . '%2C' . round($rs['theordtot'],2) . '%0A';
			}
			print '</div>'; ?>
			<div style="margin-top:10px">
				<a download="ectstatsby<?php print ($index2==1?'quantity':'amount')?>.csv" href="data:application/octet-stream,<?php
					print $yyPrId.'%2C'.$yyPrName.'%2C'.$yyTotSal.'%2C'.$yyAmount.'%0A';
					print $dldata;
				?>">Click Here For CSV Download</a>
			</div>
<?php	}else
			displayemptyresults();
		ect_free_result($result);
?>
			</div>
<?php
	}
	flush();
	print '</div>'; ?>
			<div style="padding-top:20px">
			  <h2><?php print $yyTopCou?></h2>
<?php
	$sSQLopts='SELECT SUM(coPriceDiff*cartQuantity) AS theordtot,ordCountry ';
	$sSQLopts.='FROM cartoptions INNER JOIN cart ON cartoptions.coCartID=cart.cartID LEFT OUTER JOIN products ON cart.cartProdId=products.pID INNER JOIN orders ON cart.cartOrderID=orders.ordID ' . ($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'');
	$sSQLopts.=$whereclause . ' GROUP BY ordCountry';
	$numalloptions=0;
	$alloptions=[];
	$result=ect_query($sSQLopts) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$alloptions[$numalloptions++]=$rs;
	}
	ect_free_result($result);

	$sSQL="SELECT SUM(cartQuantity) AS thecount,SUM(cartProdPrice*cartQuantity) AS theordtot,ordCountry ";
	$sSQL.="FROM products INNER JOIN cart ON products.pID=cart.cartProdID INNER JOIN orders ON cart.cartOrderID=orders.ordID " . ($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'');
	$sSQL.=$whereclause . ' GROUP BY ordCountry ORDER BY thecount DESC LIMIT 0,100';
	// print '<div>' . $sSQL . '</div>';
	$result=ect_query($sSQL) or ect_error();
	if(ect_num_rows($result)>0){
		print '<div class="stattbl">';
		print '<div class="stattblrow"><div>'.$yyCntNam.'</div><div>' . $yyTotSal . '</div><div>' . $yyAmount . '</div></div>';
		$dldata='';
		while($rs=ect_fetch_assoc($result)){
			$addoptions=0;
			if($numalloptions > 0){
				foreach($alloptions as $key => $val){
					if($val['ordCountry']==$rs['ordCountry']){
						$addoptions=$val['theordtot'];
						break;
					}
				}
			}
			print '<div class="stattblrow"><div>' . $rs['ordCountry'] . '</div><div>' . $rs['thecount'] . '</div><div style="text-align:right">' . number_format($rs['theordtot']+$addoptions, $GLOBALS['currDecimals'],'.','') . '</div></div>';
			$dldata.=$rs['ordCountry'] . '%2C' . $rs['thecount'] . '%2C' . round($rs['theordtot']+$addoptions,2) . '%0A';
		}
		print '</div>'; ?>
		<div style="margin-top:10px">
			<a download="ectcountrystats.csv" href="data:application/octet-stream,<?php
				print $yyCntNam.'%2C'.$yyTotSal.'%2C'.$yyAmount.'%0A';
				print $dldata;
			?>">Click Here For CSV Download</a>
		</div>
<?php
	}
	ect_free_result($result);
?>
            </div>
<?php
	}
}elseif(getpost("grouping")=="6"){
	$hasresults=TRUE;
	if($hasresults){
		print '<div style="overflow:auto">';
		for($index2=1; $index2<=2; $index2++){
			$sSQL="SELECT SUM(cartQuantity) AS thecount,SUM((cartProdPrice+IFNULL((SELECT SUM(coPriceDiff) FROM cartoptions WHERE coCartID=cartID),0))*cartQuantity) AS theordtot,pSection ";
			$sSQL.="FROM products INNER JOIN cart ON products.pID=cart.cartProdID INNER JOIN orders ON cart.cartOrderID=orders.ordID " . ($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'');
			$sSQL.=$whereclause . getdatesql('ordDate') . ' GROUP BY pSection ';
			if($index2==1)
				$sSQL.='ORDER BY thecount DESC';
			else
				$sSQL.='ORDER BY theordtot DESC';
			if(getpost("numresults")!="all") $sSQL.=" LIMIT 0,".(getpost("numresults")==""?100:getpost("numresults"));
			// print '<div>' . $sSQL . '</div>';
?>
			<div style="padding-top:20px;width:49%;min-width:800px;float:left;margin-right:1%;margin-bottom:20px">
			  <h2><?php
					print (getpost("numresults")!="all"?replace($yyTopSal,"100",getpost("numresults")):replace($yyTopSal,"100",""));
					if($index2==1) print ' By Quantity'; else print ' By Amount'; ?></h2>
<?php
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0){
				print '<div class="stattbl">';
				print '<div class="stattblrow"><div>'.$yyID.'</div><div>'.$yyCatNam.'</div><div>'.replace($yyTotSal,' ','&nbsp;').'</div><div>'.$yyAmount.'</div></div>';
				$dldata='';
				while($rs=ect_fetch_assoc($result)){
					$prodname='*undefined*';
					$sSQL="SELECT sectionName FROM sections WHERE sectionID='" . escape_string($rs['pSection']) . "'";
					$result2=ect_query($sSQL) or ect_error();
					if($rs2=ect_fetch_assoc($result2)) $prodname=$rs2['sectionName'];
					print '<div class="stattblrow"><div>' . $rs['pSection'] . '</div><div>' . $prodname . '</div><div>' . $rs['thecount'] . '</div><div style="text-align:right">' . number_format($rs['theordtot'], $GLOBALS['currDecimals'],'.','') . '</div></div>';
					$dldata.=$rs['pSection'] . '%2C' . rawurlencode('"' . str_replace('"','""',$prodname) . '"') . '%2C' . $rs['thecount'] . '%2C' . round($rs['theordtot'],2) . '%0A';
				}
				print '</div>'; ?>
				<div style="margin-top:10px">
					<a download="ectstatsby<?php print ($index2==1?'quantity':'amount')?>.csv" href="data:application/octet-stream,<?php
						print 'ID%2C'.$yyCatNam.'%2C'.$yyTotSal.'%2C'.$yyAmount.'%0A';
						print $dldata;
					?>">Click Here For CSV Download</a>
				</div>
<?php		}else
				displayemptyresults();
			ect_free_result($result);
?>
			</div>
<?php	}
	}
}elseif(getpost("grouping")=="7"){
	$manufacturer_cache=[];
	$whereand='WHERE ';
	$whereclause='';
	if(@$sectionids!=''){
		$sSQL.='WHERE ' . (getpost('notsection')=='ON' ? 'NOT ' : '') . "(products.pSection IN (" . $sectionids . ")) ";
		$whereand='AND ';
	}
	if(getpost('stext')!='' && is_array(@$_POST['stsearch'])){
		$sText=escape_string($stext);
		$aText=explode(' ', $sText);
		$aFields=$stsearch;
		if (($key = array_search('ordaffiliate', $aFields)) !== false) unset($aFields[$key]);
		if (($key = array_search('cartprodid', $aFields)) !== false) $aFields[$key]='pID';
		if (($key = array_search('cartprodname', $aFields)) !== false) $aFields[$key]='pName';
		if(getpost('stype')=='exact'){
			$whereclause.=$whereand.'(';
			$rowcounter=0;
			$arrelms=count($aFields);
			foreach($aFields as $thefield){
				if(is_array($thefield))$thefield=$thefield[0];
				$whereclause.=$thefield . " LIKE '%" . $sText . "%' ";
				if(++$rowcounter < $arrelms) $whereclause.='OR ';
			}
			$whereclause.=') ';
		}else{
			$sJoin='AND ';
			if(getpost('stype')=='any') $sJoin='OR ';
			$whereclause.=$whereand.'(';
			$whereand=' AND ';
			$index=0;
			$numFields=count($aFields);
			foreach($aFields as $thefield){
				if(is_array($thefield))$thefield=$thefield[0];
				$whereclause.='(';
				$rowcounter=0;
				$arrelms=count($aText);
				foreach($aText as $theopt){
					if(is_array($theopt))$theopt=$theopt[0];
					$whereclause.=$thefield . " LIKE '%".$theopt."%' ";
					if(++$rowcounter < $arrelms) $whereclause.=$sJoin;
				}
				$whereclause.=') ';
				if(++$index < $numFields) $whereclause.='OR ';
			}
			$whereclause.=') ';
		}
	}
	print '<div style="overflow:auto">';
	for($index2=1; $index2<=2; $index2++){
		$orderclause.=getdatesql('ordDate');
		$orderclause=str_replace('WHERE ','AND ',$orderclause);
		$sSQL="SELECT pID,pName,pInStock,pStockByOpts,pManufacturer," . 
			"(SELECT SUM(cartQuantity) FROM cart INNER JOIN orders ON cart.cartOrderID=orders.ordID ".($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'')."WHERE cartProdID=pID " . $orderclause . ") AS thecount," .
			"(SELECT SUM((cartProdPrice+IFNULL((SELECT SUM(coPriceDiff) FROM cartoptions WHERE coCartID=cartID),0))*cartQuantity) FROM cart INNER JOIN orders ON cart.cartOrderID=orders.ordID ".($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'')."WHERE cartProdID=pID " . $orderclause . ") AS theordtot " .
			"FROM products ";
		$sSQL.=$whereclause;
		if($index2==1)
			$sSQL.='ORDER BY thecount DESC';
		else
			$sSQL.='ORDER BY theordtot DESC';
		if(getpost("numresults")!="all") $sSQL.=" LIMIT 0,".(getpost("numresults")==""?100:getpost("numresults"));
		//print "<div style=\"clear:both\"><hr>".$sSQL."</div>\n";
?>
			<div style="padding-top:20px;width:49%;min-width:800px;float:left;margin-right:1%">
			  <h2><?php
		print (getpost("numresults")!="all"?replace($yyTopSal,"100",getpost("numresults")):replace($yyTopSal,"100",""));
		if($index2==1) print ' By Quantity'; else print ' By Amount'; ?></h2>
<?php
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0){
			print '<div class="stattbl">';
			print '<div class="stattblrow"><div>'.$yyPrId.'</div><div>'.$yyPrName.'</div>' . (@$stockstatsmanufacturer?'<div>Manufacturer</div>':'') . '<div>'.replace($yyInStk,' ','&nbsp;').'</div><div>'.replace($yyTotSal,' ','&nbsp;').'</div><div>'.$yyAmount.'</div></div>';
			$dldata='';
			$hasoption=FALSE;
			while($rs=ect_fetch_assoc($result)){
				$prodname=$rs['pName'];
				if(is_null($rs['theordtot'])) $rs['theordtot']=0;
				if(is_null($rs['thecount'])) $rs['thecount']=0;
				$manufacturername='';
				if(@$stockstatsmanufacturer){
					if(!array_key_exists($rs['pManufacturer'],$manufacturer_cache)){
						$sSQL="SELECT scName FROM searchcriteria WHERE scID='" . escape_string($rs['pManufacturer']) . "'";
						$result2=ect_query($sSQL) or ect_error();
						if($rs2=ect_fetch_assoc($result2)){
							$manufacturername=$manufacturer_cache[$rs['pManufacturer']]=$rs2['scName'];
						}else
							$manufacturer_cache[$rs['pManufacturer']]='';
						ect_free_result($result2);
					}else{
						$manufacturername=$manufacturer_cache[$rs['pManufacturer']];
					}
				}
				if($rs['pStockByOpts']){
					$optresults=[];
					
					$sSQL="SELECT coOptID,SUM(cartQuantity) AS optQuant,SUM((cartProdPrice+IFNULL((SELECT SUM(coPriceDiff) FROM cartoptions WHERE coCartID=cartID),0))*cartQuantity) AS optAmount FROM cartoptions INNER JOIN cart ON cartoptions.coCartID=cart.cartID INNER JOIN orders ON cart.cartOrderID=orders.ordID ".($orddiscount!=''?"INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID ":'')."WHERE cartProdID='" . escape_string($rs['pID']) . "'" . $orderclause . " GROUP BY coOptID";
					
					//print "<div style=\"clear:both\"><hr>".$sSQL."</div>\n";
					
					$result2=ect_query($sSQL) or ect_error();
					while($rs2=ect_fetch_assoc($result2)){
						$optresults[$rs2['coOptID']]['quant']=$rs2['optQuant'];
						$optresults[$rs2['coOptID']]['amount']=$rs2['optAmount'];
						//print "xxx: " . $rs2['coOptID'] . " : " . $rs2['optQuant'] . " : " . $rs2['optAmount'] . "<br>";
					}
					
					$sSQL="SELECT optID,optGrpName,optName,optStock FROM optiongroup INNER JOIN options ON optiongroup.optGrpID=options.optGroup INNER JOIN prodoptions ON options.optGroup=prodoptions.poOptionGroup WHERE prodoptions.poProdID='" . escape_string($rs['pID']) . "'";
					$result2=ect_query($sSQL) or ect_error();
					while($rs2=ect_fetch_assoc($result2)){
						$hasoption=TRUE;
						print '<div class="stattblrow"><div>' . $rs['pID'] . '</div><div>' . htmlspecials($prodname) . '</div>' . (@$stockstatsmanufacturer?'<div>' . $manufacturername . '</div>':'') . '<div>';
						$dldata.=rawurlencode($rs['pID']) . '%2C' . rawurlencode('"' . str_replace('"','""',$prodname) . '"') . '%2C' . (@$stockstatsmanufacturer?rawurlencode('"' . str_replace('"','""',$manufacturername) . '"').'%2C':'');
						print $rs2['optStock'] . '</div><div>' . $rs['thecount'] . '</div><div style="text-align:right">' . number_format($rs['theordtot'], $GLOBALS['currDecimals'],'.','') . '</div><div>' . htmlspecials($rs2['optGrpName']) . '</div><div>' .htmlspecials($rs2['optName']);
						$dldata.=$rs2['optStock'] . '%2C' . $rs['thecount'] . '%2C' . round($rs['theordtot'],2) . '%2C' . rawurlencode('"' . strreplace('"','""',$rs2['optGrpName']) . '"') . '%2C' . rawurlencode('"' . strreplace('"','""',$rs2['optName']) . '"');
						
						print '</div><div>' . (isset($optresults[$rs2['optID']]) ? @$optresults[$rs2['optID']]['quant'] : '-');
						print '</div><div>' . (isset($optresults[$rs2['optID']]) ? number_format(@$optresults[$rs2['optID']]['amount'], $GLOBALS['currDecimals'],'.','') : '-');
						$dldata.='%2C' . (isset($optresults[$rs2['optID']]) ? @$optresults[$rs2['optID']]['quant'] : '') . '%2C' . (isset($optresults[$rs2['optID']]) ? number_format(@$optresults[$rs2['optID']]['amount'], $GLOBALS['currDecimals'],'.','') : '');
						
						print '</div></div>' . "\n";
						$dldata.='%0A';
					}
					ect_free_result($result2);
				}else{
					print '<div class="stattblrow"><div>' . $rs['pID'] . '</div><div>' . htmlspecials($prodname) . '</div>' . (@$stockstatsmanufacturer?'<div>' . $manufacturername . '</div>':'') . '<div>';
					$dldata.=rawurlencode($rs['pID']) . '%2C' . rawurlencode('"' . str_replace('"','""',$prodname) . '"') . '%2C' . (@$stockstatsmanufacturer?rawurlencode('"' . str_replace('"','""',$manufacturername) . '"').'%2C':'');
					print $rs['pInStock'];
					$dldata.=$rs['pInStock'];
					print '</div><div>' . $rs['thecount'] . '</div><div style="text-align:right">' . number_format($rs['theordtot'], $GLOBALS['currDecimals'],'.','') . '</div></div>' . "\n";
					$dldata.='%2C' . $rs['thecount'] . '%2C' . round($rs['theordtot'],2) . '%0A';
				}
			}
			print '</div>'; ?>
			<div style="margin-top:10px">
				<a download="ectstatsby<?php print ($index2==1?'quantity':'amount')?>.csv" href="data:,<?php
					if($hasoption)
						print $yyPrId.'%2C'.$yyPrName.'%2C'.(@$stockstatsmanufacturer?'Manufacturer%2C':'').$yyInStk.'%2C'.$yyTotSal.'%2C'.$yyAmount.'%2C'.'OptionGroup'.'%2C'.'Option'.'%0A';
					else
						print $yyPrId.'%2C'.$yyPrName.'%2C'.(@$stockstatsmanufacturer?'Manufacturer%2C':'').$yyInStk.'%2C'.$yyTotSal.'%2C'.$yyAmount.'%0A';
					print $dldata;
				?>">Click Here For CSV Download</a>
			</div>
<?php	}else
			displayemptyresults();
		ect_free_result($result);
?>
			</div>
<?php
	}
	print '</div>'; ?>



<?php
}elseif(getpost("grouping")=="8"){
	$hasresults=TRUE;
	if($hasresults){
		print '<div style="overflow:auto">';
		for($index2=1; $index2<=2; $index2++){
			$sSQL="SELECT ordEmail,COUNT(ordID) AS theorders,SUM(cartQuantity) AS thecount,SUM((cartProdPrice+IFNULL((SELECT SUM(coPriceDiff) FROM cartoptions WHERE coCartID=cartID),0))*cartQuantity) AS theordtot ";
			$sSQL.="FROM products INNER JOIN cart ON products.pID=cart.cartProdID INNER JOIN orders ON cart.cartOrderID=orders.ordID ";
			$sSQL.=$whereclause . ' GROUP BY ordEmail ';
			if($index2==1)
				$sSQL.='ORDER BY theorders DESC';
			else
				$sSQL.='ORDER BY theordtot DESC';
			if(getpost("numresults")!="all") $sSQL.=" LIMIT 0,".(getpost("numresults")==""?100:getpost("numresults"));
			// print '<div>' . $sSQL . '</div>';
?>
			<div style="padding-top:20px;width:49%;min-width:800px;float:left;margin-right:1%;margin-bottom:20px">
			  <h2><?php
					print (getpost("numresults")!="all"?replace($yyTopSal,"100",getpost("numresults")):replace($yyTopSal,"100",""));
					if($index2==1) print ' Num. Of Sales'; else print ' By Amount'; ?></h2>
<?php
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0){
				print '<div class="stattbl">';
				print '<div class="stattblrow"><div>'.$yyID.'</div><div>'."Customer Name".'</div><div>'."Num. of Sales".'</div><div>Line Items</div><div>'.$yyAmount.'</div></div>';
				$dldata='';
				while($rs=ect_fetch_assoc($result)){
					$prodname='*undefined*';
					$sSQL="SELECT ordID,ordName,ordLastName FROM orders WHERE ordEmail='" . escape_string($rs['ordEmail']) . "' ORDER BY ordDate DESC LIMIT 0,1";
					$result2=ect_query($sSQL) or ect_error();
					if($rs2=ect_fetch_assoc($result2)){
						$prodname=trim_($rs2['ordName'].' '.$rs2['ordLastName']);
						$ordid=$rs2['ordID'];
					}
					print '<div class="stattblrow"><div><a href="adminorders.php?id=' . $ordid . '" target="vieworders">' . $rs['ordEmail'] . '</a></div><div><a href="adminorders.php?id=' . $ordid . '" target="vieworders">' . $prodname . '</a></div><div>' . $rs['theorders'] . '</div><div>' . $rs['thecount'] . '</div><div style="text-align:right">' . number_format($rs['theordtot'], $GLOBALS['currDecimals'],'.','') . '</div></div>';
					$dldata.=$rs['ordEmail'] . '%2C' . rawurlencode('"' . str_replace('"','""',$prodname) . '"') . '%2C' . $rs['theorders'] . '%2C' . $rs['thecount'] . '%2C' . round($rs['theordtot'],2) . '%0A';
				}
				print '</div>'; ?>
				<div style="margin-top:10px">
					<a download="ectstatsby<?php print ($index2==1?'quantity':'amount')?>.csv" href="data:application/octet-stream,<?php
						print 'ID%2C'."Customer Name".'%2C'."Num Sales".'%2C'."Line Items".'%2C'.$yyAmount.'%0A';
						print $dldata;
					?>">Click Here For CSV Download</a>
				</div>
<?php		}else
				displayemptyresults();
			ect_free_result($result);
?>
			</div>
<?php	}
	}
}else{ ?>
			<div style="text-align:center;margin:80px">Please select a results format and press the &quot;Stats&quot; button.</div>
<?php
} // grouping
?>
			<div style="text-align:center;margin:20px"><a href="admin.php"><strong><?php print $yyAdmHom?></strong></a></div>
