<?php

/**
* @version 2.8.9
* @package Joomla 2.5
* @subpackage DT Register
* @copyright Copyright (C) 2006 DTH Development
* @copyright contact dthdev@dthdevelopment.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/

class DtregisterControllerCalendar extends DtrController {

   var $name ='calendar';

	function __construct($config = array()){

		 parent::__construct($config);

		  $this->view = & $this->getView( 'calendar', 'html' );

		  $this->view->setModel($this->getModel('event'));

		  $this->view->setModel($this->getModel( 'location' ));

		  $this->view->setModel($this->getModel( 'user' ));

		  $this->view->setModel($this->getModel( 'member' ));

		  $this->view->setModel($this->getModel( 'field' ));
		  $this->view->setModel($this->getModel( 'category' ));

		  $this->registerDefaultTask("index");

	}

	function index(){
        global $mainframe;
		$cat = JRequest::getVar('cat','all' );
		
		// echo $view = JRequest::getVar('calview','');
        
		$this->view->assign('cat',$cat);
	   	$this->view->setLayout('index');

		$this->view->display();

	}

	function events(){

	   $startdate = JREquest::getVar('showdate');

	   $viewtype = JREquest::getVar('viewtype','month');

       $cat = JREquest::getVar('cat','all');
if($cat == 'all') {
	$cat = array();
}
	   $daterange = DTrCommon::getDateRangeByViewType($startdate,$viewtype);

	   $mevt = $this->getModel('event');

	   $tevt = $mevt->table;
     //  pr($daterange);
	   $start_date = new JDate($daterange['startdate']);
	   $end_date = new JDate($daterange['enddate']);
	  // $where = " (b.dtstart between '".($start_date->toFormat('%Y-%m-%d'))."' and  '".($end_date->toFormat('%Y-%m-%d'))."' or
	    //           b.dtend between '".($start_date->toFormat('%Y-%m-%d'))."' and  '".($end_date->toFormat('%Y-%m-%d'))."') ";
				   
				   //($r1start == $r2start) || ($r1start > $r2start ? $r1start <= $r2end : $r2start <= $r1end);
				//   "('".($start_date->toFormat('%Y-%m-%d'))."' == b.dtstart) || ('".($start_date->toFormat('%Y-%m-%d'))."' > b.dtstart ? '".($start_date->toFormat('%Y-%m-%d'))."' <= $r2end : b.dtstart <= $r1end)";
				//prd($cat);
	   $query = $mevt->listingQuery(array(),(array)$cat);
	   
	   $where = "(if('".($start_date->toFormat('%Y-%m-%d'))."' = b.dtstart,1,0) OR if('".($start_date->toFormat('%Y-%m-%d'))."' > b.dtstart,if('".($start_date->toFormat('%Y-%m-%d'))."' < b.dtend ,1,0 ),if(b.dtstart <= '".($end_date->toFormat('%Y-%m-%d'))."',1,0)))";
	   
	   $query = str_replace("order by dtstart , dtstarttime", "",$query);
	   $query = str_replace("group by b.slabId", "",$query);
	  // prd($query.$where);
	  echo "<pre>";
echo $query." and ".$where ;
	   $events = $tevt->query($query." and ".$where." group by b.slabId order by dtstart , dtstarttime",null,null); 
       
	   $this->view->assign('eventTable',$tevt);
	   $this->view->assign('events',$events);
        ob_clean();
	   $this->display();

	}
	
	function check_google_auth() {
		require_once(JPATH_SITE.DS.'components'.DS.'com_dtregister'.DS.'lib'.DS.'google-api'.DS.'apiClient.php');
		require_once(JPATH_SITE.DS.'components'.DS.'com_dtregister'.DS.'lib'.DS.'google-api'.DS.'contrib'.DS.'apiCalendarService.php');
		$client = new apiClient();
		$client->setApplicationName("Dtreg");
		$client->setClientId('104978521689-da0l8eq7vlnv76vnh36gh42brjmpagbi.apps.googleusercontent.com');
		$client->setClientSecret('OYIT1IorBqcK5hnlv9Da07OC');
		$client->setRedirectUri('http://www.joomlaeventregistration.com/j25/components/com_dtregister/google_api_auth.php');
		$client->setDeveloperKey('AIzaSyAyyhb1g0uEDg0WbQniTYGgmgmtZdDkxbg');
		if($client->getAccessToken()) {
		   
		   echo 'true';
		   
		} else {
		
			echo 'false';
		}
	}
	
	function auth() {
		
		global $google_app_name,$google_key,$google_client_id,$google_client_secret;
		$weekdays_map = array('SU','MO','TU','WE','TH','FR','SA');
		require_once(JPATH_SITE.DS.'components'.DS.'com_dtregister'.DS.'lib'.DS.'google-api'.DS.'apiClient.php');
		require_once(JPATH_SITE.DS.'components'.DS.'com_dtregister'.DS.'lib'.DS.'google-api'.DS.'contrib'.DS.'apiCalendarService.php');
		$client = new apiClient();
		$client->setApplicationName($google_app_name);
		
		// Visit https://code.google.com/apis/console?api=calendar to generate your
		// client id, client secret, and to register your redirect uri.
		$client->setClientId($google_client_id);
		$client->setClientSecret($google_client_secret);
		$client->setRedirectUri(JURI::root(false).'google_api_auth.php');
		$client->setDeveloperKey($google_key);
		$cal = new apiCalendarService($client);
		if(isset($_POST['cid'])) {
			
			$_SESSION['google_export_events'] = $_POST['cid'];
			
		}
		if (isset($_GET['logout'])) {
		  unset($_SESSION['token']);
		  die;
		}
		
		if (isset($_GET['code']) && !isset($_SESSION['token'])) {
		  $client->authenticate();
		  $_SESSION['token'] = $client->getAccessToken();
		  
		}
		
		if (isset($_SESSION['token'])) {
		  $client->setAccessToken($_SESSION['token']);
		}
		
		if ($client->getAccessToken()) { // export events here .
		if(isset($_REQUEST['calender_id'])){
			$_SESSION['google_calendar_id'] = $_REQUEST['calender_id'];
		}
		
		  if(!isset($_SESSION['google_calendar_id']) || $_SESSION['google_calendar_id'] == "") {
		     $calList = $cal->calendarList->listCalendarList();
			 echo JText::_('DT_SELECT_GOOGLE_CALENDAR')."<br />";
			 foreach($calList['items'] as $calendar) {
				 $cal_info = $cal->calendarList->get($calendar['id']);
				
			 	?>
                <a href="<?php echo'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'].'?calender_id='.$calendar['id'] ?>"><?php echo $cal_info['summary']; ?></a><br/>
                <?php
			 }
			
			} else {
					$config =& JFactory::getConfig();
					$offset = $config->getValue('config.offset');
					$this->getModel('event');
					
					if(isset($_SESSION['google_export_events']) && count($_SESSION['google_export_events'])) {
					   foreach($_SESSION['google_export_events'] as $slabId) {
						   $dtevent = new TableEvent();
						   $cal_data = $dtevent->get_google_data($slabId,$_SESSION['google_calendar_id']);
						   
						   if($cal_data !== false){
							  $event = new Event();
							  $event->setSummary($cal_data->title);
							  $event->setLocation($cal_data->name);
							  $start = new EventDateTime();
							  $start->setDateTime($cal_data->dtstart.'T'.$cal_data->dtstarttime);
							  $start->setTimeZone($offset);
							  $event->setStart($start);
							  
							  $end = new EventDateTime();
							  $end->setDateTime($cal_data->dtend.'T'.$cal_data->dtendtime);
							  $end->setTimeZone($offset);
							  $event->setEnd($end);
							  
							  $createdEvent = $cal->events->insert($_SESSION['google_calendar_id'], $event); 
							 
							  $google_evt_id =$createdEvent['id'];
							  
							  $dtevent->slabId = $slabId;
							  $dtevent->save_google_cal_event_id($_SESSION['google_calendar_id'],$google_evt_id);
							  // TO DO export repeat event
							  /*$until_or_count = ($cal_data->countselector == 'until')?$cal_data->rpuntil:$cal_data->rpcount;
							  $rule = "RRULE:FREQ=".strtoupper($cal_data->repeatTtype).";".strtoupper($cal_data->countselector).":".$until_or_count;
							  $rule .= ";INTERVAL=1";
							  switch($cal_data->repeatTtype) {
								  case 'daily': 
								  break;
								  case 'weekly':
									  
									  $weekdays = explode(",",$cal_data->weekdays);	
									  $temp = array();				
									  foreach($weekdays as $day){
										  $temp[] = $weekdays_map[$day];
									  }
									  $weekdays = $temp;
									  ";BYDAY=".implode(",",$weekdays);
								  break;
								  case 'monthly':

								  break;
							  }
							  */
							  $message = JText::_('DT_EVENTS_EXPORTED');
							
						   }else {
							   $message = JText::_('DT_EVENTS_EXPORTED');
						   		
						   }
					   }
					}
					
				     unset($_SESSION['google_export_events']);
				     unset($_SESSION['google_calendar_id']);
				     
					 $_SESSION['token'] = $client->getAccessToken();
					 if(isset($_SERVER['HTTP_REFERER'])) {
					  ?>
						 <script>
						  // alert("<?php //echo $message;?>");
						   window.parent.DTjQuery(".google_externalSite").dialog('close');
						 </script>
					  <?php
					 } else {
					 ?>
						<script>
						 // alert("<?php //echo $message;?>");
						  window.close();
						</script>
					 <?php
					 }
			   
			}
		   
		} else {
		  
		  $authUrl = $client->createAuthUrl();
		 // print "<a class='login' href='$authUrl' target='new'>Click Me!</a>";
		  ?>
          <script>
          window.open( "<?php echo $authUrl; ?>", "Google Auth", "menubar=0,location=0,height=700,width=700" );
		  window.parent.DTjQuery(".google_externalSite").dialog('close');
          </script>
          <?php
		}
		
		die;
	}

}

?>