<?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 Redistributor extends AppModel {
	
	var $virtualFields = array(
		'name' => "CONCAT(Redistributor.first_name,' ', Redistributor.last_name)"
	);
	
	public $belongsTo  = array(
		'State' => array('className' => 'State', 'foreignKey' => 'state_id', 'fields' => array('id', 'state'), 'type'=>'inner'), 
		'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'=>'inner'),
		'Depot' => array('className' => 'Depot', 'foreignKey' => 'depot_id', 'fields' => array('id', 'title'), 'type'=>'inner'),
		'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 redistributorList($depot_id=0, $user=null, $isService=false){
		$conditions = 1; // array();
		if ($depot_id){
			//$conditions['Customer.depot_id'] = $depot_id;
			$conditions = "Redistributor.depot_id  = $depot_id";
		}else if ($user){
			switch($user['Role']['grade']){
				case 3:
				$conditions = 'Redistributor.region_id = '. $user['region_id'];
				break;
				case 4:
				case 5:
				case 6:
					$conditions = "Redistributor.depot_id  = ".$user['depot_id'];			
				break;
				/*
				case 3:
					$conditions = "Redistributor.region_id  = ".$user['region_id'];
				break;
				case 4:
					$conditions = "Redistributor.depot_id  = ".$user['depot_id'];
				break;
				case 5:
					$conditions = "Redistributor.user_id  = ".$user['id']." OR Redistributor.user_id IN (SELECT uid2 FROM user_relations WHERE user_id = ".$user['id'].")";
				break;
				case 6:
					$conditions = "Redistributor.depot_id  = ".$user['depot_id'];
				break; */
			}
		}
		
		$redistributors = $this->query('SELECT Redistributor.id, CONCAT_WS(" ", Redistributor.first_name, Redistributor.last_name) as name FROM redistributors AS Redistributor WHERE '.$conditions.' ORDER BY name asc');
		$list = array();
		$jsonList = array();
		if($redistributors){
			foreach($redistributors as $redistributor){
				$list[$redistributor['Redistributor']['id']] = $redistributor['0']['name'];
				$jsonList[] = array('id'=>$redistributor['Redistributor']['id'], 'value' => $redistributor['0']['name']);
			}
		}
		if ($isService){
			return $jsonList;
		}else{
			return $list;
		}
	}
	
	public function redistributorListByRole($user, $isService = false){
		return $this->redistributorList(0, $user, $isService);
	}
}