<?php

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

require_once( JPATH_BASE . DS . 'components' . DS . 'com_community' . DS . 'libraries' . DS . 'core.php');

class plgCommunityPlg_Rsevents extends CApplications
{

	var $name 		= "Rsevents Application";
	var $_name		= 'rsevents';
	var $_path		= '';
	var $_user		= '';
	var $_my		= '';

    function plgCommunityPlg_Rsevents(& $subject, $config)
    {
    	$this->_path	= JPATH_BASE . DS . 'administrator' . DS . 'components' . DS . 'com_rsevents';
		$this->_user	= & CFactory::getActiveProfile();
		$this->_my		= & CFactory::getUser();
			
		parent::__construct($subject, $config);
    }

	/**
	 * Return itemid for Rsevents
	 */	 	
	function getItemid()
	{
		$db =& JFactory::getDBO();
		$Itemid = 0;

    	if ($Itemid < 1)
		{
        	$db->setQuery("SELECT id FROM #__menu WHERE link LIKE '%index.php?option=com_rsevents%' AND published = 1");
        	$Itemid = $db->loadResult();

        	if ($Itemid < 1)
			{
         	   $Itemid = 0;
        	}
    	}
	    
	    return $Itemid;
	}
	
	function onProfileDisplay()
	{
		// Load language
		JPlugin::loadLanguage( 'plg_rsevents', JPATH_ADMINISTRATOR );
				
		// Attach CSS
		$document	=& JFactory::getDocument();
		$css		= JURI::base() . 'plugins/community/plg_rsevents/style.css';
		$document->addStyleSheet($css);
		
		
		if( !file_exists( $this->_path . DS . 'rsevents.php' ) )
		{
			$rse_exist = 0;
			$content = "<div class=\"icon-nopost\"><img src='".JURI::base()."components/com_community/assets/error.gif' alt=\"\" /></div>";	
			$content .= "<div class=\"content-nopost\">".JText::_('RSE_NOT_INSTALLED')."</div>";
		}else
		{
			$user		= & CFactory::getActiveProfile();
			$userName = $user->getDisplayName();
			$userId = $user->id;
			$events	= $this->_getEvents();
			$itemId = $this->getItemid();
			$rse_exist = 1;
			
			$cache =& JFactory::getCache('plgCommunityPlg_Rsevents');
			$cache->setCaching($this->params->get('cache', 1));
			$callback = array('plgCommunityPlg_Rsevents', '_getRseventsHTML');
			
			$content = $cache->call($callback, $userName, $userId, $rse_exist, $events, $itemId);
		}	
		return $content;
	}
	
	function _getRseventsHTML($userName, $userId, $rse_exist, $events, $itemId)
	{
		ob_start();
		// Verify if rsevents is installed
		if($rse_exist)
		{			
			if( !$events )
			{
				?>
				<div class="icon-nopost">
		            <img src="<?php echo JURI::base(); ?>plugins/community/plg_rsevents/favicon.png" alt="" />
		        </div>
		        <div class="content-nopost">
		            <?php echo $userName; ?> <?php echo JText::_('RSE_NO_EVENTS'); ?>
		        </div>
				<?php
			}
			else
			{
			?>
				<div id="community-rsevents-wrap">
				  <div class="ctitle"><?php echo JText::_('RSE_GOING') ?></div>
				    <table cellpadding="2" cellspacing="0" border="0" width="100%">
					
					<?php foreach( $events['isregistered'] as $event ): ?>
					    <tr>
					        <td width="15">
					            <img src="<?php echo JURI::base(); ?>plugins/community/plg_rsevents/favicon.png" alt="" />
					        </td>
					        <td valign="top">
					            <a href="<?php echo JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid=' . $event->IdEvent . '&Itemid=' . $itemId);?>">
									<?php echo $event->EventName; ?>
								</a>
								<?php if( !empty( $event->LocationName ) ): ?>
									<?php echo JText::_('RSE_AT'); ?>
									<a href="<?php echo JRoute::_( 'index.php?option=com_rsevents&view=locations&layout=show&cid=' . $event->IdLocation . '&IdEvent='.$event->IdEvent.'&Itemid=' . $itemId);?>"><?php echo $event->LocationName;?></a>
								<?php endif; ?>
							</td>
					        
					        <td width="150" align="right">
							<?php
								$start		= new JDate($event->EventStartDate);
								echo $start->toFormat( '%d/%m/%Y' );
								echo ' - ';
								$end		= new JDate($event->EventEndDate);
								echo $end->toFormat( '%d/%m/%Y' );
							?>
					        </td>
						</tr>
					<?php endforeach; ?>
					</table>					
					
          <div class="ctitle"><?php echo JText::_('RSE_CREATED') ?></div>
            <table cellpadding="2" cellspacing="0" border="0" width="100%">
          
          <?php foreach( $events['manages'] as $event ): ?>
              <tr>
                  <td width="15">
                      <img src="<?php echo JURI::base(); ?>plugins/community/plg_rsevents/favicon.png" alt="" />
                  </td>
                  <td valign="top">
                      <a href="<?php echo JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid=' . $event->IdEvent . '&Itemid=' . $itemId);?>">
                  <?php echo $event->EventName; ?>
                </a>
                <?php if( !empty( $event->LocationName ) ): ?>
                  <?php echo JText::_('RSE_AT'); ?>
                  <a href="<?php echo JRoute::_( 'index.php?option=com_rsevents&view=locations&layout=show&cid=' . $event->IdLocation . '&IdEvent='.$event->IdEvent.'&Itemid=' . $itemId);?>"><?php echo $event->LocationName;?></a>
                <?php endif; ?>
              </td>
                  
                  <td width="150" align="right">
              <?php
                $start    = new JDate($event->EventStartDate);
                echo $start->toFormat( '%d/%m/%Y' );
                echo ' - ';
                $end    = new JDate($event->EventEndDate);
                echo $end->toFormat( '%d/%m/%Y' );
              ?>
                  </td>
            </tr>
          <?php endforeach; ?>
          </table>
				</div>
			<?php
			}
		}
		
		$content	= ob_get_contents();
		ob_end_clean();
		return $content;
	}
	
	/**
	 * Returns the list of events and its properties for the specific browsed user
	 * 
	 * @access private
	 * 
	 * returns	Array	An array of object list
	 **/	 	
	function _getEvents()
	{
		$db		=& JFactory::getDBO();
		$limit	= '10';
		
		// events where user is registered
	
		$query = "SELECT e.IdEvent , e.EventName , e.EventStartDate , e.EventEndDate , l.IdLocation , l.LocationName FROM #__rsevents_events e LEFT JOIN #__rsevents_locations l ON l.IdLocation=e.IdLocation LEFT JOIN #__rsevents_subscriptions s ON  s.IdEvent=e.IdEvent WHERE e.published = '1' AND e.EventType = 1 AND s.IdUser='".$this->_user->id."'";
		
		$db->setQuery( $query );

		$registered = $db->loadObjectList();		
		
		// events he created
		$query  = "SELECT e.IdEvent , e.EventName , e.EventStartDate , e.EventEndDate , l.IdLocation , l.LocationName FROM #__rsevents_events e LEFT JOIN #__rsevents_locations l ON l.IdLocation=e.IdLocation WHERE e.published = '1' AND e.EventType = 1 AND e.IdUser='".$this->_user->id."'";
	
    $db->setQuery( $query );

    $managed = $db->loadObjectList();

		return array('isregistered' => $registered, 'manages' => $managed); 
	}
}
