<?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' );


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

		// Register Extra tasks
		$this->registerTask( 'accepted' , 'changeStatus');
		$this->registerTask( 'pending' , 'changeStatus');
		$this->registerTask( 'denied' , 'changeStatus');
		$this->registerTask( 'apply' , 'save');
	}
	

	/**
	 * 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 = JRequest::getVar('cid');
		$row= & JTable::getInstance('Rsevents_Subscriptions','Table');
		$idTicket = JRequest::getVar('IdTicket');
		$idSubscription = JRequest::getVar('IdSubscription');
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		
		//ticket details 
		$db->setQuery("SELECT TicketName FROM #__rsevents_tickets WHERE IdTicket = ".$idTicket);
		$ticketName = $db->loadResult();
		
		$numTickets = ($post['TicketsSubscribed'] == 0 || empty($post['TicketsSubscribed'])) ? 1 : $post['TicketsSubscribed'];
		
		//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();
		
		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.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."'");

				$subscriptionDetailsObj = $db->loadObject();
				
				//ticket info 
				$ticketinfo = $numTickets. ' '.JText::_('RSE_TICKET_SEPARATOR').' '.$ticketName;

				//categories
				$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 =".$subscriptionDetailsObj->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);
				
				$toChange = array('{EventName}','{EventDescription}','{EventStartDate}','{EventEndDate}','{EventHost}','{LocationName}','{LocationCity}','{CategoryName}','{username}','{LocationCountry}','{LocationZip}','{TicketInfo}');
				$with = array($subscriptionDetailsObj->EventName , $subscriptionDetailsObj->EventDescription , date($rseventsConfig['global.dateformat'],$subscriptionDetailsObj->EventStartDate) , date($rseventsConfig['global.dateformat'],$subscriptionDetailsObj->EventEndDate), $subscriptionDetailsObj->EventHost,$subscriptionDetailsObj->LocationName,$subscriptionDetailsObj->LocationCity,$categoryname, $subscriptionDetailsObj->username,$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." , TicketsSubscribed  = ".$post['TicketsSubscribed']." WHERE IdSubscription=".$row->IdSubscription);
				$db->query();
			} else
			{
				$db->setQuery("INSERT INTO #__rsevents_subscription_tickets (IdSubscription,IdTicket,TicketsSubscribed) VALUES ('".$row->IdSubscription."' , '".$idTicket."' , ".$post['TicketsSubscribed'].")");
				$db->query();
			}
			$msg = JText::_('RSE_SUBSCRIBER_SAVE' );
		} else {
			$msg = JText::_('RSE_SUBSCRIBER_SAVE_ERROR' );
		}
		
		switch(JRequest::getCmd('task'))
		{
			case 'apply' :
					$link = 'index.php?option=com_rsevents&task=editsubscription&cid='.$row->IdSubscription;

			break;
			
			case 'save' :
					$link = 'index.php?option=com_rsevents&task=listsubscriptions';

			break;
		}
		
		$this->setRedirect($link, $msg);
	}

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

	function delete()
	{
		$model = $this->getModel('subscriptions');
		$db = & JFactory::getDBO();
		$row =& JTable::getInstance('Rsevents_Subscriptions','Table');
				
		$cid=JRequest::getVar('cid',array(0),'request','array');
		if(is_array($cid)) $cid = $cid[0];

		$row->load($cid);
		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( 'index.php?option=com_rsevents&task=listsubscriptions', $msg );
	}
	
	function remove()
	{
		$db = &JFactory::getDBO();
		$model = $this->getModel('subscriptions');
		$row =& JTable::getInstance('Rsevents_Subscriptions','Table');
		$cids=JRequest::getVar('cid',array(0),'request','array');

		if(!empty($cids))
		{
			foreach($cids as $cid)
			{
				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( 'index.php?option=com_rsevents&task=listsubscriptions', $msg );
	}

	/**
	 * cancel editing a record
	 * @return void
	 */
	function cancel()
	{
		$msg = JText::_('RSE_CANCEL_OPERATION' );
		$this->setRedirect( 'index.php?option=com_rsevents&task=listsubscriptions', $msg );
	}
	
	function changeStatus()
	{
		global $mainframe;

		$db 	=& JFactory::getDBO();
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$cid		= JRequest::getVar( 'cid', array(), '', 'array' );
		$cids = implode( ',', $cid );
		
		
		switch($this->getTask())
		{
			case 'accepted':
				$state = 1;
				$db->setQuery("UPDATE #__rsevents_subscriptions SET ValidationDate=now() WHERE IdSubscription IN ( ". $cids ." )");
				$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 , s.IdSubscription 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 IN (".$cids.")");
				$subscriptionDetails = $db->loadObjectList();
					
				foreach($subscriptionDetails as $subscriptionDetailsObj)
				{
					
					//categories
					$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 =".$subscriptionDetailsObj->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 details
					$db->setQuery("SELECT IdTicket , TicketsSubscribed FROM #__rsevents_subscription_tickets WHERE IdSubscription = ".$subscriptionDetailsObj->IdSubscription);
					$ticketDetails = $db->loadObject();
					
					$numTickets = (empty($ticketDetails->TicketsSubscribed) || $ticketDetails->TicketsSubscribed == 0) ? 1 : $ticketDetails->TicketsSubscribed;
					
					$db->setQuery("SELECT TicketName FROM #__rsevents_tickets WHERE IdTicket = ".$ticketDetails->IdTicket);
					$ticketName = $db->loadResult();
					
					//ticket info
					$ticketinfo = $numTickets . ' '.JText::_('RSE_TICKET_SEPARATOR').' '.$ticketName;
					
					$toChange = array('{EventName}','{EventDescription}','{EventStartDate}','{EventEndDate}','{EventHost}','{LocationName}','{LocationCity}','{CategoryName}','{username}','{LocationCountry}','{LocationZip}','{TicketInfo}');
					$with = array($subscriptionDetailsObj->EventName , $subscriptionDetailsObj->EventDescription , date($rseventsConfig['global.dateformat'],$subscriptionDetailsObj->EventStartDate) , date($rseventsConfig['global.dateformat'],$subscriptionDetailsObj->EventEndDate), $subscriptionDetailsObj->EventHost,$subscriptionDetailsObj->LocationName,$subscriptionDetailsObj->LocationCity,$categoryname, $subscriptionDetailsObj->username,$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);
				}
				$action = JText::_('RSE_SUBSCRIBER_ACTION_AC');
			break;
			case 'pending':
			default:
				$state = 0;
				$db->setQuery("UPDATE #__rsevents_subscriptions SET ValidationDate='' WHERE IdSubscription IN ( ". $cids ." )");
				$db->query();
				$action = JText::_('RSE_SUBSCRIBER_ACTION_PE');
			break;
			case 'denied':
				$state = -1; 
				$db->setQuery("UPDATE #__rsevents_subscriptions SET ValidationDate='' WHERE IdSubscription IN ( ". $cids ." )");
				$db->query();
				$action = JText::_('RSE_SUBSCRIBER_ACTION_DE');
			break;
		}
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1)
		{
			JError::raiseError(500, JText::_('RSE_SUBSCRIBER_SELECT_ACTION' .$action, true ) );
		}
		
		$query = 'UPDATE #__rsevents_subscriptions'
		. ' SET SubscriptionState = ' . (int) $state
		. ' WHERE IdSubscription IN ( '. $cids .' )'
		;
		$db->setQuery( $query );
		if (!$db->query())
		{
			JError::raiseError(500, $db->getErrorMsg() );
		}

		$mainframe->redirect( 'index.php?option=com_rsevents&task=listsubscriptions' );
	}

	
}