<?php
	if(!isset($storeID)){
		$storeID = 0;
	}
	
	require_once($_SERVER['DOCUMENT_ROOT'] . "/admin/inc/class.features.inc.php");
	$storeObj = new stores();
	$theLocations = $storeObj->getStoreLocations();
	
	if(count($theLocations) == 1){
		$theLocations[0]['store_name'] = "Home";
		$theLocations[0]['store_id_share'] = 0;
		$theLocations[0]['store_id'] = 0;
	}else{
		array_push($theLocations, array("store_id" => "0", "store_name" => "Home", "store_update" => "0000-00-00 00:00:00", "store_id_share" => "0"));
	}
	
	foreach($theLocations as $location){
		if($storeID == $location['store_id_share']){
			$masterFile = $_SERVER['DOCUMENT_ROOT'] . "/admin/inc/adItemsWanted" . str_replace(" ", "_", $location['store_name']) . ".php";
			
			/*GET THE AD BREAK DAY OF THE STORE*/
			//$adBreak = "Wednesday";
			$storeURL = "https://afsshareportal.com/lookUpFeatures.php?action=storeInfoCurl&website_url=" . WEB_URL;
			$chStore = curl_init();
			curl_setopt($chStore, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($chStore, CURLOPT_URL, $storeURL);
			curl_setopt($chStore, CURLOPT_HEADER, false);
			$result=curl_exec($chStore);
			
			$theStoreInfo = json_decode($result, true);
			$adBreak = $theStoreInfo[0]['store_breakStart'];
			$adBreakEnd = $theStoreInfo[0]['store_breakEnd'];
			$usedLocation = $location;
			
			break;
		}
	}
	
	//delete the adItemsWanted file if it is the ad break day and the file has not already been updated
	$todayText = date("l");
	$todayMidnight = strtotime('today midnight');
	
	if(file_exists($masterFile)){
		if($todayText == $adBreak){
			$startTime = strtotime('today midnight');
		}else{
			$startTime = strtotime('last ' . $adBreak . " midnight");
		}
		
		if($todayText == $adBreakEnd){
			$endTime = strtotime('today midnight');
		}else{
			$endTime = strtotime('next ' . $adBreakEnd . " midnight");
		}
		
		$fileTime = filemtime($masterFile);
		
		if(!($fileTime > $startTime && $fileTime < $endTime)){	
			unlink($masterFile);
		}
	}
	
	
	if(!isset($numWanted) || is_null($numWanted)){
		$numWanted = 4;
	}
	
	if(!isset($rowCount) || is_null($rowCount)){
		$rowCount = 4;
	}
	
	if(!isset($viewType) || is_null($viewType)){
		$viewType = "all";
	}
	
	$allItemsHTML = array();
	$extraItems = array();
	
	if(file_exists($masterFile)){
		$allItemsHTML = unserialize(file_get_contents($masterFile));
		
	}
	
	$usedLocation['wantedIDs'] = array();
	if(count($allItemsHTML) > 0){
		foreach($allItemsHTML as $oneItem){
		  array_push($usedLocation['wantedIDs'], $oneItem['id']);
		}
	}
	
	
	if(count($allItemsHTML) < $numWanted){
		include($_SERVER['DOCUMENT_ROOT'] . "/admin/inc/simple_html_dom.php");
		
		$adVersions = json_decode(AD_VERSIONS, true);
		$url = $adVersions['version1']['link'] . "/AllAvailableItems";
		
		//$url = str_replace("http://www.ecomadviewer.com/V87", "http://adstudio.ampmfl.com/AdViewer/V87", $url);
		
		//if store specific, get the link based on store id
		if($storeDeals != "home"){
			foreach($adVersions as $version){
				if(in_array($storeDeals, $version['stores'])){
					$url = $version['link'] . "/AllAvailableItems";
				}
			}
		}
		
		$ch = curl_init();
		//curl_setopt($ch, CURLOPT_URL, "http://www.google.com");
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$output = curl_exec($ch);
		
		if(!curl_errno($ch)){
			$info = curl_getinfo($ch);
			echo "";
			//echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
		}
		curl_close($ch);
		
		$html = str_get_html($output);
		
		//$allItemsHTML = array();
		$totalCnt = count($allItemsHTML);
		
		//get the number of random items
		$randCieling = max($numWanted, 10);
		
		//echo gettype($html)."<br><br>";
		if(gettype($html) == "object"){
			foreach($html->find('div.ad-space-box') as $elm){
				//echo $elm->outertext;
				$priceText = (string)$elm->find(".cn_price", 0)->plaintext;
				
				if(!($priceText === "" || $priceText === "0")){
					//echo gettype($priceText) . " - " . $priceText . "<br>";
					
					$item['id'] = $elm->getAttribute("data-adspace-id");
					$item['picture'] = $elm->find(".cn_picture img", 0)->src;
					
					$theDetails = "";
					foreach($elm->find('.ct_productdetails') as $details){
						$theDetails .= $details->plaintext . "<br>";
					}
					$item['description'] = substr($theDetails, 0, -4);
					
					$item['price'] = $elm->find(".cn_price", 0)->plaintext;
					
					if(($elm->find(".cn_unit", 0))){
						$item['unit'] = (string)$elm->find(".cn_unit", 0)->plaintext;
					}else{
						$item['unit'] = null;
					}
					
					if(!in_array($item['id'], $usedLocation['wantedIDs'])){
						array_push($extraItems, $item);
						$totalCnt++;
					}
				}
				if($totalCnt == $randCieling) break;
			}
			
			$html->clear(); 
		}
		unset($html);
	}
	
	
	$newCount = 0;
	shuffle($allItemsHTML);
	shuffle($extraItems);
	$allItemsHTML = array_merge($allItemsHTML, $extraItems);
	$useArray = array_slice($allItemsHTML,0,$numWanted);
	$cntAll = count($useArray);
	if($cntAll > 0){
?>
		<div class="storeDeals <?php echo $viewType; ?>">
			<a class="ad-control left" href="#" data-slide="prev">&lsaquo;</a>
			<a class="ad-control right" href="#" data-slide="next">&rsaquo;</a>
			<div class="dealHeader">
			  <h3>Currently on Special</h3>
			</div>
			<div class="caption clearfix">
			  <?php
				foreach($useArray as $anItem){
					$newCount++;
					$specialClass = "";
					$newRow = ($newCount % $rowCount) == 0 ? true : false;
					$theLast = ($newCount % $numWanted) == 0 ? true : false;
					if($theLast || $newRow){
						$specialClass = "theLast";
					}
			  ?>
				<div class="weeklySpecial clearfix <?php echo $specialClass; ?>">
				  <img src="<?php echo $anItem['picture']; ?>" alt="<?php echo $anItem['description']; ?>"/>
				  <p><?php echo $anItem['description']; ?></p>
				  <h5 class="price">
					<?php
						echo $anItem['price'] . " ";
						if(!is_null($anItem['unit'])) echo $anItem['unit'];
					?>
				  </h5>
				</div>
			  <?php
					if(($theLast || $newRow) && $viewType != "single"){
			  ?>
					<div style="clear:both;"></div>
			  <?php
					}
				}
			  ?>
			</div>
			  <?php
				if($priceWarning){
			  ?>
					<p style="clear: both;text-align:center;"><small>Prices and availability subject to change in each location. <a href="/weeklyAd">View our ad</a> to verify prices.</small></p>
			  <?php
				}
			  ?>
			<div class="dealFooter">
			  <a class="btn btn-primary btn-medium" href="/weeklyAd"><i class="icon-columns"></i>&nbsp; View our ad</a>
			</div>
		</div>
<?php
	}
?>

<script>
	var pageView = "<?php echo $viewType; ?>";
	
	if(pageView == "single"){
		$(".storeDeals.single .caption .weeklySpecial").addClass("hideObject");
		$(".storeDeals.single .caption .weeklySpecial").eq(0).removeClass("hideObject");
		
		if($(".storeDeals.single .caption .weeklySpecial").length < 1){
			$(".ad-control").addClass("hideObject");
		}else{
			$(".ad-control.right").removeClass("hideObject");
			$(".ad-control.left").addClass("hideObject");
		}
		
		$('.storeDeals.single .ad-control').live("click", function(e){
		  //console.log("clicked ");
		  e.preventDefault();
		  var $thePosts = $(this).siblings(".caption");
		  var theIndex = $thePosts.children(".weeklySpecial").not(".hideObject").index();
		  var total = $thePosts.children(".weeklySpecial").length;
		  
		  
		  if($(this).is(".right")){
			var shouldHide = (theIndex + 2) < total ? false : true;
			if(shouldHide){
			  $(".ad-control.right").addClass("hideObject");
			}else{
			  $(".ad-control.left").removeClass("hideObject");
			}
			var next = (theIndex + 1) < total ? theIndex + 1 : theIndex;
		  }else{
			var shouldHide = (theIndex - 2) < 0 ? true : false;
			if(shouldHide){
			  $(".ad-control.left").addClass("hideObject");
			}else{
			  $(".ad-control.right").removeClass("hideObject");
			}
			var next = (theIndex - 1) >= 0 ? theIndex - 1 : theIndex;
		  }
		  
		  $thePosts.children().eq(theIndex).addClass("hideObject");
		  $thePosts.children().eq(next).removeClass('hideObject');
		  
		  //console.log("shouldHide: " + shouldHide + "\ntotal: " + total + "\nthe index is: " + theIndex + "\nnext: " + next);
		});
	}else{
		$(".ad-control").addClass("hideObject");
	}
</script>
