<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
App::uses('Controller', 'Controller');
ini_set('memory_limit', '2048M');
/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
	public $components = array('Session','Auth','Cookie');
	var $user;
	public $paginate = array(
        'limit' => PAGE_LIMIT,
		);
	function beforeFilter(){
		$this->user = $this->Auth->user();
		
	}

	function beforeRender(){
		$this->_setLanguage();
		$this->user = $this->Auth->user();
		$roleid = $this->Auth->user("role_id");
		$urlcheck = $this->params['controller']."/".$this->action;
		$pdata = $this->Auth->user('permission');
		$urlCondition = 0;
		$allowurl =array('0'=>'users/login','1'=>'users/dashboard','2'=>'customerrors/deniedpermission', '3'=>'tracking/trackusers', '4'=>'devicelog/index232','5'=>'stocks/getModelOptions','6'=>'customers/getLatLong', '7'=>'devicelog/mapkmllayer','8'=>'users/autologin','9'=>'ajax_report/day_user_calls','10'=>'services/updatecustomer','11'=>'spy/getdrcreport');	
		
		if(!empty($pdata)) {
			$pdata= array_merge($allowurl,$pdata);
		} else {
			$pdata=$allowurl;
		}
		if($this->params['controller'] == 'ajax_report'){
			$actions = array('active_users'=>'report1', 'nonactive_users'=>'report1', 'day_calls'=>'report1','numberof_customers'=>'report1', 'numberof_visits'=>'report1','customer_notvisits'=>'report1', 'average_calls'=>'report1', 'callreports'=>'report1', 'customerreports'=>'report1',
				'total_sale'=>'report2', 'ridistribtution_sales'=>'report2', 'totalamount_payment'=>'report2', 'totalexpenceamount'=>'report2', 'averevenue_sale'=>'report2', 'avecost_case'=>'report2', 
				'active_customer'=>'report3','nomaplocation_customer'=>'report3','activepurch_customer'=>'report3', 'total_customers'=>'report3', 'total_redistributors'=>'report3', 'customer_trend'=>'report3');
			if ( !empty($actions[$this->action])){
				$urlcheck = $this->params['controller']."/".$actions[$this->action];
			}				
		}
		
			
		if( !in_array($urlcheck,$pdata) && !$this->request->is('ajax') ){
			
			if(!empty($this->user['Role']['grade']) && $this->user['Role']['grade'] == 1){				
				//Do nothing
			}else{
				$this->redirect('/customerrors/deniedpermission');
				exit;
			}
		}
		if ($this->Auth->loggedIn()){
			$this->user = $this->Auth->user();
			
			$this->set('user', $this->user);
		}else{
			$this->set('user', false);
		}
		if ($this->request->is('ajax')){
			$this->layout = null;
		}
	}
	
	function gradPermission($grade){
	
		$user = $this->Auth->user();
		/*if ($user['Role']['grade'] > $grade){
			
			$this->render('/Errors/access_denied');
			return false;
		}else{
			return true;
		}*/
		return true;
	}

	function roleBasePermission($roledata){
	  
		/*$pdata = $this->Auth->user('permission');
		$urlcheck = $this->params['controller']."/".$this->action;
		if (!in_array($urlcheck, $pdata)){
			
			$this->redirect('/customerrors/deniedpermission');
			return false;
		}else{
			return true;
		}*/
	}

	function checkroleBasePermission($urlcheck){
		$pdata = $this->Auth->user('permission');
		$alodata="Not Allow";
		if(in_array($urlcheck,$pdata)){
				$alodata="Allow";
		}
	}
	function _setLanguage() {
	        if ($this->Cookie->read('lang') && !$this->Session->check('Config.language')){
	            $this->Session->write('Config.language', $this->Cookie->read('lang'));
	        }
	        //if the user clicked the language URL
	        else if (isset($this->params['language']) &&($this->params['language'] !=  $this->Session->read('Config.language'))){
	            $this->Session->write('Config.language', $this->params['language']);
	            $this->Cookie->write('lang', $this->params['language'], false, '30 days');
	        }
    	}
	

/************************** PTG calendar START **************************/		
	function getYearlyCalendar($year){
		$this->loadModel('PtgCalendar');
		$setupData = $this->PtgCalendar->findByYear($year); //pr($setupData);
		
		$calendar = array();
		if(!empty($setupData)){
			$wk1_start = date('Y-m-d', strtotime($setupData['PtgCalendar']['wk1_start']));
			$wk1_end = date('Y-m-d', strtotime($setupData['PtgCalendar']['wk1_end']));
			$calendar = calendar($wk1_start , $wk1_end); //pr($calendar); */
		}
		
		return $calendar;
	}
	
	function getMonthlyCalendar($year, $month){
		$this->loadModel('PtgCalendar');
		$setupData = $this->PtgCalendar->findByYear($year); //pr($setupData);
		
		$monthlyCalendar = array();
		if(!empty($setupData)){
			$wk1_start = date('Y-m-d', strtotime($setupData['PtgCalendar']['wk1_start']));
			$wk1_end = date('Y-m-d', strtotime($setupData['PtgCalendar']['wk1_end']));
			$calendarArray = calendar($wk1_start , $wk1_end); 
			
			$monthlyCalendar = $calendarArray[$month]; //pr($monthlyCalendar);
		}
		
		return $monthlyCalendar;
	}
	
	/* ----------------------------------------------------------
	 *  NOTE : 
	 *	If this method is called for MONTHLY CASE : work on '$weekNo' separatly
	 * ---------------------------------------------------------- */
	function _getPTGCalendarData($date){
	    
	    $PTGCalendar = array();
		$authUser = $this->Auth->user(); 
	    if(date('Y', strtotime($date)) == date('Y') && !empty($authUser['current_year_calendar'])){			
			$calendar = $authUser['current_year_calendar'];
		}else{
			$calendar = $this->getYearlyCalendar(date('Y', strtotime($date)));
		}
		
		if(!empty($calendar)){
		    $PTGCalendar['calendar'] = $calendar;
		    $PTGCalendar['month'] = $month = getMonthNo($calendar, $date);
			$monthArray = $calendar[$month]; //pr($monthArray);
			$PTGCalendar['week'] = $weekNo = getWeekNo($monthArray, $date);
		}
			
		return $PTGCalendar;
	}
	
	function _dateParams($type, $date){
		switch($type){
			case 'daily':
				$dateParams['prev'] = date('Y-m-d', strtotime('-1 day', strtotime($date)));
				$dateParams['next'] = date('Y-m-d', strtotime('+1 day', strtotime($date)));
				$dateParams['date'] = $date;
				$dateParams['title'] = date('F d, Y', strtotime($date));
			break; 
			
			case 'weekly':
				
				if(date('Y', strtotime($date)) == date('Y')){
					$authUser = $this->Auth->user(); 
					$calendar = $authUser['current_year_calendar'];
				}else{
					$calendar = $this->getYearlyCalendar(date('Y', strtotime($date)));
				}
				
				if(!empty($calendar)){
					$dateParams['month'] = $month = getMonthNo($calendar, $date);
					$monthArray = $calendar[$month]; //pr($monthArray);
					$dateParams['week'] = $weekNo = getWeekNo($monthArray, $date);
					$weekArray = $calendar[$month][$weekNo]; 
					$dateParams['from'] = $weekArray[0];
					$dateParams['to'] = $weekArray[count($weekArray) - 1]; //pr($dateParams);
					
					if(!in_array($month, [1,12])){
						if(!in_array($weekNo, [1, count($monthArray)])){
							$dateParams['prev'] = $monthArray[$weekNo-1][0];
							$dateParams['next'] = $monthArray[$weekNo+1][0];
						}elseif($weekNo == 1){
							$dateParams['next'] = $monthArray[$weekNo+1][0];
							$prevMonthArray = $calendar[$month-1];
							$dateParams['prev'] = $prevMonthArray[count($prevMonthArray)][0];
						}elseif($weekNo == count($monthArray)){
							$dateParams['prev'] = $monthArray[$weekNo-1][0];
							$nextMonthArray = $calendar[$month+1]; //pr($nextMonthArray);
							$dateParams['next'] = $nextMonthArray[1][0];
						}

					}elseif($month == 1){
						if(!in_array($weekNo, [1, count($monthArray)])){
							$dateParams['prev'] = $monthArray[$weekNo-1][0];
							$dateParams['next'] = $monthArray[$weekNo+1][0];
						}elseif($weekNo == 1){
							$dateParams['next'] = $monthArray[$weekNo+1][0];
							$prevCalendar = $this->getYearlyCalendar(date('Y', strtotime($date))-1);
							if($prevCalendar){
								$prevWeekArray = $prevCalendar[12][count($prevCalendar[12])];
								$dateParams['prev'] = $prevWeekArray[0];
							}
						}elseif($weekNo == count($monthArray)){
							$dateParams['prev'] = $monthArray[$weekNo-1][0];
							$nextMonthArray = $calendar[$month+1]; //pr($nextMonthArray);
							$dateParams['next'] = $nextMonthArray[1][0];
						}	
						
					}elseif($month == 12){
						if(!in_array($weekNo, [1, count($monthArray)])){
							$dateParams['prev'] = $monthArray[$weekNo-1][0];
							$dateParams['next'] = $monthArray[$weekNo+1][0];
						}elseif($weekNo == 1){
							$dateParams['next'] = $monthArray[$weekNo+1][0];
							$prevMonthArray = $calendar[$month-1];
							$dateParams['prev'] = $prevMonthArray[count($prevMonthArray)][0];
						}elseif($weekNo == count($monthArray)){
							$dateParams['prev'] = $monthArray[$weekNo-1][0];
							$nextCalendar = $this->getYearlyCalendar(date('Y', strtotime($date))+1);
							if($nextCalendar){
								//$nextWeekArray = $nextCalendar[1][count($nextCalendar[1])];
								//$dateParams['next'] = $nextWeekArray[0];
								$dateParams['next'] = $nextCalendar[1][1][0];								
							}
						}
					}
					
				}else{
					$dateParams['month'] = date('n', strtotime($date));
					$dateParams['week'] = $weekNo = "";
					$dateParams['from'] = date('Y-m-01');
					$dateParams['to'] = date('Y-m-t');
				}
				
				$dateParams['title'] = date('F', mktime(0, 0, 0, $month, 10)).' '.date('Y', strtotime($date)).', Week '.$weekNo;
				$dateParams['sub_title'] = date('M d', strtotime($dateParams['from'])).' - '.date('M d', strtotime($dateParams['to']));
				
			break;
			
			case 'monthly':
			
				if(date('Y', strtotime($date)) == date('Y')){
					$authUser = $this->Auth->user();
					$calendar = $authUser['current_year_calendar'];
				}else{
					$calendar = $this->getYearlyCalendar(date('Y', strtotime($date)));
				}
				
				if(!empty($calendar)){ 
					//$month = date('n', strtotime($date));
					$dateParams['month'] = $month = getMonthNo($calendar, $date); 
					$dateParams['number_of_weeks'] = count($calendar[$month]);
					$monthArray = $calendar[$month]; //pr($monthArray);
					$dateParams['from'] = $monthArray[1][0];
					$dateParams['to'] = end($monthArray[count($monthArray)]); 
					
					if(!in_array($month, [1,12])){
						$prevMonthArray = $calendar[$month-1];
						$dateParams['prev'] = $prevMonthArray[count($prevMonthArray)][0];
						$nextMonthArray = $calendar[$month+1];
						$dateParams['next'] = end($nextMonthArray[1]);
					}elseif($month == 1){
						$nextMonthArray = $calendar[$month+1];
						$dateParams['next'] = end($nextMonthArray[1]);
						$prevCalendar = $this->getYearlyCalendar(date('Y', strtotime($date))-1);
						if($prevCalendar){ 
							$dateParams['prev'] = end($prevCalendar[12][1]);
						}
					}elseif($month == 12){
						$prevMonthArray = $calendar[$month-1];
						$dateParams['prev'] = $prevMonthArray[count($prevMonthArray)][0];
						$nextCalendar = $this->getYearlyCalendar(date('Y', strtotime($date))+1);
						if($nextCalendar){
							$dateParams['next'] = $nextCalendar[1][1][0];
						}
					}
				}else{
					$dateParams['month'] = date('n', strtotime($date));
					$dateParams['from'] = date('Y-m-01', strtotime($date));
					$dateParams['to'] = date('Y-m-t', strtotime($date));
					$dateParams['prev'] = date('Y-m-01', strtotime(date('Y-m', strtotime($date)). ' -1 months'));
					$dateParams['next'] = date('Y-m-01', strtotime(date('Y-m', strtotime($date)). ' +1 months'));
				}
				
				
				$dateParams['title'] = date('F', mktime(0, 0, 0, $month, 10)).' '.date('Y', strtotime($date));
				$dateParams['sub_title'] = date('M d', strtotime($dateParams['from'])).' - '.date('M d', strtotime($dateParams['to']));
   
			break;
			
			case 'between':			    
		
				if (!empty($this->request->query['from'])){
					$dateParams['from'] = $this->request->query['from'];
				}else{
					$dateParams['from'] = date('Y-m-d');
				}
				
				if (!empty($this->request->query['to'])){
					$dateParams['to'] = $this->request->query['to'];
				}else{
					$dateParams['to'] = date('Y-m-d');
				}	
				
				$dateParams['title'] = __('From %s to %s', date('M d, Y', strtotime($dateParams['from'])), date('M d, Y', strtotime($dateParams['to'])));
				
			break;
			
		} 
		
		$this->set(compact('dateParams'));
		return $dateParams;
	}
	
	/************************** PTG calendar END **************************/
	
	function _getPTGCalendarRangeParams($query){
		$pfrom = $query['pfrom'];
		$fromWeek = $query['fromWeek'];
		$pto = $query['pto'];
		$toWeek = $query['toWeek'];
		
		## check if year is same
		## However Currently allowing the report only if year is same
		if(date('Y', strtotime($pfrom)) == date('Y', strtotime($pto))){
			## Get calendar
			if(date('Y', strtotime($pfrom)) == date('Y')){
				$authUser = $this->Auth->user();
				$calendar = $authUser['current_year_calendar'];
			}else{
				$calendar = $this->getYearlyCalendar(date('Y', strtotime($pfrom)));
			}
			//$calendarFrom = $calendarTo = $calendar;
			
		}
		/* else{
			$calendarFrom = $this->getYearlyCalendar(date('Y', strtotime($pfrom)));
			$calendarTo = $this->getYearlyCalendar(date('Y', strtotime($pto)));
		}
		
		if(!empty($calendarFrom)){
			$calendarFrom = $this->getYearlyCalendar(date('Y'));
		}
		if(!empty($calendarTo)){
			$calendarTo = $this->getYearlyCalendar(date('Y'));
		}
		$betweenParams['calendarFrom'] =  $calendarFrom;
		$betweenParams['calendarTo'] =  $calendarTo; 
		
		$monthFrom = date('n', strtotime($pfrom));
		$monthTo = date('n', strtotime($pto));
		
		$betweenParams['from'] = $calendarFrom[$monthFrom][$fromWeek][0];
		$betweenParams['to'] = end($calendarTo[$monthTo][$toWeek]); 
		*/
		
		//pr($calendar);
		$monthFrom = date('n', strtotime($pfrom));
		$monthTo = date('n', strtotime($pto));
		
		
		for($smon = $monthFrom; $smon <= $monthTo; $smon++){
			// Get the weeks from the calendar for the current month
			$mweeks = array_keys($calendar[$smon]);
			if ($smon == $monthFrom) {
				// For the first month, include weeks from $fromWeek onwards
				$betweenParams['selectedPeriod'][$smon] = array_slice($mweeks, $fromWeek - 1); // Adjusting for 0-index
			} elseif ($smon == $monthTo) {
				// For the last month, include weeks up to $toWeek
				$betweenParams['selectedPeriod'][$smon] = array_slice($mweeks, 0, $toWeek); // $toWeek is exclusive
			} else {
				// For all the months in between, include all weeks
				$betweenParams['selectedPeriod'][$smon] = $mweeks;
			}
		} 
		
		$betweenParams['from'] = $calendar[$monthFrom][$fromWeek][0];
		$betweenParams['to'] = end($calendar[$monthTo][$toWeek]); 
		
		$betweenParams['calendar'] =  $calendar;
		
		
		$betweenParams['title'] = __('From %s to %s', 
			date('F Y', strtotime($pfrom)) . ', Week ' . $fromWeek, 
			date('F Y', strtotime($pto)) . ', Week ' . $toWeek
		);
		
		$betweenParams['sub_title'] = __('From %s to %s', 
			date('M d, Y', strtotime($betweenParams['from'])), 
			date('M d, Y', strtotime($betweenParams['to']))
		);
		
	
		$weekrangeFrm = getWeekrange($calendar[$monthFrom]);
		foreach($weekrangeFrm as $wk => $range){
			$fromWeeks[$wk] = 'Week '.$wk.' ('. date('d M', strtotime($range['start'])).' to '.date('d M', strtotime($range['end'])).')';
		}
		
		$weekrangeTo = getWeekrange($calendar[$monthFrom]);
		foreach($weekrangeTo as $wk => $range){
			$toWeeks[$wk] = 'Week '.$wk.' ('. date('d M', strtotime($range['start'])).' to '.date('d M', strtotime($range['end'])).')';
		}
		
		$this->set(compact('betweenParams', 'fromWeeks', 'toWeeks'));
						
		return $betweenParams;
	}
	
	/* function _getBetweenParams($mfrom, $mto){
		## check if year is same
		if(date('Y', strtotime($mfrom)) == date('Y', strtotime($mto))){
			## Get calendar
			if(date('Y', strtotime($mfrom)) == date('Y')){
				$authUser = $this->Auth->user();
				$calendar = $authUser['current_year_calendar'];
			}else{
				$calendar = $this->getYearlyCalendar(date('Y', strtotime($mfrom)));
			}
			
			## Report Start and End date
			$betweenParams['from'] = $calendar[date('n', strtotime($mfrom))][1][0];
			$toLastWkArr = end($calendar[date('n', strtotime($mto))]);
			$betweenParams['to'] = end($toLastWkArr ); 
			
			## Find number of months 
			
		}else{
			## get calendar for each years
		}
		
		return $betweenParams;
	} */
    
	
}
