<?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
global $catid,$isrootsection,$prodfilter,$adminProdsPerPage,$minloglevel,$thesessionid,$Count,$usecsslayout,$storeurl,$csalsoboughttitle,$useStockManagement,$csrecommendedtitle,$csrelatedtitle,$csbestsellerstitle,$crosssellnotsection,$prodlist,$orsortby,$productcolumns,$prodseparator,$crosssellcolumns,$crosssellrows,$csrecommendedtitle,$crosssellaction,$csstyleprefix,$countryTaxRate,$defimagejs,$optjs,$cs,$WSP,$OWSP,$TWSP;
if(@$_SERVER['CONTENT_LENGTH']!='' && $_SERVER['CONTENT_LENGTH'] > 10000) exit;
$WSP=$OWSP='';
$TWSP='pPrice';
$cs=@$csstyleprefix;
get_wholesaleprice_sql();
if(@$crosssellcolumns==''){ if(@$productcolumns=='') $crosssellcolumns=3; else $crosssellcolumns=$productcolumns; }
if(@$crosssellrows=='') $crosssellrows=1;
$numberofproducts = $crosssellcolumns * $crosssellrows;
$productcolumns=$crosssellcolumns;
$cssavenobuyorcheckout=@$GLOBALS['nobuyorcheckout'];
$cssavenoshowdiscounts=@$GLOBALS['noshowdiscounts'];
$cssavenoproductoptions=@$GLOBALS['noproductoptions'];
$cssaveproductpagelayout=@$GLOBALS['productpagelayout'];
$cssaveshowcategories=@$GLOBALS['showcategories'];
$cssavemagictoolboxproducts=@$GLOBALS['magictoolboxproducts'];
$cssaveforcedetailslink=@$GLOBALS['forcedetailslink'];
if(@$GLOBALS['csnobuyorcheckout']) $GLOBALS['nobuyorcheckout']=TRUE;
if(@$GLOBALS['csnoshowdiscounts']) $GLOBALS['noshowdiscounts']=TRUE;
if(@$GLOBALS['csnoproductoptions']) $GLOBALS['noproductoptions']=TRUE;
if(@$GLOBALS['csproductpagelayout']!='') $GLOBALS['productpagelayout']=$GLOBALS['csproductpagelayout'];
if(@$GLOBALS['productpagelayout']!=''){ $GLOBALS['usecsslayout']=$GLOBALS['nomarkup']=TRUE; $GLOBALS['sstrong']=$GLOBALS['estrong']=''; }
$GLOBALS['hasshippingdiscount']=$GLOBALS['hasproductdiscount']=TRUE;
if(! @isset($GLOBALS['forcedetailslink'])) $GLOBALS['forcedetailslink']=TRUE;
$iNumOfPages=1;
@$GLOBALS['showcategories']=FALSE;
@$GLOBALS['magictoolboxproducts']='';
$isrootsection=TRUE;
if(! @isset($Count)) $Count=0; else $Count=($Count+$crosssellcolumns)-($Count % $crosssellcolumns);
$catid = '0';
$noblankdescription=(strpos(','.strreplace(' ','',@$GLOBALS['productpagelayout']).',',',description,')!==FALSE||strpos(','.strreplace(' ','',@$GLOBALS['quickbuylayout']).',',',description,')!==FALSE);
$GLOBALS['wantmanufacturer']=strpos(@$GLOBALS['productpagelayout'].@$GLOBALS['quickbuylayout'],'manufacturer')!==FALSE || @$GLOBALS['googletagid']!='';
if(is_numeric(@$_REQUEST['sortby'])) $_SESSION['sortby']=(int)$_REQUEST['sortby'];
if(@$_SESSION['sortby']!='') $dosortby=$_SESSION['sortby'];
if(@$orsortby!='') $dosortby=$orsortby;
if(@$dosortby==2 || @$dosortby==12)
	$sSortBy=' ORDER BY products.pId'.(@$dosortby==12?' DESC':'');
elseif(@$dosortby==14||@$dosortby==15)
	$sSortBy=' ORDER BY pSKU'.(@$dosortby==15?' DESC,pId':',pId');
elseif(@$dosortby==3||@$dosortby==4)
	$sSortBy=' ORDER BY '.$TWSP.(@$dosortby==4?' DESC,pId':',pId');
elseif(@$dosortby==5)
	$sSortBy='';
elseif(@$dosortby==6||@$dosortby==7)
	$sSortBy=' ORDER BY pOrder'.(@$dosortby==7?' DESC,pId':',pId');
elseif(@$dosortby==8||@$dosortby==9)
	$sSortBy=' ORDER BY pDateAdded'.(@$dosortby==9?' DESC,pId':',pId');
elseif(@$dosortby==10)
	$sSortBy=' ORDER BY pManufacturer,pId';
elseif(@$dosortby==16)
	$sSortBy=' ORDER BY pNumRatings DESC,pId';
elseif(@$dosortby==17)
	$sSortBy=' ORDER BY IF(pNumRatings=0,0,pTotRating/pNumRatings) DESC,pNumRatings DESC,pId';
elseif(@$dosortby==18)
	$sSortBy=' ORDER BY pNumSales DESC,pId';
elseif(@$dosortby==19)
	$sSortBy=' ORDER BY pPopularity DESC,pId';
elseif(@$dosortby==13)
	$sSortBy=' ORDER BY RAND()';
else
	$sSortBy=' ORDER BY '.getlangid('pName',1).(@$dosortby==11?' DESC,pId':',pId');
if(@$prodlist=='') $prodlist='';
if(getpost('mode')!='checkout' && getpost('mode')!='add' && getpost('mode')!='go' && getpost('mode')!='paypalexpress1' && getpost('mode')!='authorize'){
	$GLOBALS['alreadygotadmin']=getadminsettings();
	$cssaveprodfilter=$prodfilter;
	$prodfilter=0;
	$thesessionid=getsessionid();
	if(@$_SESSION['clientID']!='' && @$_SESSION['clientLoginLevel']!='') $minloglevel=$_SESSION['clientLoginLevel']; else $minloglevel=0;
	$result2=ect_query('SELECT sectionID FROM sections WHERE sectionDisabled>'.$minloglevel) or ect_error();
	$addcomma='';
	if(@$crosssellnotsection=='') $crosssellnotsection=''; else $addcomma=',';
	while($rs2=ect_fetch_assoc($result2)){
		$crosssellnotsection.=$addcomma . $rs2['sectionID'];
		$addcomma=',';
	}
	ect_free_result($result2);
	$crosssellactionarr = explode(',', @$crosssellaction);
	for($csindex=0; $csindex < count($crosssellactionarr); $csindex++){
		$crosssellaction=trim($crosssellactionarr[$csindex]);
		$addcomma=''; $relatedlist='';
		if($crosssellaction=='alsobought'){ // Those who bought what's in your cart also bought.
			if(@$csalsoboughttitle=='') $crossselltitle='Customers who bought these products also bought.'; else $crossselltitle=$csalsoboughttitle;
			if($prodlist==''){
				$addcomma='';
				$sSQL = "SELECT cartProdID FROM cart WHERE cartCompleted=0 AND cartSessionID='" . escape_string($thesessionid) . "'";
				$result=ect_query($sSQL) or ect_error();
				while($rs=ect_fetch_assoc($result)){
					$prodlist.=$addcomma . "'" . escape_string($rs['cartProdID']) . "'";
					$addcomma=',';
				}
				ect_free_result($result);
			}
			$addcomma=$relatedlist='';
			$thecount=0;
			$alldone=FALSE;
			if($prodlist!=''){
				$sSQL="SELECT cartOrderID FROM cart WHERE cartOrderID<>0 AND cartProdID IN (".$prodlist.") AND cartSessionID<>'".strreplace("'",'',$thesessionid)."' ORDER BY cartOrderID DESC";
				$result=ect_query($sSQL) or ect_error();
				while($rs=ect_fetch_assoc($result)){
					$sSQL="SELECT cartProdID FROM cart WHERE cartProdID NOT IN (".$prodlist.($relatedlist!=''?','.$relatedlist:'').") AND cartOrderID=" . $rs['cartOrderID'];
					$result2=ect_query($sSQL) or ect_error();
					while($rs2=ect_fetch_assoc($result2)){
						$relatedlist.=$addcomma . "'" . escape_string($rs2['cartProdID']) . "'";
						$addcomma=",";
						$thecount++;
						if($thecount>=$numberofproducts){ $alldone=TRUE; break; }
					}
					ect_free_result($result2);
					if($alldone) break;
				}
				ect_free_result($result);
			}
		}elseif($crosssellaction=='recommended'){ // Recommended products (Needs v5.1)
			if(@$csrecommendedtitle=='') $crossselltitle='These products are our current recommendations for you.'; else $crossselltitle=$csrecommendedtitle;
			if($prodlist==''){
				$sSQL = "SELECT cartProdID FROM cart WHERE cartCompleted=0 AND cartSessionID='" . escape_string($thesessionid) . "'";
				$result=ect_query($sSQL) or ect_error();
				$addcomma='';
				while($rs=ect_fetch_assoc($result)){
					$prodlist.=$addcomma . "'" . escape_string($rs['cartProdID']) . "'";
					$addcomma=',';
				}
				ect_free_result($result);
			}
			$sSQL = 'SELECT pID FROM products WHERE ' . (@$GLOBALS['ectsiteid']!='' ? 'pSiteID='.$GLOBALS['ectsiteid'].' AND ' : '') . 'pDisplay<>0 AND pRecommend<>0';
			if($prodlist!='') $sSQL.=' AND NOT (pID IN (' . $prodlist . '))';
			if($crosssellnotsection!='') $sSQL.=' AND NOT (pSection IN (' . $crosssellnotsection . '))';
			$addcomma=''; $relatedlist='';
			$result=ect_query($sSQL) or ect_error();
			while($rs=ect_fetch_assoc($result)){
				$relatedlist.=$addcomma . "'" . escape_string($rs['pID']) . "'";
				$addcomma=',';
			}
			ect_free_result($result);
		}elseif($crosssellaction=='related'){ // Products recommended with this product (Would need v5.1)
			if(@$csrelatedtitle=='') $crossselltitle='These products are recommended with items in your cart.'; else $crossselltitle=$csrelatedtitle;
			if($prodlist==''){
				$addcomma='';
				$sSQL = "SELECT cartProdID FROM cart WHERE cartCompleted=0 AND cartSessionID='" . escape_string($thesessionid) . "'";
				$result=ect_query($sSQL) or ect_error();
				while($rs=ect_fetch_assoc($result)){
					$prodlist.=$addcomma . "'" . escape_string($rs['cartProdID']) . "'";
					$addcomma=',';
				}
				ect_free_result($result);
			}
			if($prodlist!=''){
				$sSQL = 'SELECT rpRelProdID FROM relatedprods WHERE (rpProdID IN (' . $prodlist . ') AND NOT (rpRelProdID IN (' . $prodlist . ')))';
				if(@$GLOBALS['relatedproductsbothways']) $sSQL.=' UNION SELECT rpProdID FROM relatedprods WHERE (rpRelProdID IN (' . $prodlist . ') AND NOT (rpProdID IN (' . $prodlist . ')))';
				$addcomma=''; $relatedlist='';
				$result=ect_query($sSQL) or ect_error();
				while($rs=ect_fetch_assoc($result)){
						$relatedlist.=$addcomma . "'" . escape_string($rs['rpRelProdID']) . "'";
						$addcomma=',';
				}
				ect_free_result($result);
			}
		}elseif($crosssellaction=='bestsellers'){ // Top X best sellers
			$relatedlist='';
			$sSQL="SELECT adminBestSellerDate,adminBestSellerCache FROM admin WHERE adminID=1";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$bscache=trim_($rs['adminBestSellerCache']);
				$bsdate=strtotime($rs['adminBestSellerDate']);
			}
			$todaytime=strtotime(date('Y-m-d'));
			if(@$csbestsellerstitle=='') $crossselltitle='These are our current best sellers.'; else $crossselltitle=$csbestsellerstitle;
			$bscache_arr=explode(',',$bscache);
			if(count($bscache_arr)<$numberofproducts || $todaytime-$bsdate>=(60*60*24)){
				$sSQL = 'SELECT cartProdID,COUNT(cartProdID) AS pidcount FROM cart INNER JOIN products ON cart.cartProdID=products.pID WHERE cartCompleted<>0 AND ' . (@$GLOBALS['ectsiteid']!='' ? 'pSiteID='.$GLOBALS['ectsiteid'].' AND ' : '') . 'pDisplay<>0 ' . (@$crosssellsection!='' ? ' AND pSection IN (' . $crosssellsection . ')' : '') . (@$crosssellnotsection!='' ? ' AND NOT (pSection IN (' . $crosssellnotsection . '))' : '');
				if(@$GLOBALS['bestsellerlimit']!='') $sSQL.=" AND cartDateAdded>'".date('Y-m-d H:i:s', time()-($GLOBALS['bestsellerlimit']*60*60*24))."'";
				$sSQL.=' GROUP BY cartProdID ORDER BY pidcount DESC LIMIT 0,' . $numberofproducts;
				$result=ect_query($sSQL) or ect_error();
				while($rs=ect_fetch_assoc($result)){
					$relatedlist.=$addcomma . "'" . escape_string($rs['cartProdID']) . "'";
					$addcomma=',';
				}
				ect_free_result($result);
				
				$sSQL="UPDATE admin SET adminBestSellerDate='" . date('Y-m-d') . "',adminBestSellerCache='" . escape_string($relatedlist) . "' WHERE adminID=1";
				ect_query($sSQL) or ect_error();
			}else
				$relatedlist=$bscache;
		}elseif($crosssellaction=='section'){ // Top X from a given category
			if(@$GLOBALS['cssectiontitle']=='') $crossselltitle='These are our Weekly Specials.'; else $crossselltitle=$GLOBALS['cssectiontitle'];
			if(is_numeric(@$GLOBALS['crosssellsection'])){
				$sSQL = 'SELECT products.pID FROM products LEFT JOIN multisections ON products.pId=multisections.pId WHERE ' . (@$GLOBALS['ectsiteid']!='' ? 'pSiteID='.$GLOBALS['ectsiteid'].' AND ' : '') . "(products.pSection='" . $GLOBALS['crosssellsection'] . "' OR multisections.pSection='" . $GLOBALS['crosssellsection'] . "') AND pDisplay<>0";
				$addcomma=''; $relatedlist='';
				$result=ect_query($sSQL) or ect_error();
				while($rs=ect_fetch_assoc($result)){
					$relatedlist.=$addcomma . "'" . escape_string($rs['pID']) . "'";
					$addcomma=',';
				}
				ect_free_result($result);
			}else
				print '<p>Invalid $crosssellsection</p>';
			$GLOBALS['crosssellsection']='';
		}elseif($crosssellaction=='productlist'){ // A list of defined products
			if(@$GLOBALS['csproductlisttitle']=='') $crossselltitle='These are our Weekly Specials.'; else $crossselltitle=$GLOBALS['csproductlisttitle'];
			if(trim_(@$GLOBALS['crosssellproducts'])!=''){
				$rlarray=explode(',',$GLOBALS['crosssellproducts']);
				$addcomma=''; $relatedlist='';
				foreach($rlarray as $rlvalue){
					$relatedlist.=$addcomma . "'" . escape_string($rlvalue) . "'";
					$addcomma=',';
				}
			}else
				print '<p>No $crosssellproducts defined</p>';
		}else
			if($crosssellaction!='') print '<p>Unrecognized crosssell action ' . $crosssellaction . '</p>';
		if($relatedlist!=''){
			$csssaveprodlist=$prodlist;
			$prodlist=$relatedlist;
			$sSQL='SELECT pId,pSKU,' . getlangid('pName',1) . ',' . $WSP . 'pPrice,pListPrice,pSection,pSell,pStockByOpts,pStaticPage,'.getaltlang('pStaticURL',8388608).',pInStock,pExemptions,pTax,pTotRating,pNumRatings,pBackOrder,pCustomCSS,';
			$templayoutarray=explode(',',strtolower(@$GLOBALS['productpagelayout'].','.@$GLOBALS['quickbuylayout']));
			foreach($templayoutarray as $layoutoption){
				if(substr(strtolower(trim($layoutoption)),0,6)=='custom'){
					if(strpos($sSQL,strreplace('custom','pCustom',$layoutoption).',')===FALSE)$sSQL.=strreplace('custom','pCustom',$layoutoption).',';
				}elseif(substr(trim($layoutoption),0,1)=='<'&&preg_match('/%custom(\d+)%/i',$layoutoption,$matchnum)){
					if(strpos($sSQL,'pCustom'.$matchnum[1].',')===FALSE)$sSQL.='pCustom'.$matchnum[1].',';
				}
			}
			$sSQL.='pDateAdded,pMinQuant,pSchemaType,'.($GLOBALS['wantmanufacturer']?getlangid('scName',131072).',':'').($noblankdescription?'':"'' AS ") . getlangid('pDescription',2) . ',' . getlangid('pLongDescription',4) . ' FROM products '.($GLOBALS['wantmanufacturer']?'LEFT OUTER JOIN searchcriteria on products.pManufacturer=searchcriteria.scID ':'').'WHERE ' . (@$GLOBALS['ectsiteid']!='' ? 'pSiteID='.$GLOBALS['ectsiteid'].' AND ' : '') . 'pDisplay<>0 AND pId IN (' . $prodlist . ')';
			$sSQL.=(@$crosssellnotsection!='' && $crosssellaction=='related' ? ' AND NOT (pSection IN (' . $crosssellnotsection . '))' : '');
			if($useStockManagement && @$GLOBALS['noshowoutofstock']) $sSQL.=' AND pInStock>pMinQuant';
			$sSQL.=$sSortBy . (@$GLOBALS['crosssellsectionmax']!=''?' LIMIT 0,' . $GLOBALS['crosssellsectionmax']:'');
			$allprods=ect_query($sSQL) or ect_error();
			$saveAdminProdsPerPage=$adminProdsPerPage;
			$adminProdsPerPage=ect_num_rows($allprods);
			if(ect_num_rows($allprods) > 0){
				if(!@$GLOBALS['nocrossselltitle']) print '<p class="cstitle">' . $crossselltitle . '</p>';
				include './vsadmin/inc/incproductbody2.php';
			}
			ect_free_result($allprods);
			$adminProdsPerPage=$saveAdminProdsPerPage;
			$prodlist=$csssaveprodlist;
		}
	}
	$prodfilter=$cssaveprodfilter;
}
$GLOBALS['forcedetailslink']=$cssaveforcedetailslink;
$GLOBALS['magictoolboxproducts']=$cssavemagictoolboxproducts;
$GLOBALS['showcategories']=$cssaveshowcategories;
$GLOBALS['productpagelayout']=$cssaveproductpagelayout;
$GLOBALS['noproductoptions']=$cssavenoproductoptions;
$GLOBALS['nobuyorcheckout']=$cssavenobuyorcheckout;
$GLOBALS['noshowdiscounts']=$cssavenoshowdiscounts;
?>