<?php 

if($_POST['redefine'])
{
	//if redefine is set it means we made an ajax call, otherwise this file was included and these vairables are already set!
	include_once("_dirinfo.php");
	include_once(PATH_TO_ROOT."init.php");
	
	$tableName = $_POST['project'];
	$projectId = $_POST['project_id'];
	$export_select = $_POST['exportSelect'];
	$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
	//also we delete all data for this project
	$dataTable = $export_select == 8 ? '_DatamapAscii' : '_DatamapBinary';
	$sql = "DELETE FROM $dataTable WHERE id_project = $projectId";
	$db->SQLexecute($sql);
	echo '{success:true}';
}
	$db->ChangeDatabase(DB_WARPIT_WEBCATI);
 	$id_language = $_POST['id_language'];
 	$id_lngDef = $_POST['id_lngDef'];			
//lets get the language data
   	$sql = "SELECT * FROM $tableName"."_language INNER JOIN _LanguageText ON id_text_type = id_text WHERE id_language = $id_language OR id_language=$id_lngDef";
	$resLng = $db->SQLexecute($sql);
	while ($rowLng = $db->fetchAssoc($resLng))
	{
		if($rowLng['id_question'] == $id_language || !$lngArray[ $rowLng['id_question'] ][ $rowLng['variable'] ])
			$lngArray[ $rowLng['id_question'] ][ $rowLng['variable'] ] = $rowLng['id_text_type'] == 2 ? addslashes( $rowLng['lngText']) : $rowLng['lngText'] ; 
	}

if($export_select == 8)
{
//we fill the table with the variables
			$sql_qname = "SELECT id, tip_sql, q_name, les_sql, variableTypeBase, variableTypeOpen FROM ".$tableName;
//	 				echo "$sql_qname<br>";
 				$db->ChangeDatabase(DB_WARPIT_WEBCATI);
 				if(!$result_qname = $db->SQLexecute($sql_qname)) {echo "alert('db erro!222');".$db->GetError(); exit;}
 				unset($all_qname);
  				while ($row_qname = mysql_fetch_array($result_qname)) {
 					$all_qname[] = $row_qname['q_name'];  
 					$q_type[$row_qname['q_name']] = $row_qname['tip_sql']; 
 				}
 				//lets calculate the maximum variable length needed (max(length
 				$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
 				//changed describe!
 				$allVarsRes = $db->describe($tableName."_structure");// "DESCRIBE ".$tableName."_structure LIMIT 1";
 				if(!$allVarsRes) {echo "alert('db erro333!');".$db->GetError(); exit;}
 				foreach ($allVarsRes as $varRow)
 				{
 					$varMaxLen[] = "MAX( LENGTH(".$varRow['field'].")) AS ".$varRow['field'];
 				}
 				
 				
   				$sqlGetMax = "SELECT ".implode(',',$varMaxLen)." FROM ".$tableName."_structure";
				if(!$allVarsRes = $db->SQLexecute($sqlGetMax)) {echo "alert('db erro333!');".$db->GetError(); exit;}
				unset($varMaxLen);
 				while ($varRow = $db->fetchArray($allVarsRes))
 				{
 					$number_of_variables = mysql_num_fields($allVarsRes);
 					for ($nv=0;$nv<$number_of_variables;$nv++) {
 						$varMaxLen[] = $varRow[$nv];
 					}
 				}
				// echo "$sql_all_vars<br>";
   				//$result_all_vars = mysql_db_query($CATI_base_structure, $sql_all_vars, $SQLconnect);
   				
   				$sql_all_vars = "SELECT * FROM ".$tableName."_structure LIMIT 1";
				
   				if(!$result_all_vars = $db->SQLexecute($sql_all_vars)){echo "alert('db erro444!');".$db->GetError().$sql_all_vars; exit;}
   					//$row_all_vars = $db->fetchArray($result_all_vars);
 						
 					$number_of_variables = mysql_num_fields($result_all_vars);
					$start_number = 1;
 					for ($nv=0;$nv<$number_of_variables;$nv++) {
 						$name_of_variable = mysql_field_name($result_all_vars, $nv);
 						$type_of_variable = mysql_field_type($result_all_vars, $nv);
 						$basename_of_variable_array = explode("_", $name_of_variable,2);
 						$basename_of_variable = $basename_of_variable_array[0];
 						if (in_array($basename_of_variable, $all_qname)) {
 							$system_name = $basename_of_variable; 
 						} else {
 							$system_name = "SYSTEM";
 						}
 						//if ($pre_system_name == $system_name) unset($system_name); else $pre_system_name = $system_name;
 
				// pogledam, max vrednost in zgradim array vseh odgovorov, max vrednost rabim da dolocim max dolzino polja
 						if ($type_of_variable == "string" || $type_of_variable == "date") {
 						$fill_var_type = "A";
 						} else {
 		   				$fill_var_type = "F";
 						}
 						$get_max_val = $varMaxLen[$nv];
 						if (!$get_max_val) $get_max_val = 1;
 						$values[] = "($projectId,'$system_name','$name_of_variable','$fill_var_type',$start_number,$get_max_val)";
   				
					$start_number =	$start_number + $get_max_val + 1; 
				}
				$sql = "INSERT INTO _DatamapAscii(id_project,sys_name,var_name,var_type,start_col,length_col)";
				$sql .= "VALUES ".implode(',',$values);
				if(!$db->SQLexecute($sql)) {echo "alert('db erro666!');".$db->GetError(); exit;}
}else if($export_select == 9)
{

// precitam imena vseh variabl v polje
     				$sql_qname = "SELECT id, tip_sql, q_name, les_sql, anno_sql FROM ".$tableName;
//		 				echo "$sql_qname<br>";
    				$db->ChangeDatabase(DB_WARPIT_WEBCATI);
 					if(!$result_qname = $db->SQLexecute($sql_qname)) {echo "alert('db erro!222');".$db->GetError(); exit;}
 					require_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
		    	
    				unset($all_qname);
     				while ($row_qname = mysql_fetch_array($result_qname)) {
    					$all_qname[] = $row_qname['q_name'];  
    					$q_type[$row_qname['q_name']] = $row_qname['tip_sql'];
    					$q_sub_type[$row_qname['q_name']] = $row_qname['anno_sql'];
    					$q = Question::createQuestionFromTable($db,$tableName,$row_qname['id']);
							$odgovori = $q->odg_sql;
							$odgovori = str_replace("/","<*>",$odgovori);
							$odgovori = str_replace("<<+>","</",$odgovori);
    					$q_label[$row_qname['q_name']] = explode("<*>", $odgovori);
							$q_legenda[$row_qname['q_name']] = explode("/", $q->leg_sql);
    					$length_var_num[$row_qname['q_name']] = $row_qname['lenght_variable_base']; 
    				}
    				$sql_all_vars = "SELECT * FROM ".$tableName."_structure LIMIT 1";
//	 					echo "$sql_all_vars<br>";
    				//$result_all_vars = mysql_db_query($CATI_base_structure, $sql_all_vars, $SQLconnect);
    				$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
 					if(!$result_all_vars = $db->SQLexecute($sql_all_vars)) {echo "alert('db erro!333');".$db->GetError(); exit;}
 				
    				$row_all_vars = mysql_fetch_array($result_all_vars);
  					$number_of_variables = mysql_num_fields($result_all_vars);
						$start_number = 1;
						$mrvar_cnt = 1;
						$bin_codes = array("1","2","3","4","5","6","7","8","9","0","X","Y");
						$bin_codes_cnt = 0;
						$bin_card_cnt = 1;
						$bin_column_cnt = 1;
  					for ($nv=0;$nv<$number_of_variables;$nv++) {
  					    
  						$name_of_variable = mysql_field_name($result_all_vars, $nv);
  						$type_of_variable = mysql_field_type($result_all_vars, $nv);
  						$basename_of_variable_array = explode("_", $name_of_variable,2);
  						$basename_of_variable = $basename_of_variable_array[0];
  						
  						if (in_array($basename_of_variable, $all_qname)) {
  							$system_name = $basename_of_variable; 
  						} else {
  							$system_name = "SYSTEM";
  						}
  						if ($pre_system_name == $system_name) unset($system_name); else $pre_system_name = $system_name;
// rabim se vse vrednosti ki so mozne v eni variabli, rabim tudi dolzino
  						if ($type_of_variable != "string") {
								unset($get_max_val);
								if ($pre_system_name == "SYSTEM") {
  								if ($system_name AND $bin_column_cnt > 1) {
  									$mrvar_cnt = 0;
  									if ($bin_column_cnt >= 80) {
  											$bin_column_cnt = 1;
  									} else {
  										$bin_column_cnt++;
  									}	
  								}	
									unset($rec_bin_code);
    		   				$sql_get_max = "SELECT MAX(".$name_of_variable."), MIN(" . $name_of_variable . ") FROM ".$tableName."_structure";
//   			  				echo $sql_get_max."<br>";
							$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
 							if(!$result_get_max = $db->SQLexecute($sql_get_max)) {echo "alert('db erro!333');".$db->GetError(); exit;}
 				
        					//$result_get_max = mysql_db_query($CATI_base_structure, $sql_get_max, $SQLconnect);
    							$row_get_max = mysql_fetch_row($result_get_max);
                                
                                //28.1.2015 Tanis, včasih se zgodi, da je negativna vrednost daljša kot pozitivna, zato preverimo katera je daljša
                                if(strlen($row_get_max[0]) > strlen($row_get_max[1]))
                                {
        							$get_max_val = strlen($row_get_max[0]);
                                }
                                else 
                                {
                                    $get_max_val = strlen($row_get_max[1]);
                                }
    							if (!$get_max_val ) $get_max_val = $length_var_num[$pre_system_name];
    							if (!$get_max_val ) $get_max_val = 1;
									unset($var_value);
	 								if ($bin_column_cnt + $get_max_val > 80) $bin_column_cnt = 1;
									$bin_column = $bin_column_cnt;
									$bin_card = $bin_card_cnt;
									//include("./datamap_binary_define.php");
									$values[] = "($projectId,'$pre_system_name','$name_of_variable',$start_number,'$var_value','$bin_card','$bin_column','$rec_bin_code','$get_max_val')";
									$mrvar_cnt = 0;
 									$bin_column_cnt = $bin_column_cnt + $get_max_val;
									$system_var_chk = 1;
									$start_number++;
	  						} else {
									if ($q_type[$basename_of_variable] == 1) {
										if ($system_name AND !$system_var_chk) {
    									if ($bin_column_cnt >= 80) {
    										$bin_column_cnt = 1;
    										$bin_card_cnt++;
    									} else {
    										$bin_column_cnt++;
    									}
										}	
										$bin_codes_cnt_sr = 0;
  									foreach ($q_label[$basename_of_variable] as $key_q_label => $item_q_label) {
  										$item_qlab_arrray = explode(" ",$item_q_label,2);
											$var_value = $item_qlab_arrray[0];
											$get_max_val = 1;
											$rec_bin_code = $bin_codes[$bin_codes_cnt_sr];
											$bin_column = $bin_column_cnt;
											$bin_card = $bin_card_cnt;
  									//include("./datamap_binary_define.php");
										$values[] = "($projectId,'$pre_system_name','$name_of_variable',$start_number,'$var_value','$bin_card','$bin_column','$rec_bin_code','$get_max_val')";
											if ($bin_codes_cnt_sr == 11) {
												$bin_codes_cnt_sr = 0;
												if ($bin_column_cnt >= 80) {
  												$bin_column_cnt = 1;
													$bin_card_cnt++;
												} else {
													$bin_column_cnt++;
												}	
											} else	{
												$bin_codes_cnt_sr++;
											}	
											unset($system_name);
											$start_number++;
  									}
									} elseif ($q_type[$basename_of_variable] == 2) {
//										echo $basename_of_variable." :basename_of_variable | $name_of_variable :name_of_variable | $bin_card_cnt | $bin_column_cnt<br>";
 										$bin_column_cnt++;

										$bin_codes_cnt_sr = 0;
  									foreach ($q_legenda[$basename_of_variable] as $key_q_label => $item_q_label) {
//											echo "$key_q_label => $item_q_label<br>";
  										$item_qlab_arrray = explode(" ",$item_q_label,2);
											$var_value = $item_qlab_arrray[0];
											$get_max_val = 1;
											$rec_bin_code = $bin_codes[$bin_codes_cnt_sr];
											$bin_column = $bin_column_cnt;
											$bin_card = $bin_card_cnt;
  										//include("./datamap_binary_define.php");
									$values[] = "($projectId,'$pre_system_name','$name_of_variable',$start_number,'$var_value','$bin_card','$bin_column','$rec_bin_code','$get_max_val')";
   				
											if ($bin_codes_cnt_sr == 11) {
												$bin_codes_cnt_sr = 0;
												if ($bin_column_cnt >= 80) {
  												$bin_column_cnt = 1;
													$bin_card_cnt++;
												} else {
													$bin_column_cnt++;
												}	
											} else	{
												$bin_codes_cnt_sr++;
											}	
											unset($system_name);
											$start_number++;
  									}
									} elseif ($q_type[$basename_of_variable] == 3) {
										if ($q_sub_type[$basename_of_variable] > 0) {
   										$bin_column_cnt++;
  										$bin_codes_cnt_sr = 0;
    									foreach ($q_label[$basename_of_variable] as $key_q_label => $item_q_label) {
    										$item_qlab_arrray = explode(" ",$item_q_label,2);
  											$var_value = $item_qlab_arrray[0];
  											$get_max_val = 1;
  											$rec_bin_code = $bin_codes[$bin_codes_cnt_sr];
  											$bin_column = $bin_column_cnt;
  											$bin_card = $bin_card_cnt;
    										//include("./datamap_binary_define.php");
										$values[] = "($projectId,'$system_name','$name_of_variable',$start_number,'$var_value','$bin_card','$bin_column','$rec_bin_code','$get_max_val')";
  											if ($bin_codes_cnt_sr == 11) {
  												$bin_codes_cnt_sr = 0;
  												if ($bin_column_cnt >= 80) {
    												$bin_column_cnt = 1;
  													$bin_card_cnt++;
  												} else {
  													$bin_column_cnt++;
  												}	
  											} else	{
  												$bin_codes_cnt_sr++;
  											}	
  											unset($system_name);
  											$start_number++;
    									}
										} else {
  										if ($system_name AND !$system_var_chk) {
  											$bin_codes_cnt = 0;
  											$mrvar_cnt = 0;
  											if ($bin_column_cnt >= 80) {
    											$bin_column_cnt = 1;
  												$bin_card_cnt++;
  											} else {
  												$bin_column_cnt++;
  											}	
  										}	
    									$item_qlab_arrray = explode(" ",$q_label[$basename_of_variable][$mrvar_cnt],2);
  										$var_value = $item_qlab_arrray[0];
  										$get_max_val = 1;
  										$rec_bin_code = $bin_codes[$bin_codes_cnt];
  										$bin_column = $bin_column_cnt;
  										$bin_card = $bin_card_cnt;
   										//include("./datamap_binary_define.php");
										$values[] = "($projectId,'$pre_system_name','$name_of_variable',$start_number,'$var_value','$bin_card','$bin_column','$rec_bin_code','$get_max_val')";
  										$mrvar_cnt++;
    									if ($bin_codes_cnt == 11) {
  	 										$bin_codes_cnt = 0;
  											if ($bin_column_cnt >= 80) {
    											$bin_column_cnt = 1;
  												$bin_card_cnt++;
  											} else {
  												$bin_column_cnt++;
  											}	
    									} else	{
    										$bin_codes_cnt++;
    									}
  										$start_number++;
										}
									}
									unset($system_var_chk);
								}
  						}
							if ($bin_column_cnt >= 80) {
  							$bin_column_cnt = 1;
								$bin_card_cnt++;
							}
						}
				$sql = "INSERT INTO _DatamapBinary(id_project,sys_name,var_name,field_cnt,var_value,bin_card,bin_column,var_rec_value,bin_length)";
				$sql .= "VALUES ".implode(',',$values);
				if(!$db->SQLexecute($sql)) {echo "alert('db erro666!');".$db->GetError(); exit;}
}

?>