<?php
/**
 * @brief		Clubs List
 * @author		<a href='https://www.invisioncommunity.com'>Invision Power Services, Inc.</a>
 * @copyright	(c) Invision Power Services, Inc.
 * @license		https://www.invisioncommunity.com/legal/standards/
 * @package		Invision Community
 * @since		13 Feb 2017
 */

namespace IPS\core\modules\front\clubs;

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
	header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
	exit;
}

/**
 * Clubs List
 */
class _directory extends \IPS\Dispatcher\Controller
{
	/**
	 * Execute
	 *
	 * @return	void
	 */
	public function execute()
	{
		/* Permission check */
		if ( !\IPS\Settings::i()->clubs )
		{
			\IPS\Output::i()->error( 'no_module_permission', '2C349/2', 403, '' );
		}
		
		/* CSS */
		\IPS\Output::i()->cssFiles = array_merge( \IPS\Output::i()->cssFiles, \IPS\Theme::i()->css( 'styles/clubs.css', 'core', 'front' ) );
		if ( \IPS\Theme::i()->settings['responsive'] )
		{
			\IPS\Output::i()->cssFiles = array_merge( \IPS\Output::i()->cssFiles, \IPS\Theme::i()->css( 'styles/clubs_responsive.css', 'core', 'front' ) );
		}

		/* JS */
		\IPS\Output::i()->jsFiles = array_merge( \IPS\Output::i()->jsFiles, \IPS\Output::i()->js( 'front_clubs.js', 'core', 'front' ) );
		
		/* Location for online list */
		\IPS\Session::i()->setLocation( \IPS\Http\Url::internal( 'app=core&module=clubs&controller=directory', 'front', 'clubs_list' ), array(), 'loc_clubs_directory' );

		/* Pass up */
		parent::execute();
	}
	
	/**
	 * List
	 *
	 * @return	void
	 */
	protected function manage()
	{	
		$baseUrl = \IPS\Http\Url::internal( 'app=core&module=clubs&controller=directory', 'front', 'clubs_list' );
		
		/* All Clubs: Sort */
		$sortOption = \IPS\Settings::i()->clubs_default_sort;
		if ( isset( \IPS\Request::i()->sort ) and in_array( \IPS\Request::i()->sort, array( 'last_activity', 'members', 'content', 'created', 'name' ) ) )
		{
			$sortOption = \IPS\Request::i()->sort;
		}
		
		/* All Clubs: Filters */
		$filters = array();
		$mineOnly = FALSE;
		if ( isset( \IPS\Request::i()->filter ) and \IPS\Request::i()->filter === 'mine' )
		{
			$mineOnly = TRUE;
			$baseUrl = $baseUrl->setQueryString( 'filter', 'mine' );
		}
		foreach ( \IPS\Member\Club\CustomField::fields() as $field )
		{
			$k = "f{$field->id}";
			if ( $field->filterable and isset( \IPS\Request::i()->$k ) )
			{
				switch ( $field->type )
				{
					case 'Checkbox':
					case 'YesNo':
						if ( in_array( \IPS\Request::i()->$k, array( 0, 1 ) ) )
						{
							$filters[ $field->id ] = \IPS\Request::i()->$k;
							$baseUrl = $baseUrl->setQueryString( 'f' . $field->id, \IPS\Request::i()->$k );
						}
						break;
						
					case 'CheckboxSet':
					case 'Radio':
					case 'Select':
						$options = json_decode( $field->extra, TRUE );
						foreach ( \IPS\Request::i()->$k as $id )
						{
							if ( isset( $options[ $id ] ) )
							{
								if( $field->type == 'CheckboxSet' )
								{
									$filters[ $field->id ][ $id ] = $id;
								}
								else
								{
									$filters[ $field->id ][ $id ] = $options[ $id ];
								}
							}
						}
						$baseUrl = $baseUrl->setQueryString( 'f' . $field->id, array_keys( $filters[ $field->id ] ) );
						
						break;
				}
			}
		}
		
		/* Get Featured Clubs */
		$featuredClubs = \IPS\Member\Club::clubs( \IPS\Member::loggedIn(), NULL, 'RAND()', FALSE, array(), 'featured=1' );
		
		/* Get All Clubs */
		$perPage = 24;
		$page = isset( \IPS\Request::i()->page ) ? intval( \IPS\Request::i()->page ) : 1;
		$allClubs = \IPS\Member\Club::clubs( \IPS\Member::loggedIn(), array( ( $page - 1 ) * $perPage, $perPage ), $sortOption, $mineOnly, $filters );
		$pagination = \IPS\Theme::i()->getTemplate( 'global', 'core', 'global' )->pagination( $baseUrl, ceil( $allClubs->count( TRUE ) / $perPage ), $page, $perPage );
		
		/* Get my clubs */
		$myClubsActivity = NULL;
		if ( \IPS\Member::loggedIn()->member_id )
		{
			$myClubsActivity = \IPS\Content\Search\Query::init()->filterByClub( \IPS\Member::loggedIn()->clubs() )->setLimit(6)->setOrder( \IPS\Content\Search\Query::ORDER_NEWEST_UPDATED )->search();
		}
		
		/* Build Map */
		$mapMarkers = NULL;
		if ( \IPS\Settings::i()->googlemaps and \IPS\Settings::i()->google_maps_api_key )
		{
			$mapMarkers = array();
			
			$where = array( array( 'location_lat IS NOT NULL' ) );
			if ( !\IPS\Member::loggedIn()->member_id )
			{
				$where[] = array( "type<>?", \IPS\Member\Club::TYPE_PRIVATE );
			}
			elseif ( !\IPS\Member::loggedIn()->modPermission('can_access_all_clubs') )
			{
				$where[] = array( "( type<>? OR status IN('" . \IPS\Member\Club::STATUS_MEMBER .  "','" . \IPS\Member\Club::STATUS_MODERATOR . "','" . \IPS\Member\Club::STATUS_LEADER . "') )", \IPS\Member\Club::TYPE_PRIVATE );
			}
			
			$select = \IPS\Db::i()->select( array( 'id', 'name', 'location_lat', 'location_long' ), 'core_clubs', $where );
			if ( \IPS\Member::loggedIn()->member_id )
			{
				$select->join( 'core_clubs_memberships', array( 'club_id=id AND member_id=?', \IPS\Member::loggedIn()->member_id ) );
			}
			
			foreach ( $select as $club )
			{
				$mapMarkers[ $club['id'] ] = array(
					'lat'	=> floatval( $club['location_lat'] ),
					'long'	=> floatval( $club['location_long'] ),
					'title'	=> $club['name']
				);
			}
		}

		if ( \IPS\Member::loggedIn()->member_id )
		{
			\IPS\Output::i()->sidebar['contextual'] = \IPS\Theme::i()->getTemplate('clubs')->myClubsSidebar( \IPS\Member\Club::clubs( \IPS\Member::loggedIn(), 10, 'last_activity', TRUE ), $myClubsActivity );
		}
				
		/* Display */
		\IPS\Output::i()->title = \IPS\Member::loggedIn()->language()->addToStack('module__core_clubs');
		\IPS\Output::i()->output = \IPS\Theme::i()->getTemplate('clubs')->directory( $featuredClubs, $allClubs, $pagination, $baseUrl, $sortOption, $myClubsActivity, $mapMarkers );
	}
	
	/**
	 * Filter Form
	 *
	 * @return	void
	 */
	protected function filters()
	{		
		$fields = \IPS\Member\Club\CustomField::roots();
		
		$form = new \IPS\Helpers\Form('filter', 'filter');
		
		if ( \IPS\Member::loggedIn()->member_id )
		{
			$form->add( new \IPS\Helpers\Form\Radio( 'club_filter_type', isset( \IPS\Request::i()->filter ) ? \IPS\Request::i()->filter : 'all', TRUE, array( 'options' => array(
				'all'	=> 'all_clubs',
				'mine'	=> 'my_clubs'
			) ) ) );
		}
		
		foreach ( $fields as $field )
		{
			if ( $field->filterable )
			{
				$k = "f{$field->id}";
				switch ( $field->type )
				{
					case 'Checkbox':
					case 'YesNo':
						$input = new \IPS\Helpers\Form\CheckboxSet( 'field_' . $field->id, isset( \IPS\Request::i()->$k ) ? \IPS\Request::i()->$k : array( 1, 0 ), FALSE, array( 'options' => array(
							1			=> 'yes',
							0			=> 'no',
						) ) );
						$input->label = $field->_title;
						$form->add( $input );
						break;
						
					case 'CheckboxSet':
					case 'Radio':
					case 'Select':
						$options = json_decode( $field->extra, TRUE );
						$input = new \IPS\Helpers\Form\CheckboxSet( 'field_' . $field->id, isset( \IPS\Request::i()->$k ) ? \IPS\Request::i()->$k : array_keys( $options ), FALSE, array( 'options' => $options ) );
						$input->label = $field->_title;
						$form->add( $input );
						break;
				}
			}
		}
		
		if ( $values = $form->values() )
		{
			$url = \IPS\Http\Url::internal( 'app=core&module=clubs&controller=directory', 'front', 'clubs_list' );
			
			if ( \IPS\Member::loggedIn()->member_id and $values['club_filter_type'] === 'mine' )
			{
				$url = $url->setQueryString( 'filter', 'mine' );
			}
			
			foreach ( $fields as $field )
			{
				if ( $field->filterable )
				{					
					switch ( $field->type )
					{
						case 'Checkbox':
						case 'YesNo':
							if ( count( $values[ 'field_' . $field->id ] ) === 1 )
							{
								$url = $url->setQueryString( 'f' . $field->id, array_pop( $values[ 'field_' . $field->id ] ) );
							}
							break;
							
						case 'CheckboxSet':
						case 'Radio':
						case 'Select':
							$options = json_decode( $field->extra, TRUE );
							if ( count( $values[ 'field_' . $field->id ] ) > 0 and count( $values[ 'field_' . $field->id ] ) < count( $options ) )
							{
								$url = $url->setQueryString( 'f' . $field->id, $values[ 'field_' . $field->id ] );
							}
							break;
					}
				}
			}
			
			\IPS\Output::i()->redirect( $url );
		}
		
		if( \IPS\Request::i()->isAjax() )
		{
			\IPS\Output::i()->output = $form->customTemplate( array( call_user_func_array( array( \IPS\Theme::i(), 'getTemplate' ), array( 'forms', 'core' ) ), 'popupTemplate' ) );
		}
		else
		{
			\IPS\Output::i()->output = $form;
		}
	}
	
	/**
	 * Create
	 *
	 * @return	void
	 */
	protected function create()
	{
		$availableTypes = array();
		if ( \IPS\Member::loggedIn()->member_id ) // Guests can't create any type of clubs
		{
			foreach ( explode( ',', \IPS\Member::loggedIn()->group['g_create_clubs'] ) as $type )
			{
				if ( $type !== '' )
				{
					$availableTypes[ $type ] = 'club_type_' . $type;
				}
			}
		}
		if ( !$availableTypes )
		{
			\IPS\Output::i()->error( \IPS\Member::loggedIn()->member_id ? 'no_module_permission' : 'no_module_permission_guest', '2C349/1', 403, '' );
		}
		
		$club = new \IPS\Member\Club;
		if ( $form = $club->form( FALSE, TRUE, $availableTypes ) )
		{
			$form->class = 'ipsForm_vertical';
		}
		else
		{
			if ( !$club->approved and \IPS\Member::loggedIn()->modPermission('can_access_all_clubs') )
			{
				$club->approved = TRUE;
				$club->save();
			}
			
			\IPS\Output::i()->redirect( $club->url() );
		}
		
		\IPS\Output::i()->title = \IPS\Member::loggedIn()->language()->addToStack('create_club');
		if( \IPS\Request::i()->isAjax() )
		{
			\IPS\Output::i()->output = $form->customTemplate( array( call_user_func_array( array( \IPS\Theme::i(), 'getTemplate' ), array( 'forms', 'core' ) ), 'popupTemplate' ) );
		}
		else
		{
			\IPS\Output::i()->output = \IPS\Theme::i()->getTemplate( 'clubs' )->create( $form );
		}
	}
}