<?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/_ajax/class.groups.php");


class importOldProjManipulator extends GridDataManipulator
{
	/**
	 * old database
	 *
	 * @var db
	 */
	public $dbNew; 
	public $wcOld;
	
	public function selectAction()
	{
		$this->db->ChangeDatabase($this->wcOld['RM_cati_base'] );
		$_POST['SQL'] = "SELECT id,proj_name,naziv_proj FROM projects";
		
		return parent::selectAction();
	}
	
	
	private function checkProjectName($str) {
		if (is_numeric($str[0]))
			return "P";
		else
			return "";		
	}
	
	
	public function importOldAction()
	{
		$this->db->ChangeDatabase($this->wcOld['RM_cati_base'] );
		$sql = "SELECT id,proj_name,language FROM projects WHERE id IN (".$_POST['projects'].")";
		$res = $this->db->SQLexecute($sql);
		while ($row = $this->db->fetchAssoc($res))
		{
			$add2projName = $this->checkProjectName($row['proj_name']);
			
			$proj[$row['id']] = $add2projName.$row['proj_name'];
			$proj_old[$row['id']] = $row['proj_name'];
			$lang[$row['id']] = $row['language'];
		}
		
		$this->dbNew->ChangeDatabase( DB_WARPIT_WEBCATI_BASE);
		$crP = new wcGroupsTreeDataMan($this->dbNew,'_Projects');
		$crP->table = "_Projects";
		$crP->tableGrid = "_Projects";
		$crP->tableTree = "_ProjectsTree";
		$lngConversion = array(1 => 45,91,61,30,54,76,83,67,90,31,70,87,23);

		$projectsArr = explode(',',$_POST['projects']);
		foreach ($projectsArr as $projId) {
			$_POST['parId'] = 0;
			$_POST['nodeText'] = $proj[$projId];
			//$orderTree = $_POST['tPos'];
			$_POST['nodeId'] = 0;
			$language = $_POST['projectLanguage'] = $lngConversion[ $lang[$projId] ];
			
			$crProRes =  json_decode( $crP->insertProjectAction() ,true);
			if(!$crProRes['success'])
			{
				$errors[] = $proj[$projId].':'.$crProRes['error'];
				$errData[] = $this->dbNew->GetError();
				continue;
			}
			$newProjId = $crProRes['insertId'];
			
			// !!! changed by Borut, this is not necessary, I move this into class.groups create table !!!  
			//$this->dbNew->ChangeDatabase(DB_WARPIT_WEBCATI);
			//$this->dbNew->SQLexecute("ALTER TABLE  `".$proj[$projId]."` ADD  `old_id` INT NOT NULL,ADD `up_down_rotchk` INT NOT NULL, ADD  `up_down_rotvar` INT NOT NULL");
			
			$this->db->ChangeDatabase( $this->wcOld['RM_cati'] );
			$oldQres = $this->db->SQLexecute("SELECT * FROM ".$proj_old[$projId]." ORDER BY q_pos");
			$autoId = 5;
			$qPos = 1;
			$lngValues = array();
			$multiLngValue = array();
			$questions = array();
			$questTree = array();
			while ($oldQuestion = $this->db->fetchAssoc($oldQres))
			{
				$oldQuestion['q_pos'] = $qPos;
				$qPos++;
			//copy all data that is needed in new questionairse
				$questions[] = $this->extractQuestion($oldQuestion);
				
				$questTree[] = "($autoId,0,$autoId,".($autoId-3).",'{$oldQuestion['q_name']}',1,0)";
				
				if($oldQuestion['nav_sql'])
					$lngValues[] = "($autoId,$language,1,'".str_replace('<+>','/', $oldQuestion['nav_sql'] )."')";
				if($oldQuestion['vpr_sql'])
					$lngValues[] = "($autoId,$language,2,'".str_replace('<+>','/', $oldQuestion['vpr_sql'])."')";
				if($oldQuestion['odg_sql'])
					$lngValues[] = "($autoId,$language,3,'".str_replace('<+>','/', $oldQuestion['odg_sql'])."')";
				if($oldQuestion['leg_sql'])
					$lngValues[] = "($autoId,$language,4,'".str_replace('<+>','/', $oldQuestion['leg_sql'])."')";
				if($multiLang = $oldQuestion['multilanguage_all'])
				{
					$multiLngValue = array();
					$lngAll = explode('<->',$multiLang);
					foreach ($lngAll as $lngArr) {
						$lngArr = explode('<;>',$lngArr);
						$langTmp = $lngArr[0];
						for($i=1;$i<=4;$i++)
						if($lngArr[$i])
							$lngValues[] = "($autoId,$langTmp,$i,'".str_replace('<+>','/', $lngArr[$i] )."')";
							
						if($lngArr[5])
							$leaveTxtValues[] = "($langTmp,40,$newProjId,$autoId,'".$lngArr[5]."')";
						if(!in_array($langTmp,$multiLngValue))	
							$multiLngValue[] = $langTmp;
					}
					
				}
				
					
				$autoId++;
					
			}
			
			$columns = "q_pos,q_name,tip_sql,les_sql,goto_sql,fil_sql,con_sql,open_sql,anno_sql,attachAnswers,attachFalse,srot_sql,erot_sql,qrot_sql,must_answer,disable_question,answers_filter,variableTypeBase,variableTypeOpen,open_answers,multi_nogo_answers,qleave_js_alert,filter_answer,hasStructure,use_for_quotas,isFinal,old_id";
			try {
				$this->dbNew->ChangeDatabase( DB_WARPIT_WEBCATI);
				$sql = "INSERT INTO ".$proj[$projId]."($columns) VALUES ".implode(',',$questions);
				$this->dbNew->SQLexecute($sql);
				
				$sql = "INSERT INTO ".$proj[$projId]."_tree(id,id_sup,id_question,orderBy,idLab,is_leaf,showTogether) VALUES ".implode(',',$questTree);
				$this->dbNew->SQLexecute($sql);
				
				$sql = "INSERT INTO ".$proj[$projId]."_language(id_question,id_language,id_text_type,lngText)VALUES ".implode(',',$lngValues);
				$this->dbNew->SQLexecute($sql);
				
				$this->dbNew->ChangeDatabase( DB_WARPIT_WEBCATI_BASE);
				if($multiLngValue)
				{
					foreach ($multiLngValue as $langTmp) {
						$mltLngVals[] = "($newProjId,$langTmp)";
					}
					
					$sql = "INSERT INTO _LanguageProjects(id_project,id_language)VALUES ".implode(',',$mltLngVals);
					$this->dbNew->SQLexecute($sql);
				}
				if($leaveTxtValues)
				{
					$sql = "INSERT INTO _LanguageUserInterface(id_language,id_text_type,id_project,id_question,lngText)VALUES ".implode(',',$leaveTxtValues);
					$this->dbNew->SQLexecute($sql);
				}
				$succIds[] = $newProjId;
			}
			catch (Exception $e)
			{
				$errors[] = $proj[$projId].':Unknown error while importing data!';
				$errData[] = $e;
			}
			
			
		}
		if($succIds)
		{
			$crStr = new bqwcGridDataMan($this->dbNew,'lala');
			$_POST['deleteConfirm'] = true;
			$_POST['id_project'] = implode(',',$succIds);
			$crStr->createStructureAction();
		}
		if($errors)
			return "{success:false,errors:'".implode('<br>',$errors)."',errData:'".addslashes( implode('<br>',$errData) )."'}";
			
		
		
		return "{success:true}";
	}
	//to keep local variables
	private function extractQuestion(&$oldQuestion)
	{
		extract($oldQuestion);
		if($tip_sql == 1)
		{
			if($drg_sql == 'D')//the last question will be open
			{
				$ans= explode('/',$odg_sql);
				$lastAns = explode(' ', $ans[ count($ans) - 1 ],2 );
				$openAnsers = $lastAns[0];
			}
			$Nles_sql = $open_sql == 2 ? 7 : 1;
		}
		else if($tip_sql == 2) 
		{
			$Nles_sql = $les_sql == 5 ? $Nles_sql = 7:$les_sql;
			if($les_sql == 4)
				$tip_sql = 3;
			else if($les_sql == 3)
				$tip_sql = 4;
				
			if($drg_sql == 'D')//the last question will be open
			{
				$ans= explode('/',$odg_sql);
				$lastAns = explode(' ', $ans[ count($ans) - 1 ],2 );
				$lastVal = $lastAns[0];
				$ans[ count($ans) - 1 ] .= '(1)';
				$openAnsers = $lastVal;
				for($i=2;$i<=$open_sql;$i++)
				{
					$lastVal++;
					$ans[] = $lastVal.' '.$lastAns[1]."($i)";
					$openAnsers .= ':'.$lastVal;
				}
				$oldQuestion['odg_sql'] = implode('/',$ans);
			}
		}
		else if($tip_sql == 3) 
		{
			if($anno_sql)
			{
				$tip_sql = 2;
				$Nles_sql = 5;
				//we must create/expand/shorten legend to be exact as ano!
				$leg = explode('/',$leg_sql);
				$maxLeg = 0;
				foreach ($leg as $oneLegend) {
						$oneLegExpl = explode(' ',$oneLegend,2);
						if($oneLegExpl[0]>$maxLeg) $maxLeg = $oneLegExpl[0];
					}
				while (count($leg) < $anno_sql)
				{
					$maxLeg++;
					$leg[] = $maxLeg.' '. $maxLeg;
				}
				//if legend is bigger then anno, we cut it
				$legCnt = count($leg);
				for($i=$anno_sql;$i<$legCnt;$i++ )
					unset($leg[$i]);
					
				$oldQuestion['leg_sql'] = implode('/',$leg);
			}
			else
			{
				$Nles_sql = 4;
				$leg_sql = '';
			}
			if($drg_sql == 'D')//the last question will be open
				{
					$ans= explode('/',$odg_sql);
					$allValues = array();
					foreach ($ans as $oneAnswer) {
						$oneAnsExpl = explode(' ',$oneAnswer,2);
						$allValues[] = $oneAnsExpl[0];
					}
					
					$lastAns = explode(' ', $ans[ count($ans) - 1 ],2 );
					$lastVal = $lastAns[0];
					//lets find maximum value so that we can upgrade that
					$ans[ count($ans) - 1 ] .= '(1)';
					$openAnsers = $lastVal;
					for($i=2;$i<=$open_sql;$i++)
					{
						while (in_array($lastVal,$allValues))
							$lastVal++;
						$allValues[] = $lastVal;
						$ans[] = $lastVal.' '.$lastAns[1]."($i)";
						$openAnsers .= ':'.$lastVal;
					}
					$oldQuestion['odg_sql'] = implode('/',$ans);
				}
			
		}
		else if($tip_sql == 4) 
		{
			$Nles_sql = 6;
			$Nopen_sql = $open_sql;
			$type_variable_base = $type_variable_open;
		}
		else if($tip_sql == 8)
			$tip_sql = 5;
		else if($tip_sql == 9)
			$tip_sql = 6;
			
		if($type_variable_base == 1)
			$varBase = 4;
		else
			$varBase = 0;
		if($type_variable_open == 1)
			$varOpen = 4;
		else
			$varOpen = 0;
			
		$useForQuotas = $brk_sql == 'D' ? 1 : 0;
		
		
		return "( $q_pos,'$q_name',$tip_sql, '$Nles_sql','$goto_sql','$fil_sql','$con_sql','$open_sql','$anno_sql','$sklic_sql','$attach_false','$srot_sql','$erot_sql','$qrot_sql','$must_answer','$disable_question','$answers_filter',$varBase,$varOpen,'$openAnsers','$multi_nogo_answers','$qleave_js_alert','$filter_answer',1,'$useForQuotas',0,$id)";
		
	}
	
}


	$wcOld = configLoader::loadConfig('webcati_old');
	$dbOld = new db();
	$dbOld->SetDatabaseConnection($wcOld['username'],$wcOld['password'],$wcOld['server']);
	
	$manipulator = new importOldProjManipulator($dbOld,$_POST['RMtable']);
	$manipulator->dbNew = $db;
	$manipulator->wcOld = $wcOld;
	
	$comm = $_POST['action'].'Action';
	if(method_exists($manipulator,$comm))
		echo $manipulator->$comm();
	else 
	{
		
		Echo '{success:false,error:"Unknown action!"}';	
		
	}


?>
