<?php
	include_once ("_dirinfo.php");
	include_once (PATH_TO_ROOT."init.php");
	include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.gridData.php");
	include_once(PATH_TO_ROOT."config.php");
	
	
	class questStatManipulator extends GridDataManipulator
	{
		public function selectAction()
		{		
                       $projName = $_POST['projName'];
	
                        if (isset($_POST['Cas']))$cas=$_POST['Cas'];
                        else $cas=2; //določi sekunde

                      	 $tabela=$this->db->SQLexecute("SHOW TABLES FROM ".DB_WARPIT_WEBCATI_BASE." LIKE 'QDetails_".$_SESSION['UserInfo']['id']."'");
                      	 $obstaja=$this->db->fetchArray($tabela);
     
                      	 $this->db->LogWrite($cas, true, "cacacas:");
	                                       	                       	
	                
	                       	if (count($obstaja)<=1)
	                       	{
	                       		
	                       		//ustvari temp tabelo
	                       		$_POST['prvik']="drugi";
	                       		$sqlTemp=" CREATE TABLE IF NOT EXISTS " .DB_WARPIT_WEBCATI_BASE.".QDetails_".$_SESSION['UserInfo']['id']." ( id INT NOT NULL   , suspect BOOLEAN NOT NULL , questStart int(11)  DEFAULT 0 , questEnd int(11) DEFAULT 0  , betwen VARCHAR(20) , firstk VARCHAR(20) , clicks INT UNSIGNED  DEFAULT 0 , qcharts INT UNSIGNED  DEFAULT 0 , acharts INT UNSIGNED  DEFAULT 0 , lcharts INT UNSIGNED  DEFAULT 0 , nvisits INT UNSIGNED  DEFAULT 0 , isti_odgovor VARCHAR(5) );";
	                       		$res= $this->db->SQLexecute($sqlTemp);
	                       		
	                       		//kolikokrat je bil uporabnik na vpraÅ¡anju
	                       		$sql="SELECT id_structure, q_name , count( * ) AS kliki FROM ".DB_WARPIT_WEBCATI_BASE.".".$projName."___EngineLog GROUP BY  id_structure, q_name; ";
	                       		$res= $this->db->SQLexecute($sql);
	                       		while ($rows = $this->db->fetchAssoc($res)) {
	                       			$kliki[$rows['id_structure']][$rows['q_name']]=$rows['kliki'];
	                       		}
	                       		
	                       		//dolžine vprašalnikov, odgovorov, legend
	                       		$sqlq = "SELECT  id_question, id_text_type, id_language, Length(lngText) AS dolzina FROM  ".DB_WARPIT_WEBCATI.".".$projName."_language";
	                       		$result = $this->db->SQLexecute($sqlq);
	                       		while ($rows = $this->db->fetchAssoc($result)) {
	                       			$charts[$rows['id_question']][$rows['id_language']][$rows['id_text_type']]=$rows['dolzina'];
	                       		}
	                       		
	                       		$res= $this->db->SQLexecute("SELECT id_language FROM ".DB_WARPIT_WEBCATI.".".$projName."_language GROUP BY id_language;");
	                       		$temp=$this->db->fetchAssoc($res);
	                      		$language=$temp['id_language'];

	                       		
	                       		//napolni podatke
	                       		$rows=array();
	                       		$sql="SELECT id, id_structure, q_name, questStart, questEnd, questEnd - questStart AS betwen, id_question, id_user, eventLogger FROM ".DB_WARPIT_WEBCATI_BASE.".".$projName."___EngineLog ";
	                       		$res= $this->db->SQLexecute($sql);
	                       		while ($row = $this->db->fetchAssoc($res)) {
	                       			
	                       			$rows['id']=$row['id'];
	                       			$rows['questStart']=$row['questStart'];
	                       			$rows['questEnd']=$row['questEnd'];
	                       			$rows['betwen']=(string)gmdate("H:i:s", $row['betwen']);	
	                       			
	                       			$json = null;
	                       			if ($row['eventLogger']!=null)
	                       			{
	                       				$json = json_decode( $row['eventLogger']);
	                       		
	                       				$rows['firstk']= "v času ".(string)gmdate("i:s",   $json[0]->clickTime - $row['questStart'])." minute" ;
	                       				$rows['clicks']= sizeof($json);
	                       		
	                       				// ali je večkrat kliknil isti odgovor
	                       				$pogoj=false;
	                       				for ($i=0; $i<sizeof($json); $i++)
	                       				{
	                       				for ($j=$i+1; $j<sizeof($json); $j++)
	                       					{
	                       						if ($json[$i]->objName == $json[$j]->objName && $json[$i]->objValue == $json[$j]->objValue)
	                       							{
	                       								$pogoj=true;
	                       									break;
	                       							}	                       		
	                       					}
	                       				}
	                       				if ($pogoj)
	                       				{
	                       					$rows['isti_odgovor'] = "yes";
	                       					$odg=true;
	                       				}
	                       				else 
	                       				{
	                       					$rows['isti_odgovor'] = "no";
	                       					$odg=false;
	                       				}
	                       			}
	                       			else
	                       			{
		                       			$rows['firstk']= "/" ;
		                       			$rows['clicks']= 0;
		                       			$rows['isti_odgovor']="no";// če event loger ne obstaja, ni večkrat kliknil istega odgovora
		                       			$odg=false;
	                       			}
	                       			$rows['nvisits'] = $kliki[$row['id_structure']][$row['q_name']];
	                       		
	                       				//st. chars
	                       			if (isset($charts[$row['id_question']][$language][4]))
	                       			{
	                       				$rows['lcharts']= $charts[$row['id_question']][$language][4];
	                       			}
	                       			else $rows['lcharts']=0;
	                       		
	                       			if (isset($charts[$row['id_question']][$language][2]))
	                       			{
	                       				$rows['qcharts']=$charts[$row['id_question']][$language][2];
	                       			}
	                       			else $rows['qcharts']=0;
	                       		
	                       			if (isset($charts[$row['id_question']][$language][3]))
	                       			{
	                       				$rows['acharts']=$charts[$row['id_question']][$language][3];
	                       			}
	                       			else $rows['acharts']=0;
	                       		
	                       		
	                       			$prehiterKlik=false;
	                       			if (sizeof($json)>0)
	                       			{
	                       		
	                       			$prejsniCas=$json[0]->clickTime;
	                       			for ($i=1; $i<sizeof($json); $i++)
	                       			{
	                       		
	                       			if (($json[$i]->clickTime - $prejsniCas)< $cas)
	                       			{
	                       				$prehiterKlik=true;
	                       				break;
	                       			}
	                       			$prejsniCas=$json[$i]->clickTime;
	                       			}
	                       			}
	                       		
	                       			if ($odg || $json[0]->clickTime - $row['questStart']<$cas ||   $prehiterKlik)
	                       			{
	                       			$rows['suspect']=true;
	                       		
	                       		}
	                       		else { $rows['suspect']=false; }
	                       		
	                       		$polje[]=$rows;
	                       		}
              		
	                       	$new = array();
							foreach($polje as $key=>$value) {
							    $new[] = "'".implode("', '", $value)."'";
							}
							$query = "(".implode("), (", $new).")";
							$sq=	"INSERT INTO " .DB_WARPIT_WEBCATI_BASE.".QDetails_".$_SESSION['UserInfo']['id']."  (id, questStart, questEnd, betwen, firstk, clicks, isti_odgovor, nvisits, lcharts, qcharts, acharts, suspect) VALUES ".$query.";";
							$this->db->SQLexecute($sq);
	                       		
	                       	}  

	        //        $this->fetchSelect();
	               
	         //       $this->createSelectSQL();
	                
                    return parent::selectAction();
		}
		
		
		// ročno sortiranje, trenutno se ne uporablja
		function sortiraj(array $array, $key, $asc = true) {
			$result = array();
			//settype($result->id,"integer");
			$values = array();
			foreach ($array as $id => $value) {
				$this->db->LogWrite($id, false, "pridobljena vrstica:");
				$values[$id] = isset($value[$key]) ? $value[$key] : '';
			}
			 
			if ($asc) {
				asort($values);
			}
			else {
				arsort($values);
			}
		
			foreach ($values as $key => $value) {
				$result[] = $array[$key];
			}
			
			return $result;
		}
		
	}  
    $db->ChangeDatabase($_POST['database']);

	$manipulator = new questStatManipulator($db,$_POST['RMtable']);

	$comm = $_REQUEST['action'].'Action';
	if(method_exists($manipulator,$comm))
		echo $manipulator->$comm();
	else 
	{
		echo '{success:false,error:"Unknown action!"}';	
        }
?>
