<?php

/**
* @desc This report displays an analysis of your funnel
*/
$reports["_FUNNEL_ANALYSIS"] = Array(
	"ClassName" => "FunnelAnalysis", 
	"Category" => "_PERFORMANCE",
	"canAggregate" => false,  
	"icon" => "images/icons/32x32/funnelanalysis.png",
	"Options" => "daterangeField,profileselector",
	"Filename" => "funnel_analysis",
	"Distribution" => "Premium",
	"Order" => 10,
	"ReportVersion" => 1.0,
	"MinimumVersion" => 3.0,
	"EmailAlerts" => false,
	"Update" => false
);

class FunnelAnalysis extends Report {
	
	function Settings() {		
		$this->funneltablename = $this->profile->tablename."_funnels";

		$this->columnDefinitions[] = array("Label" => _CONVERSION_PERC);
		$this->columnDefinitions[] = array("Label" => _STAGE);
		$this->columnDefinitions[] = array("Label" => _UNIQUE_VISITORS);
		$this->columnDefinitions[] = array("Label" => _BOUNCE_RATE);
		$this->columnDefinitions[] = array("Label" => _RETENTION_PERC);
		$this->columnDefinitions[] = array("Label" => _VALUE);

		$this->help = _HELP_TEXT_FUNNELS;

		$this->sortTable=false;

		$this->displayReportButtons=false;

		$this->displayTotalRow = false;

	}

	function RGBtoHex($rgb){
		if(!is_array($rgb)){
			$color = substr($rgb, strpos($rgb, "(") + 1,  -1);
			$rgb = explode(",", $color);
		}

		$R = $rgb[0];
		$G = $rgb[1];
		$B = $rgb[2];

		$R = dechex($R);
		If (strlen($R)<2){
			$R='0'.$R;
		}

		$G=dechex($G);
		If (strlen($G)<2){
			$G='0'.$G;
		}

		$B=dechex($B);
		If (strlen($B)<2){
			$B='0'.$B;
		}

		return '#' . $R . $G . $B;
	}

	function DisplayReport() {
		
		$this->ReportHeader(); 
		
		if(!isset($this->funnelid)){
			echoNotice($this->SettingsButton()._SELECT." "._FUNNEL);
			return false;
		}
		
		if (CheckIfTableExists($this->funneltablename) != 1) {
			echoNotice(_NO_DATA_TO_DISPLAY,"margin:5px;");
			return false;
		}

		$data = $this->GetReportData();
		if(!$data){
			return false;	
		}

		$this->addlabel = _FUNNEL.": ". $this->funnelname;		

		echo '<script src="components/d3.v3/d3-funnel.min.js"></script>';
		echo '<style type="text/css">
			.funnel-graph{ width: 25%; float:left; height:220px; }
			.funnel-table{ width: 70%; float:right; }
		</style>';

		$graph = "F" . md5(time() . rand(0,1000));

		$funneldata = [];

		foreach ($data as $k => $v) {
			if(strpos("haystack", "rgb") !== false){
				$color = $this->RGBtoHex( $this->graphcolors[$k] );
			} else {
				$color = $this->graphcolors[$k];
			}

			$funneldata[] = array( $v[1], intval($v[2]), $color  );

			$data[$k][1] = "<span style='color:{$color};'>{$v[1]}</span>";
		}

		echo "<div id='$graph' class='funnel-graph' data-chart='". json_encode($funneldata) ."'></div>";
		echo "<div class='funnel-table'>";		
			$this->Table($data);
		echo "</div>";
		echo "<div style='clear:both;'></div>";

		echo "<script type='text/javascript'>lg.FunnelChart(\"$graph\");</script>";

		
	}

	function GetReportData(){
		global $db;

		$q = $db->Execute("select * from {$this->funneltablename} where funnelid=". $db->Quote($this->funnelid) ." order by id");
		
		$i=0;
		while (($q) && ($data = $q->FetchRow())) {
			if ($data['funnelid'] == $data['id']) {
				# funnelname
				$this->funnelname = $data['label'];

			} else if ($data['funnelid']!=$data['id'] && $i == 0) {
				$url1 = $data['url'];
				$label1 = $data['label'];
				$value1 = $data['value'];
				$i++;
			} else {
				$ourls[$i] = $data['url'];
				$olabels[$i] = $data['label'];
				$ovalues[$i] = $data['value'];
				$i++;
			}
		}

		if($i == 0){
			echoWarning(_NO_FUNNEL_DEF);
			return false;
		}



		# 1. get all the ips that started at the first url and put that in a temp table
		if (@$url1=="" || @$url1=="any") {
			$q = $db->Execute("select count(distinct visitorid) from {$this->profile->tablename} where timestamp >=". $db->Quote($this->from) ." and timestamp <=". $db->Quote($this->to));
			$data=@$q->FetchRow();
			$total_pop = $data[0];
		} else {
			$query = "create temporary table {$this->profile->tablename}_temp_fips (visitorid int(11))";
			
			$db->Execute($query) or die (_ERROR.":" . $db->ErrorMsg());
			$sqlstr = $this->makesql($url1,"");
			$query  = "insert into {$this->profile->tablename}_temp_fips select visitorid from {$this->profile->tablename} as a,{$this->profile->tablename_urls} as u,{$this->profile->tablename_urlparams} as up,{$this->profile->tablename_referrers} as r where timestamp >=". $db->Quote($this->from) ." and timestamp <=". $db->Quote($this->to) ." and a.url=u.id and a.params=up.id and a.referrer=r.id $sqlstr group by visitorid";
			  
			$db->Execute($query);

			$q = $db->Execute("select count(distinct visitorid) from {$this->profile->tablename}_temp_fips");
			$data=@$q->FetchRow();
			$total_pop = $data[0];
		}

		# 2. from the above get all ips that made it to the other urls
		$i=1;
		while (@$ourls[$i]!="") {
			if ($url1=="" || $url1=="any") {
				$sqlstr = $this->makesql($ourls[$i], "");
				$result = $db->Execute("select count(distinct visitorid) from {$this->profile->tablename} as a,{$this->profile->tablename_urls} as u,{$this->profile->tablename_urlparams} as up,{$this->profile->tablename_referrers} as r where timestamp >=". $db->Quote($this->from) ." and timestamp <=". $db->Quote($this->to) ." and a.url=u.id and a.params=up.id and a.referrer=r.id $sqlstr")  or die ("Error:" . $db->ErrorMsg());
			} else {
				$sqlstr = $this->makesql($ourls[$i],"m.");
				$result = $db->Execute("select count(distinct t.visitorid) from {$this->profile->tablename} as a, {$this->profile->tablename}_temp_fips as t,{$this->profile->tablename_urls} as u,{$this->profile->tablename_urlparams} as up,{$this->profile->tablename_referrers} as r where a.timestamp >=". $db->Quote($this->from) ." and a.timestamp <=". $db->Quote($this->to) ." and a.visitorid=t.visitorid and a.url=u.id and a.params=up.id and a.referrer=r.id $sqlstr")  or die ("Error:" . $db->ErrorMsg());
			}
			$data = @$result->FetchRow();
			$url_pop[$i] =$data[0];
			$i++;
		}

		// create data array
		$r = 0;
		$data = [];

		//set the first row
		if (!@$url1) {
			if (!@$funnelname) {
				echoWarning(_NO_FUNNEL_FOUND);
				return false;   
			}
			echoWarning(_FUNNEL .":". $funnelname . "<br/>" . _DEFINITION_INCOMPLETE);
			return false;
		}
		
		$data[$r][0]= 100;
		$data[$r][1]= $label1;
		$data[$r][2]= $total_pop;
		$data[$r][3]= 0;
		$data[$r][4]= 0;
		$data[$r][5]= ($value1*$total_pop);

		//set the rest
		$r=1;
		$i=1;
		while (@$ourls[$i] != "") {
			$data[$r][0] = @round((($url_pop[$i]/$total_pop)*100),2); 
			$data[$r][1] = $olabels[$i];
			$data[$r][2] = $url_pop[$i];
			if ($i <= 1) {
				@$data[$r][3] = (($url_pop[$i]/$total_pop)*100)-100;
				@$data[$r][4] = (($url_pop[$i]/$total_pop)*100);
			} else {
				@$data[$r][3] = (($url_pop[$i]/$url_pop[($i-1)])*100)-100;
				@$data[$r][4] = (($url_pop[$i]/$url_pop[($i-1)])*100);
			}
			$data[$r][5] = ($url_pop[$i]*$ovalues[$i]);
			
			$data[$r][6]= $ourls[$i];
			$i++;
			$r++;
		}

		reset($data);
		return $data;

	}	
	
	function makesql($urls,$prefix) {
		global $db;

		$urls=explode(",",$urls); 
		$gi=0;
		$sqlstr="";

		while (@$urls[$gi]!="") {
			$urls[$gi]=trim($urls[$gi]);
			if ($gi==0) {
				$cond="and (";
			} else {
				$cond="or";
			}
			if (strpos(" ".$urls[$gi], "*")!=FALSE) {
				//we do a like style
				$urls[$gi]=str_replace("*", "%", $urls[$gi]);
				if (strpos(" ".$urls[$gi],"ttp://")!=FALSE) {
					$sqlstr.="$cond r.referrer like ". $db->Quote($urls[$gi]);
				} else {
					$sqlstr.="$cond concat(u.url,up.params) like ". $db->Quote($urls[$gi]);
				}
			} else {
				if (strpos(" ".$urls[$gi],"http:")!=FALSE) {
					$sqlstr.="$cond r.referrer=". $db->Quote($urls[$gi]);
				} else {
					if (strpos("?",$urls[$gi])!=FALSE) {
						$sqlstr.="$cond concat(u.url,up.params)=". $db->Quote($urls[$gi]);
					} else {
						$sqlstr.="$cond u.url=". $db->Quote($urls[$gi]);
					}
				}
			}
			$gi++;
		}
		
		return $sqlstr.")";
	}
	
	function DisplayCustomForm() {
		global $db,$session;


        //TODO: CHECK IF IT NEEDS A FIX.
        //$q = $db->Execute("select id,label from {$this->funneltablename} where id=funnelid");
		$ii=1;
		echo "<div class='form-group'>";
			echo "<label for='funnelid'>". _SELECT ."</label>";
			echo "<select class='report_option_field form-control' id='funnelid'>";
			if (!$q->fields) {
				// Probably no table.  When we create a test, we'll create the table.
				echo "<option value=''>"._NONE."</option>";
			}
			while (($q) && ($data=@$q->FetchRow())) {
				echo "<option value='{$data['id']}'>{$data['label']}</option>";
			}
			echo "</select>";
		
			if($session->canEditProfiles()){
				echo "<a href='definereport.php?conf={$this->profile->profilename}&labels=_FUNNEL_ANALYSIS' data-title='". _LOGAHOLIC_FUNNEL_ANALYSIS ."' class='optionlink open_iframe_window'>"._MANAGE_FUNNELS."</a>";
			}

		echo "</div>";
	}
	
	function GetFunnelid() {
		global $db;
		
		$q = @$db->Execute("select id,label from {$this->funneltablename} where id=funnelid LIMIT 1");
		$data=@$q->FetchRow();
		return $data[0]; 
	}	
	
	function EditFunnel() {
		global $ourls,$db;
		
		$olabels = [];
		if ($this->funnel=="create") {
			//this is new
		} else {
			// get info from database
			$ourls=[];
			$q = $db->Execute("select * from {$this->funneltablename} where funnelid=". $db->Quote($this->funnelid) ." order by id");
			$i=0;
			while (($q) && ($data=@$q->FetchRow())) {
				if ($data['funnelid']==$data['id']) {
					//funnelname
					$this->funnelname=$data['label'];
				}else {
					//rest
					$ourls[$i]=$data['url'];
					$olabels[$i]=$data['label'];
					$ovalues[$i]=$data['value'];
					$i++;
				}
			}
		}
		
		echo "<form method='post' id=\"editform\" name=\"editform\">";

			echo "<h3>". _DEFINE_FUNNEL ."</h3>";

			echo "<div class='form-group'>
				<label>"._FUNNEL_NAME."</label>
				<input class='form-control' placeholder='". _GIVE_FUNNEL_NAME ."' type='text' size='30' name='funnelname' maxval='50' value=\"".@$this->funnelname."\" />
			</div>";
		
			$form_id = md5(time());
			echo "<div id='{$form_id}' class='report-options'><table class='table'>";
				echo "<label>". _FUNNEL_DEF ."</label>";

				echo "<tr><td><label>"._LABELNAME."</label></td><td><label>"._PAGES."</label></td><td><label>"._VALUE."</label></td><td></td></tr>";

				if(count($olabels) == 0) {
					echo "<tr class='conditions_row'>
							<td><input placeholder='"._LABELNAME."' class='form-control' src='field' rel='1' name='field1' id='field1' value='' autocomplete='off'></td>
							<td><input placeholder='"._PAGES."' class='form-control funnelqbuilder' src='group' rel='1' name='group1' id='group1' value='' autocomplete='off'></td></td>
							<td><input placeholder='"._VALUE."' class='form-control' src='value' rel='1' name='value1' id='value1' value='' autocomplete='off'></td>

	                        <td><div class='btn-group'>
	                            <a class='btn btn-default plus_btn noOption'>+</a>
	                            <a class='btn btn-default min_btn noOption' disabled='disabled'>-</a>
	                        </div></td>
	                    </tr>";
				} else {
					for($c = 0; $c < count($olabels); $c++) {
					echo "<tr class='conditions_row'>
							<td><input placeholder='"._LABELNAME."' class='form-control' src='field' rel='".($c + 1)."' name='field".($c + 1)."' id='field".($c + 1)."' value='".@$olabels[$c]."' autocomplete='off'></td>
							<td><input placeholder='"._PAGES."' class='form-control funnelqbuilder' src='group' rel='".($c + 1)."' name='group".($c + 1)."' id='group".($c + 1)."' value='".@$ourls[$c]."' autocomplete='off'></td>
							<td><input placeholder='"._VALUE."' class='form-control' src='value' rel='".($c + 1)."' name='value".($c + 1)."' id='value".($c + 1)."' value='".@$ovalues[$c]."' autocomplete='off'></td>

	                        <td><div class='btn-group'>
	                            <a class='btn btn-default plus_btn noOption'>+</a>
	                            <a class='btn btn-default min_btn noOption'>-</a>
	                        </div></td>
	                    </tr>";
					}
				}
			echo "</table></div>";

			echo "<script type='text/javascript'>plusMinusForm('{$form_id}', 'field', 'group', 'value', false);</script>";
			echo "<script type='text/javascript'>
					var conf_name = '{$this->profile->profilename}';
					var from_date = '{$this->from}';
					var to_date = '{$this->to}';
					$(\".funnelqbuilder\").on('keyup', function(event) {
						QBuilderHelpForms('funnelentry', event, $(this).val() + '@' + 'group' + $(this).attr('rel') + '@' + 'funnelentry', 'forminput');
					});

					$(\".funnelqbuilder\").on('click', function(event) {
						QBuilderHelpForms('funnelentry', event, $(this).val() + '@' + 'group' + $(this).attr('rel') + '@' + 'funnelentry', 'forminput');
					});
			</script>";
			
			echo "<div class='form-group'>
				<input type='hidden' name='funnel' value=\"save\" />
				<input type='hidden' name='funnelid' value=\"".@$this->funnelid."\" />
				<input type='hidden' name='edit' value=\"".@$this->funnel."\" />
				<input type='hidden' name='conf' value=\"{$this->profile->profilename}\" />

				<input class='btn btn-primary' type='submit' value='". _SAVE ."' />
			</div>";

		echo "</form>";
	}

	function SaveFunnel() {
		global $db,$databasedriver;

		if ($_REQUEST["funnelname"]=="") {
			$_REQUEST["funnelname"]=_UNNAMED_FUNNEL_REPORT;
		}
		
		if(!empty($this->funnelid)){		
			if ($this->funnelid) {
				//update funnel
				$db->Execute("update {$this->funneltablename} set label=".$db->Quote($_REQUEST["funnelname"])." where id=". $db->Quote($_REQUEST["funnelid"])."");
				$db->Execute("delete from {$this->funneltablename} where funnelid=".$db->Quote($_REQUEST["funnelid"])." and id!=funnelid") or die ($db->ErrorMsg());

				// loop the other urls
				if (@$_REQUEST["group1"]=="") {
					$_REQUEST["group1"]="any";
				}
				$i=1;
				while ($i < 25) {
					$field = "";
					if(!empty($_REQUEST["field$i"])){
						$field = $_REQUEST["field$i"];
					}
					$value = 0;
					if(!empty($_REQUEST["value$i"])){
						$value = $_REQUEST["value$i"];
					}
					$group = "";
					if(!empty($_REQUEST["group$i"])){
						$group = $_REQUEST["group$i"];
					}
					if ($group || $field) {
						$db->Execute("insert into {$this->funneltablename} (funnelid, label, url, value) values (". $db->Quote($_REQUEST["funnelid"]).",". $db->Quote($field) .",". $db->Quote($group) .",". $db->Quote($value) .")");
					}
					$i++;
				}
			
				return "<div style='margin: 3px 5px; float: left;' class=\"warning ui-state-highlight ui-corner-all\">"._UPDATED.": <b>".$_REQUEST["funnelname"]."</b></div>";  
			} 
		}else {
			# If the tables don't already exists, then create them...

				$db->Execute("CREATE OR REPLACE TABLE  $this->funneltablename (".
				"id " . ($databasedriver == "sqlite"? "INTEGER PRIMARY KEY ": "int(11) NOT NULL auto_increment ") . "," .
				"funnelid int(11) default NULL,
				label varchar(100) NOT NULL default '',
				value double(100,2) NOT NULL default '0.00',
				url blob default NULL ".
				($databasedriver == "sqlite" ? "" : ", PRIMARY KEY  (id)") . 
				") ENGINE=MyISAM  CHARSET=utf8");

			$q = $db->Execute("SELECT label FROM {$this->funneltablename} WHERE label = ".$db->Quote($_REQUEST["funnelname"])."");
			while($check = $q->fetchRow()){
				echoWarning("Funnel name already taken!");
				return;
			}
			# Insert the funnel
			$db->Execute("insert into {$this->funneltablename} (label) values (". $db->Quote($_REQUEST["funnelname"]).")");
			$nfid=$db->Insert_ID();
			$db->Execute("update {$this->funneltablename} set funnelid=". $db->Quote($nfid) ." where id=". $db->Quote($nfid));

			// loop the other urls
			if (@$_REQUEST["group1"]=="") {
				$_REQUEST["group1"]="any";
			}
			
			if ($_REQUEST["group1"]!="") {
				$i=1;
				while ($i < 25) {
					$field = "";
					if(!empty($_REQUEST["field$i"])){
						$field = $_REQUEST["field$i"];
					}
					$value = 0;
					if(!empty($_REQUEST["value$i"])){
						$value = $_REQUEST["value$i"];
					}
					$group = "";
					if(!empty($_REQUEST["group$i"])){
						$group = $_REQUEST["group$i"];
					}
					if ($group) {
						$db->Execute("insert into {$this->funneltablename} (funnelid, label, url, value) values (".$db->Quote($nfid).",".@$db->Quote($field).",".$db->Quote($group).",".$db->Quote($value).")");
					}
					$i++;
				}
				$i++;
			}
					
			echoNotice(_SAVED."!");
			return;
		}
	}

	function DeleteFunnel() {
		global $db;
		$db->Execute("delete from {$this->funneltablename} where funnelid=". $db->Quote($this->funnelid)."") or die ($db->ErrorMsg());
		
		echoNotice(_DELETED_FUNNEL."!");
	}
	
	function Welcome() {		
		$msg = ">" ._LOGAHOLIC_FUNNEL_ANALYSIS."</h3>";

		$msg .= "<span>". _WHAT_IS_FUNNEL ."</span>";
		
		$msg .= _CHOOSE_FUNNEL_OR;
		$msg .= "<a data-title='". _LOGAHOLIC_FUNNEL_ANALYSIS ."' href=definereport.php?labels=_FUNNEL_ANALYSIS&funnel=create&conf={$this->profile->profilename}>"._CREATE_NEW_FUNNEL."</a>.";
		
		$msg .= "<br/><br/><h4>"._WHATS_SALES_FUNNEL."?</h4><span>" . _A_SALES_TUNNEL. "</span>";

		echoNotice($msg);
	}
	
	function Toppanel() {
		$link = "definereport.php?conf={$this->profile->profilename}&labels=_FUNNEL_ANALYSIS";

		echo "<div class='nav-tabs-custom'>";
		    echo "<ul class='nav nav-tabs'>";
		    if($this->funnel == "manage"){
		        echo "<li class='active'><a href='{$link}&funnel=manage'>". _MANAGE_FUNNELS . "</a></li>";
		        echo "<li class=''><a href='{$link}&funnel=create'>". _CREATE_NEW_FUNNEL . "</a></li>";
		    } else {
		        echo "<li class='active'><a href='{$link}&funnel=create'>". _CREATE_NEW_FUNNEL . "</a></li>";
		        echo "<li class=''><a href='{$link}&funnel=manage'>". _MANAGE_FUNNELS . "</a></li>";
		    }
		     echo "<li class='pull-right'><a class='text-help-btn'><i class='fa fa-info'></i></a></li>";
		    echo "</ul>";
		echo "</div>";		
		echo "<div class='text-help' style='display:none;'>";
		if($this->funnel =="manage"){
			$this->Welcome();
		} else {
			echoNotice("<button class=\"close\" aria-hidden=\"true\" data-dismiss=\"alert\" type=\"button\">x</button>					
				<b>"._STAGE." 1:</b><br>"._FIRST_FUNNEL_PAGE_DEF. ":<br>https://www.google.*
				<br/><br/>
				<b>" ._STAGE." 2, 3, 4 "._ETCETERA.":</b><br>"._ENTER_OTHER_FUNNEL_PAGES."<P>". _ENTER_MULTIPLE_FUNNEL_PAGES."<P>
				". _ENTER_OPTIONALLY_STAGE_VALUE ."<P>
				". _DONT_FORGET_LABEL ."</div>
			");
		}
		echo "</div>";
		
		echo "<script type='text/javascript'>
		$('.text-help-btn').on('click', function(){
			$('.text-help').toggle();
		});
		</script>";


	}

	function ManageFunnels() {
		global $db;

		echo "<h3>". _MANAGE_FUNNELS ."</h3>";

		$link = "definereport.php?labels=_FUNNEL_ANALYSIS&conf={$this->profile->profilename}";

		echo "<table class='table'>";

		$q = @$db->Execute("select id,label from {$this->funneltablename} where id=funnelid");
		if (!$q) {
			echo "<tr><td>". _NO_DATA_TO_DISPLAY ."</td><td></td><td></td></tr>";
		} else {
			while ($data = $q->FetchRow()) {
				echo "<tr>";
	            	echo "<td>{$data['label']}</td>";
	            	echo "<td><a data-title='". _LOGAHOLIC_FUNNEL_ANALYSIS ."' href='{$link}&funnelid={$data['id']}&funnel=edit' >". _EDIT ."</a></td>";
	           		echo "<td><a data-title='". _LOGAHOLIC_FUNNEL_ANALYSIS ."' href='{$link}&funnelid={$data['id']}&funnel=delete' >". _DELETE ."</a></td>";
	            echo "</tr>";
			}
		}

		echo "</table>";
	}
	
	function DefineReport() {
		if(empty($this->funnel)){
			$this->funnel = "manage";
		}

		$this->Toppanel();

		echo "<div class='define-content'>";	
			
			if (isset($this->funnel) && $this->funnel=="save") {
				$message = $this->SaveFunnel();
				if (isset($this->funnelid)) { 
					$this->funnel="edit"; 
				}
			} else if (isset($this->funnel) && $this->funnel=="delete") {
				$message = $this->DeleteFunnel();
			}

			if ($this->funnel=="manage") {
				$this->ManageFunnels();	

			} else if ($this->funnel=="create" || $this->funnel=="edit") {
				$this->EditFunnel();
			} else if ($this->funnel=="report") {
				if (!$this->funnelid) {
					$this->ManageFunnels();	
				}
			}
			
			if(isset($message)) {
				echo $message;
			}		
		echo "</div>";
	}
	
	function UpdateStats($from = '', $to = '',$print = 2) {
		return false;
	}
}
?>