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

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

class RedorectopmMan extends GridDataManipulator{
	public $id_project;
	
	
	public function createSelectSQL()
	{
		
		$this->SQLfrom = "FROM $this->table a LEFT JOIN _Interviewer b ON a.id_user = b.id"
		." LEFT JOIN _RedirectEndLink c ON c.id_project = a.id_project AND a.id_user = c.id_user"
		." LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._wwwPoints d ON a.id_user = d.id_user AND a.id_project = d.id_project AND d.id_purpose = 24";
		
		
		$_POST['SQL'] = "SELECT a.id,a.wwwlink,b.email,c.*,d.webPoints ".$this->SQLfrom;
		
		if($fu = $_POST['filterUsed'])
		{
			if($fu == 1)
				$this->where['fu'] = "a.id_user != 0";
			else if($fu == 2)
				$this->where['fu'] = "a.id_user = 0";
		}
		
		return parent::createSelectSQL();
	}
	public function selectAction()
	{
		
		
		$echo = '{success:true';
 		if(!$this->arr ) 
 		{
 			if($this->fetchSelect() === false) return $this->db->JsonError();
 		}
 		
 		//fetch the number of used and unused!
 		unset($this->where['fu']);
 		$sql = "SELECT count(*) $this->SQLfrom WHERE a.id_user = 0 AND ".implode(' AND ',$this->where);	;
		$res = $this->db->SQLexecute($sql);
		$row = $this->db->fetchRow($res);
		$notUsed = $row[0];
		
		$sql = "SELECT count(*) $this->SQLfrom WHERE a.id_user != 0 AND ".implode(' AND ',$this->where);	;
		$res = $this->db->SQLexecute($sql);
		$row = $this->db->fetchRow($res);
		$used = $row[0];
 		
		
		$addOn = $_POST['addOn'];
		if($addOn )
		{
			$group = $_POST['toGroup'];
			
			while ($row = $this->db->fetchArray( $this->rsCount) )
			{
				if($user = $row['id_user'])
					$val[] = "($group , $user )";
				
			}
		
			if($val)
			{
				if($addOn=='copy')
				{
					$sql = "INSERT IGNORE INTO _group_link VALUES " . implode(',',$val);
					
					If (!$this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: '.$sql." }";}
				}
				
			}
			
		}
		
		//let's get statistics for statuses!
		$sql = "SELECT b.id_status,statusComment AS comment,freq FROM (SELECT count(*) as freq,int_finish FROM _RedirectEndLink WHERE id_project = $this->id_project GROUP BY int_finish) a INNER JOIN _RedirectStatus b ON b.id_project=$this->id_project AND a.int_finish = b.id_status";
		$res = $this->db->SQLexecute($sql);
		while ($row = $this->db->fetchRow($res))
		{
			$chartArr[] = $row;
		}
		//fill with used and unused!
		$chartArr[] = array( 0, 'Used links' , $used);
		$chartArr[] = array(  0, 'Unused links' ,$notUsed);
		
		
		//let's get statistics by date for the chart chart :) PUT ON HOLD
		/*$sql = "SELECT freq,b.id_status,statusComment,date AS comment FROM (SELECT count(*) as freq,int_finish,DATE_FORMAT(endTime,'%Y-%m-%d') as date FROM _RedirectEndLink WHERE int_finish > 0 AND id_project = $this->id_project GROUP BY int_finish,date ORDER BY date,int_finish) a INNER JOIN _RedirectStatus b ON b.id_project=$this->id_project AND a.int_finish = b.id_status";
		$res = $this->db->SQLexecute($sql);
		//in each row I need the date and the 
		while ($row = $this->db->fetchAssoc($res))
		{
			$flashArr[$row['date'] ] [ $row['id_status']  ] = $row;
		}
		*/
		if (isset($_POST['start']) )
		{
			$echo.= ', results:'.$this->results;
		}
		
			$echo.= ', STATEMENT: "'.$this->sql.'",rows: '.json_encode($this->arr);
			$echo.= ", usedLinks : $used , unUsedLinks : $notUsed, chartData:{ rows:".json_encode($chartArr);
			$echo.='} }';
			return $echo;	
	}
	
	public function cleanLinksAction()
	{
		$sql = "UPDATE _RedirectLinks SET id_user = 0";
		if($ids = $_POST['ids'])
		{
			$sql .= " WHERE id IN ( $ids )";
		}
		else //clean all links
		{
			$sql .= " WHERE id_project = " . $this->id_project;
		}
		$this->db->SQLexecute($sql);
		
		return "{success : true }";
		
	}
	public function deleteLinksAction()
	{
		$sql = "DELETE FROM _RedirectLinks ";
		if($ids = $_POST['ids'])
		{
			$sql .= " WHERE id IN ( $ids )";
		}
		else //clean all links
		{
			$sql .= " WHERE id_project = " . $this->id_project;
			if($_POST['used'])
				$sql .= " AND id_user > 0";
			else if($_POST['unused'])
				$sql .= " AND id_user = 0";
		}
		$this->db->SQLexecute($sql);
		return "{success : true }";
		
	}
	
	public function resetPointsAction()
	{
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "DELETE FROM _wwwPoints WHERE id_purpose = 24 AND id_project = ".$_POST['id_project'];
		$this->db->SQLexecute($sql);
		return "{success:true}";
	}
	public function calculatePointsAction()
	{
		$sql = "SELECT a.id_user,c.webPoints FROM $this->table a INNER JOIN _RedirectEndLink b ON a.id_project = b.id_project AND a.id_user = b.id_user INNER JOIN _RedirectStatus c ON a.id_project = c.id_project AND b.int_finish = c.id_status WHERE a.id_project = $this->id_project AND a.id_user > 0 AND c.id_status != 0";
		//print $sql; exit;
		$res = $this->db->SQLexecute($sql);
		while ($row = $this->db->fetchRow($res))
		{
			$val[] = "(".implode(',',$row).",$this->id_project,24, NOW() )";
		}
		$this->resetPointsAction();
		if($val)
		{
			$sql = "INSERT INTO _wwwPoints (id_user,webPoints,id_project,id_purpose,modificationDate) VALUES ".implode(',',$val);
			$this->db->SQLexecute($sql);	
		}
		
		return "{success: true}";
		
		
	}
	
}
	
	
	$db->ChangeDatabase($_POST['database']);
	
	$manipulator = new RedorectopmMan($db,$_POST['RMtable']);	
	$manipulator->id_project = $_POST['id_project'];
	$comm = $_POST['action'].'Action';
	if(method_exists($manipulator,$comm))
		echo $manipulator->$comm();
	else 
	{
		echo '{success:false,error:"Unknown action!"}';	
	}

?>