<?php

/**
* @desc Definitions for this report: Time to Conversion

    Time Spent: The amount of time it took for a visitor to reach the KPI/target page. (From the first detected timestamp in this date range)
    Visit Share: The percentage of visitors that fall into this time range.
    Visitors: The number of visitors that 'converted' within this time range.
    Average Duration: The average time that elapsed before reaching the KPI/target page (in minutes, unless specified otherwise).

*/
$reports["_TIME_TO_CONVERSION"] = Array(
	"ClassName" => "TimeToConversion", 
	"Category" => "_PERFORMANCE",
	"canAggregate" => false, 
	"icon" => "images/icons/32x32/time_to_conversion.png",
	"Options" => "daterangeField,profileselector,displaymode,roadto,limit,columnSelector",
	"Filename" => "time_to_conversion",
	"Distribution" => "Premium",
	"Order" => 8,
	"ReportVersion" => 1.0,
	"MinimumVersion" => 3.0,
	"EmailAlerts" => true,
	"Update" => false
);

class TimeToConversion extends Report {

	function Settings() {
		$this->DefaultDisplay = "pie";
		$this->DisplayModes = "table,pie";
		$this->columnDefinitions[] = array("Label" => "_TIME_SPENT");
		$this->columnDefinitions[] = array("Label" => "_UNIQUE_VISITORS");
		$this->columnDefinitions[] = array("Label" => "_AVERAGE_DURATION_IN_MINUTES");
		$this->columnDefinitions[] = array("Label" => "_VISIT_SHARE");
	}
	
	function DefineQuery() {
		global $db;

		
		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 $query;
        }
        
        $kpi = getID($this->roadto,"urls");
        # we need to do a real table because of the union query
        $table = $this->profile->tablename."_clength"; 
        $prequery = "drop table $table";
        @$db->Execute($prequery);        
        $prequery = "CREATE OR REPLACE TABLE  $table (length int(11), visitorid char(32)) ENGINE=MyISAM  CHARSET=utf8";
        $db->Execute($prequery);
        
        #get the entry time for converted users
        $entrytime = subsetDataToSourceID("SELECT (c.timestamp-min(a.timestamp)) as length, a.visitorid  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=". $db->quote($kpi) ." and c.visitorid=a.visitorid and (status=200 or status=302) group by a.visitorid", $this->trafficsource);
        $converted = "insert into $table $entrytime";
        $db->Execute($converted);
        
        $range = $db->Execute("select min(length), max(length),count(*) from $table");
        $range_data = $range->FetchRow();
        $min = $range_data[0];
        $max = $range_data[1];
        $total_visitors=$range_data[2];
        $blocksize=($max-$min)/8;
        //$query  = subsetDataToSourceID("select \"0 to 10 seconds            \", ((count(*)*1.0)/$total_visitors*100),count(*), avg(length)/60, \"1\" as ord from $table where length >=0 and length <=10 union ",$this->trafficsource);
        $query  = subsetDataToSourceID("select \"0 to 60 seconds            \", count(*), avg(length)/60, ((count(*)*1.0)/$total_visitors*100),\"1\" as ord from $table where length >=0 and length <=60 union ",$this->trafficsource);
        $query  .= subsetDataToSourceID("select \"1 to 10 minutes            \", count(*), avg(length)/60, ((count(*)*1.0)/$total_visitors*100),\"2\" as ord from $table where length >60 and length <=600 union ",$this->trafficsource);
        $query  .= subsetDataToSourceID("select \"10 to 30 minutes            \", count(*), avg(length)/60, ((count(*)*1.0)/$total_visitors*100),\"3\" as ord from $table where length >600 and length <=1800 union ",$this->trafficsource);
        $query  .= subsetDataToSourceID("select \"30 min to 1 hour            \", count(*), avg(length)/60, ((count(*)*1.0)/$total_visitors*100),\"4\" as ord from $table where length >1800 and length <=3600 union ",$this->trafficsource);
        $query  .= subsetDataToSourceID("select \"1 hour to 24 hours            \", count(*), CONCAT(FORMAT(((avg(length)/60)/60),1),' hours'), ((count(*)*1.0)/$total_visitors*100),\"5\" as ord from $table where length >3600 and length<=86400 union ",$this->trafficsource);
        $query  .= subsetDataToSourceID("select \"1 day to 7 days            \", count(*), CONCAT(FORMAT((((avg(length)/60)/60)/24),1),' days'), ((count(*)*1.0)/$total_visitors*100),\"6\" as ord from $table where length >86400 and length<=(86400*7) union ",$this->trafficsource);
        $query  .= subsetDataToSourceID("select \"more than 1 week            \", count(*), CONCAT(FORMAT((((avg(length)/60)/60)/24),1),' days'), ((count(*)*1.0)/$total_visitors*100),\"7\" as ord from $table where length >(86400*7) ",$this->trafficsource);
        $query .= " order by ord";

        $this->applytrafficsource = false;

		return $query;
	}
	
	function GetReportData(){
		global $db;
        $q = $this->DefineQuery();
        if ($q!==false) {
            if ($this->applytrafficsource == true) { $q = subsetDataToSourceID($q,$this->trafficsource);  }
            $db->SetFetchMode(ADODB_FETCH_NUM);
            $result = $db->Execute($q);
            $data = $result->Getarray();
            $db->SetFetchMode(ADODB_FETCH_BOTH);
            return $data;
        } else {
            # if the report is not based on a single database query, this is where the data will be created
            return false;
        }	
	}
	
	function UpdateStats($from = '', $to = '',$print = 2) {
		# we need actual uniques for this report, so don't update datafiles
		return false;		
	}
}
?>
