<?php

/**
* @desc This report displays the keyword conversion
*/
$reports["_KEYWORD_CONVERSION"] = Array(
	"ClassName" => "KeywordConversion", 
	"Category" => "_PERFORMANCE",
	"canAggregate" => false,  
	"icon" => "images/icons/32x32/keywordconversion.png",
	"Options" => "daterangeField,profileselector,trafficsource,roadto,search,limit,columnSelector",
	"Filename" => "keyword_conversion",
	"Distribution" => "Premium",
	"Order" => 6,
	"ReportVersion" => 1.0,
	"MinimumVersion" => 3.0,
	"EmailAlerts" => false,
	"Update" => false
);

class KeywordConversion extends Report {

	function Settings() {		
		global $db;
		$this->columnDefinitions[] = array("Label" => "_KEYWORDS","actionmenu" => 'keyword');
		$this->columnDefinitions[] = array("Label" => "_UNIQUE_VISITORS");
		$this->columnDefinitions[] = array("Label" => "_CONVERTED_VISITORS", "bchart" => true);
		$this->columnDefinitions[] = array("Label" => "_CONVERSION_RATE");
		$this->actionmenu_type = 'keyword';
		$this->datafiles = false;
	}
	
	function DefineQuery() {
		global $db, $nc;
		
		# DROP The temporary tables so that there wont be any duplication errors
		$db->Execute("DROP TABLE IF EXISTS {$this->profile->tablename}_top_entry_converted");
		$db->Execute("DROP TABLE IF EXISTS {$this->profile->tablename}_entrypages");
		$db->Execute("DROP TABLE IF EXISTS {$this->profile->tablename}_top_entry");
		
		if(empty($this->roadto)){ 
			if ($this->profile->targetfiles) {
				$targets=explode(",",$this->profile->targetfiles);
				$this->roadto = $targets[0];		
			}else{
				return false;
			}			
		}
		 if (!$this->roadto) {
            $this->columnDefinitions = [];
			$this->columnDefinitions[] = array("Label" => _INFO);
			$this->setupColumnDefinitions();
            $query = "select \""._CHOOSE_TARGET_FILE."\"";
            return;
        }
        
        # first, get the ID of the target page
        $kpi = getID($this->roadto,"urls");         
       
        $top_entry_converted_search="";
        if (!empty($this->search)) {
            $searchst = $this->SearchMatchingIDs($this->search,"keywords",$this->searchmode,$this->profile->tablename_keywords);
            $top_entry_converted_search = str_replace("and keywords IN", "where entry IN", $searchst);          
        } else {
			$searchst = "";
		}
		$db->Execute("SET SESSION group_concat_max_len = 65535");
        # get the entry keyword of each converted user for a certain KPI, then count the ocurrences
        $entrypages_for_conversion = subsetDataToSourceID("SELECT a.visitorid as cvisitor, SUBSTRING_INDEX(Group_Concat(a.keywords order by a.timestamp),',',1) as entry FROM {$this->profile->tablename} as a, {$this->profile->tablename_conversions} as c where (c.timestamp >=". $db->quote($this->from) ." and c.timestamp <=". $db->quote($this->to) .") and (a.timestamp >=". $db->quote($this->from) ." and a.timestamp <= c.timestamp) and c.url='$kpi' and c.visitorid=a.visitorid and (status=200 or status=302) group by a.visitorid", $this->trafficsource);
        $converted = "create temporary table {$this->profile->tablename}_top_entry_converted SELECT $nc entry, count(distinct cvisitor) as conversions from ($entrypages_for_conversion) as cvisitors $top_entry_converted_search group by entry";
        $db->Execute($converted);        
        
        # next, get the entry keyword for each visitor
        $entrypages = "create temporary table {$this->profile->tablename}_entrypages ". subsetDataToSourceID("SELECT $nc visitorid, SUBSTRING_INDEX(Group_Concat(keywords order by timestamp),',',1) as keywords FROM {$this->profile->tablename} where (timestamp >=". $db->quote($this->from) ." and timestamp <=". $db->quote($this->to) .") and (status=200 or status=302) group by visitorid", $this->trafficsource);
        $db->Execute($entrypages);
         
        # now count the top entry keywords
        $nokw = getID("","keyword");
        $toppages = "create temporary table {$this->profile->tablename}_top_entry SELECT $nc keywords, count(distinct visitorid) as visitors from {$this->profile->tablename}_entrypages, {$this->profile->tablename}_top_entry_converted where entry=keywords $searchst and keywords!='$nokw' group by keywords order by visitors desc limit {$this->limit}";       
        $db->Execute($toppages);
                
        # now join it all together
        $query = "select $nc k.keywords, visitors, conversions, CONCAT(FORMAT((conversions/visitors)*100,2),' %') as crate from {$this->profile->tablename}_top_entry as a LEFT JOIN {$this->profile->tablename}_top_entry_converted as b on (b.entry=a.keywords) LEFT JOIN {$this->profile->tablename_keywords} as k on (k.id=a.keywords) order by visitors desc";
		
        $applytrafficsource = false;
		
		return $query;
	}
	
	function DisplayReport() {		
		if (empty($this->profile->targetfiles)) {
			$this->ReportHeader();
			echoNotice(_REPORT_NEEDS_KPI. "<br/><br/><a href='profile.php?conf={$this->profile->profilename}#_KPI' class='btn btn-default'>". _EDIT_PROFILE .": ". _KPI ."</a>", "margin:10px;");
			return;
		}
		parent::DisplayReport();
	}
	
	function UpdateStats($from = '', $to = '',$print = 2) {
		# because the query takes too long
		return false;		
	}
}
?>
