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

$interviewer = '_Interviewer';
$intStructure = '_InterviewerStructure';

class quotaStatManipulator extends GridDataManipulator
{
	public function selectAction()
	{
		//lets get the total values!!!
	//	$sql = "SELECT count";
		$idLayer = $_POST['id_layer'];
		$this->addWhere("id_layer = $idLayer");
		if($_POST['customSort'])
			$this->sort = json_decode($_POST['customSort'], true);
		//let's get all recoded values from zis layer!
		$layerCols = $this->db->get('quota_layer','layer='.$idLayer,'id_question,source,q_name,id_project');
		//let's make a table :)
		foreach ($layerCols as $lCol) {
			$colRec = $this->db->get('recolabel','id_project = '.$lCol['id_project'].' and id_question = '.$lCol['id_question'].' AND source='.$lCol['source'],'id_reconum,rec_label');

			if($colRec)
			{
				foreach ($colRec as $cr) {


				$recLabels[($lCol['source'] == 2 ? 'QT_' : 'TP_').$lCol['q_name']   ] [ $cr['id_reconum'] ] = $cr['rec_label'];
				//$recLabels[($lCol['source'] == 2 ? 'QT_' : 'TP_').$lCol['q_name']   ] [ $cr['id_reconum'] ] = $cr['rec_label'];

				}
			}

		}

		//print_r($recLabels);

		$this->sql= $this->createSelectSQL();
		if (is_array($this->sort) )
		{
			if($_POST['customSort']){
				$orderBy = array();
				foreach ($this->sort as $key => $value) {
					$orderBy[] = $value['field'] ." ".$value['direction'];
				}
				$this->sql .= " ORDER BY ".implode(",",$orderBy);
			}else
				$this->sql .= ' ORDER BY '.implode(',',$this->sort);
		}

		if (isset($_POST['start']) )
		{
			$countSql = $this->sql;


			$this->sql .= ' LIMIT '.$_POST['start'].", ".$_POST['limit'];


			if(!$this->rsCount = $this->db->SQLexecute($countSql))
			{
				return false;
			}
			$this->results = $this->db->NumRows($this->rsCount);
		}
		echo "/*$this->sql*/";
		$this->arr = array();
		If (!$this->rs = $this->db->SQLexecute($this->sql)) {return false;}
				unset($totalLab);
				while($obj = $this->db->fetchAssoc($this->rs)){
					$obj['q_todo'] = $obj['q_value'] - $obj['q_done'];
				    if ($recLabels) foreach ($recLabels as $rCol => $recArr) {
				    	if (!$totalLab) $totalLab = $rCol.'_lab';
						$obj[$rCol.'_lab'] = $recArr[ $obj[$rCol] ] ;
					}
					$this->arr[] = $obj;
					$all['q_value'] += $obj['q_value'];
					$all['q_done'] += $obj['q_done'];
					$all['q_todo'] += $obj['q_todo'];



				}


		if($all)
		{
			//we have to go trough the array again to add percentages
			foreach ($this->arr as &$obj) {
				extract($obj);
				if($all['q_value'])
					$obj['q_val_percent'] = $q_value / $all['q_value'] * 100 ;
				if($q_value)
					$obj['q_done_row'] = $q_done / $q_value * 100;
				if($all['q_value'])
					$obj['q_done_total'] = $q_done / $all['q_value'] * 100  ;
				if($all['q_done'])
					$obj['q_done_percent'] = $q_done / $all['q_done'] * 100;

				if($q_value)
					$obj['q_todo_row'] = $q_todo / $q_value * 100;
				if($all['q_value'])
					$obj['q_todo_total'] = $q_todo / $all['q_value'] * 100  ;
				if($all['q_todo'])
					$obj['q_todo_percent'] = $q_todo / $all['q_todo'] * 100;
			}

			$all['q_done_total'] = $all['q_done'] / $all['q_value'] * 100;
			$all['q_todo_total'] = $all['q_todo'] / $all['q_value'] * 100;
			$all[$totalLab] = '<b>TOTAL</b>';
			$this->arr[] = $all;
		}

		//$sql = "INSERT INTO quota_export SET  id_layer = ".$idLayer.", quota_table = \"".addslashes(serialize($this->arr))."\" ON DUPLICATE KEY UPDATE quota_table = \"".addslashes(serialize($this->arr))."\"";
		//$this->db->SQLexecute($sql);

	return parent::selectAction();
	}
	public function resetQuotasAction(){
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

		$sql = "TRUNCATE TABLE ".substr($this->tableAddon, 0, -5);
		$r['success'] = true;
		if(!$this->db->SQLexecute($sql)) $r['success'] = false;
		echo json_encode($r);
	}
}



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

$tableName = $_POST['RMtable'];
$tableAddon = $tableName.'Addon';


	$manipulator = new quotaStatManipulator($db,$_POST['RMtable']);
	$manipulator->tableAddon = $tableAddon;
$comm = $_REQUEST['action'].'Action';
if(method_exists($manipulator,$comm))
	echo $manipulator->$comm();
else
{

	echo '{success:false,error:"Unknown action!"}';

}


?>
