<?php
App::uses('AppController', 'Controller');
class CalendarsController extends AppController {

/**
 * Controller name
 *
 * @var string
 */
	var $events;

	public function index(){
		
		$inactive_events = $this->Calendar->find('list', array('fields'=>array('id'), 'conditions'=>array('Calendar.status'=>ACTIVE, 'Calendar.eventclosedate <' =>date('Y-m-d H:i:s')))); 
		
		if(!empty($inactive_events)){
			$this->Calendar->updateAll(
				array('Calendar.status' =>INACTIVE),
				array('Calendar.id' => $inactive_events)
			);
		}
		
          if(!empty($this->request->query['list'])){
				$conditions = [];
				
				//filter for keyword
				if (!empty($this->request->query['q']) ){
					$conditions['OR']['Calendar.eventtitle LIKE'] =  '%'.$this->request->query['q'].'%';
					$conditions['OR']['Calendar.eventdescription LIKE'] =  '%'.$this->request->query['q'].'%';
					$conditions['OR']['Calendar.adress LIKE'] =  '%'.$this->request->query['q'].'%';
				}
				
				//filter status
				if ( !empty($this->request->query['s'])){
					$conditions['Calendar.status'] = $this->request->query['s'];
				}
				
				//filter event start date and event close date
				if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
					$conditions[] = array('Calendar.eventopendate BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));			
					}elseif (!empty($this->request->query['from'])){
					$conditions['Calendar.eventopendate >= '] = $this->request->query['from'];
					} elseif (!empty($this->request->query['to'])){
					$conditions['Calendar.eventclosedate <= '] = $this->request->query['to'];
				}
				
				//pagination
				$order=$this->paginate['order'] = array('Calendar.eventopendate'=>'desc', 'Calendar.starttime'=>'desc');
				$querystring = $this->request->query;
				
				//fetching Event data
				$calendardatas = $this->paginate('Calendar', $conditions);
				
				//sending data to view
				$this->set(compact('querystring','calendardatas','offset'));
				$this->render('eventlist');
			}else{
				$monthNames = Array("January", "February", "March", "April", "May", "June", "July",
				"August", "September", "October", "November", "December");    
				
				if (!isset($this->request->params['named']["m"])) $this->request->params['named']["m"] = date("n");
				if (!isset($this->request->params['named']["y"])) $this->request->params['named']["y"] = date("Y");

				$currentMonth = $this->request->params['named']["m"]; 
				$currentYear = $this->request->params['named']["y"]; 

				$p_year = $currentYear;
				$n_year = $currentYear;
				$p_month = $currentMonth-1;
				$n_month = $currentMonth+1;

				if ($p_month == 0 ) {
					$p_month = 12;
					$p_year = $currentYear - 1;
				}

				if ($n_month == 13 ) {
					$n_month = 1;
					$n_year = $currentYear + 1;
				}
				$days=array('1'=>"Sunday",'2'=>"Monday",'3'=>"Tuesday",'4'=>"Wednesday",'5'=>"Thursday",'6'=>"Friday",'7'=>"Saturday");

				$timestamp = mktime(0,0,0,$currentMonth,1,$currentYear);
				$maxday = date("t",$timestamp);
				$thismonth = getdate ($timestamp);
				$startday = $thismonth['wday'];
				if($currentMonth<10)
					 $currentMonth="0".$currentMonth;
				$conditions['date_format(Calendar.eventopendate,"%Y-%m")'] = $currentYear."-".$currentMonth;
				$uid=$this->Auth->user('id');
				$roleid=$this->Auth->user('role_id');
			   // $data= $this->Calendar->query("SELECT * FROM events where date_format(eventopendate,'%Y-%m')='".$currentYear."-".$currentMonth."'");
				//$eventdata=$this->Calendar->find('list',array('fields'=>array('Calendar.id','Calendar.eventopendate'),'conditions'=>array('date_format(Calendar.eventopendate,"%Y-%m")'=>$currentYear."-".$currentMonth, 'OR'=>array('Calendar.uid'=>$uid, 'Calendar.role LIKE "%'.$roleid.'%"') ) )); pr($eventdata);
				
				//$eventdata=$this->Calendar->find('all',array('conditions'=>array('date_format(Calendar.eventopendate,"%Y-%m")'=>$currentYear."-".$currentMonth, /* 'OR'=>array('Calendar.uid'=>$uid) */ ) )); pr($eventdata);
				
				$eventdata=$this->Calendar->find('list',array('fields'=>array('Calendar.id','Calendar.eventopendate'),'conditions'=>array('date_format(Calendar.eventopendate,"%Y-%m")'=>$currentYear."-".$currentMonth), 'order'=>array('Calendar.eventopendate'=>'desc', 'Calendar.starttime'=>'desc') )); //pr($eventdata);
			
				$this->set(compact('eventdata','days','monthNames','p_year','n_year','p_month','n_month','currentMonth','currentYear','timestamp','maxday','thismonth','startday','roles'));
			}
	}
    
	public function deleteAllEvents(){
			
			//restrict "get" type of data
			if (!$this->request->is('post')) {
				throw new MethodNotAllowedException();
			}
			
			if(!empty($this->request->data['deleteAllValue'])){
				
				//delete multiple records according to multiple ids
				$this->Calendar->deleteAll(array('Calendar.id'=>explode(",", $this->request->data['deleteAllValue'])));
				$this->Session->setFlash(__('All selected Events was deleted successfully') );
				$this->redirect(array('action'=>'index', '?'=>array('list'=>1)));
			}
			exit;
		}
	
	public function getrole($roleid){
		$resourcedata= array();
           switch($roleid) {

				case "1":
					$resourcedata['source']=1;
                    $resourcedata['destination']=11;
				    break;
				case "2":
					$resourcedata['source']=2;
                    $resourcedata['destination']=6;
				    break;
				
				case "3":
					$resourcedata['source']=3;
					$resourcedata['destination']=6;
					break;
				case "4":
					$resourcedata['source']=4;
					$resourcedata['destination']=6;
					break;
				case "5":
					$resourcedata['source']=5;
					$resourcedata['destination']=6;
					break;
				case "6":
						$resourcedata['source']=6;
						$resourcedata['destination']=6;
						break;
				case "7":
					$resourcedata['source']=7;
					$resourcedata['destination']=8;
					break;
				
				case "8":
					$resourcedata['source']=8;
					$resourcedata['destination']=8;
					break;
				
				case "9":
					$resourcedata['source']=9;
					$resourcedata['destination']=11;
					break;
				
				case "10":
					$resourcedata['source']=10;
					$resourcedata['destination']=11;
					break;
				case "11":
					$resourcedata['source']=11;
					$resourcedata['destination']=11;
					break;
			    default:
					break;
		   }
			
               return $resourcedata;
		   
	}


	public function viewevent(){
     
	  if(!empty($this->params['named']['data'])){
			$roleid=$this->Auth->user('role_id');
			$conditions['md5(Calendar.eventopendate)'] = $this->params['named']['data'];
	  }elseif(!empty($this->params['named']['id'])){
		  $conditions['Calendar.id'] = $this->params['named']['id'];
	  }	//$eventdata=$this->Calendar->find('all',array('conditions'=>array('md5(Calendar.eventopendate)'=>$this->params['named']['data'],'OR'=>array('Calendar.uid'=>$roleid,' find_in_set ('.$roleid.',Calendar.role) ' ))));
		
		
			$eventdata=$this->Calendar->find('all',array('conditions'=>$conditions)); //pr($eventdata);

			$this->set(compact('eventdata'));
	 if(empty($eventdata)) {
		   $this->Session->setFlash(__('No event found'), 'default', array());
	  }
	 
	}
	
	public function delete($id=0){
	//	$this->gradPermission(1);
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		if(!$id){
			$this->redirect('/index');
		}
		$this->Calendar->id = $id;
		$calendar = $this->Calendar->read();//pr($calendar);die();

		$data = array();
		$data['serialize'] = serialize($calendar);
		$data['model_id'] = $calendar['Calendar']['id'];
		$this->Calendar->id = $id;
		$this->Calendar->delete();
		$this->loadModel('Audit');
			$this->Audit->saveDeletedData($data['model_id'], 'Event', $this->Auth->user('id') , $data['serialize'],'Event Has been Deleted',STATUS_DELETE);
		$this->Session->setFlash(__('Event was deleted sucessfully'));
		if(!empty($this->request->query['list'])){
			$this->redirect(array('action'=>'index', '?'=>array('list'=>1))); 
		 }else{
			$this->redirect(array('action'=>'index'));
		 }
	}

	public function getdata(){
		//print_r($this->request->data);
		/*	$timestamp = mktime(0,0,0,$currentMonth,1,$currentYear);
			$maxday = date("t",$timestamp);*/
		 return new CakeResponse(array('body'=> json_encode($this->request->data['startyear']),'status'=>200));
		 exit;
	}

	public function add(){	
		/* $roleid=$this->Auth->user('role_id');
		$resourcedata = $this->getrole($roleid);
		$this->loadModel('Role');
		$roles = $this->Role->find('all',array('conditions'=>array('Role.id >='=>$resourcedata['source'], 'Role.id <='=>$resourcedata['destination'])));  */

	    if($this->request->data){ //pr($this->request->data); die();
	
			 $this->request->data['Calendar']=$this->request->data['Calendar'];
		
			$eventstartdate = new DateTime($this->request->data["Calendar"]["eventopendate"]);
			$eventclosedate = new DateTime($this->request->data["Calendar"]["eventclosedate"]);

			if($eventstartdate > $eventclosedate) {
				echo 'Event start date should be less than event close date';
			     $this->Session->setFlash(__('Event start date should be less than event close date'), 'default', array());
			}
			else
			{   
				/* $this->request->data['Calendar']['role']=implode(",",$this->request->data["role"]); 
				$stdate=explode(" ",$this->request->data["Calendar"]["eventopendate"]);
				$enddate=explode(" ",$this->request->data["Calendar"]["eventclosedate"]);
				$this->request->data['Calendar']['starttime']=$stdate['1'];
				$this->request->data['Calendar']['eventopendate']=$stdate['0'];
				$this->request->data['Calendar']['eventclosedate']=$enddate['0'];
				$this->request->data['Calendar']['endtime']=$enddate['1'];
				$this->request->data['Calendar']['status']='1'; */
				$this->request->data['Calendar']['uid']=$this->Auth->user('role_id');	//created by	   
				/* if($this->Calendar->save($this->request->data)) {
						 $this->Session->setFlash(__('Event has been submitted successfully'), 'default', array());
						
				} else {
					    echo 'Problem to save event';
						 $this->Session->setFlash(__('Problem to save event'), 'default', array());
				} */
				
				$calendar = $this->Calendar->save($this->request->data); 
				
			/* 	if ($this->request->data['Calendar']['region_id']){
					$rdata = array();
					foreach ($this->request->data['Calendar']['region_id'] as $region_id){
						$rdata[] = array('Calendar_id'=>$calendar['Calendar']['id'], 'region_id'=>$region_id);
					}
					$this->loadModel('CalendarRegion');
					$this->CalendarRegion->primaryKey = null;
					@$this->CalendarRegion->saveAll($rdata, false);
				}
				
				if ($this->request->data['Calendar']['depot_id']){
					$data = array();
					foreach ($this->request->data['Calendar']['depot_id'] as $depot_id){
						$data[] = array('Calendar_id'=>$calendar['Calendar']['id'], 'depot_id'=>$depot_id);
					}
					
					$this->loadModel('CalendarDepot');
					$this->CalendarDepot->primaryKey = null;
					@$this->CalendarDepot->saveAll($data, false);
				} */
				
				if (!empty($this->request->data['Calendar']['user_id'])){
					$data = array();
					foreach ($this->request->data['Calendar']['user_id'] as $user_id){
						$data[] = array('calendar_id'=>$calendar['Calendar']['id'], 'user_id'=>$user_id);
					}
					
					$this->loadModel('CalendarUser');
					@$this->CalendarUser->saveAll($data, false);
				}else{
					if (!empty($this->request->data['Calendar']['depot_id'])){
						$data = array();
						foreach ($this->request->data['Calendar']['depot_id'] as $depot_id){
							$data[] = array('calendar_id'=>$calendar['Calendar']['id'], 'depot_id'=>$depot_id);
						}
						
						$this->loadModel('CalendarDepot');
						$this->CalendarDepot->primaryKey = null;
						@$this->CalendarDepot->saveAll($data, false);
					}else{
						if (!empty($this->request->data['Calendar']['region_id'])){
							$rdata = array();
							foreach ($this->request->data['Calendar']['region_id'] as $region_id){
								$rdata[] = array('calendar_id'=>$calendar['Calendar']['id'], 'region_id'=>$region_id);
							}
							$this->loadModel('CalendarRegion');
							$this->CalendarRegion->primaryKey = null;
							@$this->CalendarRegion->saveAll($rdata, false);
						}
					}
				}
				
				
				$this->Session->setFlash(__('Compaign was added sucessfully'));
				$this->redirect(array('action'=>'index'));
			}
		}
        $years=$this->genertaehourminute(2014,2030);
        $hours=$this->genertaehourminute(1,24);
		$minutes=$this->genertaehourminute(1,60);
		$monthNames = Array(1=>"January", 2=>"February", 3=>"March", 4=>"April", 5=>"May", 6=>"June", 7=>"July",
			8=>"August", 9=>"September", 10=>"October", 11=>"November", 12=>"December");

		
		$this->loadModel('Region');
		$regions = $this->Region->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));
		
		$this->loadModel('Role');
		$roles = $this->Role->getRolesList();
		
		$this->loadModel('User');
		$users = $this->User->find('list', array('fields'=>array('id', 'name'), 'conditions'=>array('status'=>ACTIVE), 'order'=>array('name'=>'asc')));
		
		$this->set(compact('hours','minutes','years','monthNames','roles','regions','users'));
	}
	
	public function edit($id=0){	

	    if($this->request->data){ //pr($this->request->data); die();
	
			 $this->request->data['Calendar']=$this->request->data['Calendar'];
		
			$eventstartdate = new DateTime($this->request->data["Calendar"]["eventopendate"]);
			$eventclosedate = new DateTime($this->request->data["Calendar"]["eventclosedate"]);

			if($eventstartdate > $eventclosedate) {
				echo 'Event start date should be less than event close date';
			     $this->Session->setFlash(__('Event start date should be less than event close date'), 'default', array());
			}
			else
			{   
				
				/* $stdate=explode(" ",$this->request->data["Calendar"]["eventopendate"]);
				$enddate=explode(" ",$this->request->data["Calendar"]["eventclosedate"]);
				$this->request->data['Calendar']['starttime']=$stdate['1'];
				$this->request->data['Calendar']['eventopendate']=$stdate['0'];
				$this->request->data['Calendar']['eventclosedate']=$enddate['0'];
				$this->request->data['Calendar']['endtime']=$enddate['1'];
				$this->request->data['Calendar']['status']='1'; */
				$this->request->data['Calendar']['uid']=$this->Auth->user('role_id');	//created by	   
				
				$calendar = $this->Calendar->save($this->request->data); 

				if (!empty($this->request->data['Calendar']['user_id'])){
					$this->loadModel('CalendarUser');
					$this->CalendarUser->deleteAll(array('calendar_id'=>$calendar['Calendar']['id']), false);
					
					$data = array();
					foreach ($this->request->data['Calendar']['user_id'] as $user_id){
						$data[] = array('calendar_id'=>$calendar['Calendar']['id'], 'user_id'=>$user_id);
					}
					
					
					@$this->CalendarUser->saveAll($data, false);
				}else{
					if (!empty($this->request->data['Calendar']['depot_id'])){
						
						$this->loadModel('CalendarDepot');
						$this->CalendarDepot->deleteAll(array('calendar_id'=>$calendar['Calendar']['id']), false);
						
						$data = array();
						foreach ($this->request->data['Calendar']['depot_id'] as $depot_id){
							$data[] = array('calendar_id'=>$calendar['Calendar']['id'], 'depot_id'=>$depot_id);
						}
						
						
						$this->CalendarDepot->primaryKey = null;
						@$this->CalendarDepot->saveAll($data, false);
					}else{
						if (!empty($this->request->data['Calendar']['region_id'])){
							
							$this->loadModel('CalendarRegion');
							$this->CalendarRegion->deleteAll(array('calendar_id'=>$calendar['Calendar']['id']), false);
							
							$rdata = array();
							foreach ($this->request->data['Calendar']['region_id'] as $region_id){
								$rdata[] = array('calendar_id'=>$calendar['Calendar']['id'], 'region_id'=>$region_id);
							}
							
							$this->CalendarRegion->primaryKey = null;
							@$this->CalendarRegion->saveAll($rdata, false);
						}
					}
				}
				
				
				$this->Session->setFlash(__('Event was updated sucessfully'));
				if(!empty($this->request->query['list'])){
					$this->redirect(array('action'=>'index', '?'=>array('list'=>1))); 
				}else{
					$this->redirect(array('action'=>'index'));
				}
			}
		}
		
		if (!empty($id)){
			$this->Calendar->id = $id;
			$this->request->data = $this->Calendar->read(); //pr($this->request->data);
			
			if(!empty($this->request->data['Region'])){
				foreach($this->request->data['Region'] as $r){
					$this->request->data['Calendar']['region_id'][] = $r['id'];
				}
			}
			
			if(!empty($this->request->data['Depot'])){
				foreach($this->request->data['Depot'] as $d){
					$this->request->data['Calendar']['depot_id'][] = $d['id'];
				}
			}
			
			if(!empty($this->request->data['User'])){
				foreach($this->request->data['User'] as $u){
					$this->request->data['Calendar']['user_id'][] = $u['id'];
				}
			}
		}
		
        $years=$this->genertaehourminute(2014,2030);
        $hours=$this->genertaehourminute(1,24);
		$minutes=$this->genertaehourminute(1,60);
		$monthNames = Array(1=>"January", 2=>"February", 3=>"March", 4=>"April", 5=>"May", 6=>"June", 7=>"July",
			8=>"August", 9=>"September", 10=>"October", 11=>"November", 12=>"December");

		
		$this->loadModel('Region');
		$regions = $this->Region->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));
		
		$this->loadModel('Depot');
		$depots = $this->Depot->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));
		
		$this->loadModel('Role');
		$roles = $this->Role->getRolesList();
		
		$this->loadModel('User');
		$users = $this->User->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		
		$this->set(compact('hours','minutes','years','monthNames','roles','regions','depots','users'));
		
		$this->render('add');
	}

    public function genertaehourminute($starthm,$hm){
		$hmtime=array();
		for($i=$starthm;$i<=$hm;$i++){
          if($i<10)
             $hmtime[$i]="0".$i;
		  else
			  $hmtime[$i]=$i;
		}
		return $hmtime;
	}
	
	public function getUserOptions(){
		$result = $conditions = array();
		
		$conditions['status'] = ACTIVE;
		
		/* $this->request->data['regionIds'] = 2;
		$this->request->data['depotIds'] = 10;  */
		//if (!empty($this->request->data['regionIds']) && !empty($this->request->data['depotIds'])){ 
			
			if (!empty($this->request->data['regionIds'])){ 
				$conditions['region_id'] = $this->request->data['regionIds'];
			}
			
			if (!empty($this->request->data['depotIds'])){ 
				$conditions['depot_id'] = $this->request->data['depotIds'];
			}
			
			if (!empty($this->request->data['roleId'])){ 
				$conditions['role_id'] = $this->request->data['roleId'];
			}
			
			$this->loadModel('User');
			
			$users = $this->User->find('list', array('fields'=>array('id','name'),'conditions'=>$conditions, 'order'=>array('name'=>'asc'))); //pr($users);
			$result['users'] = $users;
		//}
		echo json_encode($result);
		exit;
	}
 }