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

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

class IncentiveopmMan extends GridDataManipulator{
	public $id_incentive_group;
	
	
	public function createSelectSQL()
	{
		
		$this->SQLfrom = "FROM $this->table a LEFT JOIN _Interviewer b ON a.id_user = b.id";
		
		
		$_POST['SQL'] = "SELECT a.*, b.email ".$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";
		}
        
        
        if(isset($_POST['srcquery']))
        {
            $query = mysql_real_escape_string($_POST['srcquery']);
            foreach(json_decode(stripslashes($_POST['srcfields']), TRUE) as $field)
            {
                switch($field)
                {
                    case 'email': $tmpSql[] = "b.email LIKE '%" . $query . "%'";break;
                    default:  $tmpSql[] = "a." . $field . " LIKE '%" . $query . "%'"; break;
                 }
            }
            unset($_POST['srcquery']);
            unset($_POST['srcfields']);
            
            $this->where[] = "(" . implode(" OR ", $tmpSql) . ")";
        }
		
		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,incentive_status   
		                  FROM _IncentiveCoupons 
		                  WHERE id_incentive_group = $this->id_incentive_group
		                  GROUP BY incentive_status) a 
                  INNER JOIN _IncentiveStatus b ON b.id_project=$this->id_incentive_group AND a.incentive_status = 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 coupons' , $used);
		$chartArr[] = array(  0, 'Unused coupons' ,$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 _IncentiveCoupons SET id_user = 0, startTime = '0000-00-00 00:00:00', endTime = '0000-00-00 00:00:00'";
		if($ids = $_POST['ids'])
		{
			$sql .= " WHERE id IN ( $ids )";
		}
		else //clean all links
		{
			$sql .= " WHERE id_incentive_group  = " . $this->id_incentive_group;
		}
		$this->db->SQLexecute($sql);
		
		return "{success : true }";
		
	}
	public function deleteLinksAction()
	{
		$sql = "DELETE FROM _IncentiveCoupons ";
		if($ids = $_POST['ids'])
		{
			$sql .= " WHERE id IN ( $ids )";
		}
		else //clean all links
		{
			$sql .= " WHERE id_incentive_group  = " . $this->id_incentive_group;
			if($_POST['used'])
				$sql .= " AND id_user > 0";
			else if($_POST['unused'])
				$sql .= " AND id_user = 0";
		}
		$this->db->SQLexecute($sql);
		return "{success : true }";
		
	}
}
	
	
	$db->ChangeDatabase($_POST['database']);
	
	$manipulator = new IncentiveopmMan($db,$_POST['RMtable']);	
	$manipulator->id_incentive_group = $_POST['id_incentive_group'];
	$comm = $_POST['action'].'Action';
	if(method_exists($manipulator,$comm))
		echo $manipulator->$comm();
	else 
	{
		echo '{success:false,error:"Unknown action!"}';	
	}

?>