<?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");

class bqwcTreeDataMan extends TreeDataManipulator {

	public function selectAction() {
		parent::selectAction();
		$nodes = $this->nodes;
		$this->db->LogWrite(print_r($nodes,true),false,"projekti iz selectAction original class");
		
		include (PATH_TO_ROOT."_support/include.projectRights.php");
				
		return json_encode($bla);
	}
	
	
}


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"."_structure WHERE (status IS NULL OR status=54) AND uniqueAddress_1 != ''"));
					$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);
			}
			
			
			$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) {
				//let's get upfolder name
				$tmpRes = $this->db->fetchAssoc( $this->db->SQLexecute("SELECT id,idLab FROM _ProjectsTree WHERE id = (SELECT id_sup FROM _ProjectsTree c WHERE c.id = $id)"));
				$projekat = $tmpRes['idLab'];
				$sqlTmp = "(SELECT '$id' AS projId,id as strucId, @cnt := @cnt+1 as id,'$projekat' AS projekat,'$projName' as podprojekat, uniqueAddress_1,".
				"(IF(status=1 AND status_rec=1 ,IF(flag_bad=101,1,2),3 )) as status FROM $projName"."_structure ";
				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 .= " AND (".$_POST['visitsFilter'].") AND flag_bad  = 101 ";
					
					$sqlTmp .= ")";
					
				} else if($projFilter[$id])
					$sqlTmp .= "WHERE id IN (". implode(',',$projFilter[$id]) ."))";
				
				$sqlProj[] = $sqlTmp;
			}
			$_POST['SQL'] = "SELECT * FROM (".implode(" UNION ",$sqlProj) .") as t ";
			//$res = $this->db->SQLexecute($sql);
			echo "/*".$_POST['SQL']." */";
			$this->fetchSelect();
			return parent::selectAction();
		}
		else
		{
			return parent::selectAction();
		}
	}
	
	public function saveVisitsAction()
	{
		$this->db->ChangeDatabase(DB_WARPIT_MYSTERY);
		$idUser = $_SESSION['UserInfo']['id'];
		$this->db->SQLexecute("INSERT INTO _Visits VALUES(NULL,0,'{$_POST['folder']}',0,0,0,$idUser)");
		$folderId = $this->db->GetLastInsertId();
		
		
		$combIds = explode(',',$_POST['combId']);
		$uqA = explode(',',$_POST['uniqId']);
		
		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 _Visits VALUES".implode(',',$values) );
		
		}
		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!"}';	
	
}
?>