<?php
/**
* @version 1.0.0
* @package RSEvents! 1.0.0
* @copyright (C) 2009 www.rsjoomla.com
* @license GPL, http://www.gnu.org/copyleft/gpl.html
*/

// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

if (file_exists(JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'helpers'.DS.'rsevents.php'))
	require_once(JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'helpers'.DS.'rsevents.php');

class rseventsControllerSubscriptions extends rseventsController
{
	/**
	 * constructor (registers additional tasks to methods)
	 * @return void
	 */
	function __construct()
	{
		parent::__construct();

	}
	

	/**
	 * save a record (and redirect to main page)
	 * @return void
	 */
	function save()
	{
		global $mainframe;
		$db= JFactory::getDBO();
		$model = $this->getModel('subscriptions');
		$post=JRequest::get('post');
		$cid = intval(JRequest::getVar('cid'));
		$row= & JTable::getInstance('Rsevents_Subscriptions','Table');
		$idTicket = intval(JRequest::getVar('IdTicket'));
		$idEvent = intval(JRequest::getVar('IdEvent',0,'request'));
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		
		
		
		//get the itemId
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		//get current status
		$db->setQuery("SELECT SubscriptionState FROM #__rsevents_subscriptions WHERE IdSubscription='".$cid."'");
		$SubscriptionState = $db->loadResult();
		
		if(!$row->bind($post)) {
			return JError::raiseWarning(500, $row->getError());
		}
		
		$row->SubscriptionDate = strtotime(date('Y-m-d'));
		$db->setQuery("SELECT IdEvent FROM #__rsevents_tickets WHERE IdTicket='".$idTicket."'");
		$row->IdEvent = $db->loadResult();
		
		$mainframe->triggerEvent('rse_onBeforeStoreSubscriber',array(array('data'=>&$row)));
		
		if ($row->store()) {

			if($post['SubscriptionState'] == 1)
			{
				// Send mail if the status of the subscription is accepted
				
				$db->setQuery("SELECT e.IdEvent ,e.EventName ,e.EventDescription ,e.EventStartDate , e.EventEndDate , e.EventHost , l.LocationName, l.LocationCity , l.LocationZip , l.LocationCountry , u.username, s.Email FROM #__rsevents_events e LEFT JOIN #__rsevents_subscriptions s ON s.IdEvent = e.IdEvent LEFT JOIN #__users u ON u.id=s.IdUser LEFT JOIN #__rsevents_locations l ON e.IdLocation=l.IdLocation WHERE s.IdSubscription='".$cid."'");

				$subscriptionDetailsObj = $db->loadObject();
				
				//category details
				$categoryname = array();
				$db->setQuery("SELECT c.CategoryName , c.IdCategory FROM #__rsevents_categories c LEFT JOIN #__rsevents_events_cat ec ON ec.IdCategory = c.IdCategory WHERE ec.IdEvent =".$idEvent);
				$categs = $db->loadObjectList();
				
				foreach($categs as $categ)
					$categoryname[] = '<a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=listcategoryevents&cid='.$categ->IdCategory.':'.JFilterOutput::stringURLSafe($categ->CategoryName).$itemId)).'">'.$categ->CategoryName.'</a>';
				
				$categoryname = implode(',',$categoryname);
				
				//ticket info
				$ticketinfo = $post['NumTickets'] . ' '.JText::_('RSE_TICKET_SEPARATOR').' '.$post['TicketName'];
				
				$eventLink = '<a target="_blank" href="'.html_entity_decode(JRoute::_(JURI::root().'index.php?option=com_rsevents&view=events&layout=show&cid='.$subscriptionDetailsObj->IdEvent.':'.JFilterOutput::stringURLSafe($subscriptionDetailsObj->EventName).$itemId)).'">'.$subscriptionDetailsObj->EventName.'</a>';

				$toChange = array('{EventName}','{EventDescription}','{EventStartDate}','{EventEndDate}','{EventHost}','{LocationName}','{LocationCity}','{CategoryName}','{username}','{EventLink}','{LocationCountry}','{LocationZip}','{TicketInfo}');
				$with = array($subscriptionDetailsObj->EventName , $subscriptionDetailsObj->EventDescription , rseventsHelper::translateDate(date($rseventsConfig['global.dateformat'],$subscriptionDetailsObj->EventStartDate)) , rseventsHelper::translateDate(date($rseventsConfig['global.dateformat'],$subscriptionDetailsObj->EventEndDate)), $subscriptionDetailsObj->EventHost,$subscriptionDetailsObj->LocationName,$subscriptionDetailsObj->LocationCity,$categoryname, $subscriptionDetailsObj->username,$eventLink,$subscriptionDetailsObj->LocationCountry,$subscriptionDetailsObj->LocationZip,$ticketinfo);
				
				
				$from		= $rseventsConfig['emails.from'];
				$fromName	= $rseventsConfig['emails.from.name'];
				$to			= $subscriptionDetailsObj->Email;
				$subject	= $rseventsConfig['emails.activation.subject'];
				$body		= $rseventsConfig['emails.activation.content'];
				$body		= str_replace($toChange , $with ,$body);
				$mode		= $rseventsConfig['emails.activation.type'];
				$replyto	= $rseventsConfig['emails.reply'];
				$cc			= !empty($rseventsConfig['emails.cc']) ? $rseventsConfig['emails.cc'] : null;
				$bcc		= !empty($rseventsConfig['emails.bcc']) ? $rseventsConfig['emails.bcc'] : null;
				
				if($SubscriptionState != 1 && $rseventsConfig['emails.activation.enable'] == 1)
				JUtility::sendMail($from , $fromName , $to , $subject , $body , $mode , $cc , $bcc , null , $replyto);
				
			}
			
			if($cid)
			{
				$db->setQuery("UPDATE #__rsevents_subscription_tickets SET IdTicket ='".$idTicket."' WHERE IdSubscription=".$row->IdSubscription);
				$db->query();
			} else
			{
				$db->setQuery("INSERT INTO #__rsevents_subscription_tickets (IdSubscription,IdTicket,TicketsSubscribed) VALUES ('".$row->IdSubscription."' , '".$idTicket."' , '1')");
				$db->query();
			}
			$msg = JText::_( 'RSE_SUBSCRIBER_SAVE' );
		} else {
			$msg = JText::_( 'RSE_SUBSCRIBER_SAVE_ERROR' );
		}
		
		$mainframe->triggerEvent('rse_onAfterStoreSubscriber',array(array('data'=>&$row)));
		
		$this->setRedirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=subscriptions&IdEvent='.$idEvent.$itemId)), $msg);
	}

	/**
	 * remove record(s)
	 * @return void
	 */
	

	function delete()
	{
		$model = $this->getModel('subscriptions');
		$db = & JFactory::getDBO();
		$row =& JTable::getInstance('Rsevents_Subscriptions','Table');
		$user= &JFactory::getUser();
		
		//get the itemId
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		$userId = rseventsModelSubscriptions::getSubscriptionUser();
		$cid=JRequest::getVar('cid',0,'request');
		$cid = intval($cid);
		$idEvent		= JRequest::getVar( 'IdEvent', 0, 'request');
		$idEvent = intval($idEvent);
		$row->load($cid);
		
		if($user->usertype == 'Super Administrator' || $user->id == $userId)
		{	
			if(!$row->delete($cid)) 
			{
				$msg = JText::_( 'RSE_SUBSCRIBER_DELETE_ERROR' );
			} else 
			{
				$db->setQuery("DELETE FROM #__rsevents_subscription_tickets WHERE IdSubscription=".$cid);
				$db->query();
				$msg = JText::_( 'RSE_SUBSCRIBER_DELETE1' );
			}
			$this->setRedirect( html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=subscriptions&IdEvent='.$idEvent.$itemId)), $msg );
		} else $this->setRedirect( html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$idEvent.$itemId)), JText::_('RSE_ACCESS_DENIED') );
	}

	
	function pending()
	{
		global $mainframe;
		
		$model 			= $this->getModel('subscriptions');
		$db 			=& JFactory::getDBO();
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$user			= &JFactory::getUser();
		$userId 		= rseventsModelSubscriptions::getSubscriptionUser();
		$cid			= intval(JRequest::getVar( 'cid', 0, 'request'));
		$idEvent		= intval(JRequest::getVar( 'IdEvent', 0, 'request'));
		
		//get the itemId
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		if($user->usertype == 'Super Administrator' || $userId == $user->id)
		{
			$state = 0;
			$db->setQuery("UPDATE #__rsevents_subscriptions SET ValidationDate='' WHERE IdSubscription ='". $cid ." '");
			$db->query();
			$db->setQuery("UPDATE #__rsevents_subscriptions SET SubscriptionState = '".$state."' WHERE IdSubscription = '". $cid ."'");
			$db->query();
			
			$mainframe->redirect( html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=subscriptions&IdEvent='.$idEvent.$itemId)) );
		} else $mainframe->redirect( html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events'.$itemId)) , JText::_('RSE_ACCESS_DENIED') );
	}
	
	function denied()
	{
		global $mainframe;
		
		$model 			= $this->getModel('subscriptions');
		$db 			= & JFactory::getDBO();
		$user			= &JFactory::getUser();
		$userId 		= rseventsModelSubscriptions::getSubscriptionUser();
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$cid			= intval(JRequest::getVar( 'cid', 0, 'request'));
		$idEvent		= intval(JRequest::getVar( 'IdEvent', 0, 'request'));
		
		//get the itemId
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		if($user->usertype == 'Super Administrator' || $userId == $user->id)
		{
			$state = -1;
			$db->setQuery("UPDATE #__rsevents_subscriptions SET ValidationDate='' WHERE IdSubscription ='". $cid ." '");
			$db->query();
			$db->setQuery("UPDATE #__rsevents_subscriptions SET SubscriptionState = '".$state."' WHERE IdSubscription = '". $cid ."'");
			$db->query();
			
			$mainframe->redirect( html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=subscriptions&IdEvent='.$idEvent.$itemId) ));
		} else $mainframe->redirect( html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events'.$itemId)) , JText::_('RSE_ACCESS_DENIED') );
	}
	
	function accepted()
	{
		global $mainframe;

		$model 			= $this->getModel('subscriptions');
		$db 			= &JFactory::getDBO();
		$user			= &JFactory::getUser();
		$userId 		= rseventsModelSubscriptions::getSubscriptionUser();
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$cid			= intval(JRequest::getVar( 'cid', 0, 'request'));
		$idEvent		= intval(JRequest::getVar( 'IdEvent', 0, 'request'));
		
		//ticket details
		$db->setQuery("SELECT IdTicket,TicketsSubscribed FROM #__rsevents_subscription_tickets WHERE IdSubscription = ".$cid);
		$ticketDetails = $db->loadObject();
		
		$numTickets = ($ticketDetails->TicketsSubscribed == 0 || empty($ticketDetails->TicketsSubscribed) ) ? 1 : $ticketDetails->TicketsSubscribed;
		
		$db->setQuery("SELECT TicketName FROM #__rsevents_tickets WHERE IdTicket = ".$ticketDetails->IdTicket);
		$ticketName = $db->loadResult();
		
		//get the itemId
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;

		if($user->usertype == 'Super Administrator' || $userId == $user->id)
		{
			$state = 1;
			$db->setQuery("UPDATE #__rsevents_subscriptions SET ValidationDate=now() WHERE IdSubscription = '". $cid ."'");
			$db->query();
			$db->setQuery("UPDATE #__rsevents_subscriptions SET SubscriptionState = '".$state."' WHERE IdSubscription = '". $cid ."'");
			$db->query();
			
			
			// Send mail if the status of the subscription is accepted
			
			$db->setQuery("SELECT e.IdEvent , e.EventName ,e.EventDescription ,e.EventStartDate , e.EventEndDate , e.EventHost , l.LocationName, l.LocationCity , l.LocationCountry , l.LocationZip , u.username, s.Email FROM #__rsevents_events e LEFT JOIN #__rsevents_subscriptions s ON s.IdEvent = e.IdEvent LEFT JOIN #__users u ON u.id=s.IdUser LEFT JOIN #__rsevents_locations l ON e.IdLocation=l.IdLocation WHERE s.IdSubscription ='".$cid."'");
			$subscriptionDetails = $db->loadObjectList();
				
			foreach($subscriptionDetails as $subscriptionDetailsObj)
			{
				$eventLink = '<a target="_blank" href="'.html_entity_decode(JRoute::_(JURI::root().'index.php?option=com_rsevents&view=events&layout=show&cid='.$subscriptionDetailsObj->IdEvent.':'.JFilterOutput::stringURLSafe($subscriptionDetailsObj->EventName).$itemId)).'">'.$subscriptionDetailsObj->EventName.'</a>';
				
				//category details
				$categoryname = array();
				$db->setQuery("SELECT c.CategoryName , c.IdCategory FROM #__rsevents_categories c LEFT JOIN #__rsevents_events_cat ec ON ec.IdCategory = c.IdCategory WHERE ec.IdEvent =".$idEvent);
				$categs = $db->loadObjectList();
				
				foreach($categs as $categ)
					$categoryname[] = '<a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=listcategoryevents&cid='.$categ->IdCategory.':'.JFilterOutput::stringURLSafe($categ->CategoryName).$itemId)).'">'.$categ->CategoryName.'</a>';
				
				$categoryname = implode(',',$categoryname);
				
				//ticket info
				$ticketinfo = $numTickets . ' '.JText::_('RSE_TICKET_SEPARATOR').' '.$ticketName;
				
				$toChange = array('{EventName}','{EventDescription}','{EventStartDate}','{EventEndDate}','{EventHost}','{LocationName}','{LocationCity}','{CategoryName}','{username}','{EventLink}','{LocationCountry}','{LocationZip}','{TicketInfo}');
				$with = array($subscriptionDetailsObj->EventName , $subscriptionDetailsObj->EventDescription , rseventsHelper::translateDate(date($rseventsConfig['global.dateformat'],$subscriptionDetailsObj->EventStartDate)) , rseventsHelper::translateDate(date($rseventsConfig['global.dateformat'],$subscriptionDetailsObj->EventEndDate)), $subscriptionDetailsObj->EventHost,$subscriptionDetailsObj->LocationName,$subscriptionDetailsObj->LocationCity,$categoryname, $subscriptionDetailsObj->username,$eventLink,$subscriptionDetailsObj->LocationCountry,$subscriptionDetailsObj->LocationZip,$ticketinfo);
				
				
				$from		= $rseventsConfig['emails.from'];
				$fromName	= $rseventsConfig['emails.from.name'];
				$to			= $subscriptionDetailsObj->Email;
				$subject	= $rseventsConfig['emails.activation.subject'];
				$body		= $rseventsConfig['emails.activation.content'];
				$body		= str_replace($toChange , $with ,$body);
				$mode		= $rseventsConfig['emails.activation.type'];
				$replyto	= $rseventsConfig['emails.reply'];
				$cc			= !empty($rseventsConfig['emails.cc']) ? $rseventsConfig['emails.cc'] : null;
				$bcc		= !empty($rseventsConfig['emails.bcc']) ? $rseventsConfig['emails.bcc'] : null;
				
				if($rseventsConfig['emails.activation.enable'] == 1) JUtility::sendMail($from , $fromName , $to , $subject , $body , $mode , $cc , $bcc , null , $replyto);
			}


			$mainframe->redirect( html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=subscriptions&IdEvent='.$idEvent.$itemId) ));
		} else $mainframe->redirect( html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events'.$itemId)) , JText::_('RSE_ACCESS_DENIED') );
	}

	
}