<?php

class autocode {
	
	private $db;
	
	private $qLabels;
	private $qLabCount;
	private $qLabVarName;
	private $qLabAutoId;
	private $sqlLabValues;
	private $qLabCountAll;
	private $sqlBasicVals;
	
	
	/**
	 * @param Object $db - An instance of an database object
	 * @return bool
	 */
	public function __construct($db) {
		$this->db = $db;
		return true;
	}
	
	
	/**
	 * Check if recode is already made
	 *
	 */
	public function getCodeStatus($tableName) {
		$this->db->ChangeDatabase(DB_WARPIT_WEBRECODE);
		$check = $this->db->TableExists($tableName);
		
		if ($check) return true;
		
		// else
		return false;
	}
	
	
	/**
	 * Read labels which are not yet recoded
	 *
	 */
	public function getLabelsForCoding($x,$strucVars,$tableName,$qRecVars,$recVars,$qLabels,$qLabCount,$qLabVarName,$qLabAutoId,$sqlLabValues) {
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$strucRes = $this->db->SQLexecute("SELECT id,".implode(',',$strucVars)." FROM $tableName"."_structure WHERE recoded=0 AND status=1 AND status_rec=1");
		
		while ($row = $this->db->fetchAssoc($strucRes))
		{
			$sqlBasicValsTmp = array();
			$sqlBasicValsTmp[] = $row['id'];
			$structId[] = $row['id'];
			
			//for each question
			foreach ($qRecVars as $qName => $recVars) {
				$hasAnswer = false;
				//for each variable of the question
				foreach ($recVars as $var) {
					$label = $row[$var];
					if($label)
					{
						$hasAnswer = true;
						if(( $id_var = array_search($label,$qLabels[$qName])) === false  )
						{//this label was not yet indexed!
							//in this array we store the labels seperated by questions!
							$qLabels[$qName][] = $label;
							//in this array we store the count of the labels!
							$qLabCount[$qName][] = 1;
							//in this array we store the recode variable of this label
							$qLabVarName[$qName][] = 'r_'.$qName;
							//in this array we store the increment of the AI key that the label will get, to use in the calc table!
							$qLabAutoId[$qName][] = $x;
							
							//we set id_var to one more then the last key!
							$id_var = array_pop( array_keys( $qLabels[$qName] )  ) +1;
							//$id_var = count($qLabels[$qName] );
							$sqlLabValues[] = "($x,".$id_var.",'". addslashes($label). "','$qName')";
							$x++;
						}
						else
						{
							$qLabCount[$qName][$id_var]++;
							//we set id_var to one more then the found key!
							$id_var++;
						}
						
					}
					else 
						$id_var = 'null';
					$sqlBasicValsTmp[] = $id_var;
				}
				if($hasAnswer)
					$qLabCountAll[$qName]++;
				
			}
			$sqlBasicVals[] = "(".implode(',',$sqlBasicValsTmp).")";
		}
		
		$this->set_qLabels($qLabels);
		$this->set_qLabCount($qLabCount);
		$this->set_qLabVarName($qLabVarName);
		$this->set_qLabAutoId($qLabAutoId);
		$this->set_sqlLabValues($sqlLabValues);
		$this->set_qLabCountAll($qLabCountAll);
		$this->set_sqlBasicVals($sqlBasicVals);
		
		// set that this labels were already coded
		$this->markAsCoded($structId,$tableName);
		
		return $x;
	}
	

	public function get_qLabels() { return $this->qLabels; }
	public function get_qLabCount() { return $this->qLabCount; }
	public function get_qLabVarName() { return $this->qLabVarName; }
	public function get_qLabAutoId() { return $this->qLabAutoId; }
	public function get_sqlLabValues() { return $this->sqlLabValues; }
	public function get_qLabCountAll() { return $this->qLabCountAll; }
	public function get_sqlBasicVals() { return $this->sqlBasicVals; }
	
	
	private function set_qLabels($qLabels) { $this->qLabels = $qLabels; }
	private function set_qLabCount($qLabCount) { $this->qLabCount = $qLabCount; }
	private function set_qLabVarName($qLabVarName) { $this->qLabVarName = $qLabVarName; }
	private function set_qLabAutoId($qLabAutoId) { $this->qLabAutoId = $qLabAutoId; }
	private function set_sqlLabValues($sqlLabValues) { $this->sqlLabValues = $sqlLabValues; }
	private function set_qLabCountAll($qLabCountAll) { $this->qLabCountAll = $qLabCountAll; }
	private function set_sqlBasicVals($sqlBasicVals) { $this->sqlBasicVals = $sqlBasicVals; }
	
	
	/**
	 * in *_structure marked records as coded
	 */  
	private function markAsCoded($id,$tableName) {
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$this->db->SQLexecute("UPDATE ".$tableName."_structure SET recoded=1 WHERE id IN (".implode(",",$id).")");
		return true;
	}
	
	
	public function createRecodeTables($tableName, $col) {
		$this->db->ChangeDatabase(DB_WARPIT_WEBRECODE);
		
	 	$this->db->SQLexecute("CREATE TABLE IF NOT EXISTS $tableName (
			id int(10),
			".implode(' int(10) ,',$col) ." int(10),
			PRIMARY KEY (id)
		) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci");
			
	
		$this->db->SQLexecute("CREATE TABLE IF NOT EXISTS `".$tableName."_calc` (
		  `id` int(10) unsigned NOT NULL auto_increment,
		  `id_label` int(11) NOT NULL,
		  `number` int(5) default NULL,
		  `procent` char(6) collate utf8_unicode_ci default NULL,
		  `recoded_id` int(6) default NULL,
		  `var_name` varchar(20) collate utf8_unicode_ci NOT NULL,
		  PRIMARY KEY  (`id`),
		  KEY `id_label` (`id_label`),
		  KEY `recoded_id` (`recoded_id`),
		  KEY `var_name` (`var_name`)
		) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ");
		
		
		$this->db->SQLexecute("CREATE TABLE IF NOT EXISTS `".$tableName."_labels` (
		  `id` int(11) NOT NULL auto_increment,
		  `id_var` int(10) unsigned NOT NULL,
		  `label` text collate utf8_unicode_ci default NULL,
		  `var_name` varchar(20) collate utf8_unicode_ci NOT NULL,
		  PRIMARY KEY  (`id`),
		  UNIQUE KEY `id_var_name` (`id_var`,`var_name`),
		  KEY `var_rec` (`var_name`),
		  KEY `id_label` (`id_var`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ");
		
		
		$this->db->SQLexecute("CREATE TABLE IF NOT EXISTS `".$tableName."_multicode` (
		  `id_calc` int(10) unsigned NOT NULL,
		  `recoded_id` int(10) unsigned NOT NULL,
		  UNIQUE KEY `id_calc_2` (`id_calc`,`recoded_id`),
		  KEY `id_calc` (`id_calc`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci");
		
		
		$this->db->SQLexecute("CREATE TABLE IF NOT EXISTS `".$tableName."_rec_def` (
		  `id` int(3) NOT NULL auto_increment,
		  `var_arry` text collate utf8_unicode_ci,
		  `var_label` varchar(250) collate utf8_unicode_ci default NULL,
		  `var_rec` varchar(16) collate utf8_unicode_ci default NULL,
		  `rec_def` varchar(250) collate utf8_unicode_ci default NULL,
		  `filter` text collate utf8_unicode_ci,
		  `finish` int(1) default NULL,
		  `id_question` int(3) default NULL,
		  `logical_varpart` int(3) default NULL,
		  `multicode` int(1) default '0',
		  PRIMARY KEY  (`id`),
		  UNIQUE KEY `var_rec` (`var_rec`)
		) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ");
		
		
		$this->db->SQLexecute("CREATE TABLE IF NOT EXISTS `".$tableName."_var_lab` (
		  `varname` char(25) collate utf8_unicode_ci default NULL,
		  `lab` char(250) collate utf8_unicode_ci NOT NULL,
		  UNIQUE KEY `varname` (`varname`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci");
	
		
		//we add the column in the structure!!
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$this->db->SQLexecute("ALTER TABLE $tableName"."_structure ADD recoded BOOL DEFAULT 0");
		
		return true;
	}
	
	
	public function fillRecodeDefinitionTable($tableName,$recDef,$recDefLab) {
		$this->db->ChangeDatabase(DB_WARPIT_WEBRECODE);

		foreach ($recDef as $var_rec => $varArr) {
			$recDefValues[] = "('". implode('#',$varArr)."' , '".$recDefLab[$var_rec]."' , '$var_rec' , '".$recDefLab[$var_rec]."')" ;
		}
		$this->db->SQLexecute("INSERT INTO $tableName"."_rec_def (var_arry,var_label,var_rec,rec_def) VALUES ".implode(',',$recDefValues ) );
		
		return true;
	}
	
	
	public function fillVarLabTable($tableName,$varLab) {
		$this->db->ChangeDatabase(DB_WARPIT_WEBRECODE);

		$this->db->SQLexecute("INSERT INTO $tableName"."_var_lab VALUES ".implode(',',$varLab) );
		
		return true;
	}	
	
	
	public function loadExistingCodes($tableName) {
		
	}
	
	
}
?>