	<?php
/*Ajax za localdataentry.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 . "webcati/_forms/ExImportData/form.php");

class localdataentry extends GridDataManipulator {

	/*
	 * @selectAction
	 * */
	function selectAction($table, $id) {
		define('DB_WARPIT_WEBCATI_BASE', 'Warpit_Webcati_base');

		/*$_POST['SQL'] = "Select $table.*,ifnull({$table}_tree.idLab,'/') as idLab ,f.name as templateName,ifnull( {$table}_tree.orderBy ,(SELECT c.orderBy FROM {$table}_tree c WHERE c.id_question = $table.id )   ) as group_id ".
		"$selVpr from $table LEFT JOIN {$table}_tree ON {$table}_tree.id = (SELECT id_sup FROM {$table}_tree b WHERE b.id_question = $table.id )"
			." LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._DesignerManager e ON $table.id = e.id_question AND id_project = {$id} AND type_device = 0 AND id_special = 0 LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._DesignerTemplates f ON e.id_template = f.id";
			*/
		$_POST['SQL'] = "Select $table.*,ifnull({$table}_tree.idLab,'/') as idLab". 
",f.name as templateName,ifnull( {$table}_tree.orderBy ,(SELECT c.orderBy FROM {$table}_tree c WHERE c.id_question = {$table}.id )   ) as group_id". 
",ifnull((SELECT lngText FROM {$table}_language b WHERE id_question = {$table}.id AND id_language = 91 AND id_text_type = 1)".
",ifnull((SELECT lngText FROM {$table}_language b WHERE id_question = {$table}.id AND id_language = 91 AND id_text_type = 1),'')) as nav_sql".
",ifnull((SELECT lngText FROM {$table}_language b WHERE id_question = {$table}.id AND id_language = 91 AND id_text_type = 2)".
",ifnull((SELECT lngText FROM {$table}_language b WHERE id_question = {$table}.id AND id_language = 91 AND id_text_type = 2),'')) as vpr_sql".
",ifnull((SELECT lngText FROM {$table}_language b WHERE id_question = {$table}.id AND id_language = 91 AND id_text_type = 3)".
",ifnull((SELECT lngText FROM {$table}_language b WHERE id_question = {$table}.id AND id_language = 91 AND id_text_type = 3),'')) as odg_sql".
",ifnull((SELECT lngText FROM {$table}_language b WHERE id_question = {$table}.id AND id_language = 91 AND id_text_type = 4)".
",ifnull((SELECT lngText FROM {$table}_language b WHERE id_question = {$table}.id AND id_language = 91 AND id_text_type = 4),'')) as leg_sql".
",ifnull((SELECT lngText FROM {$table}_language b WHERE id_question = {$table}.id AND id_language = 91 AND id_text_type = 5),".
"ifnull((SELECT lngText FROM {$table}_language b WHERE id_question = {$table}.id AND id_language = 91 AND id_text_type = 5),'')) as atr_sql".
",ifnull((SELECT lngText FROM {$table}_language b WHERE id_question = {$table}.id AND id_language = 91 AND id_text_type = 8)".
",ifnull((SELECT lngText FROM {$table}_language b WHERE id_question = {$table}.id AND id_language = 91 AND id_text_type = 8),''))". 
"as grp_sql from {$table} LEFT JOIN {$table}_tree ON {$table}_tree.id = (SELECT id_sup FROM {$table}_tree b WHERE b.id_question = {$table}.id )".
"LEFT JOIN Warpit_Webcati_base._DesignerManager e ON {$table}.id = e.id_question AND id_project = {$id} AND type_device = 0 AND id_special = 0 ". 
"LEFT JOIN Warpit_Webcati_base._DesignerTemplates f ON e.id_template = f.id ".
"LEFT JOIN Warpit_Webcati_base._QuestionRotation g ON {$table}.id = g.id_question ".
"AND g.id_project = {$id} HAVING q_pos > 0 ORDER BY q_pos,group_id ASC,q_pos ASC LIMIT 0, 10";
		
		//$_POST['SQL'] = "Select Blaz.*,ifnull(Blaz_tree.idLab,'/') as idLab ,f.name as templateName,ifnull( Blaz_tree.orderBy ,(SELECT c.orderBy FROM Blaz_tree c WHERE c.id_question = Blaz.id )   ) as group_id ,ifnull((SELECT lngText FROM Blaz_language b WHERE id_question = Blaz.id AND id_language = 91 AND id_text_type = 1),ifnull((SELECT lngText FROM Blaz_language b WHERE id_question = Blaz.id AND id_language = 91 AND id_text_type = 1),'')) as nav_sql,ifnull((SELECT lngText FROM Blaz_language b WHERE id_question = Blaz.id AND id_language = 91 AND id_text_type = 2),ifnull((SELECT lngText FROM Blaz_language b WHERE id_question = Blaz.id AND id_language = 91 AND id_text_type = 2),'')) as vpr_sql,ifnull((SELECT lngText FROM Blaz_language b WHERE id_question = Blaz.id AND id_language = 91 AND id_text_type = 3),ifnull((SELECT lngText FROM Blaz_language b WHERE id_question = Blaz.id AND id_language = 91 AND id_text_type = 3),'')) as odg_sql,ifnull((SELECT lngText FROM Blaz_language b WHERE id_question = Blaz.id AND id_language = 91 AND id_text_type = 4),ifnull((SELECT lngText FROM Blaz_language b WHERE id_question = Blaz.id AND id_language = 91 AND id_text_type = 4),'')) as leg_sql,ifnull((SELECT lngText FROM Blaz_language b WHERE id_question = Blaz.id AND id_language = 91 AND id_text_type = 5),ifnull((SELECT lngText FROM Blaz_language b WHERE id_question = Blaz.id AND id_language = 91 AND id_text_type = 5),'')) as atr_sql,ifnull((SELECT lngText FROM Blaz_language b WHERE id_question = Blaz.id AND id_language = 91 AND id_text_type = 8),ifnull((SELECT lngText FROM Blaz_language b WHERE id_question = Blaz.id AND id_language = 91 AND id_text_type = 8),'')) as grp_sql from Blaz LEFT JOIN Blaz_tree ON Blaz_tree.id = (SELECT id_sup FROM Blaz_tree b WHERE b.id_question = Blaz.id ) LEFT JOIN Warpit_Webcati_base._DesignerManager e ON Blaz.id = e.id_question AND id_project = 5850 AND type_device = 0 AND id_special = 0 LEFT JOIN Warpit_Webcati_base._DesignerTemplates f ON e.id_template = f.id LEFT JOIN Warpit_Webcati_base._QuestionRotation g ON Blaz.id = g.id_question AND g.id_project = 5850 HAVING q_pos > 0 ORDER BY q_pos,group_id ASC,q_pos ASC LIMIT 0, 10";
		//Samo vprašanja
		//$this -> addWhere("id=9");
		//$this -> addWhere("q_pos > 0");
		//$this -> addWhere("id = 9");
		//$this -> whereKeyword = "WHERE";
		$this -> fetchSelect();
		//return $this->arr;
		return parent::selectAction();
	}

	/*
	 * function jsonDesode
	 * */
	function jsonDecode($string, $assoc = true, $fixNames = true) {
		if (strpos($string, '(') === 0) {
			$string = substr($string, 1, strlen($string) - 2);
			// remove outer ( and )
		}
		if ($fixNames) {
			$string = preg_replace("/(?<!\"|'|\w)([a-zA-Z0-9_]+?)(?!\"|'|\w)\s?:/", "\"$1\":", $string);
		}
		return json_decode($string, $assoc);
	}

	/*
	 * function arrReturn
	 * */
	function arrReturn($string) {
		if ($string != '') {
			$arr = array();
			$pieces = explode(",", $string);
			for ($r = 0; $r < sizeof($pieces); $r++) {
				array_push($arr, str_replace(" ", "", $pieces[$r]));
				//$arr[$i]= str_replace(" ", "", $pieces[$r]);
			}
			return ($arr);
		} else
			return false;
	}

	/*
	 * function saveData
	 *	@data -> array data from form
	 *  @pravila za vpisovanje v db
	 *  @param tableName ->ime tabele Blaz_Structure
	 * 	1->single response (zapiše se vrednost, samo eno polje q1)
	 * 	2->scale (razdeli na odgovore in zapiše vrednost q1_1 1 recimo)
	 * 	3->multy response (naredi se toliko stolpsev kot je možnih odgovorov q4_1..., zapiše se vrenost v titega, ki je odkljukan)
	 * 	4->open (q3_1 zapiše se vrednost odgovora)
	 * */
	function saveData($dataArr, $tipArr, $tableName) {
		//Create sql statement
		// $tips vsebuje ime, tip, odg (int)
		$tips = $this -> createSql($tipArr);
		$count = sizeof($tips);	
		$countDataArr=0; //<-- štetje za vrednost iz $dataArr
		//count
		$end = $count - 1;
		//for end
		//start sql statement
		$sql = "INSERT INTO ".$tableName." (";
		$sqlValue = 'VALUE(';
		$blaz='';
		for ($n = 0; $n < $count; $n++) {
			$value = explode('=', $dataArr[$countDataArr]); //<----pridobivanje vrednosti iz $dataArr(forma)
			$blaz.='n='.$n.' value='.$value[1].' count'.$countDataArr.'**';
			switch ($tips[$n]['tip']) {
				case 1 : 
				/**
				 * for SINGLE Q
				 */
					$sql .= $tips[$n]['ime'];
					if ($value[1] != '') {
						$sqlValue .= '"' . $value[1] . '", ';
					} else $sqlValue .= 'NULL, ';
					$countDataArr++;
					break;
				case 2 : 
				/**
				 * for SCALE
				 */
				 	//$scaleP='';
					$st 		= $tips[$n]['odg']; //koliko je stolpcev v bazi
					$endCase 	= $st - 1;
					//$scaleP.='Število odgovorov: '.$st.', število countArr: '.$countDataArr;
					for ($k = 0; $k < $st; $k++) {
						$num 		= $k + 1;
						$col 		= $tips[$n]['ime'] . '_' . $num;
						$valueS		= explode('=', $dataArr[$countDataArr]);
						//$scaleP.="(scale ".$col."vrednost=".$valueS[1]." arrayCount=".$countDataArr.")";
						if ($valueS[1] != '') {
							$sqlValue 	.= '"' . $valueS[1] . '", ';
						} else
							$sqlValue 	.= 'NULL, ';
							$sql 		.= $col;
						if ($k != $endCase) {
							$sql 	.= ', ';
						}
						$countDataArr++;
					}
					//return $scaleP;
					break;
				case 3 :
					/**
					 * for MULTY Q
					 * q6_1, q6_2, q6_3
					 */
					//MR ,->%2C
					$valueExplode;
					$valueCount;
					$answers		= $tips[$n]['answers']; 	//<-- pridobimo odgovore
					$valueAnswers	= explode('/', $answers);	//<-- ločimo na /
					$valueAnswerArr	= array();
					for($i=0;$i<sizeof($valueAnswers);$i++){
						$arrPushString	= explode(' ', $valueAnswers[$i]);
						array_push($valueAnswerArr, $arrPushString[0]);
					}
					$vrednosti 		= false;
					//preberemo odgovore
					if (strpos($value[1], '%2C') !== false) {
							$valueExplode	= explode("%2C", $value[1]);
							$valueCount		= sizeof($valueExplode);
							$vrednosti 		= true;
					}
					//return var_dump($valueAnswerArr).'///'.var_dump($valueExplode);
					$st 		= $tips[$n]['odg'];
					$endCase 	= $st - 1;
					//število odgovorov
					for($k=0 ; $k<$st ; $k++){
						$num 	= $k+1;
						$sql	.= $tips[$n]['ime'] . '_' . $num;
						$najden	= false;
						if($vrednosti){//če obstaja več vrednosti
							for($m=0 ; $m<$valueCount ; $m++){
									if($valueAnswerArr[$k]==$valueExplode[$m]){
										$sqlValue .= '"' . $valueExplode[$m] . '", ';
										$najden	= true;
									}		
							}
						}else{//če je samo ena vrednost
							if($valueAnswerArr[$k]==$value[1]){
								$sqlValue .= '"' . $value[1] . '", ';
								$najden	= true;
							}	
						}
						if(!$najden){$sqlValue .= 'NULL, ';}
						if ($k != $endCase) {$sql .= ', ';}
					}	
					$countDataArr++;
					break;
				case 4 : 
					/**
					 * for OPEN Q
					 */
					$sql .= $tips[$n]['ime'] . '_1';
					if ($value[1] != '') {
						$sqlValue .= '"' . $value[1] . '", ';
					} else $sqlValue .= 'NULL, ';
					$countDataArr++;
					break;
			}
			if ($n != $end) {$sql .= ', ';
			}
		}
		$sql 		.= ')';
		$sqlValue 	= substr($sqlValue, 0, -2);
		$sqlValue 	.= ')';
		$sql 		.= $sqlValue;
		//return $sql.'/////'.$blaz;
		If (!$rs = $this -> db -> SQLexecute($sql)) {

			return '{"success":false,"error":"' . $this -> db -> GetError() . '", STATEMENT: "' . $sql . '"}';

		} else {

			return '{"success":true,"insert_id":' . $this -> db -> GetLastInsertId() . ', sql statement: ' . $sql . ' }';
		}
	}

	/**
	 * createSql insert into
	 * desc: create sql for savedata ->$tipArr
	 */
	function createSql($tipArr) {
		$keyArray = array_keys($tipArr);
		//shranimo imena
		$justTips = array();
		$count = sizeof($tipArr);
		for ($i = 0; $i < $count; $i++) {
			$odgCount = explode('/', $tipArr[$keyArray[$i]]['odg']);
			$an = array("ime" => $keyArray[$i], "tip" => $tipArr[$keyArray[$i]]['tip'], "odg" => sizeof($odgCount), "answers" =>$tipArr[$keyArray[$i]]['odg']);
			array_push($justTips, $an);
		}
		return $justTips;
	}

}

/**
 * get data from configure inputs
 */
if (isset($_POST['actionBlaz'])) {
	//Pridobivanje podatkov za post
	$db -> ChangeDatabase('Warpit_Webcati');
	$tableName 		= $_POST['tableName'];
	$id				= $_POST['id'];
	$manipulator	= new localdataentry($db, $tableName);
	$action 		= $_POST['actionBlaz'];
	$createQ 		= array();
	$arr 			= $manipulator -> jsonDecode($manipulator -> selectAction($tableName, $id));
	$rows 			= ($arr['rows']);
	
	for ($i = 0; $i < count($rows); $i++) {
		//Fil array
		$ar = array("goto" => $manipulator -> arrReturn($rows[$i]['goto_sql']), "fil" => $manipulator -> arrReturn($rows[$i]['fil_sql']), "con" => $manipulator -> arrReturn($rows[$i]['con_sql']), "tip" => $rows[$i]['tip_sql'], "leg" => $rows[$i]['leg_sql'], "odg" => $rows[$i]['odg_sql']);
		//set ime as key
		$createQ[$rows[$i]['q_name']] = $ar;
	}
	echo json_encode($createQ);
}

/**
 * save data into db
 */
if (isset($_POST['actionSave'])) {
	//Pridobivanje podatkov za post
	$db -> ChangeDatabase('Warpit_Webcati_base');
	$tableName 		= $_POST['tableName'].'_structure';
	$manipulator 	= new localdataentry($db, $tableName);
	$returnData;
	//vsi podatki
	$tipPodatkov 	= json_decode($_POST[arr], true);
	$trueData 		= array();
	//pravilni podatki
	if (empty($_POST['podatki'])) {
		$returnData = 'Podatki uspešno poslovani, vendar je to prazna množica!';
	} else {
		$arrayData 	= explode('&', $_POST['podatki']);
		$count 		= count($arrayData);
		for ($j = 0; $j < $count; $j++) {
			array_push($returnData, $arrayData[$j]);
			//Preverjanje veljavnosti
			$poslano = explode('=', $arrayData[$j]);
			if ($poslano[1] != '') {
				array_push($trueData, $arrayData[$j]);
			}
		}
		//$manipulator -> saveData($arrayData);
	}
	echo json_encode($manipulator -> saveData($arrayData, $tipPodatkov, $tableName)); //-->CALL FUNCTION saveData($array,$array,$table)
	//echo json_encode($manipulator -> createSql($tipPodatkov));
	//echo json_encode(print_r($tipPodatkov));
}
?>