<?php 
include_once ("_dirinfo.php");

include_once (PATH_TO_ROOT."init.php");
include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.gridData.php");

class UserSamplingMan extends GridDataManipulator{
	
	function createSamplingDataAction()
	{
		
		$tableName = $this->tableName;
		$this->db->ChangeDatabase(DB_WARPIT_USERSPOOL);
		$this->db->SQLexecute("DROP TABLE IF EXISTS ".$tableName);
		
		$fields = $this->db->get('_InterviewerStructure','id IN ('.$_POST['fields'].')','field_name,data_type,field_text');
		include (PATH_TO_ROOT.'config.php');
		$sql = "CREATE TABLE $tableName  (
		id INT NOT NULL AUTO_INCREMENT ,
		select_N INT NOT NULL,
		freq_N INT NOT NULL,
		percent FLOAT(10,2) NOT NULL";
		foreach ($fields as $data) {
			$sql .= ','.$data['field_name']." ".getDataType($data['data_type']);
			$fldNames[] = $data['field_name'];
			$headers[] = $data['field_text'];
		}
		
		$sql .= ", PRIMARY KEY (id)) ENGINE = MYISAM";
		
		$this->db->SQLexecute($sql);
		$sql = "SELECT count(*) FROM _Interviewer a INNER JOIN _group_link b ON a.id = b.id WHERE b.id_group = ".$_POST['id_group'];
		$res = $this->db->SQLexecute($sql);
		$row = $this->db->fetchRow($res);
		$count = $row[0];
		
		$fldNames = implode(',',$fldNames);
		//load the data from interviewer table
		$sql = "INSERT INTO $tableName (freq_N,percent,$fldNames) SELECT count(DISTINCT a.id),count(DISTINCT a.id)/$count*100,".$fldNames." FROM _Interviewer a INNER JOIN _group_link b ON a.id = b.id WHERE b.id_group = ".$_POST['id_group']." GROUP BY $fldNames";
		$this->db->SQLexecute($sql);
		
		//lets write this data in the tree as an invisible data that will not show!
		$sql = "DELETE FROM _SamplingTemplates WHERE id_user = ".$_SESSION['UserInfo']['id'];
		$this->db->SQLexecute($sql);
		$sql = "INSERT INTO _SamplingTemplates (id_sup,id_user,id_group,id_fields) VALUES (-1,".$_SESSION['UserInfo']['id'].",".$_POST['id_group'].",'".$_POST['fields']."')";
		$this->db->SQLexecute($sql);
		
		return "{success:true}";
	}
	function updateSamplingAction()
	{
				
		
		$this->db->ChangeDatabase(DB_WARPIT_USERSPOOL);
		
		$tableName = $this->tableName;
		
		
		$data = $this->db->get('_SamplingTemplates',$this->treeWhere,'id_group,id_fields');
		$fieldIds = $data[0]['id_fields'];
		$idGroup = $data[0]['id_group']; 
		
		$fields = $this->db->get('_InterviewerStructure','id IN ('.$fieldIds.')','field_name,data_type,field_text');
		
		if(!$fields)
			return "{success: false, error:'Fields not found!'}";
		foreach ($fields as $data) {
			$fldNames[] = $data['field_name'];
			$conWhere[] = $tableName.'.'.$data['field_name'].' = samplerUpdateTmp.'.$data['field_name'];
		}
		
		$sql = "SELECT count(DISTINCT a.id) FROM _Interviewer a INNER JOIN _group_link b ON a.id = b.id WHERE b.id_group IN (".$idGroup.")";
		$res = $this->db->SQLexecute($sql);
		$row = $this->db->fetchRow($res);
		$count = $row[0];
		
		$fldNames = implode(',',$fldNames);
		$this->db->SQLexecute("DROP TEMPORARY TABLE IF EXISTS samplerUpdateTmp");
		//load the data from interviewer table
		$sql = "CREATE TEMPORARY TABLE samplerUpdateTmp SELECT 0 as recExists,count(DISTINCT a.id) as freq,count(DISTINCT a.id)/$count*100 as percent,".$fldNames." FROM _Interviewer a INNER JOIN _group_link b ON a.id = b.id WHERE b.id_group IN (".$idGroup.") GROUP BY $fldNames";
		$this->db->SQLexecute($sql);
	
		//lets update existing
		$sql = "UPDATE $tableName INNER JOIN samplerUpdateTmp ON ".implode(' AND ',$conWhere)." SET freq_N = freq,$tableName.percent = samplerUpdateTmp.percent,samplerUpdateTmp.recExists = 1";
		$this->db->SQLexecute($sql);
		//insert if some new combinations are available
		$sql = "INSERT INTO $tableName (freq_N,percent,$fldNames) SELECT freq,percent,$fldNames FROM samplerUpdateTmp WHERE recExists = 0";
		$this->db->SQLexecute($sql);
		//delete combinations that are not anymore existant :)
		$sql = "DELETE FROM $tableName WHERE NOT EXISTS (SELECT * FROM samplerUpdateTmp WHERE ".implode(' AND ',$conWhere).") ";
		$this->db->SQLexecute($sql);
		
		return "{success:true}";
	}
	function addGroupAction()
	{
		$this->db->ChangeDatabase(DB_WARPIT_USERSPOOL);
		
		$idGroup = $_POST['id_group'];
		$data = $this->db->get('_SamplingTemplates',$this->treeWhere,'id_group');
		$groups = explode(',', $data[0]);
		if($_POST['remove'])
		{
			$key = array_search($idGroup,$groups);
			if($key !== false)
				unset( $groups[ $key  ]  );
		}
		else
		{
			if( !in_array( $idGroup, $groups )  )
				$groups[] = $idGroup;
		}
		$idGroup = implode(',',$groups); 
				
		
		$sql = "UPDATE _SamplingTemplates SET id_group = '$idGroup' WHERE ".$this->treeWhere;
		$this->db->SQLexecute($sql);
		
		
		$groupData = $this->db->get('_groups','id IN ('.$idGroup.')');
		foreach ($groupData as $gr) {
			$storeData[] = array($gr['id'],$gr['idLab']);
		}
				
		
		$this->updateSamplingAction();
		return "{success: true, groupStore: ". json_encode($storeData) . "}";
	}
	
	function runSamplingAction()
	{
		$toGroup = $_POST['toGroup'];
		$this->db->ChangeDatabase(DB_WARPIT_USERSPOOL);
		$data = $this->db->get('_SamplingTemplates',$this->treeWhere,'id_group,id_fields');
		$fieldIds = $data[0]['id_fields'];
		$idGroup = $data[0]['id_group']; 
		
		$fields = $this->db->get('_InterviewerStructure','id IN ('.$fieldIds.')','field_name,data_type,field_text');
		
		
		foreach ($fields as $data) {
			$fldNames[] = $data['field_name'];
			//$conWhere[] = $tableName.'.'.$data['field_name'].' = samplerUpdateTmp.'.$data['field_name'];
		}
		
		$mainRez =  $this->db->SQLexecute("SELECT * FROM $this->tableName");
		while($mainRow = $this->db->fetchAssoc($mainRez))
		{
			$limit = $mainRow['select_N'];
			if($limit > 0)
			{
				//let's prepare the WHERE statement
				$conWhere = array();
				$conWhere[] = "b.id_group IN ($idGroup)";
				foreach ($fldNames as $field) {
					$conWhere[] = $field. ' = "' . $mainRow[$field] .'"';
				}
				$sql = "INSERT IGNORE INTO _group_link (id_group,id) SELECT ".$toGroup.",a.id FROM _Interviewer a INNER JOIN _group_link b ON a.id = b.id WHERE ".implode(' AND ',$conWhere)." GROUP BY id ORDER BY rand() LIMIT $limit";
				//echo $sql."\n";
				$this->db->SQLexecute($sql);
				
			}
		}
		
		return "{success: true}";
	}
}
	
	
	$db->ChangeDatabase($_POST['database']);
	
	$manipulator = new UserSamplingMan($db,$_POST['RMtable']);	
	
	$idTemplate = $_POST['id_template'];
		
		if(!$idTemplate)
		{
			$manipulator->treeWhere = 'id_user = '.$_SESSION['UserInfo']['id'];
			$manipulator->tableName = 'samplingDataUser___'.$_SESSION['UserInfo']['id'];
		}
		else
		{
			$manipulator->treeWhere = 'id = '.$idTemplate;
			$manipulator->tableName = 'samplingDataTemplate___'.$idTemplate;
		}
	
	$comm = $_POST['action'].'Action';
	if(method_exists($manipulator,$comm))
		echo $manipulator->$comm();
	else 
	{
		echo '{success:false,error:"Unknown action!"}';	
	}

?>