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

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


class bqwcTreeDataMan extends TreeDataManipulator 
{
	
	
	public function AddVisitFolderAction() {
		
		$sql = "INSERT INTO ".DB_WARPIT_MYSTERY."._Visits SET 
					idLab = '".$_POST['folderName']."',
					id_user = '".$_SESSION['UserInfo']['id']."'";	
		$this->db->SQLexecute($sql);
		echo "/*".$sql."*/";
		return "{success:true}";
		
	}
	
	
	public function deleteVisitsAction() {
			
		$sql = "DELETE FROM ".DB_WARPIT_MYSTERY."._Visits 
					WHERE id_sup = ".$_POST['id']." OR id = ".$_POST['id'];
		$this->db->SQLexecute($sql);
		
		return "{success:true}";
		
	}
	
}


class preper extends GridDataManipulator 
{
public function getAllSelectedProjects($checkIds,&$allProjects)
	{
		$sql= "SELECT * FROM _ProjectsTree WHERE id IN (".$checkIds.")";
		$res = $this->db->SQLexecute($sql);
		while($row = $this->db->fetchAssoc($res) )
		{
			if($row['is_leaf'])
				$allProjects[$row['id']] = $row['idLab'];
			else 
				$folders[] = $row['id'];
		}
		if($folders)
		{
			$sql= "SELECT * FROM _ProjectsTree WHERE id_sup IN (".implode(',',$folders).")";
			$res = $this->db->SQLexecute($sql);
			while($row = $this->db->fetchAssoc($res) )
			{
				$newP[] = $row['id'];
			}
			if($newP)
				$this->getAllSelectedProjects( implode(',',$newP) ,$allProjects);
		}
	}
	
public function selectAction()
	{
		if($this->table == 'project_count')
		{
			$arr = array();
			
			if($_POST['projectIds'])
			{
				$allProjects = array();
				$this->getAllSelectedProjects($_POST['projectIds'],$allProjects);
				//let's get all the data
				foreach ($allProjects as $id => $projName) {
					$sql = $this->db->fetchRow( $this->db->SQLexecute("SELECT count(*) FROM $projName"."_structure WHERE status=1 AND status_rec=1 AND flag_bad = 101"));
					$potvrdena += $sql[0];
					
					$sql = $this->db->fetchRow( $this->db->SQLexecute("SELECT count(*) FROM $projName"."_structure WHERE status=1 AND status_rec=1 AND flag_bad != 101"));
					$zavrsena += $sql[0];
					
					$sql = $this->db->fetchRow( $this->db->SQLexecute("SELECT count(*) FROM ".$projName."___sample" ));
					$planirana += $sql[0];
				}
				global  $languagePack;
				$arr[] = array('status_posete' => $languagePack['potvrdjena_status'],'broj' => $potvrdena);
				$arr[] = array('status_posete' => $languagePack['zavrsena_status'],'broj' => $zavrsena);
				$arr[] = array('status_posete' => $languagePack['planirana_status'],'broj' => ($planirana - $zavrsena - $potvrdena) );
			}
			
			
			$ret['success'] = true;
			$ret['rows'] = $arr;
			
			return json_encode($ret);
		}
		else if($this->table == 'pregledPoseta')
		{
			$allProjects = array();
			
			
			
			if($_POST['projectIds'])
				$this->getAllSelectedProjects($_POST['projectIds'],$allProjects);
			else if($_POST['visitsFolder']) 
			//we get all projects and records that are in this visits group
			{
				$this->db->ChangeDatabase(DB_WARPIT_MYSTERY);
				$rows = $this->db->get('_Visits','id_sup = '.$_POST['visitsFolder']);
				foreach ($rows as $row) {
					$projFilter[$row['id_project']][] = $row['id_structure'];
				}
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
				$sql = $this->db->SQLexecute("SELECT id,proj_name FROM _Projects WHERE id IN (". implode(',', array_keys($projFilter) )  .")" );
				while ($row = $this->db->fetchAssoc($sql)) {
					$allProjects[$row['id']] = $row['proj_name'];
				}
				
				
			}
			else 
			{
				$this->arr = array();
				return parent::selectAction();
			}
			
			$this->db->SQLexecute("SET @cnt:=0");
			foreach ($allProjects as $id => $projName) {
				
				$sqlTmp = " ( SELECT '$id' AS projId, ";
				$sqlTmp .= "	a.id as strucId, ";
				// this variable is for createing uniqe id in extjs grid so we don-t have 
				// problems with presenting data in grid, otherwise if some records have the same 
				// id extjs grid doesn't show this records
				$sqlTmp .= "	@cnt := @cnt+1 as id,";
				// with this sql statement I get father project of current selected project
				$sqlTmp .= "	(SELECT idLab FROM _ProjectsTree  WHERE id = (SELECT id_sup FROM _ProjectsTree c WHERE c.id = $id)) AS projekat,";
				$sqlTmp .= "	'".$projName."' as podprojekat, "; 
				$sqlTmp .= "	b.id_sample, b.id_sampleTable,"; // data of id sample and Sample table
				$sqlTmp .= "	(IF(status=1 AND status_rec=1 ,IF(flag_bad=101,1,2),3 )) as status, "; // Current status of record/sample
				$sqlTmp .= "	a.d_start  as visitDateTime "; // Visit date
					
				$sqlTmp .= "  FROM ".$projName."_structure as a ";
				$sqlTmp .= "  RIGHT JOIN  ".$projName."___sample as b ON a.id_sample = b.id ";
				
				
				
				if($_POST['projectIds']) {
				//$sqlTmp .= "WHERE (status=1 AND status_rec=1 OR (status IS NULL OR status = 54) AND uniqueAddress_1 != '' ) ";
					
					if ($_POST['visitsFilter']) $sqlTmp .= " WHERE (".$_POST['visitsFilter'].") AND flag_bad  = 101 ";
					
					$sqlTmp .= ")";
					
				} else if($projFilter[$id])
					$sqlTmp .= "WHERE a.id IN (". implode(',',$projFilter[$id]) ."))";				
				$sqlProj[] = $sqlTmp;
				
				
				$sampleSQL = " SELECT id_sampleTable FROM ".$projName."___sample GROUP BY id_sample ";
				$resSample  = $this->db->SQLexecute($sampleSQL);
				while ($zadSample = $this->db->fetchAssoc($resSample)) $sampleIds[] = $zadSample['id_sampleTable'];				
				
			}
			
			$_POST['SQL'] = "SELECT * FROM (".implode(" UNION ",$sqlProj) .") as t ";
			if ($sampleIds) {
			
				$sampleSQL = "SELECT id, name FROM _CapiTables WHERE id IN (".implode(",",$sampleIds).")";
				$resSample  = $this->db->SQLexecute($sampleSQL);
				while ($zadSample = $this->db->fetchAssoc($resSample)) {
					$sqlUnion[] = "( SELECT ".$zadSample['id']." as id_sampleTable, id as id_sample, street as uniqueAddress_1 FROM capi___".$zadSample['name']." ) ";
				}
				
				$_POST['SQL'] .= " LEFT JOIN ( SELECT * FROM (".implode(" UNION ",$sqlUnion) .") as q ) as s ON t.id_sample = s.id_sample AND t.id_sampleTable = s.id_sampleTable  ";
				
			}			
			//$res = $this->db->SQLexecute($sql);
			echo "/*".$_POST['SQL']." */";
			$this->fetchSelect();
			return parent::selectAction();
		}
		else
		{
			return parent::selectAction();
		}
	}
	
	public function saveVisitsAction()
	{
	
		$idUser = $_SESSION['UserInfo']['id'];
		
		// I create new directory where visits will be saved
		$this->db->SQLexecute("INSERT INTO ".DB_WARPIT_MYSTERY."._Visits (`id`, `id_sup`, `idLab`, `id_project`, `id_structure`, `is_leaf`, `id_user`) VALUES (NULL,0,'{$_POST['folder']}',0,0,0,$idUser)");
		$folderId = $this->db->GetLastInsertId();
			
		$combIds = explode(',',$_POST['combId']);
		$uqA = explode('<,>',$_POST['uniqId']);
		
		// all visits to insert into this new folder
		foreach ($combIds as $id=>$combId) {
			$tmp = explode('_',$combId);
			$values[] = "(NULL,$folderId,'{$uqA[$id]}',{$tmp[0]},{$tmp[1]},1,$idUser)";
		}
		if ($values)
		{
			$this->db->SQLexecute("INSERT INTO ".DB_WARPIT_MYSTERY."._Visits (`id`, `id_sup`, `idLab`, `id_project`, `id_structure`, `is_leaf`, `id_user`) VALUES ".implode(',',$values) );
		
		}
		return "{success:true}";
	}
	
	public function moveVisitsAction() {
		
		if (!$_POST['combId']) return "{success:true, message: 'no records to add, visits are not confirmed or done'}";
		$combIds = explode(',',$_POST['combId']);		
		$uqA = explode('<,>',$_POST['uniqId']);
		
		
		foreach ($combIds as $id=>$combId) {
			$tmp = explode('_',$combId);		
			$values[] = "(NULL,".$_POST['node'].",'".$uqA[$id]."',".$tmp[0].",".$tmp[1].",1,'".$_SESSION['UserInfo']['id']."')";
		}
		
		if ($values)
		{
			$sql = "INSERT IGNORE INTO ".DB_WARPIT_MYSTERY."._Visits (`id`, `id_sup`, `idLab`, `id_project`, `id_structure`, `is_leaf`, `id_user`) ";
			$sql .= "  VALUES ".implode(',',$values);
			$this->db->SQLexecute($sql);
		
		}
		//echo "/*".$sql."*/";
		return "{success:true}";
		
	}
	
 	public function updateAction() {
 		
 		if ($_POST['id_record'] && $_POST['project_name'] && $_POST['value']) {
 			$sql = "UPDATE ".DB_WARPIT_WEBCATI_BASE.".".$_POST['project_name']."_structure SET d_start = '".$_POST['value']."' WHERE id = ".$_POST['id_record'];
 			$this->db->SQLexecute($sql);
 		} 
 		return "{success:true}";
 	}
	
}

$db->ChangeDatabase($_POST['database']);
$tableName = $_POST['RMtable'];

if($_POST['RMcomp'] == 'grid')
$manipulator = new preper($db,$tableName);
else
$manipulator = new bqwcTreeDataMan($db,$tableName);

$comm = $_POST['action'].'Action';
if(method_exists($manipulator,$comm))
	echo $manipulator->$comm();
else 
{
	
	Echo '{success:false,error:"Unknown action!"}';	
	
}
?>