<?php

include_once("common.inc.php");
AccessCheck();

if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
	die('Ajax only');
}

if (!isset($_REQUEST["conf"])) { die(_MISSING_REQUIRED_PARAM); }
if (!isset($_REQUEST["labels"]) || empty($_REQUEST["labels"])) { die(_MISSING_REQUIRED_PARAM); }


function AdvancedOptions($reportoptions) {
	global $optionvalues,$r,$reports,$validUserRequired,$session,$edition,$profile;

	echo "<div class='advanced-report-options'>";

		//echo "<button class='btn  advanced-options-toggler' type='button'>". _ADVANCED_REPORT_OPTIONS ." <span class='fa fa-caret-down'></span></button>";

		echo "<div class='advanced-options-form'>";
			
			if(in_array("trafficsource", $reportoptions) !== false) {
				echo "<div class='form-group'><label for='trafficsource' style='color: #333;'>"._FILTERS."</label>";
				if(empty($optionvalues['trafficsource'])) { $optionvalues['trafficsource'] = 0; }
				echo printTrafficSourceSelectUI($optionvalues['trafficsource']);
				echo "</div>";
			}

			if(in_array("profileselector", $reportoptions) !== false) {
				if(LOGAHOLIC_BASE_EDITION !== $edition[4]) {					
					
					if(!$validUserRequired || $session->isAdmin() || $session->allProfiles ){
						echo "<div class='form-group'><label for='profileselector'>".ucwords(_PROFILE).":</label>";
						echo "<input type=text name=\"profileselector\" class=\"form-control\" value=\"$profile->profilename\"></div>";
						
					} else {
						if(!empty($session->user_profiles) && count($session->user_profiles) > 1){
							echo "<div class='form-group'><label for='profileselector'>".ucwords(_PROFILE).":</label>";
							echo "<input type=text name=\"profileselector\" class=\"form-control\" value=\"$profile->profilename\"></div>";
						}
					}
				}
			}

			if(in_array("crawlerselect", $reportoptions) !== false) {
				echo "<div class='form-group'>";
				echo "<label for=\"crawlerselect\">"._TRAFFIC.": </label>";
				echo "<select class='report_option_field form-control' id=\"crawlerselect\" name=\"crawlerselect\">";
					echo "<option ";
					if(isset($this->crawlerselect) && $this->crawlerselect == 2) {
						echo"selected='selected'";						
					}
					echo " value='2'>"._ALL_HUMANS_AND_BOTS."</option>";

					echo "<option ";
					if(!isset($this->crawlerselect) || $this->crawlerselect == 0) {
						echo"selected='selected'";
					}
					echo " value='0'>"._HUMANS_ONLY."</option>";

					echo "<option "; if(isset($this->crawlerselect) && $this->crawlerselect == 1) {
						echo"selected='selected'";						
					}
					echo " value=\"1\">"._BOTS_ONLY."</option>";
				echo "</select>";
				echo "</div>";
			}

			if(in_array("human", $reportoptions) !== false) {
				echo "<div class='form-group'>";
				echo "<label for=\"human\">"._TRAFFIC.": </label>";
				echo "<select class='report_option_field form-control' id=\"human\" name=\"human\">";
					echo "<option ";
					if(!isset($r->human) || $r->human == 0) {
						echo"selected='selected'";
					}
					echo " value='0'>"._HUMANS_ONLY."</option>";

					echo "<option ";
					if(isset($r->human) && $r->human == 1) {
						echo"selected='selected'";	
						//$r->fileNameExpension .= ".C1";
					}
					echo " value='1'>"._ALL_HUMANS_AND_BOTS."</option>";

					
					
				echo "</select>";
				echo "</div>";
			}
			
			# If this reports does not create datafiles we should not be able to recreate them.
			$exceptions = array("_BOUNCE_RATE", "_EXIT_RATE", "_BOUNCE_RATE_PER_DAY", "_TOP_CITIES", "_NEW_VS_RETURNING", "_PAGETIME");
			if((isset($reports[$r->label_constant]['Update']) && $reports[$r->label_constant]['Update'] === false) && !in_array($r->label_constant, $exceptions) ) {
				// lala
			} else {

				echo "<div class='form-group'><label for='regenerateDatafiles'>". _RECREATE_DATAFILES ."</label>";
				echo "<select id=\"regenerateDatafiles\" name=\"regenerateDatafiles\" class=\"form-control\">";
				echo "<option value=\"false\">No</option>";
				echo "<option value=\"true\">Yes</option>";		
				echo "</select></div>";
			
			}
			if(in_array("columnSelector", $reportoptions) !== false) {
				if($r->displaymode != 'pie' && $r->displaymode != 'bubble') {
					columnSelector();
				}
			}

		echo "</div>";
	echo "</div>";

}

function columnSelector() {
	global $r, $optionvalues;
	$fields = $r->fieldsarray();
	
	if(!empty($optionvalues['displaymode']) && $optionvalues['displaymode'] != 'table') {
		$display = " style='display: none;'";
	} else {
		$display = "";
	}

	$always_display = array("_DATE","_MINUTE_SHORT","_UNIQUE_IPS");
	
	echo "<div class='form-group'>";
	echo "<label>". _SHOW_HIDE_COLUMNS ."</label>";
	echo "<div class='column-selector-form'>";
		echo "<table>";
		$i = 0;
		$first = true;
		foreach($fields as $field) {
			$name = "showColumn".$i;
			if(!isset($optionvalues[$name])) {
				$first = true;
			}else{
				$first = false;
				break;
			}
			$i ++;
		}
		$i = 0;
		foreach($fields as $field){
			$name = "showColumn".$i;
			if(isset($optionvalues[$name])) {
				$selected = "checked='yes'";				
			} else {
				$selected = "";
			}
			if($first == true) {
				
				if (isset($r->columnDefinitions[$i]["hide_column"])== true && $r->displaymode == "table") {
					$selected = "";	
				} else if (isset($r->columnDefinitions[$i]["show_line"]) &&  $r->columnDefinitions[$i]["show_line"] === false) {
					$selected = "";	
				} else {
					$selected = "checked='yes'";
				}
				
			}

			$disabled = "";
			if(in_array($r->columnDefinitions[$i]["Label"], $always_display)){
				$disabled = "disabled";
			}

			echo "<tr><td><input class='noTextInput' type='checkbox' {$selected} {$disabled} name='showColumn{$i}' /></td><td>{$field}</td></tr>";
			$i ++;
		}
		echo "</table>";
	echo "</div>";
	echo "</div>";
}

$labels = ( empty($_POST['labels']) ) ? $_GET['labels'] : $_POST['labels'];
if (!isset($reports[$labels])) { die('invalid label'); }

if(!empty($labels) && $labels != 'global') {
	$report_label = $labels;
	
	$r = new $reports[$report_label]["ClassName"]();
	
	$optionvalues = ( empty($_POST) ) ? $_GET : $_POST;

	$ropts = explode(",",$reports[$report_label]["Options"]);

	$reportoptions = [];

	$i = 11;
	foreach ($ropts as $o) {
		switch ($o) {
			case 'daterangeField'		: $reportoptions[0] = $o; break;
			case 'displaymode'			: $reportoptions[1] = $o; break;
			case 'source'				: $reportoptions[2] = $o; break;
			case 'search'				: $reportoptions[3] = $o; break;
			case 'internal_site_search'	: $reportoptions[4] = $o; break;
			case 'roadto'				: $reportoptions[5] = $o; break;			
			case 'period'				: $reportoptions[6] = $o; break;
			case 'limit'				: $reportoptions[7] = $o; break;
			/* Advanced Order */
			case 'trafficsource'	: $reportoptions[8] = $o; break;
			case 'profileselector'	: $reportoptions[9] = $o; break;
			case 'columnSelector'	: $reportoptions[10] = $o; break;
			
			default: $reportoptions[$i] = $o; $i ++; break;
		}
	}
	ksort($reportoptions);
	/* reset keys */
	$reportoptions = array_values($reportoptions);
	
	if(empty($optionvalues['period'])) {
		$optionvalues['period'] = $r->period;
	}
} else {
	$reportoptions = array("daterangeField");
}

foreach($reportoptions as $reportoption) {
	if($reportoption == "daterangeField") {
		if(!empty($optionvalues['from']) && !empty($optionvalues['to'])) {
			//$minDate = date(GetCustomDateFormat(), $optionvalues['from']);
			//$maxDate = date(GetCustomDateFormat(), $optionvalues['to']);
			$minDate = LogaDate($r->profile->dateFormat, $optionvalues['from']);
			$maxDate = LogaDate($r->profile->dateFormat, $optionvalues['to']);
		} else if(!empty($optionvalues['minimumDate']) && !empty($optionvalues['maximumDate'])) {
			
			// $minDate = $optionvalues['minimumDate'];
			// $maxDate = $optionvalues['maximumDate'];
			//echo "ahh";
			// do this in case we have a language change
			$f = DateToTimestamp($optionvalues['minimumDate'],$optionvalues['maximumDate']);
			$minDate = LogaDate($r->profile->dateFormat, $f['from']);
			$maxDate = LogaDate($r->profile->dateFormat, $f['to']);

		} else {
			// $minDate = date(GetCustomDateFormat(), $from);
			// $maxDate = date(GetCustomDateFormat(), $to);
			$minDate = LogaDate($r->profile->dateFormat, $from);
			$maxDate = LogaDate($r->profile->dateFormat, $to);
		}

		?>
		<div class="form-group">		
		<label for='daterangeField'><?php echo _DATE_RANGE; ?></label>
		<input type='text' class='noOption daterangeField daterange form-control' name='daterangeField' value='<?php echo $minDate; ?> - <?php echo $maxDate; ?>'/>
		<?php
		// echo "<input type='hidden' class='isDefault fromRange' name='from' value='{$from}' />";
		// echo "<input type='hidden' class='isDefault toRange' name='to' value='{$to}' />";
		echo "<input type='hidden' class='isDefault fromRange' name='minimumDate' value='{$minDate}' />";
		echo "<input type='hidden' class='isDefault toRange' name='maximumDate' value='{$maxDate}' />";
		echo "</div>";
	}
	
	if($reportoption == "displaymode") {
		if(!empty($optionvalues['displaymode'])) {
			$default_displaymode = $optionvalues['displaymode']; 
		} else {
			if(!empty($r->DefaultDisplay)) {
				$default_displaymode = $r->DefaultDisplay;
			} else {
				$default_displaymode = "table";
			}
		}
		
		$displaymodes = explode(",", $r->DisplayModes);
		
        echo "<div class='form-group'><label for='{$reportoption}'>"._DISPLAY_MODE.":</label>";
		echo "<select id=\"displaymode\" name=\"displaymode\" class=\"form-control\">";
			foreach($displaymodes as $displaymode) {
				if($default_displaymode == $displaymode) { $sel = "selected"; } else { $sel = ""; }
				
				$l = "_". strtoupper($displaymode);
				if(defined($l)){
					$v = constant($l);
				} else {
					$v = $displaymode;
				}

				echo "<option {$sel} value=\"{$displaymode}\">".ucwords($v)."</option>";
			}
		echo "</select></div>";
	}
	
	
	
	if($reportoption == "limit") {
		if(!empty($optionvalues['limit'])) {
			$limit = $optionvalues['limit'];
		}
		if (empty($limit)) {
		   $limit = $r->limit;
		}
		echo "<div class='form-group'><label for='{$reportoption}'>"._LIMIT."<span class='small'> ("._MAX_NUMBER_OF_RESULTS_TO_SHOW.")</span></label><input type='text' size='3' name='{$reportoption}' id='limit' value='{$limit}' class='form-control small'></div>";
	}
	
	
	if($reportoption == "roadto") {
		if(!empty($optionvalues['roadto'])) {
			$roadto = $optionvalues['roadto'];
		}
        echo "<div class='form-group'><label for='{$reportoption}'>"._TARGET.":</label>";
        echo "<select id=\"roadto\" name=\"roadto\" class='form-control'>";

        if ($profile->targetfiles) {
			$targets=explode(",",$profile->targetfiles);
			foreach ($targets as $thistarget) {
				if ($thistarget) {
					if(isset($roadto)) {
						if (trim($thistarget)==$roadto) { $sel="selected"; } else { $sel=""; }
					} else {
						$sel="";
					}
					echo "<option $sel value=\"".trim($thistarget)."\">".trim($thistarget)."\n";
				}
			}
        } else {
			echo "<option selected=\"selected\" value=\"\">"._NONE."</option>";
		}
        echo "</select></div>";
	}
	
	if($reportoption == "internal_site_search") {
		if(!empty($optionvalues['internal_site_search'])) {
			$search = $optionvalues['internal_site_search'];
		} else {
			$search = $profile->GetOtherSettings("sitesearch");
			if(empty($search)) {
				$search = "";
			}
		}
        echo "<div class='form-group'><label for='{$reportoption}'>"._SEARCH."&nbsp;"._PAGE.":</label>";
        echo "<input id=\"internal_site_search\" type=text size=40 name=internal_site_search value=\"$search\" class='form-control' placeholder='example: /search.php?q=' />";
        echo "<input type=hidden name=searchmode value=\"like\"></div>";
	}
	
	// search
	if($reportoption == "search") {
		if(!empty($optionvalues['search'])) {
			$search =urldecode($optionvalues['search']);
		} else {
            $search = "";    
        }
		
		if(!empty($optionvalues['searchmode'])) {
			$searchmode = $optionvalues['searchmode'];
		} else if (!empty($r->searchmode)) {
			$searchmode = $r->searchmode;

		}

		switch($report_label) {
			case "_GOOGLE_RANKINGS":
			case "_KEYWORD_CONVERSION":
			case "_KEYWORD_TRENDS":
			case "_TOP_KEYWORDS":
			case "_TOP_KEYWORDS_DETAILS":
				$metric = _KEYWORDS;
				break;
			case "_REFERRER_CONVERSION":
			case "_REFERRER_TRENDS":
			case "_TOP_REFERRERS":
			case "_TOP_REFERRERS_DETAILS":
				$metric = _REFERRERS;
				break;
			case "_ERROR_REPORT":
			case "_MOST_CRAWLED_PAGES":
			case "_PAGE_CONVERSION":
			case "_PAGE_TRENDS":
			case "_TOP_PAGES":
			case "_TOP_PAGES_DETAILS":
				$metric = _PAGES;
				break;
			case "_MOST_ACTIVE_CRAWLERS":
				$metric = _CRAWLERS;
				break;
			case "_MOST_ACTIVE_USERS":
			case "_RECENT_VISITORS":
				$metric = _IP_NUMBERS;
				break;
			case "_TOP_FEEDS":
				$metric = _FEEDS;
				break;
			default:
				$metric = constant($report_label);
		}

		echo "<div class='form-group'>";
		echo "<label for='searchmode'>";
		echo"Find {$metric} "._THAT."</label><div class='input-group'>";
		if (empty($searchmode)) {
			$searchmode="";
		}
		
		echo "<div class='styled-select'><select class='' id='searchmode' name='searchmode' >";
		if($searchmode == "not like") {
			echo "<option value='equals'>&nbsp;"._EQUALS."</option>";
			echo "<option value='like'>&nbsp;"._MATCH."</option>";
			echo "<option value='not like' selected>&nbsp;"._DONT_MATCH."</option>";
		} elseif($searchmode == "equals") {
			echo "<option value='equals' selected>&nbsp;"._EQUALS."</option>";
			echo "<option value='like'>&nbsp;"._MATCH."</option>";
			echo "<option value='not like'>&nbsp;"._DONT_MATCH."</option>";
		} else {
			echo "<option value='equals'>&nbsp;"._EQUALS."</option>";
			echo "<option value='like' selected>&nbsp;"._MATCH."</option>";
			echo "<option value='not like'>&nbsp;"._DONT_MATCH."</option>";
		}
		echo "</select></div>";

		echo "<input style='float:left;width:100%;max-width:170px;' type='text' name='search' id='search' value='{$search}' class='form-control' placeholder='"._SEARCH."' title=\""._YOU_MAY_USE_AND_OR_SELECTORS."\"><span class='small'>";
		echo "</span></div></div>";
	}
	
	if($reportoption == 'source') {
		echo "<script>from_date = {$this->from}; to_date = {$this->to};</script><div class='form-group'>";
			echo "<label for='sourcetype'>"._SEARCH."</label>";
			echo "<div class='input-group'>";
				echo '<div class="styled-select">';
					echo "<select class='report_option_field form-control' id='sourcetype'>";
						echo "<option value=\"page\" "; if (@$optionvalues['sourcetype'] == "page") { echo "selected=\"selected\""; } echo ">"._PAGE.": </option>";
						echo "<option value=\"keyword\" "; if (@$optionvalues['sourcetype'] == "keyword") { echo "selected=\"selected\""; } echo ">"._KEYWORD.": </option>";
						echo "<option value=\"referrer\" ";     if (@$optionvalues['sourcetype'] == "referrer") { echo "selected=\"selected\""; } echo ">"._REFERRER.": </option>";
					echo "</select>";			
				echo "</div>";
				echo "<input style='float:left;width:100%;max-width:170px;' placeholder='". _SEARCH ."' class='report_option_field form-control' type=\"text\" name=\"source\" id=\"source\" value=\"".@urldecode($optionvalues['source'])."\" onkeyup=\"popupActionMenu(event, this.value+'@'+this.id+'@'+$('#sourcetype').val(), 'forminput');\" onclick=\"popupActionMenu(event, this.value+'@'+this.id+'@'+$('#sourcetype').val(), 'forminput');\" autocomplete=\"off\"><br><br>";
				echo '<span class="small"></span>';
			echo "</div>";
		echo "</div>";
	} 
	
	if($reportoption == 'period') {
		# Period selector
		$sel1 = "";
		$sel2 = "";
		$sel3 = "";
		$sel4 = "";
		
		if ($optionvalues['period'] == '_DAYS') {
			$sel1 = "selected";
		} else if ($optionvalues['period'] == '_WEEKS') { 
			$sel2 = "selected";
		} else if ($optionvalues['period'] == '_MONTHS') { 
			$sel3 = "selected";
		} else {
			$sel4 = "selected";
		}
		
		echo "<div class='form-group'><label for='period'>".strtoupper(substr(_REPORT,0,1)).substr(_REPORT,1).' '._PERIOD.":</label> ";
		
		echo "<select id='period' name='period' class='form-control'>";
			echo "<option {$sel4} value='auto'>Auto</option>";
			echo "<option {$sel1} value='_DAYS'>"._DAYS."</option>";
			echo "<option {$sel2} value='_WEEKS'>"._WEEKS."</option>";
			echo "<option {$sel3} value='_MONTHS'>"._MONTHS."</option>";
		echo "</select></div>";
	}
	
	if($reportoption != 'columnSelector' && $reportoption != 'profileselector') {
		//echo "<br/><br/>";
	}

	if($reportoption == 'country') {
		echo "<div class='form-group'>";
			echo "<label for='country'>"._COUNTRY."</label><select class='report_option_field form-control' id='country'>";
			echo "<option value=''></option>";
			foreach($cnames as $country_code => $countryname) {
				echo "<option"; if(!empty($this->country)) { if($country_code == $this->country) { echo " selected "; } } echo " value='{$country_code}'>{$countryname}</option>";
			}
			echo "</select>";
		echo "</div>";
	}

	if($reportoption == 'country_list') {				
		?>
		<div class="form-group">
	        <label><?php echo _COUNTRIES; ?></label>                    
			<input type="text" name="country_list" class="tagBox" value="<?php echo @$optionvalues['country_list'];?>" data-url="includes/available_countries.php">
	    </div>
	    <?php
	}

	if($reportoption == 'profilelist') {				
		?>
		<div class="form-group">
	        <label><?php echo _PROFILES; ?></label>                   
			<input type="text" name="profilelist" class="tagBox" value="<?php echo @$optionvalues['profilelist'];?>" data-url="includes/available_profiles.php?multi=1">
	    </div>
	    <?php
	}

}

echo "<input name='conf' id='conf' value='{$profile->profilename}' type='hidden' />";
if(!empty($labels) && $labels != 'global') {
	echo "<input name='labels' id='labels' value='{$report_label}' type='hidden' />";
}

if(!empty($r)) {
	echo $r->DisplayCustomForm();
}

AdvancedOptions($reportoptions);

if(!empty($labels)) { // Delete Report
	if(!empty($downloaded_reports)) {
		if(array_key_exists($reports[$report_label]['ClassName'], $is_download) == true) {
			echo "<a style='position: absolute; margin-top: 100px; left: 15px;' class='delete_download' href='includes/deletedownload.php?conf={$conf}&delete_download={$is_download[$reports[$report_label]['ClassName']]}'>"._DELETE_DOWNLOADED_REPORT."</a>";
		}
	}
}

// if we need to disable any outputmodes in the export menu, let javascript know about it here
// if ($r->displayReportButtons == false) {
// 	$r->remove_outputmodes = array("all");
// }
if (!empty($r->remove_outputmodes)) {
	echo "<div class='remove_outputmodes' data-outputmodes=".json_encode($r->remove_outputmodes)."></div>";
}
?>