<?php
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT."webcati/_class/class.sampler.php");

ini_set("display_errors", "1");

$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

if(isset($_POST["id_project"])) {
	$id_proj=$_POST["id_project"];
} else {
	echo "{success:false,unsuccess:'missing project ID!'}";
	exit;
}


$s=new sampler($id_proj, $db,$_POST['capi']);

if($_POST["form_action"]=="insert_samples")
{
	$sql="START TRANSACTION";
		if(!$result=$db->SQLexecute($sql))
				echo "<br/>ERROR_04:" . $db->GetError();
	
	$data=$_POST["podatki"];
	$unsuccess = array();
	
	$fields = explode(',',$_POST['fields']);
	$s->prepare_index_table_and_attributes($fields);
	
	// if we use all numbers, I have empty combPodatki
	if ($_POST['comboPodatki']) {
		foreach ($_POST['comboPodatki'] as $data => $value) {
			if(!$value > 0 ) continue;
			$att=array();
			$dataArr = explode('|',$data);
			foreach ($dataArr as $key => $code) {
				//sometimes the label can be after the code
				$code = explode(' ',$code);
				$code = $code[0];
				
				$att[$fields[$key]] = $code;
			}
			
			$num = $s->get_ids($_POST["type"], $att, $value);
			if($num === false) $failArray[] = $data;
			else if( $num == $value )
			{
				$successArray[] = $data;
			}
			else
			{
				$tmpAr = array();
				$tmpAr[] = $att;
				$tmpAr[] = $num;
				$tmpAr[] = $value;
				$unsuccess[] = $tmpAr; 
			}
				
		}
	}
	
	// in case I want to use all numbers I skip combo data and fill index table with all I have free inside telephone table 
	if ($_POST['action'] == "useAll") {
		$num = $s->useAll();
		if ($num===false) {
			echo "{success:false,unsuccess:'Error while reserving all numbers to project!'}";
			exit;
		}
	}
	
	
	if(!$_POST['capi'])
	{
		$sql = "UPDATE " . $s->index_table_name . " INNER JOIN tel___" . $s->table_name . " a ON a.id = id_tel AND a.proj_reserved = 0 SET a.proj_reserved = $s->id_project";
		//echo "/*$sql\r\n*/";
		if(!$result=$db->SQLexecute($sql))
			echo "<br/>ERROR_04:" . $db->GetError();
			
		$sql = "SELECT max(id) FROM " . $s->index_table_name . "";
		$maxId = $db->fetchArray($db->SQLexecute($sql));
		$maxId = $maxId[0];
		if(!$maxId) $maxId = 0;
		
		$sql = "UPDATE _Projects SET tel_reserve = $maxId WHERE id = $s->id_project";
		//echo "/*$sql\r\n*/";
		if(!$result=$db->SQLexecute($sql))
					echo "<br/>ERROR_05:" . $db->GetError();
	}						
	$sql="COMMIT";
		if(!$result=$db->SQLexecute($sql))
				echo "<br/>ERROR_05:" . $db->GetError();
	echo "/* succes: ";
	print_r($successArray);
	echo "<br>failure: ";
	print_r($failArray);
	echo "*/";
	
	echo "{success:true,unsuccess: ".json_encode($unsuccess)." }";			
} 
else if($_POST["grid_action"]=="get_recoded_groups")
{
	if(count($q->recoded_groups)>0)
		echo '{success:true, rows:'.json_encode($q->recoded_groups).'}';
	else
		echo $q->error;
}
else if($_POST["grid_action"]=="create_recode_group")
{
	$recode=json_decode(stripslashes($_POST["data"]));
	$lab_val=$_POST["podatki"];
	
	if($q->create_recode_group($recode, $lab_val["label"], $lab_val["value"]))
	{
		echo '{success:true, rows:[]}';
	}
	else
		echo $q->error;
}
else if($_POST["grid_action"]=="remove_category_from_group")
{
	$id=array_shift(json_decode(stripslashes($_POST["data"])));
	
	if($q->remove_category_from_group($id))
	{
		echo '{success:true, rows:[]}';
	}
	else
		echo $q->error;
}
else if($_POST["grid_action"]=="get_categories")
{
	if(isset($_POST["id"]))
	{
		$q->get_categories($_POST["id"]);
		echo '{success:true, rows:'.json_encode($q->categories_array).'}'; 
	}
	else
		echo '{success:true, rows:[]}';
}
else if($_POST["grid_action"]=="insert_answers_into_categorie")
{
	$answers=json_decode(stripslashes($_POST["data"]));
	$id_cat=$_POST["id_cat"];
	if($q->insert_answers_into_categorie($answers, $id_cat))
		echo '{success:true}';
	else
		echo $q->error;
	//else
		//echo '{success:false}';
}
else if($_POST["grid_action"]=="remove_answers_from_category")
{
	$ids_to_remove=json_decode(stripslashes($_POST["data"]));
	//$var_rec=$_POST["var_rec"];
	
	if($q->remove_answers_from_category($ids_to_remove))
	{
		echo '{success:true, rows:[]}';
	}
	else
		echo $q->error;
}
else if($_POST["grid_action"]=="get_answers_to_display")
{
	if(isset($_POST["id"]))
	{
		$q->get_answers_to_display($_POST["id"]);
		echo '{success:true, rows:'.json_encode($q->answers_to_display).'}'; 
	}
	else
		echo '{success:true, rows:[]}';
	
	
}
else if($_POST["grid_action"]=="get_answers_in_categories")
{
	if(isset($_POST["id"]))
	{
		$q->get_answers_in_categories($_POST["id"]);
		echo '{success:true, rows:'.json_encode($q->answers_in_categories).'}'; 
	}
	else
		echo '{success:true, rows:[]}';
	
}
else if($_POST["grid_action"]=="create_cat_in_recode_group")
{
	$recoded_group_id=$_POST["id"];
	$data=$_POST["podatki"];
	
	if($q->create_cat_in_recode_group($recoded_group_id, $data["category_name"], $data["category_value"]))
	{
		echo '{success:true, rows:[]}';
	}
	else
		echo $q->error;
	
}
else if($_POST["grid_action"]=="create_statistics")
{	
	if($q->create_statistics())
	{
		echo '{success:true, rows:'.json_encode($q->stat_result).'}'; 
	}
	else
		echo $q->error;
	
}


?>