<?php

/**
* @version 2.8.14
* @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
*/

defined( '_JEXEC' ) or die( 'Restricted access' );

class DtregisterControllerEventmanage extends DtrController {    

	var $name ='eventmanage';

	function __construct($config = array()){
		 
		 $config = array('default_task'=>'events','task_map'=>array('new'=>'add'));
		 parent::__construct($config);

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

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

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

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

		 $this->view->setModel($this->getModel( 'section' ),false);

		 $this->view->setModel($this->getModel( 'discountcode' ),false);

		 $this->view->setModel($this->getModel( 'file' ),false);

		 $this->view->setModel($this->getModel( 'field' ),false);
		 $this->view->setModel($this->getModel( 'user' ),false);
         
		 $this->view->setModel($this->getModel( 'payoption' ),false);
		 //$this->registerTask( 'new',  'add' );

		 //$this->registerDefaultTask("events");

		 JToolBarHelper::title(  JText::_( 'DT_EVENT_MANAGEMENT'), 'dtregister' );

	}

  function getcategory(){

	$database = &JFactory::getDBO();

	$sectionId = $_REQUEST['sectionId'];

	$options=array();

				$options[]=JHTML::_('select.option',"",JText::_('DT_SELECT_CATEGORY'));

				$query = "Select * from #__categories where section='".$sectionId ."'";

				$database->setQuery($query);

				$sections = $database->loadObjectList();

				if (is_array($sections)) 
				foreach($sections as $section){

					$options[]=JHTML::_('select.option',$section->id,$section->title);

				}

			echo $section_html = JHTML::_('select.genericlist', $options,"articlecategory","","value","text");

			?>

			<?php

			exit;

}

function getarticle(){

	$database = &JFactory::getDBO();

	$categoryId = $_REQUEST['categoryId'];

	$options=array();

				$user = JFactory::getUser();
				$options[]=JHTML::_('select.option',"","Select Article");
				$con = "";
                if(!$user->authorise('core.admin')) {
					$groups	= implode(',', $user->getAuthorisedViewLevels());
			         
				  $con = " and ".'c.access IN ('.$groups.')';
				}
				$query = "Select c.* from #__content c  where c.catid='".$categoryId ."' and `state` = '1' ".$con;

				$database->setQuery($query);

				$sections = $database->loadObjectList();
				
				if (is_array($sections)) 
				foreach($sections as $section){
					
                    if($user->authorise('core.edit',  'com_content.article.' . $section->id) != true) {
					 
					} else {
						 $options[]=JHTML::_('select.option',$section->id,$section->title);
					}

				}

			echo $section_html = JHTML::_('select.genericlist', $options,"data[event][article_id]","","value","text");

			?>

			<?php

			exit;

}

	function copy(){

      $cid = JRequest::getVar( 'cid', array(0), 'request', 'array' );
	 
	  JRequest::setVar('slabId',$cid[0]); 

	  $this->view->assign('copy',true);

	  $this->add();

   }

  function publish(){

      $cid = JRequest::getVar( 'cid', array(0), 'request', 'array' );

	  $event = $this->getModel('event')->table;
      
	   if (is_array($cid)) 
	   foreach($cid as $id){

	      $publish = 1;
		  
		  $query = "update #__dtregister_group_event set publish = ".$publish." where parent_id=".$id." or slabId=".$id; 
		  $event->rawquery($query);          

	  }

	  $this->events();
	   
   }

   function unpublish(){

      $cid = JRequest::getVar( 'cid', array(0), 'request', 'array' );

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

	   if (is_array($cid)) 
	   foreach($cid as $id){

	     $publish = 0;

		 $query = "update #__dtregister_group_event set publish = ".$publish." where parent_id=".$id." or slabId=".$id; 
		 $event->rawquery($query);    

	  }

	  $this->events();

   }

    function archive(){

      $cid = JRequest::getVar( 'cid', array(0), 'request', 'array' );

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

	   if (is_array($cid)) 
	   foreach($cid as $id){
         $archive = 1;

		 $query = "update #__dtregister_group_event set archive = ".$archive." where parent_id=".$id." or slabId=".$id; 
		 $event->rawquery($query);   

	  }

	  $this->events();   

   }

   function remove(){

      global $mainframe,$Itemid,$DT_mailfrom,$DT_fromname,$eventModifyNotification,$frontendEventNotification;

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

	  $cid = JRequest::getVar( 'cid', array(0), 'request', 'array' );
       if($DT_mailfrom == ""){
		  $conf = &JFactory::getConfig();
		  $DT_mailfrom = $conf->_registry['config']['data']->mailfrom;
	  }
	  if($DT_fromname==""){
		  $DT_fromname =$conf->_registry['config']['data']->fromname;
	  }
	 
	  $user = $this->getModel('user')->table;
	  $Tagparser = new DT_Tagparser();
	  $token_msg = "";
	  $token_msg .= '<p>'.JText::_('DT_EVENT_DELETE_MESSAGE').'</p><p>'.JText::_('DT_EVENT_NAME').': [EVENT_NAME]';
      $token_msg .= '<br />'.JText::_('DT_EVENT_DATE').': [EVENT_DATE]';
      $token_msg .= '<br />'.JText::_('DT_EVENT_TIME').': [EVENT_TIME]';
      $token_msg .= '<br />'.JText::_('DT_LOCATION').': [LOCATION]</p>';
	
	  $token_subject = JText::_('DT_EVENT_DELETE_SUBJECT');
	  $email = $frontendEventNotification;
	  if (is_array($cid)) 
	  foreach($cid as $id){

	      $event->load($id);
          $user->eventId = $id;
	  	  $user->load(0);
		   if($event->event_admin_email_set){
			  $DT_mailfrom = $event->event_admin_email_from_email;
			  $DT_fromname = $event->event_admin_email_from_name;
		  }
		  $user->TableEvent->overrideGlobal($user->TableEvent->slabId);
		  $message = $Tagparser->parsetags($token_msg,$user);
		  $subject = $Tagparser->parsetags($token_subject,$user);
		  $event->delete($id);
		  $emails = explode(";",$email);
		  if(isset($eventModifyNotification['delete'])) {
		   foreach ($emails  as $email) {
		    JUTility::sendMail($DT_mailfrom,$DT_fromname,$email,$subject,$message,1);
		   }
		  }

	  }
     
	 $mainframe->redirect( "index.php?option=".DTR_COM_COMPONENT."&controller=eventmanage&Itemid=$Itemid" );
     exit;
   }

   function unarchive(){

      $cid = JRequest::getVar( 'cid', array(0), 'request', 'array' );

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

	   if (is_array($cid)) 
	   foreach($cid as $id){

	     $archive = 0;

		 $query = "update #__dtregister_group_event set archive = ".$archive." where parent_id=".$id." or slabId=".$id; 
		 $event->rawquery($query);    

	  }

	  $this->events();

   }

	function events(){

       $archive = JRequest::getVar('archive',-1);

		if($archive==1){

		   JToolBarHelper::unarchiveList('unarchive');

		}else{

		  JToolBarHelper::archiveList('archive');

		}

        JToolBarHelper::divider();

        JToolBarHelper::publishList('publish');

    	JToolBarHelper::divider();

		JToolBarHelper::unpublishList('unpublish');

        JToolBarHelper::divider();

        JToolBarHelper::editList();

	    JToolBarHelper::divider();
        if($this->view->checkpermission_create_event()) {
        JToolBarHelper::addNew();
		
        JToolBarHelper::divider();

	    JToolBarHelper::editList('copy', JText::_( 'DT_COPY_EVENT') );
        }
	    JToolBarHelper::divider();

	    JToolBarHelper::divider();

        JToolBarHelper::deleteList();
		
		// JToolBarHelper::divider();
		
        //JToolBarHelper::custom('doexport','upload','upload',JText::_( 'DT_GOOGLE_EXPORT'),false);
	    $this->view->setLayout('list');

		$this->view->display();

	}

	function edit(){

	   JToolBarHelper::apply('apply');
       JToolBarHelper::divider();
       JToolBarHelper::save();
       JToolBarHelper::divider();
       JToolBarHelper::cancel('cancel');
       $row = $this->getModel('event')->table;
       $cid = JRequest::getVar( 'cid', array(0), 'request', 'array' );
       JRequest::setVar('slabId',$cid[0]); 
       $slabId = JRequest::getVar('slabId',0);
       $row->load($slabId);
	   $layout = 'add';
       $this->view->assign('row',$row);
       $this->view->setLayout($layout);
       $this->view->display();
       
	}

	function add(){
        JToolBarHelper::apply('apply');
        JToolBarHelper::divider();
        JToolBarHelper::save();
	    JToolBarHelper::divider();
        JToolBarHelper::cancel('cancel');
        $row = $this->getModel('event')->table;

	    $slabId = JRequest::getVar('slabId',0);

	    $row->load($slabId);

		$row->slabId = "";

	    $this->view->assign('row',$row);

	    $this->view->setLayout('add');

		$this->view->display();

	}

	function apply(){

	  global $mainframe,$Itemid,$frontendEventNotification,$DT_mailfrom,$DT_fromname,$eventModifyNotification;

	  $row = $this->getModel('event')->table;
	  $data = JRequest::getVar('data');
      $my = &JFactory::getUser();
	  if(is_array($data['event']['user_id']) && count(array_filter($data['event']['user_id'])) <1){
	     $data['event']['user_id'][] = $my->id;
		 $data['event']['user_id'] = array_filter($data['event']['user_id']);
	  }
      $type = "";
	  if(isset($_POST['data']['event']['slabId']) && $_POST['data']['event']['slabId'] > 0){
		$token_subject = JText::_('DT_EVENT_EDIT_SUBJECT');
		$token_msg = '<p>'.JText::_('DT_EVENT_EDIT_MESSAGE').'</p><p>'.JText::_('DT_EVENT_NAME').' [EVENT_NAME]!!</p>';
		$type = 'edit';
	  }else{
		   $token_subject = JText::_('DT_EVENT_CREATE_SUBJECT');
		   $token_msg = '<p>'.JText::_('DT_EVENT_CREATE_SUBJECT').'</p><p>'.JText::_('DT_EVENT_NAME').' [EVENT_NAME]!!</p>';
		   $type = 'create';
	  }
	  if($row->save($data)){

	      $email = $frontendEventNotification;
		  $user = $this->getModel('user')->table;
		  $Tagparser = new DT_Tagparser();
		 
		  if($eventModifyNotification[$type]) {
			$user->eventId = $row->slabId;
			$user->load(0);
			$message = $Tagparser->parsetags($token_msg,$user);
			$subject = $Tagparser->parsetags($token_subject,$user);
			$emails = explode(";",$email);
			 foreach ($emails  as $email)
			JUTility::sendMail($DT_mailfrom,$DT_fromname,$email,$subject,$message,1);
		  }

	  }else{
	  $mainframe->redirect("index.php?option=com_dtregister&controller=eventmanage&Itemid=$Itemid&task=edit&cid[]=".$row->slabId,$row->error);   

	  }
	
 $mainframe->redirect("index.php?option=com_dtregister&controller=eventmanage&Itemid=$Itemid&&task=edit&cid[]=".$row->slabId);

	}

	function editconfirm(){
	    global $mainframe,$Itemid;
	   	$data = DT_Session::get('event.data');
		$files = DT_Session::get('event.event_files');
		JRequest::setVar('event_files', $files, 'files');
		DT_Session::clear('event');
		$row = $this->getModel('event')->table;
		if($row->save($data) !== false){
			
		}else{
			 $mainframe->redirect("index.php?option=com_dtregister&controller=eventmanage&Itemid=$Itemid&task=edit&cid[]=".$row->slabId,$row->error);
		}
		$mainframe->redirect("index.php?option=com_dtregister&controller=eventmanage&Itemid=$Itemid");
	}
	
	function editcancel(){
	   global $mainframe,$Itemid;
	   DT_Session::clear('event');
	   $mainframe->redirect("index.php?option=com_dtregister&controller=eventmanage&Itemid=$Itemid");
	}

	function save(){

	  global $mainframe,$Itemid,$DT_mailfrom,$DT_fromname,$frontendEventNotification ,$eventModifyNotification;;

	  $row = $this->getModel('event')->table;

	  $data = JRequest::getVar('data');
	  $error = false;
	  if($data['event']['slabId']!=""){
		   $row->load($data['event']['slabId']);
		  
		   if(!$row->validDateChange($data)){

			   $this->error = JText::_("DT_REPTITIONS_NOT_VALID");

			   $error = true;

		   }
		  
	  }
	  
	  if($error){
		   DT_Session::set('event.data',$data);
		   $files = JRequest::getVar('event_files', null, 'files', 'array');
		   DT_Session::set('event.event_files',$files);
		   $this->view->setLayout('warning');
		   $this->view->assign('message',JText::_("DT_REPEAT_DELETE_WARNING"));
		   $this->view->display();
	  }else{
		
		$my = &JFactory::getUser();
		if(is_array($data['event']['user_id']) && count(array_filter($data['event']['user_id'])) <1){
	     $data['event']['user_id'][] = $my->id;
		 $data['event']['user_id'] = array_filter($data['event']['user_id']);
	    }
		
		$type = "";
		if(isset($data['event']['slabId']) && $data['event']['slabId'] > 0){
				$token_subject = JText::_('DT_EVENT_EDIT_SUBJECT');
				$token_msg = "";
				$token_msg .= '<p>'.JText::_('DT_EVENT_EDIT_MESSAGE').'</p><p>'.JText::_('DT_EVENT_NAME').': [EVENT_NAME]';
				$token_msg .= '<br />'.JText::_('DT_EVENT_DATE').': [EVENT_DATE]';
				$token_msg .= '<br />'.JText::_('DT_EVENT_TIME').': [EVENT_TIME]';
				$token_msg .= '<br />'.JText::_('DT_LOCATION').': [LOCATION]</p>';
				$type = 'edit';
		  }else{
		        $token_subject = JText::_('DT_EVENT_CREATE_SUBJECT');
				$token_msg = "";
				$token_msg .= '<p>'.JText::_('DT_EVENT_CREATE_MESSAGE').'</p><p>'.JText::_('DT_EVENT_NAME').': [EVENT_NAME]';
				$token_msg .= '<br />'.JText::_('DT_EVENT_DATE').': [EVENT_DATE]';
				$token_msg .= '<br />'.JText::_('DT_EVENT_TIME').': [EVENT_TIME]';
				$token_msg .= '<br />'.JText::_('DT_LOCATION').': [LOCATION]</p>';
				$type = 'create';
		  }
		  
		if($row->save($data) !== false){
		   
           global $eventListOrder;
		   $conf = DtrModel::getInstance('config','DtregisterModel');
		   $conf->updateEventorder($eventListOrder);
            
		  
		   $user = $this->getModel('user')->table;
		   $Tagparser = new DT_Tagparser();
		   
		  if($eventModifyNotification[$type]) {
			 $user->eventId = $row->slabId;
			 $user->load(0);
			 $message = $Tagparser->parsetags($token_msg,$user);
			 $subject = $Tagparser->parsetags($token_subject,$user);
			 $email = $frontendEventNotification;
			 $emails = explode(";",$email);
			 foreach ($emails  as $email)
			 JUTility::sendMail($DT_mailfrom, $DT_fromname,$email,$subject,$message,1);
		  }
		}else{
		$mainframe->redirect("index.php?option=com_dtregister&controller=eventmanage&Itemid=$Itemid&task=edit&cid[]=".$row->slabId,$row->error);
  
		}
 
		$mainframe->redirect("index.php?option=com_dtregister&controller=eventmanage&Itemid=$Itemid");

	  }

	}

	function getjevent(){

	   $jevt = $this->getModel('event')->tableJevt;

	   $data = $jevt->find(' evdet_id='.JRequest::getVar('eventId',0));

	   $rep = $jevt->parserule(JRequest::getVar('eventId',0));
 $params = JComponentHelper::getParams("com_jevents");
       $tz = $params->get("icaltimezonelive", "");
	   if ($tz != "" && is_callable("date_default_timezone_set"))
		{
			$timezone = date_default_timezone_get();
			//date_default_timezone_set($tz);
			$this->jeventstimezone = $timezone;
		}
	 //  prd($jevt->getObjData());

	   ob_clean();

	//   prd(json_encode($repjson));

	   if($data){

	      $data = $data[0];
		  $data->dtstart_date = strftime("%Y-%m-%d", $data->dtstart); 
		  $data->dtstart_time = strftime("%H:%M", $data->dtstart); 
		  $data->dtend_date = strftime("%Y-%m-%d", $data->dtend); 
		  $data->dtend_time = strftime("%H:%M", $data->dtend); 

	   if($rep)

	      $data->reprules = $jevt->getObjData();

	      echo json_encode($data);   

	   }else{

	      $array = array('error'=>'No event');

		  echo json_encode($array);

	   }
	if ($tz && is_callable("date_default_timezone_set"))
		{
			date_default_timezone_set($timezone);
		}
	   die;

	}

	  function orderup(){ 

	  $this->order(-1);

   }

     function orderdown(){

	  $this->order(1);

   }

	 function order($inc){

       global $mainframe,$Itemid;

	   $row = $this->getModel('event')->table;

       $cid = JRequest::getVar( 'cid', array(0), 'request', 'array' );

	   $uid = $cid[0];

	   $row->load( (int)$uid );
       global $eventListOrder ;
	   $con = "";
	   if($eventListOrder == 3) {
		   $con = ' category = "'.$row->category.'"' ;
	   }
	   $row->reorder($con);

	   $row->move( $inc, $con );     

       //$row->updateOrder();

	   $mainframe->redirect( "index.php?option=".DTR_COM_COMPONENT."&controller=eventmanage&Itemid=$Itemid" );

   }

     function saveorder(){

      global $mainframe,$Itemid;

	  $row = $this->getModel('event')->table;

	  $cid = JRequest::getVar( 'cid', array(0), 'request', 'array' );

	  $order = JRequest::getVar( 'order', array(0), '', 'array' );

	  $total = count( $cid );
      pr($order);
	  
	  if (is_array($order)) 
	  foreach( $order as $slabId => $ordering ) {

		$row->load( $slabId );

       if ($row->ordering != $ordering && $row->parent_id==0) {

			$row->ordering = $ordering;

           // prd($row->store());
           unset($row->repetition);
		   unset($row->timezone_show);
		   $row->store();
           
			if ($row->getError() !="") {

               JError::raiseError(500, $row->getError() );

				prd($row);

				exit();

			} 

		}

	 }

   $mainframe->redirect( "index.php?option=".DTR_COM_COMPONENT."&controller=eventmanage&Itemid=$Itemid" );

   }
    function removeimage(){
	   
	    $event = $this->getModel('event')->table;
		
		$slabId = JRequest::getVar('eventId',0);

		$event->slabId = $slabId;
		$event->removeImage();
		
   }
    function loadfield() {
      
	  $type = JRequest::getVar('type');
      $row = $this->getModel('event')->table;
       
      $slabId = JRequest::getVar('slabId',0);
	   
      $row->load($slabId);
	   
      $this->view->assign('row',$row);
	  $this->view->setLayout($type);

	  $this->view->display();
   
   }
   
    function showtags() {
   
   		 $this->view->setLayout('showtags');

		$this->view->display();
   
   }

}