<?php
include "/var/www/html/funciones.php";
// include "/var/www/html/conection_test.php";
	require_once 'config.php';
	require_once 'dbh.inc.php';
	require_once 'checkLogin.php';
	
	

// print_r($_FILES);
// print_r($_SERVER);
// print_r($_POST);
// print_r($_GET);
// 
// exit();
// $archivo="Cuestionario perfecto.xlsx";
$id_experience= mysqli_real_escape_string($connection, trim($_POST['id_experience']));
// $id_experience= mysqli_real_escape_string($connection, $_GET['id_experience']);;

$archivo=$_FILES["import"]["tmp_name"];
$archivoOut="uploaderTemp";
exec("ssconvert -S  '$archivo' ../temp/$archivoOut-%s.csv");
// print "ssconvert -S -D ../temp '$archivo' $archivoOut-%s.csv";print"<br>";
// print getcwd();
$q_title=explode(".", $_FILES["import"]["name"])[0];
$data_dir="../temp/";
$archivosCSV=glob("$data_dir$archivoOut*.csv");
print_r($archivosCSV);
// exit();
// $n=count($archivosCSV);
// $n=2;
// foreach (glob($archivoOut."*.csv") as $filename) 
$categoria=array();
$subcategoria=array();
$referencias=array();
$tipo=array(1=>"SCALE",2=>"OPEN");
$q=array();

$i=0;
$filename="$data_dir$archivoOut-questions.csv";
$row = 1;
if (($handle = fopen($filename, "r")) !== FALSE) 
{
// 	print $filename."\n";
	$j=0;
	while (($data = fgetcsv($handle)) !== FALSE) 
	{
// 		print_r($data);
		if($j==0)
		{
			$descripcion=$data[1];
			$pretest_date=$data[3];
			$posttest_date=$data[5];
			$sql=sprintf("insert into questionnair (q_title,description) values (%s,%s)",
			GetSQLValueString($q_title,"text"),
			GetSQLValueString($descripcion,"text")
		);
			mysqli_query($connection, $sql);
			$id_cuestionario=mysqli_insert_id($connection);
			$sql=sprintf("INSERT INTO `experience_questionnair`(`id_experience`, `id_questionnair`) VALUES (%s, %s)
			",
			GetSQLValueString($id_experience,"int"),
			GetSQLValueString($id_cuestionario,"int")
			);		
			mysqli_query($connection, $sql);
		}

		if($j>1)
		{		
	// 			$num = count($data);
// 				print_r($data);
// 				$cat=array_search($data[1],$categoria);
			$cat=array_search($data[1], array_column($categoria, 'catText'));
			if($cat===false)
			{
				$categoria[]=array("catText"=>$data[1],"id_cat_db"=>"0");
				$cat=array_search($data[1], array_column($categoria, 'catText'));
			}
	// 			$subcat=array_search($data[2],$subcategoria);
			$subcat=array_search($data[2], array_column($subcategoria, 'subcat'));
			if($subcat===false)
			{		
				$subcategoria[]=array('subcat'=>$data[2],"cat"=>$cat,"id_sub_db"=>0);
				$subcat=array_search($data[2], array_column($subcategoria, 'subcat'));
			}
			$ref=array_search($data[7],$referencias);
			$ref=array_search($data[7], array_column($referencias, 'refTexto'));
			if($ref===false)
			{
				$referencias[]=array("refTexto"=>$data[7],"id_ref_db"=>0);
				$ref=array_search($data[7], array_column($referencias, 'refTexto'));

			}
			$t=array_search($data[4],$tipo);
// 				if($t===false)
// 				{
// 					$tipo[]=$data[4];
// 					$t=array_search($data[4],$tipo);
// 				}
			$vals=explode("-", $data[5]);
			$minval=$vals[0];
			if(isset($vals[1]))$mintext=trim($vals[1]);else $mintext="";
			$vals=explode("-", $data[6]);
			$maxval=$vals[0];
			if(isset($vals[1]))$maxtext=trim($vals[1]);else $maxtext="";
			
			$q[$data[0]]=array($data[0],$cat,$subcat,$ref,$t,$minval,$mintext,$maxval,$maxtext,$data[3],"id_q_db"=>"0");
		}
		$j++;
	}
	fclose($handle);
}
// exit();
// print_r($categoria);
// print_r($subcategoria);
// print_r($referencias);
// print_r($q);
// print_r($tipo);
// 
// exit();

// $id_cuestionario=1000;
// $id_cat_db=1234;
// $id_cat_db=2345;
foreach($categoria as &$cat)
{
	$sql=sprintf("insert into category (categoria) values (%s)",
	GetSQLValueString($cat["catText"],"text")
	);
// 	print($sql);print "\n";
	mysqli_query($connection, $sql);
	$id_cat_db=mysqli_insert_id($connection);
	$cat["id_cat_db"]=$id_cat_db;
// 	$id_cat_db++;
}
// $id_subcat_db=2345;
foreach($subcategoria as &$subcat)
{
	$id_cat_db=$categoria[$subcat["cat"]]["id_cat_db"];
	$sql=sprintf("insert into subcategory (subcategoria,id_categoria) values (%s,%s)",
	GetSQLValueString($subcat["subcat"],"text"),
	GetSQLValueString($id_cat_db,"int")
	);
// 	print($sql);print "\n";
	mysqli_query($connection, $sql);
	$id_subcat_db=mysqli_insert_id($connection);
	$subcat["id_subcat_db"]=$id_subcat_db;
// 	$id_subcat_db++;
}
// $id_ref_db=5678;
foreach($referencias as &$ref)
{
	$sql=sprintf("insert into reference (referencia) values (%s)",
	GetSQLValueString($ref["refTexto"],"text")
	);
// 	print($sql);print "\n";
	mysqli_query($connection, $sql);
	$id_ref_db=mysqli_insert_id($connection);
	$ref["id_ref_db"]=$id_ref_db;
// 	$id_ref_db++;
}
// $id_q_db=3456;
$n=count($q);
foreach($q as $k=>$preg)
{
// 	$preg=$q[$k];
	$id_cat_db=$categoria[$preg[1]]["id_cat_db"];
	$id_subcat_db=$subcategoria[$preg[2]]["id_subcat_db"];
	$id_ref_db=$referencias[$preg[3]]["id_ref_db"];
	$sql=sprintf("insert into question (premise, id_category, id_subcategory, id_type, id_referencia) values (%s,%s,%s,%s,%s)",
	GetSQLValueString($preg[9],"text"),
	GetSQLValueString($id_cat_db,"int"),
	GetSQLValueString($id_subcat_db,"int"),
	GetSQLValueString($preg[4],"int"),
	GetSQLValueString($id_ref_db,"int")
	);
// 	print($sql);print "\n";
	mysqli_query($connection, $sql);
	$id_q_db=mysqli_insert_id($connection);
	$q[$k]["id_q_db"]=$id_q_db;
	if($preg[4]==1)
	{
		$sql=sprintf("insert into question_type (id_type, id_question, label, value) values (%s,%s,%s,%s),(%s,%s,%s,%s),(%s,%s,%s,%s),(%s,%s,%s,%s)",
			GetSQLValueString($preg[4],"int"),
			GetSQLValueString($id_q_db,"int"),
			GetSQLValueString("min_val","text"),
			GetSQLValueString($preg[5],"int"),
			GetSQLValueString($preg[4],"int"),
			GetSQLValueString($id_q_db,"int"),
			GetSQLValueString("min_texto","text"),
			GetSQLValueString($preg[6],"text"),
			GetSQLValueString($preg[4],"int"),
			GetSQLValueString($id_q_db,"int"),
			GetSQLValueString("max_val","text"),
			GetSQLValueString($preg[7],"int"),
			GetSQLValueString($preg[4],"int"),
			GetSQLValueString($id_q_db,"int"),
			GetSQLValueString("max_texto","text"),
			GetSQLValueString($preg[8],"text")
		); 
// 		print($sql);print "\n";
		mysqli_query($connection, $sql);

	}
	$sql=sprintf("INSERT INTO `questionnair_question`(`id_questionnair`, `id_question`) VALUES (%s, %s)
		",
		GetSQLValueString($id_cuestionario,"int"),
		GetSQLValueString($id_q_db,"int")
		);		
		mysqli_query($connection, $sql);
// 	$id_q_db++;
	
}
// print_r($q);
// exit();
// $id_subq=6789;
// $title="Pre Test";
// $descripcion="$title of $q_title";
// $sql=sprintf("insert into subquestionnair (`title`, `description`, `id_questionnair`, `date_to_administer`) values (%s,%s,%s,%s)",
// 	GetSQLValueString($title,"text"),
// 	GetSQLValueString($descripcion,"text"),
// 	GetSQLValueString($id_cuestionario,"int"),
// 	GetSQLValueString($pretest_date,"text")				
// );
// print($sql);print "\n";
// 	mysqli_query($connection, $sql);
// 	$id_subq=mysqli_insert_id($connection);
// $sql=sprintf("INSERT INTO `experience_subquestionnair`( `id_experience`, `id_subquestionnair`) VALUES (%s,%s)",
// 	GetSQLValueString($id_experience,"int"),
// 	GetSQLValueString($id_subq,"int")
// );
// 	mysqli_query($connection, $sql);
// // print_r($q);
// // exit();
// $n=count($q);
// foreach($q as $k=>$preg)
// {
// 	//print_r($data);print_r($q[$data[0]]);exit();
// // 	print_r($preg);
// 	$sql=sprintf("insert into subquestionnair_question (`id_subquestionnair`, `id_question`) values (%s,%s)",
// 		GetSQLValueString($id_subq,"int"),
// 		GetSQLValueString($q[$k]["id_q_db"],"int")
// 	);
// 	print($sql);print "\n";
// 		mysqli_query($connection, $sql);
// }
// exit();
// $id_subq++;
foreach($archivosCSV as $filename)
{
	if(strpos($filename, "questions")===false and strpos($filename, "instructions")===false)
	{
		$row = 1;
		$title=explode(".",explode("-", $filename)[1])[0];
		if (($handle = fopen($filename, "r")) !== FALSE) 
		{
// 			print $filename."\n";
			$j=0;
			while (($data = fgetcsv($handle)) !== FALSE) 
			{
// 				if($j==2)print_r($data);print"<br>";
				if($j==0)
				{
					$descripcion=$data[1];
					$fecha=$data[3];
					$sql=sprintf("insert into subquestionnair (`title`, `description`, `id_questionnair`, `date_to_administer`) values (%s,%s,%s,%s)",
						GetSQLValueString($title,"text"),
						GetSQLValueString($descripcion,"text"),
						GetSQLValueString($id_cuestionario,"int"),
						GetSQLValueString($fecha,"text")				
					);
// 					print($sql);print "\n";
						mysqli_query($connection, $sql);
						$id_subq=mysqli_insert_id($connection);
					$sql=sprintf("INSERT INTO `experience_subquestionnair`( `id_experience`, `id_subquestionnair`) VALUES (%s,%s)",
						GetSQLValueString($id_experience,"int"),
						GetSQLValueString($id_subq,"int")
					);
						mysqli_query($connection, $sql);
				
				}
				if($j>1)
				{
// 					if($j==2)print_r($data);print"<br>";
					//print_r($data);print_r($q[$data[0]]);exit();
					$sql=sprintf("insert into subquestionnair_question (`id_subquestionnair`, `id_question`) values (%s,%s)",
						GetSQLValueString($id_subq,"int"),
						GetSQLValueString($q[$data[0]]["id_q_db"],"int")
					);
// 					print($sql);print "\n";
						mysqli_query($connection, $sql);
	// 				$q[$data[0]]		
				}
				$j++;
			}
		}
	}
// 	$id_subq++;
	fclose($handle);
}
// $title="Post Test";
// $descripcion="$title of $q_title";
// $sql=sprintf("insert into subquestionnair (`title`, `description`, `id_questionnair`, `date_to_administer`) values (%s,%s,%s,%s)",
// 	GetSQLValueString($title,"text"),
// 	GetSQLValueString($descripcion,"text"),
// 	GetSQLValueString($id_cuestionario,"int"),
// 	GetSQLValueString($pretest_date,"text")				
// );
// print($sql);print "\n";
// 	mysqli_query($connection, $sql);
// 	$id_subq=mysqli_insert_id($connection);
// $sql=sprintf("INSERT INTO `experience_subquestionnair`( `id_experience`, `id_subquestionnair`) VALUES (%s,%s)",
// 	GetSQLValueString($id_experience,"int"),
// 	GetSQLValueString($id_subq,"int")
// );
// 	mysqli_query($connection, $sql);
// 
// 
// $n=count($q);
// foreach($q as $k=>$preg)
// {
// 	//print_r($data);print_r($q[$data[0]]);exit();
// 	$sql=sprintf("insert into subquestionnair_question (`id_subquestionnair`, `id_question`) values (%s,%s)",
// 		GetSQLValueString($id_subq,"int"),
// 		GetSQLValueString($q[$k]["id_q_db"],"int")
// 	);
// 	print($sql);print "\n";
// 		mysqli_query($connection, $sql);
// }
foreach($archivosCSV as $filename)
{
	exec("rm '$filename'");
}
header("Location: ".$_SERVER['HTTP_REFERER']."#questionnaires");
?>