<?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."_ajaxManipulators/_class/class.treeData.php");

/*ini_set('error_reporting', E_ALL ^ E_NOTICE);
ini_set('display_errors', '1');   */  

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

class projUsersManipulator extends GridDataManipulator {
	
	
	function prepareFieldsWithSQL() {

		$sql = "SELECT a.*,b.field_name FROM _UserProjectFieldOrder a
			LEFT JOIN _InterviewerStructure b ON a.field_type = 2 AND b.id = a.id_field
		WHERE id_project = {$_POST['par']} AND id_user = ".$_SESSION['UserInfo']['id']." ORDER BY orderBy";

		$this->db->ChangeDatabase(DB_WARPIT_USERSPOOL);
		$res = $this->db->SQLexecute($sql);
		while ($row = $this->db->fetchAssoc($res))	$rows[] = $row;
		
		
		$columns[] = 'a.id,a.id_user,a.loginSID';
		
		// here I save columnsfor pop up interviews with user_type = 4
		$columnsPopUp[] = 'a.id,a.id_user,a.loginSID';
		
		if(count($rows) == 0)
		{
			$rows[] = array('field_type' => 1,'id_field' => 1);
			$rows[] = array('field_type' => 1,'id_field' => 2);
			$rows[] = array('field_type' => 1,'id_field' => 3);
			$rows[] = array('field_type' => 1,'id_field' => 4);
			$rows[] = array('field_type' => 1,'id_field' => 5);
			$rows[] = array('field_type' => 1,'id_field' => 6); 	 	
		}
	    $filterColumns = array();
		foreach ($rows as $field)
		{
			switch ($field['field_type']) {
				case 1:
					switch ($field['id_field']) {
						case 1:	$columns[] = 'b.email';   $filterColumns[$field['field_type']][] = "email";		$columnsPopUp[] = '0 as email';	break;
						case 2:	$columns[] = 'c.status';  $filterColumns[$field['field_type']][] = "status"; 		$columnsPopUp[] = 'c.status'; 	break;
						case 3:	$columns[] = 'c.t_start'; $filterColumns[$field['field_type']][] = "t_start"; 		$columnsPopUp[] = 'c.t_start';	break;
						case 4:	$columns[] = 'c.t_stop';  $filterColumns[$field['field_type']][] = "t_stop";		$columnsPopUp[] = 'c.t_stop';	break;
						case 5:	$columns[] = 'c.t_diffs'; $filterColumns[$field['field_type']][] = "t_diffs";		$columnsPopUp[] = 'c.t_diffs';	break;
						case 6:	$columns[] = 'c.status_rec';$filterColumns[$field['field_type']][] = "status_rec";  	$columnsPopUp[] = 'c.status_rec'; 	break;
						}
				
				break;
				case 2:
					$columns[] = 'b.'.$field['field_name'];	
					$filterColumns[$field['field_type']][] = $field['field_name']; 
					$columnsPopUp[] = '0 as '.$field['field_name']; 	
				break; 
				case 3:
					$columns[] = 'c.'.$field['id_field'];
					$columnsPopUp[] = 'c.'.$field['id_field'];
                    $filterColumns[$field['field_type']][] = $field['id_field']; 
				break;
			}
		}
		$columns[] = " d.webPoints ";
		$columnsPopUp[] = '0 as webPoints';
		
		$projName = $this->db->get('_Projects',$_POST['par'],'proj_name',DB_WARPIT_WEBCATI_BASE);
	//	var_dump($columns);
		$_POST['SQL'] = "SELECT ".implode(',',$columns)." FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids a LEFT JOIN ".DB_WARPIT_USERSPOOL."._Interviewer b ON a.id_user = b.id LEFT JOIN ".DB_WARPIT_WEBCATI_BASE.".$projName"."_structure c ON a.id_user = c.user_id LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._wwwPoints d ON a.id_user = d.id_user AND d.id_project = ".$_POST['par']." WHERE a.id_project =  ".$_POST['par']." AND a.user_type IN (2) ";
		//$_POST['SQL'] = "SELECT ".implode(',',$columns)." FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids a LEFT JOIN ".DB_WARPIT_USERSPOOL."._Interviewer b ON a.id_user = b.id LEFT JOIN ".DB_WARPIT_WEBCATI_BASE.".$projName"."_structure c ON a.id_user = c.user_id LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._wwwPoints d ON a.id_user = d.id_user AND d.id_project = ".$_POST['par']." WHERE a.id_project =  ".$_POST['par']." AND a.user_type IN (2) ";

/*         if(isset($_POST['srcquery']) && isset($_POST['srcfields']))
        {
             $srcfields = json_decode( stripslashes($_POST['srcfields'])  );
             
             foreach($srcfields as &$filed)
             {
                 $field = $this->prepareFieldsWithSQL($field);
             }
             $_POST['srcFields'] = json_encode($srcfields);
             unset($filter['data']['RMtable']);
             
             $_POST['SQL'] .= " AND " . $this->filtering($_POST['filter']);
            if(!is_array($_POST['filter']))
            {
                 unset($_POST['filter']); 
            }
        }		*/
       //  var_dump($_POST['filter']);
		 if(is_array($_POST['filter']))
         {
            foreach ($_POST['filter'] as &$filter) 
            {
                if($filter['field'] == "t_start")
                {
                    $filter['field'] = "DATE_FORMAT(FROM_UNIXTIME(c.t_start),'%Y-%m-%d')";
                }elseif($filter['field'] == "t_stop")
                {
                    $filter['field'] = "DATE_FORMAT(FROM_UNIXTIME(c.t_stop),'%Y-%m-%d')";
                    
                }
                else if($filter['field'] == 'webPoints')
                {
                    $filter['field'] = 'd.webPoints';
                }
                else
                {
                    $filter['field'] = $this->prepereFilterFields($filter['field'], $filterColumns);
                }
                unset($filter['data']['RMtable']);
            }
            $_POST['SQL'] .= " AND " . $this->filtering($_POST['filter']);
            unset($_POST['filter']); 
        }
         
		//$_POST['SQL'] .= " UNION ( SELECT ".implode(',',$columnsPopUp)." FROM ".DB_WARPIT_WEBCATI_BASE.".".$projName."_structure c LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._www_ids a ON a.id = c.id_loginSID WHERE a.id_project =  ".$_POST['par']." AND a.user_type IN (4) )";
       
       //print $this->countSql;
	
	    //print $_POST['SQL'];
	}

    function prepereFilterFields($field, $filterColumns)
    {
        /*switch($field)
        {
            case "email" : return "b.email";
            case "status" : return "c.status";
            case "t_diffs" : return "c.t_diffs";
            case "status_rec" : return "c.status_rec";
            case "webPoints" : return "d.webPoints";
            default: return "c." . $field;  
        }*/
        /*print $field . "<br/>";
        var_dump($filterColumns);*/
        if(in_array($field, $filterColumns[1]))
        {
            switch($field)
            {
                case "email" : return "b.email";
                case "status" : return "c.status";
                case "t_diffs" : return "c.t_diffs";
                case "status_rec" : return "c.status_rec";
                case "webPoints" : return "d.webPoints";
                default: return "c." . $field;  
            }
        }
        else if(in_array($field, $filterColumns[2]))
        {
            return "b." . $field;
        }
        else if(in_array($field, $filterColumns[3]))
        {
            return "c." . $field;
        }
        
    }

	function selectAction()
	{
	        
            
		$tableFields = $this->prepareFieldsWithSQL();	
      //  $this->filtersRedifine();
		$this->fetchSelect();
  
		$result = parent::selectAction();
		
		$addOn = $_POST['addOn'];
		if($addOn )
		{
			$this->db->ChangeDatabase(DB_WARPIT_USERSPOOL);
			$group = $_POST['toGroup'];
			
			while ($row = $this->db->fetchArray( $this->rsCount) )
			{
				$user = $row['id_user'];
					$val[] = "( $group , $user )";
					$delVal[] = $user;
				
			}
		
			if($val)
			{
				if($addOn=='copy' || $addOn == 'move' )
				{
					$sql = "INSERT IGNORE INTO _group_link VALUES " . implode(',',$val);
					
					If (!$this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: '.$sql." }";}
				}
				
			}
			
		}
		
		return $result;
		
	}
	function updateAction()
	{

		$sql = "UPDATE ".DB_WARPIT_WEBCATI_BASE."._wwwPoints SET webPoints = ".$_POST['value']." WHERE id_project = ".$_POST['par']." AND id_user = ".$_POST['id'];
		 
		If (!$rs = $this->db->SQLexecute($sql)) {
			
				Echo '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			
			}else{
				
			
			
			$r = '{success:true';
			if($_POST['newValue'] == true)
				$r .= ',newValue:"'.$_POST['value'].'"';
			return $r. ',error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
		}
		
	}

	function exportAction() {
		header('Content-Type: text/csv');
		header('Expires: 0');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');
   		header('Content-Disposition: attachment; filename="export.csv";');
   		
   		$tableFields = $this->prepareFieldsWithSQL();
   		$res = $this->db->SQLexecute($_POST['SQL']);
		$i = 0;
		while ($zad = $this->db->fetchAssoc($res)) {
			if ($i == 0) echo implode(";",array_keys($zad))."\n";
			echo implode(";",$zad)."\n";
			$i =1;
		}
		
   		
   		
	}
}

class selectFieldsMan extends TreeDataManipulator 
{
	public function selectAction()
	{
		$_POST['checked'] = true;
		$id_project = $_POST['id_project'];
		$id_user = $_SESSION['UserInfo']['id'];
		if($_POST['RMtable'] == "_InterviewerStructure")
		{
			$this->lab = 'field_name';
			//let's get all checked ID's
			$check = $this->db->get("_UserProjectFieldOrder","id_project = $id_project AND id_user = $id_user AND field_type = 2",'id_field');
			if($check)
				$_POST['checkedIds'] = implode(',',$check);
		}
		else 
		{
			require_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
			
			if(substr( $_POST['node'],0,1 ) == 'q')
			{
				$check = $this->db->get("_UserProjectFieldOrder","id_project = $id_project AND id_user = $id_user AND field_type = 3",'id_field',DB_WARPIT_USERSPOOL);
				$this->db->ChangeDatabase($_POST['database']);
				
				$qId = $this->db->get($this->table.'_tree',substr($_POST['node'],2),'id_question' );
				$qType = $this->db->get($this->table,$qId,'tip_sql' );
				$q = Question::createQuestion($qType,$this->db);
				$q->fill($this->table,$qId );
				$filds = $q->getStructureFields();
				foreach ($filds as $fld) {
					$path['id'] = $fld;
					$path['text'] = $fld;
					$path['leaf'] = true;
					if($check)
						$path['checked'] = in_array($fld,$check); 
					else
						$path['checked'] = false;
					$nodes[] = $path;
				}
				return json_encode($nodes);
			}
			
			$_POST['SQL'] = "SELECT a.*,tip_sql FROM $this->table"."_tree a LEFT JOIN $this->table b ON a.id_question = b.id";
			$_POST['attr'] = 'tip_sql';
			$this->leafAsFolder = 'q_';
		}
		parent::selectAction();
		if($_POST['RMtable'] != "_InterviewerStructure")
		{
			
			foreach ($this->nodes as &$node) {
				if(substr( $node['id'],0,1 ) == 'q')
				{
					$q = Question::createQuestion($node['tip_sql']);
					$node['iconCls'] = $q->getIconCls();
				}
			}
			
		}
		
		return json_encode($this->nodes);
		
	}
	
	public function saveFieldsAction()
	{
		//we get the extra fields we want to show!
		
		$quest = explode(',',$_POST['questFields']);
		
		$id_project = $_POST['id_project'];
		$id_user = $_SESSION['UserInfo']['id'];
		
		//clear the fields first
		$this->db->SQLexecute("DELETE FROM _UserProjectFieldOrder WHERE id_project = ".$id_project." AND id_user = ".$id_user); 
		//insert the default variables
		$columns[] = array('dataIndex' => 'id_user','header' => 'ID', 'type' => 1, 'width' => '150');
		$fields[] =array('name'=>'id_user');
		
		$columns[] = array('dataIndex' => 'email','header' => 'Email', 'type' => 1);
		$fields[] =array('name'=>'email');
		
		$columns[] = array('dataIndex' => 'status','header' => 'Status', 'type' => 1);
		$fields[] =array('name'=>'status');
		
		$columns[] = array('dataIndex' => 't_start','header' => 'Start', 'type' => 1);
		$fields[] =array('name'=>'t_start');
		
		$columns[] = array('dataIndex' => 't_stop','header' => 'End', 'type' => 1);
		$fields[] =array('name'=>'t_stop');
		
		$columns[] = array('dataIndex' => 't_diffs','header' => 'Duration', 'type' => 1);
		$fields[] =array('name'=>'t_diffs');
        
        $columns[] = array('dataIndex' => 'status_rec','header' => 'Status Rec', 'type' => 1);
        $fields[] =array('name'=>'status_rec');
        
        $columns[] = array('dataIndex' => 'webPoints','header' => 'Points', 'type' => 1);
        $fields[] =array('name'=>'webPoints');
		
		if($inter = $_POST['interFields'])
		{
			$sql = $this->db->SQLexecute("SELECT id,field_name FROM _InterviewerStructure WHERE id IN($inter)");
			$inter = explode(',',$inter);
			while ($row = $this->db->fetchRow($sql)){
				$fld = $row[1];
				$columns[] = array('dataIndex' => $fld,'header' => $fld,'id_field' => $row[0], 'type' => 2,   'filter' => "{type: 'string'
            }" );
				$fields[] =array('name'=>$fld);
				$intCount++;
			}
		}
		if($_POST['questFields'])
		foreach ($quest as $fld) {
			$columns[] = array('dataIndex' => $fld,'header' => $fld, 'type' => 3);
			$fields[] =array('name'=>$fld);
			$qCount++;
		}
		$c = count($columns);
		
		/*for($i=0;$i<$c;$i++)
		{
			if($i<5) {$ft = 1; $fi = $i+1;  }
			else if($i<5+$intCount) {$ft = 2; $fi = $columns[$i]['id_field']; }
			else if($i<5+$intCount+$qCount) {$ft = 3; $fi = $columns[$i]['dataIndex']; }
			
			$values[] = "( $id_user,$id_project,$ft,'$fi' ,$i,0 )";
		}*/
		foreach ($columns as $key=>$ar) {
			$i = $key;
			if ($ar['type'] == 1) $fi = $key + 1;
			elseif ($ar['type'] == 2) $fi = $ar['id_field'];
			else $fi = $ar['dataIndex'];
			$values[] = "( $id_user,$id_project,".$ar['type'].",'".$fi."' ,$i,0 )";
		}
		//echo "INSERT INTO _UserProjectFieldOrder(id_user,id_project,field_type,id_field,orderBy,is_hidden) VALUES ".implode(',',$values);
		$this->db->SQLexecute("INSERT INTO _UserProjectFieldOrder(id_user,id_project,field_type,id_field,orderBy,is_hidden) VALUES ".implode(',',$values));
		
		return "{success:true, columns:".json_encode($columns). ",fields:".json_encode($fields)." }";
	}
}

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