<?php

App::uses('Model', 'Model');

/**
 * Application model for Cake.
 *
 * Add your application-wide methods in the class below, your models
 * will inherit them.
 *
 * @package       app.Model
 */

class Consumer extends AppModel {
	public $belongsTo  = array(
		'State' => array('className' => 'State', 'foreignKey' => 'state_id', 'fields' => array('id', 'state'), 'type'=>'left'), 
		 'Brand' => array('className' => 'Brand', 'foreignKey' => 'brand_id', 'fields' => array('id', 'name'), 'type'=>'left'),
		'LgArea' => array('className' => 'LgArea', 'foreignKey' => 'lg_area_id', 'fields' => array('id', 'name'), 'type'=>'left'), 
		'Region' => array('className' => 'Region', 'foreignKey' => 'region_id', 'fields' => array('id', 'title'), 'type'=>'left'),
		'Depot' => array('className' => 'Depot', 'foreignKey' => 'depot_id', 'fields' => array('id', 'title','color_code'), 'type'=>'left'),
		'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('id', 'first_name', 'last_name'), 'type'=>'inner'),
		'File' => array('className' => 'File', 'foreignKey' => 'file_id', 'fields' => array('id', 'name'), 'type'=>'left')
	);
	public function consumerList($depot_id=0, $user=null, $isService=false, $params = null){
		$conditions = 1; // array();
		$joinsStr = "";
		if ($depot_id){
			//$conditions['Consumer.depot_id'] = $depot_id;
			$conditions = "Consumer.depot_id  = $depot_id";
		}else if ($user){
			switch($user['Role']['grade']){
				
				case 3:
					
					$joinsStr = " LEFT JOIN (SELECT consumer_id FROM consumer_assigns WHERE user_id = ".$user['id'].") AS ConsumerAssign ON Consumer.id = ConsumerAssign.consumer_id ";
					
					//$conditions = "Consumer.region_id  = ".$user['region_id']." OR Consumer.user_id = ".$user['id']." OR Consumer.id IN (SELECT consumer_id FROM consumer_assigns WHERE user_id = ".$user['id'].")";
					$conditions = "(Consumer.region_id  = ".$user['region_id']." OR Consumer.user_id = ".$user['id']." OR ConsumerAssign.consumer_id IS NOT NULL)";
				break;
				case 4:
					
					$joinsStr = " LEFT JOIN (SELECT consumer_id FROM consumer_assigns WHERE user_id = ".$user['id'].") AS ConsumerAssign ON Consumer.id = ConsumerAssign.consumer_id ";
					
					//$conditions = "Consumer.user_id  = ".$user['id']." OR ConsumerAssign.consumer_id IS NOT NULL";
					
					$conditions = "(Consumer.depot_id  = ".$user['depot_id']." OR Consumer.user_id = ".$user['id']." OR ConsumerAssign.consumer_id IS NOT NULL)";
				break;
				case 5:
					//$conditions = "Consumer.user_id  = ".$user['id']." OR Consumer.user_id IN (SELECT uid2 FROM user_relations WHERE user_id = ".$user['id'].") OR Consumer.id IN (SELECT consumer_id FROM consumer_assigns WHERE user_id = ".$user['id'].")";
					
					$joinsStr = " LEFT JOIN (SELECT uid2 FROM user_relations WHERE user_id = ".$user['id'].") AS UserRelation ON Consumer.user_id = UserRelation.uid2 LEFT JOIN (SELECT consumer_id FROM consumer_assigns WHERE user_id = ".$user['id'].") AS ConsumerAssign ON Consumer.id = ConsumerAssign.consumer_id ";
					
					$conditions = "(Consumer.user_id  = ".$user['id']." OR UserRelation.uid2 IS NOT NULL OR ConsumerAssign.consumer_id IS NOT NULL )";
					
				break;
				case 6:
					
					$joinsStr = " LEFT JOIN (SELECT consumer_id FROM consumer_assigns WHERE user_id = ".$user['id'].") AS ConsumerAssign ON Consumer.id = ConsumerAssign.consumer_id ";
					
					$conditions = "(Consumer.user_id  = ".$user['id']." OR ConsumerAssign.consumer_id IS NOT NULL)";
				break;
			}
		}
		
		/*$weekDay = date('0w');
		$joinsStr = " INNER JOIN (SELECT route_id FROM user_routes WHERE user_id = ".$user['id']."  AND week = '$weekDay') AS UserRoute ON Consumer.route_id = UserRoute.route_id";*/
		
		if (!empty($user['depot_id']) && $user['Role']['grade'] > 3){
			$conditions .= " AND Consumer.depot_id  = ".$user['depot_id'];
		}
		//$consumers = $this->find('all', array('fields' => array('Consumer.id', 'CONCAT_WS(" ", Consumer.first_name, Consumer.last_name) as name'), 'conditions'=>$conditions, 'order'=>array('name'=>'asc')));
		//echo 'SELECT Consumer.id, CONCAT_WS(" ", Consumer.first_name, Consumer.last_name) as name, Consumer.depot_id FROM consumers AS Consumer'.$joinsStr.' WHERE '.$conditions.' ORDER BY name asc';
		$limit = "";
		if ($isService){
			//$limit = ' LIMIT 2000';
			if($params){
				if(!empty($params['minConsumerId']) && !empty($params['maxConsumerId'])){
					$conditions .= " AND ( Consumer.id < ".$params['minConsumerId']." OR  Consumer.id > ".$params['maxConsumerId'] . ")";
				}else if(!empty($params['minConsumerId']) && $params['minConsumerId'] > 0){
					$conditions .= " AND Consumer.id < ".$params['minConsumerId'];
				} else if(!empty($params['maxConsumerId']) && $params['maxConsumerId'] > 0){
					$conditions .= " AND Consumer.id > ".$params['maxConsumerId'];
				}
			}
			$qryString = 'SELECT Consumer.id, CONCAT_WS(" ", Consumer.first_name, Consumer.last_name) as name, Consumer.depot_id FROM consumers AS Consumer'.$joinsStr.' WHERE '.$conditions.' ORDER BY id desc LIMIT 1000';
		}else{
			$qryString = 'SELECT Consumer.id, CONCAT_WS(" ", Consumer.first_name, Consumer.last_name) as name, Consumer.depot_id FROM consumers AS Consumer'.$joinsStr.' WHERE '.$conditions.' ORDER BY name asc, created desc';
		}
		$consumers = $this->query($qryString);
		$list = array();
		$listArr = array();
		$jsonList = array();
		//pr($consumers);
		//die();
		if($consumers){
			foreach($consumers as $consumer){
				$list[$consumer['Consumer']['id']] = $consumer['0']['name'];
				$listArr[] = array('id'=> $consumer['Consumer']['id'], 'depot_id'=>$consumer['Consumer']['depot_id'], 'name'=>$consumer['0']['name']);
				$jsonList[] = array("id"=>$consumer['Consumer']['id'], 'value'=> $consumer['0']['name']);
			}
		}
		//pr($list);
		if ($isService){
			if (!$list){
				$list = null;
			}
			return array('consumers'=>array(), 'consumersList'=>$jsonList);
		}else{
			return $list;
		}
	}
	
	public function consumerListByRole($user, $isService = false){
		return $this->consumerList(0, $user, $isService);
	}
	
	public function moreConsumerListByRole($user, $params){
		return $this->consumerList(0, $user, true, $params);
	}
	
	public function _userCondition(&$conditions, $user){
		switch($user['Role']['grade']){
			case 3:
				$conditions[] = '(Consumer.user_id IN (SELECT id FROM users WHERE region_id = '.$user['region_id'].') OR Consumer.id IN (SELECT consumer_id FROM consumer_assigns WHERE user_id = '.$user['id'].'))';
			break;
			case 4:
				$conditions[] = '(Consumer.user_id IN (SELECT id FROM users WHERE depot_id = '.$user['depot_id'].') OR Consumer.id IN (SELECT consumer_id FROM consumer_assigns WHERE user_id = '.$user['id'].'))';
			break;
			case 5:
			if(isset($conditions['OR'])){
				$conditions[]['OR'] = array('Consumer.user_id'=> $user['id'], 'Consumer.user_id IN (SELECT uid2 FROM user_relations WHERE user_id = '.$user['id'].') OR Consumer.id IN (SELECT consumer_id FROM consumer_assigns WHERE user_id = '.$user['id'].') ');
			}else{
				$conditions['OR'] = array('Consumer.user_id'=> $user['id'], 'Consumer.user_id IN (SELECT uid2 FROM user_relations WHERE user_id = '.$user['id'].') OR Consumer.id IN (SELECT consumer_id FROM consumer_assigns WHERE user_id = '.$user['id'].') ');
			}
			break;
			
			case 6:
				$conditions['Consumer.user_id'] = $user['id']." OR Consumer.id IN (SELECT consumer_id FROM consumer_assigns WHERE user_id = ".$user['id'].")";
			break;
			
		}
	}
	
	public function _userRoleCondition(&$conditions, $user, &$paginate){
		
		switch($user['Role']['grade']){
			case 3:
				//$joinsStr = " LEFT JOIN (SELECT consumer_id FROM consumer_assigns WHERE user_id = ".$user['id'].") AS ConsumerAssign ON Consumer.id = ConsumerAssign.consumer_id ";
				
				//$paginate['joins'][] = array('table' => 'consumer_assigns', 'type'=>'left', 'alias'=>'ConsumerAssign', 'conditions'=>array('Consumer.id=Order.consumer_id '.$oC));
				$paginate['joins'][] = array('table' => '(SELECT id FROM users WHERE region_id = '.$user['region_id'].')', 'type'=>'left', 'alias'=>'User2', 'conditions'=>array('Consumer.user_id = User2.id'));
				
				$paginate['joins'][] = array('table' => '(SELECT consumer_id FROM consumer_assigns WHERE user_id = '.$user['id'].')', 'type'=>'left', 'alias'=>'ConsumerAssign', 'conditions'=>array('Consumer.id = ConsumerAssign.consumer_id'));
				//$conditions[] = 'Consumer.user_id IN (SELECT id FROM users WHERE region_id = '.$user['region_id'].') OR Consumer.id IN (SELECT consumer_id FROM consumer_assigns WHERE user_id = '.$user['id'].')';
				if(isset($conditions['OR'])){
					$conditions[]['OR'] = array('User2.id IS NOT NULL', 'ConsumerAssign.consumer_id IS NOT NULL');
				}else{
					$conditions['OR'] = array('User2.id IS NOT NULL', 'ConsumerAssign.consumer_id IS NOT NULL');
				}
			break;
			case 4:
				//$paginate['joins'][] = array('table' => '(SELECT id FROM users WHERE depot_id = '.$user['depot_id'].')', 'type'=>'left', 'alias'=>'User2', 'conditions'=>array('Consumer.user_id = User2.id'));
				
				$paginate['joins'][] = array('table' => '(SELECT consumer_id FROM consumer_assigns WHERE user_id = '.$user['id'].')', 'type'=>'left', 'alias'=>'ConsumerAssign', 'conditions'=>array('Consumer.id = ConsumerAssign.consumer_id'));
				
				//$conditions[] = 'Consumer.user_id IN (SELECT id FROM users WHERE depot_id = '.$user['depot_id'].') OR Consumer.id IN (SELECT consumer_id FROM consumer_assigns WHERE user_id = '.$user['id'].')';
				if(isset($conditions['OR']) ){
					$conditions[]['OR']= array('Consumer.depot_id'=> $user['depot_id'], 'ConsumerAssign.consumer_id IS NOT NULL');
				}else{
					$conditions['OR'] = array('Consumer.depot_id'=> $user['depot_id'], 'ConsumerAssign.consumer_id IS NOT NULL');
				}
			break;
			case 5:
								
				$paginate['joins'][] = array('table' => '(SELECT uid2 FROM user_relations WHERE user_id = '.$user['id'].')', 'type'=>'left', 'alias'=>'UserRelation', 'conditions'=>array('Consumer.user_id = UserRelation.uid2'));
				
				$paginate['joins'][] = array('table' => '(SELECT consumer_id FROM consumer_assigns WHERE user_id = '.$user['id'].')', 'type'=>'left', 'alias'=>'ConsumerAssign', 'conditions'=>array('Consumer.id = ConsumerAssign.consumer_id'));
				
				//$conditions['OR'] = array('Consumer.user_id'=> $user['id'], 'Consumer.user_id IN (SELECT uid2 FROM user_relations WHERE user_id = '.$user['id'].') OR Consumer.id IN (SELECT consumer_id FROM consumer_assigns WHERE user_id = '.$user['id'].') ');
				if(isset($conditions['OR'])){
					$conditions[]['OR'] = array('Consumer.user_id'=> $user['id'], 'UserRelation.uid2 IS NOT NULL OR ConsumerAssign.consumer_id IS NOT NULL');
				}else{
					$conditions['OR'] = array('Consumer.user_id'=> $user['id'], 'UserRelation.uid2 IS NOT NULL OR ConsumerAssign.consumer_id IS NOT NULL');
				}
				
				//$conditions = "Consumer.user_id  = ".$user['id']." OR UserRelation.uid2 IS NOT NULL OR ConsumerAssign.consumer_id IS NOT NULL";
			break;
			
			case 6:
				$paginate['joins'][] = array('table' => '(SELECT consumer_id FROM consumer_assigns WHERE user_id = '.$user['id'].')', 'type'=>'left', 'alias'=>'ConsumerAssign', 'conditions'=>array('Consumer.id = ConsumerAssign.consumer_id'));
				if(isset($conditions['OR'])){
					$conditions[]['OR'] = array('Consumer.user_id'=> $user['id'], 'ConsumerAssign.consumer_id IS NOT NULL' );
				}else{
					$conditions['OR'] = array('Consumer.user_id'=> $user['id'], 'ConsumerAssign.consumer_id IS NOT NULL' );
				}
				
				//$conditions['Consumer.user_id'] = $user['id']." OR Consumer.id IN (SELECT consumer_id FROM consumer_assigns WHERE user_id = ".$user['id'].")";
			break;
			
		}
		
		if (!empty($user['depot_id']) && $user['Role']['grade'] < 3){
			$conditions['Consumer.depot_id'] = $user['depot_id'];
		}
	}
	
}