<?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 Service extends AppModel {

	public $useTable = false;

	

	public function getDistributorList(){

		return $this->query("SELECT id, title, state_id FROM distributors ORDER BY title ASC");

	}
	function comment($key=''){
		$comment = array('1'=>'Free issue', '2'=>'Sampling', '3'=>'Customer on target','4'=>'Redemption');
		if($key && isset($comment[$key])){
			return $comment[$key];
		}else{
			return $comment;
		}
	}
	

	function paymentMode($key=''){

	

		$payment_mode = array('Bank Deposit' => 'Bank Deposit', 'Cash'=>'Cash', 'Cheque'=>'Cheque', 'Other' => 'Other');

		if($key){

			return $payment_mode[$key];

		}else{

			return $payment_mode;

		}

	}

	

	public function bankList(){

		$banks = $this->query("SELECT id, name FROM banks AS Bank ORDER BY name ASC");

		$bankdata = array();

		foreach($banks as $bank){

			$bankdata[] = array('id'=>$bank['Bank']['id'], 'value' => $bank['Bank']['name']);

		}

		if ($bankdata){

			return $bankdata;

		}else{

			return null;

		}

	}

	

	public function expenseTypeList(){

		$expTypes = $this->query("SELECT id, name FROM exp_types AS ExpType ORDER BY name ASC");

		$expdata = array();

		foreach($expTypes as $expType){

			$expdata[] = array('id'=>$expType['ExpType']['id'], 'value' => $expType['ExpType']['name']);

		}

		if ($expdata){

			return $expdata;

		}else{

			return null;

		}

	}

	

	public function reagionList(){

		$regions = $this->query("SELECT id, title FROM regions AS Region ORDER BY title ASC");

		$regionData = array();

		foreach($regions as $region){

			$regionData[] = array('id' => $region['Region']['id'], 'value' => $region['Region']['title']);

		}

		return $regionData;

	}

	

	/*public function statesList(){

		$states = $this->query("SELECT id, state FROM states AS State ORDER BY state ASC");

		$stateData = array();

		foreach($states as $state){

			$stateData[] = array('id' => $state['State']['id'], 'value' => $state['State']['state']);

		}

		if ($stateData){

			return $stateData;

		}else{

			return null;

		}

	}*/

	public function statesList(){
  $states = $this->query("SELECT id, state FROM states AS State ORDER BY state ASC");
  $stateData = array();
  foreach($states as $state){
   $stateData[] = array('id' => $state['State']['id'], 'value' => $state['State']['state']);
  }
  if ($stateData){
  return $stateData;
  }
  else{

			return null;

		}
 }

	/* public function routesList($uid =null){

		if(!empty($uid)){
			
			$day =date('D', strtotime(date('Y-m-d'))); 
			$week = getY3Week();
			$user_routes = $this->query("SELECT route_id FROM user_routes WHERE user_id = ".$uid."  AND week = '$week' AND day LIKE '$day%'"); //pr($user_routes);
            if(!empty($user_routes)){
				foreach($user_routes as $user_route){

					$rtIds[] = $user_route['user_routes']['route_id'];

				}
				$routes = $this->query("SELECT id, title, region_id, depot_id FROM routes AS Route WHERE id IN(".implode(',',$rtIds).") ORDER BY title ASC");
			}
		}else{
			$routes = $this->query("SELECT id, title, region_id, depot_id FROM routes AS Route ORDER BY title ASC");
		}

		$routesData = array();

		if(!empty($routes)){
			foreach($routes as $route){

				$routesData[] = array('id' => $route['Route']['id'], 'title' => $route['Route']['title'], 'region_id' => $route['Route']['region_id'], 'depot_id'=>$route['Route']['depot_id']);

			}
		}

		if ($routesData){

			return $routesData;

		}else{

			return null;

		}

	} */
	
	public function routesList($user =null){

		if(!empty($user)){
			
			$calendar = $user['current_year_calendar'];
			$year = date('Y');
			$month = getMonthNo($calendar, date('Y-m-d'));
			$monthArray = $calendar[$month];
			$week = getWeekNo($monthArray, date('Y-m-d'));
			$day = date('l');
			
			
			$userRouteCond['UserRoute.user_id'] = $user['id'];

			$userRouteCond['UserRoute.year'] = $year;
			$userRouteCond['UserRoute.month'] = $month;
			$userRouteCond['UserRoute.week']= $week;
			$userRouteCond['UserRoute.day']= $day;
			
			$UserRoute=  ClassRegistry::init('UserRoute');
			$rtIds = $UserRoute->find('list', array('conditions'=>$userRouteCond, 'fields'=>array('user_id', 'route_ids')));

			
			if(!empty($rtIds)){
				$rtIds = $rtIds[$user['id']];
				$routes = $this->query("SELECT id, title, region_id, depot_id FROM routes AS Route WHERE id IN(".$rtIds.") ORDER BY title ASC"); 
			}
		}else{
			$routes = $this->query("SELECT id, title, region_id, depot_id FROM routes AS Route ORDER BY title ASC");
		}

		$routesData = array();

		if(!empty($routes)){
			foreach($routes as $route){

				$routesData[] = array('id' => $route['Route']['id'], 'title' => $route['Route']['title'], 'region_id' => $route['Route']['region_id'], 'depot_id'=>$route['Route']['depot_id']);

			}
		}

		if ($routesData){

			return $routesData;

		}else{

			return null;

		}

	}

	

/** 

 * Request Logs

 *

 */ 

	function saveRequestLogs($request_id, $response, $url, $status, $user_id, $model_id = 0){

		if($request_id && APP_LOGS){
			
			

			//$this->query("INSERT INTO app_request_logs (request_id, user_id, url, response, status, model_id, created, modified) VALUES ('$request_id', $user_id, '".$url."', '".serialize($response)."', $status, $model_id, '".date('Y-m-d H:i:s')."', '".date('Y-m-d H:i:s')."' )");
			
			
			//$request_id = $request_id . "::" . date("YmdHis");
			
			$current_date = date('Y-m-d H:i:s');

			$this->query("
				INSERT INTO app_request_logs (request_id, user_id, url, response, status, model_id, created, modified)
				VALUES (
					'".$request_id."',
					'".$user_id."',
					'".$url."',
					'".addslashes(serialize($response))."',
					'".$status."',
					'".$model_id."',
					'".$current_date."',
					'".$current_date."'
				)
				ON DUPLICATE KEY UPDATE
					user_id = '".$user_id."',
					url = '".$url."',
					response = '".addslashes(serialize($response))."',
					status = '".$status."',
					model_id = '".$model_id."',
					modified = '".$created."'
			");

		}

	}

	

	function getRequestLogs($request_id){

		$data = $this->query("SELECT * FROM app_request_logs AS AppRequestLog WHERE request_id='$request_id' ");
		

		if ($data){

			return $data['0']['AppRequestLog'];

		}

		return null;

	}
	/**

 * target_cal_status : Get customer Call/Customer created Target

 * @params : @user_id (int)

 * return array()

 */

	function targetCalStatus($user_id = 0){

		

		$cusrrentTime = time();

		

		$d1 = date('Y-m-01', $cusrrentTime );

		$d2 = date('Y-m-t', $cusrrentTime );

		

		$targets = array();

		

		$orderEntry = $this->query("SELECT count(DISTINCT order_id) as oentry FROM sales WHERE user_id = $user_id AND sale_date between '$d1' AND '$d2' GROUP BY user_id");		

		$rSaleEntry = $this->query("SELECT count(DISTINCT redistributor_sale_id) as rsentry FROM redistributor_saleitems WHERE user_id = $user_id AND sale_date between '$d1' AND '$d2' GROUP BY user_id");		

		$visitEntry = $this->query("SELECT count(user_id) as ventry FROM customer_visits WHERE user_id = $user_id AND visiting_date between '$d1' AND '$d2 23:59:59' GROUP BY user_id");

		

		$targets['customerTarget']= "0";

		$targets['callTarget']= "0";

		//  customers created		

		$customerEntry = $this->query("SELECT count(id) as cCreated FROM customers WHERE user_id=$user_id AND status = 1 GROUP BY user_id");

		

		$targets['currentMonthCalls'] = (string)((isset($orderEntry['0']['0']['oentry'])? $orderEntry['0']['0']['oentry'] : 0 ) + (isset($rSaleEntry['0']['0']['rsentry'])?$rSaleEntry['0']['0']['rsentry']:0) + (isset($visitEntry['0']['0']['ventry'])?$visitEntry['0']['0']['ventry']:0));

		

		$targets['customerCreated'] = (string)(isset($customerEntry['0']['0']['cCreated'])?$customerEntry['0']['0']['cCreated']:0);

		

		$d1Array = explode("-", $d1);		

		//Find Monthly Targets		

		$targetQry = $this->query("SELECT target, type FROM user_targets AS Target WHERE user_id=$user_id");

		

		if($targetQry){

			foreach($targetQry as $target){

				if($target['Target']['type'] == 'Customer'){
					$targets['customerTarget'] = isset($target['Target']['target'])?$target['Target']['target']:0;
				}
				elseif($target['Target']['type'] == 'Call'){
					$userTargets = @unserialize($target['Target']['target']);
					$targets['callTarget'] = !empty($userTargets[$d1Array['1']])?$userTargets[$d1Array['1']]:0;					
				}
				/* else{
					$userTargets = @unserialize($target['Target']['target']);
					$targets['callTarget'] = !empty($userTargets[$d1Array['1']])?$userTargets[$d1Array['1']]:0;
				} */

			}

		}

		
		return $targets;

	}


}