<?php
  require('inc/sessionStart.php');
  include($_SERVER['DOCUMENT_ROOT'] . "/admin/inc/simple_html_dom.php");
?>

<?php
  $pageTitle = "Administration: Ad Items";
  $pageDescription = "";
  $pageKeywords = "";
?>

<?php
  include_once($_SERVER['DOCUMENT_ROOT'] . "/common/header.php"); 
  include_once($_SERVER['DOCUMENT_ROOT'] . "/common/mainNav.php");
  
  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"));
  }
  
  $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'];
  
  $todayText = date("l");
  $todayMidnight = strtotime('today midnight');
  
  
  
  $storeID = "0";
  $submitted = false;
  $adVersions = json_decode(AD_VERSIONS, true);
  
  if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['store_id'])){
	$storeID = $_POST['store_id'];
	unset($_POST['store_id']);
	$submitted = true;
  }
  
  foreach($theLocations as &$location){
	$location['masterFile'] = $_SERVER['DOCUMENT_ROOT'] . "/admin/inc/adItemsWanted" . str_replace(" ", "_", $location['store_name']) . ".php";
	
	
	//DELETE FILES FOR WANTED AD ITEMS IF THEY EXIST AND IT IS A NEW WEEK
	if($todayText == $adBreak && file_exists($location['masterFile'])){
	  if((filemtime($location['masterFile']) - $todayMidnight) <= 0){
		unlink($location['masterFile']);
	  }
	}
	
	if($submitted && $storeID == $location['store_id']){
	  $location['wantedIDs'] = $_POST;
	}else{
	  $location['wantedIDs'] = array();
	
	  if(file_exists($location['masterFile'])){
		$wantedItems = unserialize(file_get_contents($location['masterFile']));
		
		foreach($wantedItems as $oneItem){
		  array_push($location['wantedIDs'], $oneItem['id']);
		}
	  }
	}
	
	
	//NEED TO Get the right url
	$url = "";
	foreach($adVersions as $version){
	  if(in_array($location['store_id_share'], $version['stores'])){
		$url = $version['link'] . "/AllAvailableItems";
		break;
	  }
	}
	
	if($url == ""){
	  $url = $adVersions['version1']['link'] . "/AllAvailableItems";
	}
	
	//ECOM DID SOME CHANGING OF URLS AND THIS IS TO OVERCOME THAT
	$url = str_replace("http://www.ecomadviewer.com/V87", "http://adstudio.ampmfl.com/AdViewer/V87", $url);
  
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($ch);
	if(!curl_errno($ch)){
		$info = curl_getinfo($ch);
		echo "";
	}
	curl_close($ch);
	
	$html = str_get_html($output);
	
	$location['allItemsHTML'] = array();
	$location['pickedItems'] = array();
	$totalCnt = 0;
	$endDate = "";
	
	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 .= trim($details->plaintext) . " ";
			}
			$item['description'] = substr($theDetails, 0, -1);
			
			$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;
			}
			
			$endDate = $elm->find(".ad-date-info-text", 0)->plaintext;
			
			$location['allItemsHTML'][$item['id']] = $item;
			if(in_array($item['id'], $location['wantedIDs'])){
			  array_push($location['pickedItems'], $item);
			}
			$totalCnt++;
		}
	  }
	  
	  $html->clear(); 
	}
	
	unset($html);
	
	
	//write the submitted array to a file
	if($submitted && $storeID == $location['store_id']){
	  if(count($location['pickedItems']) > 0){
		file_put_contents($location['masterFile'], serialize($location['pickedItems']));
	  }else{
		unlink($location['masterFile']);
	  }
	}
  }
  
  
  //$masterFile = $_SERVER['DOCUMENT_ROOT'] . "/admin/inc/adItemsWanted.php";
  
?>

    <section class="container">
      <div id="blankBuffer" class="carousel-buffer"></div>
      <div id="noEditError" class="hideObject">
			<div class="alert alert-error">
				  <a class="close" data-dismiss="alert" href="#">x</a>You can only <span id="noEditErrorText"></span> if you have editing capabilities.
			</div>
	  </div>
	  <section class="container" id="storePortal">
	    <div class="row">
		  <div class="span3 sideNav">
			<?php include('inc/sideNav.php'); ?>
		  </div>
		  
		  <div class="span9 portalContent">
			<div class="contentContain">
			  <h2>Ad Item Management</h2>
			  <p>Pick at least four items to display on your home page. If you pick more than four items, each time someone visits your homepage four of the items you selected will be randomly chosen and shown to the guest. If you choose fewer than four items, the items you chose will be shown, along with random items from your ad until the quota is met.</p>
			  <p>The list will be reset each week on your ad start day, so come back each week and set your preferred items. If you don't select any items, four items will be chosen randomly.</p>
			  
			  <div class="tabbable">
				<!-- SET THE NAVIGATION LINKS -->
				<ul class="nav nav-tabs" id="myTab">
				  <?php
					$count = 0;
					
					foreach($theLocations as $aLocation){
						  if($count == 0){
								$theClass = "active";
						  }else{
								$theClass = "";
						  }
				  ?>
					<li class="<?php echo $theClass; ?>">
						  <a href="#<?php echo str_replace(" ", "_", $aLocation['store_name']); ?>" data-toggle="tab"><?php echo $aLocation['store_name']; ?> (<?php echo count($aLocation['wantedIDs']); ?>)</a>
					</li>
				  <?php
						  $count++;
					}
					
					$count = 0;
				  ?>
				</ul>
				
				<!-- CONTENT FOR EACH LOCATION -->
				<div class="tab-content" id="myTabContent">
				  
				  <?php
					foreach($theLocations as $aLocation){
					  if($count == 0){
						$theClass = " active";
					  }else{
						$theClass = "";
					  }
				  ?>
					<div class="tab-pane<?php echo $theClass; ?>" id="<?php echo str_replace(" ", "_", $aLocation['store_name']); ?>">
						<h3>Items for the <?php echo $endDate . " - " . $aLocation['store_name']; ?></h3>
						<div id="itemInfo">
						  <form action="" method="post" id="itemForm">
							<input type="hidden" name="store_id" value="<?php echo $aLocation['store_id']; ?>">
							<?php
							  foreach($aLocation['allItemsHTML'] as $anItem){
								$specialText = "";
								
								if(in_array($anItem['id'], $aLocation['wantedIDs'])){
								  $specialText = "checked";
								}
							?>
							  <div class="weeklySpecial clearfix" id="item_<?php echo $anItem['id']; ?>">
								
								<div class="specialAssign">
								  <input type="checkbox" name="item_<?php echo $anItem['id']; ?>" value="<?php echo $anItem['id']; ?>" <?php echo $specialText; ?>>
								</div>
								<div class="specialItem">
								  <img src="<?php echo $anItem['picture']; ?>" alt=""/>
								  <p><?php echo $anItem['description']; ?></p>
								  <h5 class="price">
									<?php
									  echo $anItem['price'] . " ";
									  if(!is_null($anItem['unit'])) echo $anItem['unit'];
									?>
								  </h5>
								</div>
							  </div>
							<?php
							  }// end foreach($allItemsHTML as $anItem)
							?>
							<input type="submit" value="Submit" class="btn">
							<br><br>
						  
							<div class="alert alert-error hideObject" id="badSubmit">
							  <a class="close" data-dismiss="alert" href="#">x</a> You must select either <b>zero</b> items or <b>more than three</b> items. <br>
							  You have currently selected <span id="itemCount"></span> items.
							</div>
						  </form>
						</div>
					</div>
				  <?php
					  $count++;
					}
				  ?>
				</div>
			  </div>
			  
			  
			  
			</div>
		  </div>
	    </div>
	    
      </section>
      
    </section>
      
    
    
  <script>
    $("#feedbackBtns").remove();
  </script>
  
<?php require($_SERVER['DOCUMENT_ROOT'] . '/common/footer.php'); ?>
