<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
class RoutesController extends AppController {

/**
 * Controller title
 *
 * @var string
 */

	var $components = array('Option');
	public function index(){
	    
	   // pr(date('Y-m-d H:i:s'));
	    
	   /* $this->loadModel('CustomerVisit');
	     $this->CustomerVisit->id = 684669; 
	    $cvisit = $this->CustomerVisit->read(); 
	    
	    $uid = $cvisit['CustomerVisit']['user_id'];   //pr($uid);
		$date = date('Y-m-d', strtotime($cvisit['CustomerVisit']['visiting_date'])); //pr($date); die();
		
		$this->loadModel('Customer');
		$customer = $this->Customer->findById($cvisit['CustomerVisit']['customer_id']); 
		
		$userDayRouteIds = $this->Route->getUserDayRouteIds($uid,$date); pr($userDayRouteIds); pr($customer['Customer']['route_id']);
		if(!empty($userDayRouteIds)){
			if (!in_array($customer['Customer']['route_id'],$userDayRouteIds)){
				// Customer's route_id is not in $userDayRouteIds array
				$this->CustomerVisit->id = $cvisit['CustomerVisit']['id'];
				$this->CustomerVisit->saveField('not_on_day_route', 1);
				
				// find routes title
				$userDayRoutes = $this->Route->find('list', array('fields' => array('id', 'title'), 'conditions' => array('id' => $userDayRouteIds)));
				
			}
		}*/
	    
	    
		
		$conditions = array();
		
		$this->Route->belongsTo  = array(		
			'Region' => array('className' => 'Region', 'foreignKey' => 'region_id', 'fields' => array('id', 'title'), 'type'=>'left'),'Depot' => array('className' => 'Depot', 'foreignKey' => 'depot_id', 'fields' => array('id', 'title'), 'type'=>'left'));
		$this->loadModel('Division');
		if (!empty($this->request->query['q']) ){
			$conditions['LOWER(Route.title) LIKE'] =  '%'.strtolower($this->request->query['q']).'%';
		}
		
		if(!empty($this->request->query['dv']) && empty($this->request->query['rg']) && empty($this->request->query['dp'])){
            $divisionRegion = ClassRegistry::init('DivisionsRegion');
            $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' =>$this->request->query['dv'])));
            $conditions['Route.region_id IN'] = $rIds;
        }
		if ( !empty($this->request->query['rg'])){
			$conditions['Route.region_id'] = $this->request->query['rg'];
		}
		if ( !empty($this->request->query['dp'])){
			$conditions['Route.depot_id'] = $this->request->query['dp'];
		}
		$order = $this->paginate['order'] = array('Route.title' => 'asc');
		$this->_options();
		$querystring = $this->request->query;
		$this->set(compact('querystring'));
		
		
		
		//$this->Route->Behaviors->load('Containable');
		/* $this->Route->bindModel(array(
			'hasMany' => array(
				'UserRoute' => array(
					'className' => 'UserRoute',
					'foreignKey' => 'route_id'
				)
			)
		)); */
		
		/* $this->loadModel('UserRoute'); // Load UserRoute model dynamically

		$this->UserRoute->bindModel(array(
			'belongsTo' => array(
				'User' => array(
					'className' => 'User',
					'foreignKey' => 'user_id',
					'fields' => array('username', 'first_name', 'last_name')
				)
			)
		)); 
				
		$this->paginate['contain'] = $contain = array(
			'Region', 'Depot',
			'UserRoute' => array(
				'User' => array(
					'fields' => array('id', 'username', 'first_name', 'last_name','status'), // Specify fields from User model	
				)
			)
		); */
		
		$this->loadModel('User');
		$this->User->unbindModel(array('belongsTo' => array('State', 'Division', 'Region', 'Depot', 'Role', 'File')), false);
		$userArr = $this->User->find('all', array('fields'=>array('id', 'username', 'first_name', 'last_name'), 'conditions' => array('User.status' => ACTIVE)));
		$userData = [];
		foreach($userArr as $data){
			$userData[$data['User']['id']] = $data;
		}
		
		// Fetch user route data
		$this->loadModel('UserRoute');
		$userRoutes = $this->UserRoute->find('all', array(
			'fields' => array('UserRoute.user_id', 'UserRoute.route_ids', 'UserRoute.year', 'UserRoute.month', 'UserRoute.week', 'UserRoute.day'),
			'conditions' => array('UserRoute.year' => date('Y'), 'UserRoute.month' => $this->Auth->user('current_month_no')) // Filter for current month
		));

		// Build route_id => users map
		$routeToUsers = array();
		foreach ($userRoutes as $ur) {
			$ids = explode(',', str_replace(' ', '', $ur['UserRoute']['route_ids']));
			foreach ($ids as $rid) {
				if (!isset($routeToUsers[$rid])) {
					$routeToUsers[$rid] = array();
				}
				$routeToUsers[$rid][] = array(
					'user_id' => $ur['UserRoute']['user_id'],
					'year'    => $ur['UserRoute']['year'],
					'month'   => $ur['UserRoute']['month'],
					'week'    => $ur['UserRoute']['week'],
					'day'     => $ur['UserRoute']['day']
				);
			}
		}


		
		if(isset($this->request->query['export'])){   
			if(!empty($this->request->query['offset'])){
			$offset = (int) $this->request->query['offset'];
			if($offset > 10000){
				$offset = 0;
			}
		}else{
			$offset = 0;
		}
			
			$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();		
			$routes = $this->Route->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
		} else {

		    $routes = $this->paginate('Route', $conditions);
		} //pr($routes); die();
		
		
		
		$this->set(compact('routes', 'userData', 'offset', 'routeToUsers'));
		
		if(isset($this->request->query['export'])){   
			$this->set('filename', 'routes');
			$this->render('export_routes','export_xls');
		}
		
	}
	
	public function add(){
		if ($this->request->data){
			$is_exists = $this->Route->find('count', array('conditions'=>array('LOWER(Route.title)'=>strtolower($this->request->data['Route']['title']))));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Route']['title']));
			}else{
				$this->Route->save($this->request->data);
				$this->Session->setFlash(__('Route was added successfully'));
				$this->redirect(array('action'=>'index'));
			}
		}
		$this->_options();
		//$this->loadModel('State');
	}
	
	public function edit($id=0){
		$this->loadModel('Audit');
		if (!empty($id)){
		   $this->Route->id = $id;
		   $routeData = $this->Route->find('first', array('conditions'=>array('md5(Route.id)'=>$id)));
		  // pr($routeData);die();
		  }
		if ($this->request->data){
			$is_exists = $this->Route->find('count', array('conditions'=>array('LOWER(Route.title)'=>strtolower($this->request->data['Route']['title']), 'md5(Route.id) !=' => $id)));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Route']['title']));
			}else{
				if($this->Route->save($this->request->data)){
					 $this->Audit->saveDeletedData($routeData['Route']['id'], 'Route', $this->Auth->user('id') , serialize($routeData),'Route Has been updated', STATUS_EDIT);
					}
				$this->Session->setFlash(__('Route was updated successfully'));
				$this->redirect(array('action'=>'index'));
			}
		}
		
		if (!empty($id)){
			$this->Route->id = $id;
			$this->request->data = $this->Route->find('first', array('conditions'=>array('md5(Route.id)'=>$id)));
		}
		$this->_options();
	}
	
	function _options(){		
		/*$this->loadModel('Region');
		$this->loadModel('Depot');		
		$regions = $this->Region->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));
		$depots = $this->Depot->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));		
		$this->set(compact('regions', 'depots'));*/
		$Opdata = isset($this->request->data['Route'] ) ? $this->request->data['Route']  : array();
		$this->Option->Options($Opdata, $this->user);
	}
	
	public function delete($id){
		$this->loadModel('Audit');
		if(!$id){
			$this->redirect(array('action'=>'index'));
		}
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$data = array();
			$route = $this->Route->find('first', array('conditions'=>array('md5(Route.id)'=>$id)));
			$data['serialize'] = serialize($route);//pr($data['serialize']);die();
			$data['model_id'] = $route['Route']['id'];
		if($id){
			$this->Route->deleteAll(array('md5(Route.id)'=>$id));
			$this->Audit->saveDeletedData($data['model_id'], 'Route', $this->Auth->user('id') , $data['serialize'],'Route Has been Deleted', STATUS_DELETE);
			$this->Session->setFlash(__('Route was deleted successfully'));
			$this->redirect(array('action'=>'index'));
		}
		
		
	}
	
	public function deleteAllRoutes(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		
		if(!empty($this->request->data['deleteAllValue'])){
			$this->Route->deleteAll(array('Route.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected Routes was deleted successfully') );
			$this->redirect(array('action'=>'index'));
		}
		exit;
	}
	
	public function getRoute(){
		$result = $routes = array();
		if(!empty($this->request->data['eoption']) && $this->request->data['eoption'] == 'setselrt'){
            $eoption = array();
        }else{
			$eoption = array("0"=>__('All routes'));
		}
		if (!empty($this->request->data['depot'])){
			
			$routes = $this->Route->find('list', array('conditions'=>array('depot_id'=>$this->request->data['depot']), 'fields'=>array('id','title'), 'order'=>array('title'=>'asc')));
		}
		$result['routes'] = $eoption + $routes; 
		echo json_encode($result);
		exit;
	}
	
	public function getRouteByUser(){
        $result = $routes = array();
        if(!empty($this->request->data['eoption']) && $this->request->data['eoption'] == 'setselrt'){
            $eoption = array();
        }else{
            $eoption = array("0"=>__('All routes'));
        }
        if (!empty($this->request->data['user'])){
            $this->loadModel('UserRoute');
            $rtIds = $this->UserRoute->find('list', array('conditions'=>array('user_id'=>$this->request->data['user']), 'fields'=>array('route_ids','user_id'))); 
            if(!empty($rtIds)){
				$rtIds = array_keys ($rtIds);
                $routes = $this->Route->find('list', array('conditions'=>array('id'=>$rtIds), 'fields'=>array('id','title'), 'order'=>array('title'=>'asc')));
            }
        }
        $result['routes'] = $eoption + $routes;  //pr($result['routes']);exit;
        echo json_encode($result);
        exit;
    }
	
	public function user_routes(){
		$this->set('title_for_layout', 'Route::User Routes');
		$this->loadModel('User');
		$conditions = array( 'User.status'=>ACTIVE);
		$users = array();
		$usersList = $this->User->find('all', array('fields'=>array('User.id', 'User.first_name', 'User.last_name', 'Role.name' ), 'conditions'=>$conditions, 'order'=>array('User.first_name'=>'asc', 'User.last_name'=>'asc')));
		foreach ($usersList as $ul){
			$users[$ul['User']['id']] = $ul['User']['first_name'].' '.$ul['User']['last_name']. ' ('.$ul['Role']['name'].')';
		}
		$this->set('users', $users);
	}
	
	public function route_mapping(){

		$this->loadModel('User');

		$this->loadModel('UserRoute');

		$this->UserRoute->primaryKey = null;
		
		if(!empty($this->request->data['uId']) ){

			$user_id = $this->request->data['uId'];
		    //$week_id=$this->request->data['wId'];
			//$week_id=isset($this->request->data['wId']) ? $this->request->data['wId'] : '';
			//$day_id=$this->request->data['dId'];
			//$day_id=isset($this->request->data['dId']) ? $this->request->data['dId'] : '';
		
			$period = isset($this->request->data['period']) ? $this->request->data['period'] : '';			
			$week = isset($this->request->data['week']) ? $this->request->data['week'] : '';			
			$day = isset($this->request->data['day']) ? $this->request->data['day'] : '';
			$weekText= isset($this->request->data['weekText']) ? $this->request->data['weekText'] : '';
			
			$userDetail = $this->User->find('first', array('conditions'=>array('User.id'=>$user_id)));
			
			$rConds = array();

			if(!empty($userDetail['User']['region_id'])){

				$rConds['Route.region_id'] = $userDetail['User']['region_id'];

			}

			if(!empty($userDetail['User']['depot_id'])){

				$rConds['Route.depot_id'] = $userDetail['User']['depot_id'];

			}

			$weekDays = getWeek(); 
			//pr($weekDays);

			$routes = $this->Route->find('list', array('fields'=>array('id', 'title'), 'conditions'=>$rConds, 'order' => array('title' => 'ASC') ));
		
			$mapedRoutes = $this->Route->userWeeklyRoute($user_id, $period, $week, $day);
			//pr($mapedRoutes); 
			
			
			// ----------------------
			// Handle repeated weekdays ONLY if week > 7 days
			// ----------------------
			$repeatedWeekdays = [];
			$routeMessages = [];

			if (!empty($weekText) && !empty($day)) {
				// Get year from period
				$selectedYear = date('Y', strtotime($period));

				// Extract start and end dates from weekText
				preg_match('/\((\d{2} \w{3}) to (\d{2} \w{3})\)/', $weekText, $matches);
				if (isset($matches[1]) && isset($matches[2])) {
					$startDate = date('Y-m-d', strtotime($matches[1] . ' ' . $selectedYear));
					$endDate   = date('Y-m-d', strtotime($matches[2] . ' ' . $selectedYear));

					// Generate all dates in the week
					$datesInWeek = [];
					$iDate = $startDate;
					while (strtotime($iDate) <= strtotime($endDate)) {
						$datesInWeek[] = $iDate;
						$iDate = date('Y-m-d', strtotime('+1 day', strtotime($iDate)));
					}
					
					// Only process if week has more than 7 days
					if (count($datesInWeek) > 7) {
						$PTGCalendar = $this->_getPTGCalendarData($startDate);
						
						// Find all occurrences of the selected weekday
						$selectedDayDates = [];
						foreach ($datesInWeek as $d) {
							if (strtolower(date('l', strtotime($d))) == strtolower($day)) {
								$selectedDayDates[] = $d;
							}
						}
						
						// Only show message if selected weekday occurs more than once
						if (count($selectedDayDates) > 1) {
							$repeatedWeekdays[$day] = $selectedDayDates;

							foreach ($selectedDayDates as $d) {
								$routePlanPeriod = getRoutePlanPeriod($d, $PTGCalendar);

								if ($routePlanPeriod['week'] == $week) {
									$routeMessages[] = "✔ You are updating route plan for " . date('d M Y', strtotime($d));
								} else {
									$routeMessages[] = "⚠ For " . date('d M Y', strtotime($d)) 
										. " please update route plan for " 
										. date('F', mktime(0,0,0,$routePlanPeriod['month'],1)) 
										. " Week " . $routePlanPeriod['week'] . " " . $day;
								}
							}
						}
					}
				}
			}
			

			$this->set(compact('userDetail', 'period', 'week','day','routes','weekDays', 'mapedRoutes', 'repeatedWeekdays', 'routeMessages'));

		}

	}
	public function autousers(){
		$this->loadModel('User');
		$result =  array();
		if(!empty($this->request->query['term'])){
			$this->User->unbindModelAll();
			$conditions[] = array('LOWER(CONCAT_WS(" ", User.first_name, User.last_name)) LIKE "%'.trim(strtolower($this->request->query['term'])).'%"');
			$users = $this->User->find('all', array('conditions'=>$conditions,'fields'=>array('id', 'first_name', 'last_name'), 'order'=>array('User.first_name'=>'asc', 'User.last_name'=>'asc'), 'User.status'=>ACTIVE));
			if($users){
				foreach($users as $user){
					$result[] = array('id'=>$user['User']['id'], 'label'=>$user['User']['first_name'].' '.$user['User']['last_name']);
				}
			}
		}
		echo json_encode($result, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	/* public function update_user_route(){
		
		if($this->request->data){

			$this->loadModel('User');

			$this->loadModel('UserRoute');
			  $conditions = array(
				'user_id'=>$this->request->data['Route']['user_id'],
				 "AND" => array(
					'week' => $this->request->data['Route']['week'],
					"AND" => array(
					 'day' => $this->request->data['Route']['day'])
				) );
            
            $this->UserRoute->bindModel(array(
                'belongsTo' => array(
                    'Route' => array(
                        'foreignKey' => 'route_id',
                    ),
                )
            ));
            $oldRoutes =  $this->UserRoute->find('all', array('conditions' =>  $conditions));
	
			$this->UserRoute->deleteAll($conditions, false);
			//$this->UserRoute->deleteAll(array('day' => $this->request->data['Route']['day']), false);
			//$this->UserRoute->deleteAll(array('user_id'=>$this->request->data['Route']['user_id'],"AND" => array('week' => $this->request->data['Route']['week'],"AND" => array('day' => $this->request->data['Route']['day']))) ), false);
			$routeMapData = array();
			//pr($routeMapData);

			if(!empty($this->request->data['route'])){

				$user_id = $this->request->data['Route']['user_id'];
				$day = $this->request->data['Route']['day'];
				
				foreach ($this->request->data['route'] as $key => $routeId){
			//	pr($this->request->data['route']);die;
					foreach ($routeId as $rid){

						$routeMapData[] = array('user_id'=>$user_id, 'route_id'=>$rid ,'week'=> $key,'day'=> $day,'added_by'=>  $this->user['id']);
						

					}

				}
				
				if($routeMapData){

					$this->UserRoute->saveAll($routeMapData);
					//pr($routeMapData);
					
					$this->UserRoute->bindModel(array(
                        'belongsTo' => array(
                            'Route' => array(
                                'foreignKey' => 'route_id',
                            ),
                        )
                    ));
                     $newRoutes =  $this->UserRoute->find('all', array('conditions' =>  $conditions));
	
                	/// Email  ///
            			$email = new CakeEmail('smtp');
            			$email->from(array('support@drupway.com'=> 'Y3 Support'));
            			$email->to(array('drupwaycrm@gmail.com')); //y3hqfin@fastmail.fm = Anya
            			$email->emailFormat('html');
            			$email->subject("User Route updated for user_id " . $conditions['user_id'] . " by " . $this->Auth->user('username') . " on " . date('Y-m-d H:i:s'));
            			$email->viewVars(array('oldRoutes' => $oldRoutes, 'newRoutes' => $newRoutes, 'ruid' => $conditions['user_id'], 'by' => $this->Auth->user('username')));
            			$email->template('userroutes_updated');
            			$email->send('userroutes_updated'); 
            		///----------------------------------------------------- ///

					echo __('Users route plan was updated successfully');

				}

			} else{
				echo __('Now there is no route plan for this user');
			} 

			

		}

		exit;

	} */
	
	
	public function update_user_route(){
		
		if($this->request->data){ //pr($this->request->data); 
			$week = $this->request->data['Route']['week'];
			
			if(!empty($this->request->data['route'])){
				$routeIds = implode(',', $this->request->data['route'][$week]); //pr($routeIds); //die();
			}

			$this->loadModel('UserRoute');

			if(!empty($this->request->data['Route']['period'])) {
				$period = $this->request->data['Route']['period'];
				$year = date('Y', strtotime($period));
				$month = date('n', strtotime($period));
			}
			$uId = $this->request->data['Route']['user_id'];
			$week = $this->request->data['Route']['week'];
			$day = $this->request->data['Route']['day'];
			
			$conditions = ['user_id' => $uId, 'year' => $year, 'month' => $month, 'week' => $week, 'day' => $day];
            
            $oldRoutes =  $this->UserRoute->find('all', array('conditions' =>  $conditions));
	
			$this->UserRoute->deleteAll($conditions, false);
			$routeMapData = array();
			//pr($routeMapData);

			if(!empty($this->request->data['route'])){
				
				$routeIds = implode(',', $this->request->data['route'][$week]);
				
				$routeMapData = array('user_id'=>$uId, 'year'=> $year, 'month'=> $month, 'week'=> $week,'day'=> $day, 'route_ids'=>$routeIds, 'added_by'=>  $this->user['id']);		
				
				if($routeMapData){

					$this->UserRoute->saveAll($routeMapData);
					//pr($routeMapData);
					                
					$newRoutes =  $this->UserRoute->find('all', array('conditions' =>  $conditions));
					
					$this->loadModel('Audit');
					$this->Audit->saveDeletedData($uId, 'UserRoute', $this->Auth->user('id') , serialize($oldRoutes),'UserRoute Has been updated', STATUS_EDIT);
	
                	/** Email  **/
            			/* $email = new CakeEmail('smtp');
            			$email->from(array('support@drupway.com'=> 'Y3 Support'));
            			$email->to(array('drupwaycrm@gmail.com')); //y3hqfin@fastmail.fm = Anya
            			$email->emailFormat('html');
            			$email->subject("User Route updated for user_id " . $conditions['user_id'] . " by " . $this->Auth->user('username') . " on " . date('Y-m-d H:i:s'));
            			$email->viewVars(array('oldRoutes' => $oldRoutes, 'newRoutes' => $newRoutes, 'ruid' => $conditions['user_id'], 'by' => $this->Auth->user('username')));
            			$email->template('userroutes_updated');
            			$email->send('userroutes_updated');  */
            		/**** ----------------------------------------------------- ****/

					echo __('Users route plan was updated successfully');

				}

			} else{
				echo __('Now there is no route plan for this user');
			} 

			

		}

		exit;

	}
	
	
	//** NO LONGER USED **//
	public function route_plan(){
		$this->loadModel('User');
		$user_id = !empty($this->request->query['usr'])?$this->request->query['usr']:$this->user['id'];
		$udata = $this->User->find('first', array('conditions'=>array('User.id'=>$user_id)));
		$weekDays = getWeek();
		$routesPlan = $this->Route->userRoutePlan( $user_id );
		$this->set(compact('udata', 'weekDays', 'routesPlan'));
	}
	
	public function customers($uid = 0){

		$this->loadModel('Customer');

		$this->loadModel('User');

		$this->Customer->unbindModelAll();

		//$weekDay = date('0w');
//pr($weekDay);
		/* $conditions = array(); */
		$conditions['Customer.status'] = ACTIVE;
		
		if ( !empty($this->request->query['date'])){
			$date = $this->request->query['date'];
		}else{
		    $date = date('Y-m-d'); 
		}
		
		$conditions['Customer.created <='] = $date . ' 23:59:59';

		
		
//$week =  date('W', strtotime(date('Y-m-d')));
		// $day =date('D', strtotime($date));
		/*  $d = weekOfMonth(date('Y-m-d')); 
		 
		 
		$lastDayPrev = date('Y-m-d', strtotime('last day of previous month')); //pr($lastDayPrev);
		$dPrev = weekOfMonth($lastDayPrev); //pr($dPrev);
		
		
		 
		$firstday =date('D', strtotime(date('Y-m-01'))); //pr($firstday);
		if($dPrev == 5 && $firstday == 'Sun'){
			// $week += 1; //
			$d += 1;
		}elseif($dPrev == 6 && $firstday == 'Sun'){
			// $week += 2; //
			$d += 2;
		} 

		 if ($d == 5) {
			$week = 1;
		  } elseif ($d == 6) {
			 $week = 2; 
		  } else {
			 $week = $d; 
		  } */
		  
		//$week = getY3Week($date);
		
		//pr('CRM week no. - '.$week);
		 
		 
		 
		/*  if ($d == 5) {
			$week = 1;
		  } elseif ($d == 6) {
			 $week = 2; 
		  } else {
			 $week = $d; 
		  } */
		  
		//$joins = array(array('table'=>"(SELECT route_id FROM user_routes WHERE user_id = $uid AND week = $week AND day LIKE '$day%' )", 'type'=>'inner', 'conditions'=>array('Customer.route_id = UserRoute.route_id'), 'alias'=>'UserRoute' ), array('table'=>'routes', 'alias'=>'Route', 'type'=>'inner', 'conditions'=>array('Route.id = Customer.route_id') ));

		
		$PTGCalendar = $this->_getPTGCalendarData($date);
		//$year = date('Y', strtotime($date));
		//$month = $PTGCalendar['month'];
		//$week = $PTGCalendar['week'];
		
		$rpPeriod = getRoutePlanPeriod($date, $PTGCalendar);
		$year  = $rpPeriod['year'];
		$month = $rpPeriod['month'];
		$week  = $rpPeriod['week'];
		
		$day = date('l', strtotime($date));
		
		// PTG Calendar Period (inline)
		$ptgYear = date('Y', strtotime($date));
		//$ptgMonthName = date('F', strtotime($ptgYear  . '-' . $PTGCalendar['month'] . '-01'));
		$dateObj = DateTime::createFromFormat('!m', $PTGCalendar['month']);
		$ptgMonthName = $dateObj->format('F');
		$ptgCalPeriod = $ptgMonthName . " " . $ptgYear  . ", Week " . $PTGCalendar['week'] . " " .$day;

		// Route Plan Period (inline)
		//$rpMonthName = date('F', strtotime("$year-$month-01"));
		$dateObj = DateTime::createFromFormat('!m', $month);
		$rpMonthName = $dateObj->format('F');
		$routePlanPeriod = "$rpMonthName $year, Week $week $day";
		
		$this->set('ptgCalPeriod', $ptgCalPeriod);
		$this->set('routePlanPeriod', $routePlanPeriod);
		
		$joins = array(
			array('table' => "(SELECT route_ids FROM user_routes WHERE user_id = $uid AND year = $year AND month = $month AND week = $week AND day = '$day')", 'alias' => 'UserRoute', 'type' => 'INNER', 'conditions' => array("FIND_IN_SET(Customer.route_id, UserRoute.route_ids)")),
			array('table' => 'routes', 'alias' => 'Route', 'type' => 'INNER', 'conditions' => array('Route.id = Customer.route_id')),
			array('table' => 'users', 'alias' => 'User', 'type' => 'INNER', 'conditions' => array('User.id = Customer.user_id'), 'fields' => array('user_id', 'first_name', 'last_name'))
		); //pr($joins);
		
//pr($joins);
		

		//pr($conditions);
		$customers = $this->Customer->find('all', array('fields'=>array('Customer.id', 'Customer.first_name', 'Customer.last_name', 'Customer.user_id', 'Route.title', 'User.first_name', 'User.last_name'), 'conditions'=>$conditions, 'joins'=>$joins));

		$udata = $this->User->find('first', array('conditions'=>array('User.id'=>$uid)));
		
		
		 // Fetch assigned route_ids and titles for the user from user_routes and routes
		$this->loadModel('UserRoute');
		$userRouteData = $this->UserRoute->find('first', [
			'fields' => ['UserRoute.route_ids'],
			'conditions' => ['UserRoute.user_id' => $uid, 'UserRoute.year' => $year, 'UserRoute.month' => $month, 'UserRoute.week' => $week, 'UserRoute.day' => $day,]]);
		
		$assignedRoutes = [];			
		if(!empty($userRouteData)){
			$assignedRouteIds = explode(',', $userRouteData['UserRoute']['route_ids']);
			
			$this->loadModel('Route');
			$assignedRoutes = $this->Route->find('list', [ 'fields' => ['Route.id','Route.title'], 'conditions' => ['Route.id' => $assignedRouteIds],  'order' => ['Route.title' => 'ASC']]);
		}
		
		$expectedVisitFrequency = 0;
		if($udata['Role']['grade'] > DH){
			$expectedVisitFrequency = count($customers);
		}elseif($udata['Role']['grade'] == DH){
			/* foreach ($customers as $customer) {
				// Count customers where the user_id matches the current user
				if ($customer['Customer']['user_id'] == $uid) {
					$expectedVisitFrequency++;
				}
			} */
			
			$expectedVisitFrequency = ceil(count($customers) / 2);
		}
			
		$this->set(compact('customers', 'udata', 'assignedRoutes', 'expectedVisitFrequency'));


	}
	
	/* public function userroutes($uid = 0){

		$conditions = array();

		$this->loadModel('User');
		//$week =  date('W', strtotime(date('Y-m-d')));
		 $day =date('D', strtotime(date('Y-m-d'))); 
		/// $weekDays = weekOfMonth(date('Y-m-d'));  ///
		//pr($day);
		$joins = array(array('table'=>'(SELECT route_id FROM user_routes WHERE user_id = '.$uid.'  GROUP BY route_id)', 'type'=>'inner', 'conditions'=>array('Route.id = UserRoute.route_id'), 'alias'=>'UserRoute' ));
		//$joins = array(array('table'=>"(SELECT route_id FROM user_routes WHERE user_id = '$uid' AND week = '$weekDays' AND day LIKE '$day%' GROUP BY route_id)", 'type'=>'inner', 'conditions'=>array('Route.id = UserRoute.route_id'), 'alias'=>'UserRoute' ));
		//pr($joins);
		 
		$this->paginate['joins'] = $joins;

		$routes = $this->paginate('Route', $conditions); 

		$routeWeek = $this->Route->user_rotes($uid);
		//pr($routeWeek);

		$udata = $this->User->find('first', array('conditions'=>array('User.id'=>$uid)));

		//$weekDays = getWeek();

		$this->set(compact('routes', 'routeWeek', 'udata'));

		

		if(isset($this->request->query['export'])){   

			$this->set('filename', $udata['User']['first_name'].'_'. $udata['User']['last_name'].'_weekly_routes');

			$this->render('userroutes_xls','export_xls');

		}

	} */
	
	public function userroutes($uid = 0) {
		

        $this->loadModel('UserRoute');
        $this->loadModel('Route');
		
		if(!empty($this->request->query['year'])){
            $q_year = $this->request->query['year'];
		}else{
			$q_year =  date('Y');
		}
        
        $userRouteData = $this->UserRoute->find('all', [
            'conditions' => ['UserRoute.user_id' => $uid, 'UserRoute.year' => $q_year],
            'order' => ['UserRoute.month' => 'ASC', 'UserRoute.week' => 'ASC', 'UserRoute.day' => 'ASC']
        ]); 
	
		$userRoutes = $rids = [];
		if(!empty($userRouteData)){
			foreach ($userRouteData as $route) {
				$month = $route['UserRoute']['month'];
				$week = $route['UserRoute']['week'];
				$day = $route['UserRoute']['day'];
				$routeIds = explode(',', $route['UserRoute']['route_ids']);
				$userRoutes[$q_year][$month][$week][$day] = $routeIds;
				
				$rids = array_merge($rids, $routeIds);
			}
			$this->loadModel('Route');
			$routes = $this->Route->find('list', array('fields' => ['id', 'title'], 'conditions' => ['id' =>$rids])); 
		}
		
		
		$this->loadModel('User');
		$udata = $this->User->find('first', array('conditions'=>array('User.id'=>$uid)));
		
		if($q_year == date('Y')){
			$yearlyCalendar = $this->Auth->user('current_year_calendar');
		}else{
			$yearlyCalendar = $this->getYearlyCalendar($q_year);
		}
		
        $this->set(compact('userRoutes', 'uid', 'udata', 'routes', 'q_year', 'yearlyCalendar'));
		
		if(isset($this->request->query['export'])){   
			$this->set('filename', $udata['User']['first_name'].'_'. $udata['User']['last_name'].'_'.$q_year.'_Route_Plan');
			$this->render('userroutes_xls','export_xls');
		}
    }
}