<?php

/**
* @desc This report lets you make split test of your pages and gives you an overview of wich one works the best.
*/
$reports["_URL_BASED_SPLIT_TEST"] = Array(
	"ClassName" => "UrlBasedSplitTest", 
	"Category" => "_TEST_CENTER",
	"canAggregate" => false,	
	"icon" => "images/icons/32x32/urlbasedsplittest.png",
	"Options" => "daterangeField",
	"Filename" => "url_based_split_test",
	"Distribution" => "Premium",
	"Order" => 3,
	"ReportVersion" => 1.0,
	"MinimumVersion" => 3.0,
	"EmailAlerts" => false,
	"Update" => false
);

class UrlBasedSplitTest extends Report {
	function Settings() {
		$this->help=_SPLIT_TEST_RESULTS_HELP;
		if(empty($this->pageA)){ $this->pageA = ""; }
		if(empty($this->pageB)){ $this->pageB = ""; }
		if(empty($this->roadAto )){ $this->roadAto  = ""; }
		if(empty($this->roadBto  )){ $this->roadBto   = ""; }
	}
		
	function DisplayCustomForm(){
		echo "<script>
		var conf_name = '{$this->profile->profilename}';
		var from_date = {$this->from};
		var to_date = {$this->to};
		</script>";
		echo "<div style='clear:both;'></div>";
		echo "<div class='form-group'>";
			echo "<label for='pageA'>"._PAGE." A:</label>";
			echo "<input class='report_option_field form-control' type='text' name='pageA' id='pageA' value='".@$this->pageA."' onkeyup=\"popupActionMenu(event, this.value+'@'+this.id+'@'+'page', 'forminput');\" onclick=\"popupActionMenu(event, this.value+'@'+this.id+'@'+'page', 'forminput');\">";
		echo "</div>";
		echo "<div class='form-group'>";
			echo "<label for='roadAto'>"._TARGET." A:</label>";
	        echo "<select class='report_option_field form-control' id=\"roadAto\" name=\"roadAto\">";
			 if ($this->profile->targetfiles) {
				$targets=explode(",",$this->profile->targetfiles);
				foreach ($targets as $thistarget) {
					if ($thistarget) {
						if(isset($this->roadAto)) {
							if (trim($thistarget)==$this->roadAto) { $sel="selected"; } else { $sel=""; }
						} else {
							$sel="";
						}
						echo "<option $sel value=\"".trim($thistarget)."\">".trim($thistarget)."\n";
					}
				}
				if (!$sel && !isset($this->roadAto)) {
					$this->roadAto=$targets[0];
				}
	        }
	        echo "</select>";		
		echo "</div>";
		echo "<div class='form-group'>";
			echo "<label for='pageB'>"._PAGE." B:</label>";
			echo "<input class='report_option_field form-control' type='text' name='pageB' id='pageB' value='".@$this->pageB."' onkeyup=\"popupActionMenu(event, this.value+'@'+this.id+'@'+'page', 'forminput');\" onclick=\"popupActionMenu(event, this.value+'@'+this.id+'@'+'page', 'forminput');\">";
		echo "</div>";
		echo "<div class='form-group'>";
			echo "<label for='roadBto'>"._TARGET." B:</label>";
	        echo "<select class='report_option_field form-control' id=\"roadBto\" name=\"roadBto\">";
			 if ($this->profile->targetfiles) {
				$targets=explode(",",$this->profile->targetfiles);
				foreach ($targets as $thistarget) {
					if ($thistarget) {
						if(isset($this->roadBto)) {
							if (trim($thistarget)==$this->roadBto) { $sel="selected"; } else { $sel=""; }
						} else {
							$sel="";
						}
						echo "<option $sel value=\"".trim($thistarget)."\">".trim($thistarget)."\n";
					}
				}
				if (!$sel && !isset($this->roadBto)) {
					$this->roadBto=$targets[0];
				}
	        }
	        echo "</select>";	
		echo "</div>";
	}
	function DisplayReport() {
		$this->reportHeader(); 
		
		if(empty($this->pageA) || empty($this->pageB)){
			echoNotice($this->SettingsButton()._NO_OPTIONS_FOUND);
			return;
		}

		$data1 = $this->collectData($this->pageA,$this->roadAto);
		$data2 = $this->collectData($this->pageB,$this->roadBto);
		
		$this->displayReportButtons = false;
		
		echo "<div style='width:500px;margin: 0 auto;font-size:14px;line-height:20px;padding: 10px 0 10px 0;'>";
		echo _URL_SPLIT_TEST_HEADER."<br />";
		echo "</div>";

		echo "<div style='width:500px;margin: 0 auto;font-size:12px;line-height:20px;padding: 3px;'>";
		echo "<span style='background: #de241b url(images/bg_glass_red2.png) 50% 50% repeat-x; color:#FFF;padding:3px;border:1px solid grey;border-radius:4px;'>"._PAGE." A:</span>
		<u>{$this->pageA}</u> <img src=\"images/icons/arrow_right.gif\"> <u>{$this->roadAto}</u></div>";
		
		echo "<div style='width:500px;margin: 0 auto;font-size:12px;line-height:20px;padding: 3px'>";
		echo "<span style='background: #49c106 url(images/bg_glass_green.png) 50% 50% repeat-x; padding:3px;border:1px solid grey;border-radius:4px;''>"._PAGE." B:</span>
		<u>{$this->pageB}</u> <img src=\"images/icons/arrow_right.gif\"> <u>{$this->roadBto}</u>";
		echo "</div>";
		echo "<br>";
		$this->CompareMeter(_PAGE_VISITORS.":", $data1['page_total'], $data2['page_total'], _PAGE." A: {$data1['page_total']}", _PAGE." B: {$data2['page_total']}");
		$this->CompareMeter(_TARGET_VISITORS.":", $data1['target_indirect_total'], $data2['target_indirect_total'], "{$data1['target_indirect_total']}", "{$data2['target_indirect_total']}");
		
		$this->CompareMeter(_DIRECT_CONVERSION_RATE.":", $data1["direct"] , $data2["direct"], "{$data1['direct']}% ({$data1['target_total']})", "{$data2['direct']}% ({$data2['target_total']})");
		$this->CompareMeter(_CONVERSION_RATE." over time:", $data1["indirect"] , $data2["indirect"], "{$data1['indirect']}%", "{$data2['indirect']}%");

		echo "<br>";
		$this->DisplayWinner($data1,$data2,_PAGE);
	}
		
	function decideWinner($data1,$data2){		
		
		$cfactor = 0;
		if ($data1["page_total"]==0 || $data2["page_total"]==0) {
			echo "<P><table width=50% align=center cellpadding=5 border=0 cellspacing=0 class=smallborder style='text-align:center;'>";
			echo "<tr><td valign=center><b>"._NOT_ENOUGH_DATA_TO_DETERMINE."!</b><br/><br/>";
			echo "</td></tr></table>";
		} else {
			$epop = ($data1["target_indirect_total"] + $data2["target_indirect_total"]) / ($data1["page_total"] + $data2["page_total"]);
			$eerr = sqrt(($epop * (1 - $epop) * ($data1["page_total"] + $data2["page_total"]))/($data1["page_total"] * $data2["page_total"]));
			$cfactor = @(abs((@($data1["target_indirect_total"]/$data1["page_total"]) - @($data2["target_indirect_total"]/$data2["page_total"])))/$eerr);

			if ($cfactor > 0.01) {
			 $confidence=1;
			}
			if ($cfactor > 0.06) {
			 $confidence=5;
			}
			if ($cfactor > 0.14) {
			 $confidence=10;
			}
			if ($cfactor > 0.25) {
			 $confidence=20;
			}
			if ($cfactor > 0.52) {
			 $confidence=39;
			}
			if ($cfactor > 0.68) {
			 $confidence=50;
			}
			if ($cfactor > 1.00) {
			 $confidence=68;
			}
			if ($cfactor > 1.64) {
			 $confidence=90;
			}
			if ($cfactor > 1.96) {
			 $confidence=95;
			}
			if ($cfactor > 2.58) {
			 $confidence=99;
			}
			if ($cfactor > 2.81) {
			 $confidence=99.5;
			} else {
				$confidence = 0;
			}

			if (($data1["target_indirect_total"]/$data1["page_total"]) > ($data2["target_indirect_total"]/$data2["page_total"])) {
					 $winner=_PAGE." A";
					 $loser=_PAGE." B";
			} else {
					 $winner=_PAGE." B";
					 $loser=_PAGE." A";
			}
			if ($confidence >= 90) {
				echo "<P><table width=50% align=center cellpadding=5 border=0 cellspacing=0 class=smallborder style='text-align:center;'>";
				echo "<tr><td valign=center><font size=+1>"._SPLIT_TEST_WINNER." <font color=red><b>$winner</b></font> !</font><br/><br/>";
				echo _TEST_RESULTS_ARE_SIGNIFICANT." ( > $confidence% "._CONFIDENCE." ). "._YOU_CAN_BE_ABOUT." $confidence% "._CONFIDENT_THAT." $winner "._WILL_PERFORM_BETTER_THAN." $loser";
				echo "<br>&nbsp;</td></tr></table>";
			} else {
				echo "<P><table width=50% align=center cellpadding=5 border=0 cellspacing=0 class=smallborder style='text-align:center;'>";
				echo "<tr><td valign=center><font size=+1>"._SPLIT_TEST_WINNER." <b>"._INCONCLUSIVE."</b></font><br/><br/>";
				
				echo _TEST_RESULTS_ARE_NOT_SIGNIFICANT." ( > $confidence% "._CONFIDENCE." ). "._YOU_CAN_ONLY_BE_ABOUT." $confidence% "._CONFIDENT_THAT." $winner "._WILL_PERFORM_BETTER_THAN." $loser. "._WHEN_THE_LEVEL_DROPS." $winner "._JUST_GOT_LUCKY.".";
				
				echo "<br>&nbsp;</td></tr></table>";
			}
		}
	}
	function collectData($page,$target){		
		global $db;
		$return = [];
		$return["page"] = $page;
		$return["roadto"] = $target;
		
		$page_id = getID($page,"urls");
		$target_id = getID($target,"urls");
		
		$query="select count(distinct visitorid) as users from {$this->profile->tablename_conversions} where timestamp >=". $db->quote($this->from) ." and timestamp <=". $db->quote($this->to) ." and url=". $db->quote($target_id); 
		$result=$db->Execute($query);
		$data=$result->FetchRow();
		$conversions=$data["users"];
		
		$query="select count(distinct visitorid) as users from {$this->profile->tablename} where timestamp >=". $db->quote($this->from) ." and timestamp <=". $db->quote($this->to) ." and url=". $db->quote($page_id) ." and (status=200 or status=302)";
		$result=$db->Execute($query);
		$data=$result->FetchRow();
		$page_total=$data["users"];
		
		$query="select count(distinct visitorid) as users from {$this->profile->tablename} as a, {$this->profile->tablename_referrers} as r where timestamp >=". $db->quote($this->from) ." and timestamp <=". $db->quote($this->to) ." and url=". $db->quote($target_id) ." and a.referrer=r.id and r.referrer like ". $db->quote("%{$this->profile->confdomain}{$page}") ." and (status=200 or status=302)";
		$result=$db->Execute($query);
		$data=$result->FetchRow();
		$target_total=$data["users"];
				
		$subq = "select visitorid, timestamp from {$this->profile->tablename_conversions} where url=". $db->quote($target_id) ." and timestamp between ". $db->quote($this->from) ." and ". $db->quote($this->to) ."";
		$query="select count(distinct l2.visitorid) as users from {$this->profile->tablename} as l, ($subq) as l2 where l.timestamp >=". $db->quote($this->from) ." and l.timestamp <=". $db->quote($this->to) ." and l.visitorid=l2.visitorid and l.url=". $db->quote($page_id) ." and l.timestamp < l2.timestamp and (l.status=200 or l.status=302)";
		
		$result=$db->Execute($query);
		$data=$result->FetchRow();
		$target_indirect_total=$data["users"];
		
		$return["conversions"] = $conversions;
		$return["page_total"] = $page_total;
		$return["target_total"] = $target_total;
		$return["target_indirect_total"] = $target_indirect_total;

		if($return["page_total"] > 0){
			$return['direct'] = number_format(($return["target_total"]/$return["page_total"]*100),2);
			$return['indirect'] = number_format(($return["target_indirect_total"]/$return["page_total"]*100),2);
		}else{
			$return['direct'] = 0;
			$return['indirect'] = 0;
		}
		if($return["conversions"] > 0){		
			$return["salesp"] = number_format(($return["target_indirect_total"]/$return["conversions"]*100),2);
		}else{
			$return["salesp"] = 0;
		}		
		return $return;
	}
	function buildView($data){
		if($data["page_total"] > 0){
			$direct = number_format(($data["target_total"]/$data["page_total"]*100),2);
			$indirect = number_format(($data["target_indirect_total"]/$data["page_total"]*100),2);
		}else{
			$direct = "0";
			$indirect = "0";
		}
		if($data["conversions"] > 0){		
			$salesp = number_format(($data["target_indirect_total"]/$data["conversions"]*100),2);
		}else{
			$salesp = "0";
		}
		echo "<div class='report-header'><div class='report-header-content'><div class=\"dialog_info\">"._DATE_RANGE.": ".date("d M Y",$this->from)." - ".date("d M Y",$this->to)." - "._TARGET.": {$data["roadto"]}</div></div></div>";
		echo "<table cellspacing='0' cellpadding='5' style='width:100%;'>";
		echo "<tr style='background:#C0C0C0;'><td>"._PAGE.": ". $data["page"] ."</td><td>"._USERS."</td><td>"._CONVERSIONS."</td></tr>";
		echo "<tr><td>"._PAGE." ". _VISITORS.":</td><td>". $data["page_total"] ."</td></tr>";
		echo "<tr style='background:#F1F1F1;'><td>"._PAGE." "._DIRECT_CONVERSIONS.":</td><td>". $data["target_total"] ."</td><td>" .$direct."%</td></tr>";
		echo "<tr><td>"._PAGE." "._TIMELAPSE_CONVERSIONS.":</td><td>". $data["target_indirect_total"] ."</td><td>" .$indirect."%</td></tr>";
		echo "<tr style='background:#F1F1F1;'><td colspan='3'>The page ({$data["page"]}) "._WAS_VIEWED_BY ." ".$salesp." % of ".$data["conversions"]." ". _TOTAL_CONVERTED_USERS ."</td></tr>";
		echo "</table>";		
	}
	
	function UpdateStats($from = '', $to = '',$print = 2) {
		return false;
	}
}