<?php

namespace PureCharity\Trips;

use \stdClass;

class PublicController extends TripsController {

    public $moduleConfig;

    const DATE_FORMAT = "M j, Y";
    const MONTH_FORMAT = "M Y";

	public static $event;
	public static $events;

    private $version;
    private $pluginName;
    
    public static $classPath = '\PureCharity\Trips\PublicController';

    function __construct($moduleConfig) {
        $this->moduleConfig = $moduleConfig;
    
        $this->pluginName = $this->moduleConfig['plugin']['name'];
        $this->version = $this->moduleConfig['plugin']['version'];
    }

    /**
	 * Register the stylesheets for the Dashboard.
	 *
	 * @since 1.0.0
	 */
	public function enqueueStyles() 
	{

		if (self::moduleResourceExists('trips')) {
		
			wp_enqueue_style(
				'purecharity-plugin-trips-public', 
				$this->moduleConfig['resources']['styles'] .'public/trips.css', 
				[], 
				$this->version, 
				'all'
			);

			self::handleModuleResource('trips', false);
		}
	}

    /**
	 * Register the JavaScript for the dashboard.
	 *
	 * @since 1.0.0
	 */
	public function enqueueScripts($hook) 
	{
	}

    public function gtForceTemplate() {
     
        try{
          $options = get_option( 'purecharity_plugin_trips_settings' );
          if($options['single_view_template'] == 'purecharity-plugin-template.php'){
            include($this->purecharityPluginTemplate());
          }else{
            include(TEMPLATEPATH . '/' . $options['single_view_template']); 
          }
          exit;
        }
        catch(Exception $e){
          echo "Custom template invalid.";
        }
    }

	public function handleSingleTripPreview() {
		
		$tripId = (
			!empty($_GET['trip']) ?
			intval($_GET['trip']) :
			false
		);

		if (empty($tripId)) { return; }
		
		global $PcPlugin;

		$baseModule = $PcPlugin->getModule('base', 'BaseController');
        $apiController = $baseModule->getController('ApiController');

		$eventResult = (array)$apiController->apiCall(
			'events',
			[$tripId],
			[]
		);

		if (
			empty($eventResult) ||
			empty($eventResult['event'])
		) { return; }

		$event = $eventResult['event'];

		echo '
		<meta property="og:title" content="'.strip_tags($event->name).'">
		<meta property="og:image" content="'.$event->images->small.'">
		<meta property="og:description" content="'.strip_tags($event->about).'">
		';
		return;
	}

    /**
	 * Custom CSS in case the user has chosen to use another color.
	 *
	 * @since    1.0.0
	 */
	public static function customCss()
	{
		$base_settings = get_option( 'purecharity_plugin_settings' );
		$pt_settings = get_option( 'purecharity_plugin_trips_settings' );

		// Default theme color
		if(empty($pt_settings['plugin_color'])){
			if($base_settings['main_color'] == NULL || $base_settings['main_color'] == ''){
				$color = '#CA663A';
			}else{
				$color = $base_settings['main_color'];
			}
		}else{
			$color = $pt_settings['plugin_color'];
		}


		$scripts = '
			<style>
				a.pctrip-pure-button { background: '. $color .'; }
				.fr-filtering button { background: '. $color .' }
				.pctrip-list-actions li a:hover { background: '. $color .' !important }
			</style>
		';

		return $scripts;
	}

	/**
	 * Not found layout for listing display.
	 *
	 * @since    1.0.0
	 */
	public static function listNotFound(){
		$html = "<p class='text-center'>No Trips Found.</p>" . \PureCharity\Base\PublicController::poweredBy();
		return $html;
	}

	/**
	 * Not found layout for single display.
	 *
	 * @since    1.0.0
	 */
	public static function notFound(){
		return "<p>Trip Not Found.</p>" . \PureCharity\Base\PublicController::poweredBy();
	}

	/**
	 * Live filter template.
	 *
	 * @since    1.0.1
	 */
	public static function liveSearch(){

		// Temporary disabled
		if (!self::$disableLiveSearch) {
			$options = get_option( 'purecharity_plugin_trips_settings' );
		}

		if(isset($options["live_filter"])){

			$html = '
				<div class="fr-filtering pc-trips-form-container">
					<form method="get" class="pc-trips-form-self">
				 		<fieldset class="livefilter fr-livefilter">
				 			<legend>
				 				<label for="livefilter-input">
				 					<strong>Search Trips:</strong>
				 				</label>
				 			</legend>
				 			<input id="livefilter-input" class="fr-livefilter-input pc-trips-form-input" value="'.@$_GET['query'].'" name="query" type="text">
				 			<button class="fr-filtering-button pc-trips-form-button" type="submit" style="display: none;">Filter</button>
				 		</fieldset>
			 		</form>
			 	</div>
			';
		}else{
			$html = '';
		}
		return $html;
	}

	public static function pageNumber() {
		
		$pageNumber = (
			!empty($_GET['_page']) ?
			$_GET['_page'] :
			1
		);

		$html = '<input type="hidden" id="page" name="page" value="'. $pageNumber .'" class="pc-trips-page-number-input">';

		return $html;
	}

	/**
	 * Listing HTML for Trips
	 *
	 * @since    1.0.0
	 */
	public static function listing(){

		$html = self::customCss();
		$html .= '<div class="pctrip-list-container">';

		foreach(self::$events->events as $event){
			$truncated = (strlen($event->about) > 100) ? substr($event->about, 0, 100) . '...' : $event->about;
			$html .= '
			 	<div class="pctrip-list-item pure_col pure_span_24">
			 		<div class="pctrip-list-content pure_col pure_span_24">
				 		<div class="pctrip-listing-avatar-container pure_col pure_span_4">
							<a href="?trip='.$event->id.'">
								<div class="pctrip-listing-avatar" style="background-image: url('.$event->images->small.')"></div>
							</a>
						</div>
						<div class="pctrip-list-body-container pure_col pure_span_20">
							<h3 class="pctrip-title"><a href="?trip='.$event->id.'">'.$event->name.'</a></h3>
							<p class="pctrip-date">'.self::getDateRange($event->starts_at, $event->ends_at).'</p>
							<p class="pctrip-grid-intro">'.strip_tags($truncated).'</h4>
						</div>
					</div>
			 	</div>
			';

		}

		// Paginator
		if(self::$events->meta->num_pages > 1) {
			global $PcPlugin;

			$tripsModule = $PcPlugin->getModule('trips', 'TripsController');
			$paginatorController = $tripsModule->getController('PaginatorController');

			$html .= $paginatorController::pageLinks(self::$events->meta);
		}

		$html .= '</div>';
		return $html;
	}

	/**
	 * Listing HTML for Trips
	 *
	 * @since    1.0.0
	 */
	public static function listingGrid(){
		$html = self::customCss();
		$html .= '<div class="pctrip-list-container is-grid pure_row">';

		$html .= '
		<div class="pctrip-grid-column-container">
			[COLUMN1]
		</div>
		<div class="pctrip-grid-column-container">
			[COLUMN2]
		</div>
		<div class="pctrip-grid-column-container">
			[COLUMN3]
		</div>
		<div class="pctrip-grid-column-container">
			[COLUMN4]
		</div>
		';

		$singleEventHtml = '
		<div class="pctrip-grid-item">
			<div class="flex-container">
				<div class="top">
					[IF_IMAGE]
						<div class="pctrip-grid-item-image">
							<a href="[URL]" class="invisible-anchor">
								<img src="[IMAGE]" loading="lazy" class="image" />
							</a>
						</div>
					[/IF_IMAGE]
					<div class="pctrip-grid-item-content">
						<div class="pctrip-grid-item-code">
							[CODE]
						</div>
						<div class="pctrip-grid-item-title">
							[TITLE]
						</div>
						<div class="pctrip-grid-item-meta">
							DATE: <span class="cursive">[DATE]</span>
						</div>
						<div class="pctrip-grid-item-meta">
							REGION: <span class="cursive">[REGION]</span>
						</div>
						<div class="pctrip-grid-item-description cursive">
							[DESCRIPTION]
						</div>
					</div>
				</div>
				<div class="bottom">
					<div class="pctrip-grid-item-actions">
						<a href="[URL]" class="pctrip-grid-item-button">More Info</a>
					</div>
				</div>
			</div>
		</div>
		';

		$columns = [
			'column1' => [],
			'column2' => [],
			'column3' => [],
			'column4' => [],
		];
		$columnCounter = 1;
		foreach(self::$events->events as $event){
			$truncated = (strlen($event->description) > 100) ? substr($event->description, 0, 100) . '...' : $event->description;

			if (strpos($event->name, '-') !== false) {
				$eventNameArr = explode(' - ', $event->name);

				if (!isset($eventNameArr[1])) {

					$eventNameArr[1] = '';
				}
			} else {
				
				$eventNameArr = [
					$event->name,
					'',
				];
			}

			$eventObject = [
				'image' => $event->images->large,
				'code' => trim($eventNameArr[1]),
				'title' => trim($eventNameArr[0]),
				'date' => self::getDateRange($event->starts_at, $event->ends_at),
				'region' => $event->region,
				'description' => $truncated,
				'url' => '?trip='. $event->id,
			];
			$eventHtml = $singleEventHtml;

			foreach ($eventObject as $key => $value) {
				$ifKey = strtoupper('if_'. $key);

				if (
					strpos($eventHtml, '['. $ifKey .']') !== false &&
					strpos($eventHtml, '[/'. $ifKey .']') !== false &&
					empty($value)
				) {
					$eventHtmlArr = explode('['. $ifKey .']', $eventHtml);
					$eventHtmlWithoutIf = $eventHtmlArr[0];
					$eventHtmlArr2 = explode('[/'. $ifKey .']', $eventHtmlArr[1]);
					$eventHtmlWithoutIf .= $eventHtmlArr2[1];

					$eventHtml = $eventHtmlWithoutIf;
				} else {
					$eventHtml = str_replace('['. $ifKey .']', '', $eventHtml);
					$eventHtml = str_replace('[/'. $ifKey .']', '', $eventHtml);
				}

				$eventHtml = str_replace('['. strtoupper($key) .']', $value, $eventHtml);
			}

			$columns['column'. $columnCounter][] = $eventHtml;

			$columnCounter += 1;
			if ($columnCounter >= 5) {
				$columnCounter = 1;
			}
		}

		// Columns Map
		foreach ($columns as $key => $columMarkup) {
			$html = str_replace('['. strtoupper($key) .']', implode('', $columMarkup), $html);
		}

		// Paginator
		if(self::$events->meta->num_pages > 1) {
			global $PcPlugin;

			$tripsModule = $PcPlugin->getModule('trips', 'TripsController');
			$paginatorController = $tripsModule->getController('PaginatorController');

			$html .= $paginatorController::pageLinks(self::$events->meta);
		}

		$html .= '</div>';
		return $html;
	}


	/**
	 * Single HTML for a Trip
	 *
	 * @since    1.0.0
	 */
	public static function show() {
		global $PcPlugin;
		$tripsModule = $PcPlugin->getModule('trips', 'TripsController');
		$moduleConfig = $tripsModule->getModuleConfig();

		return self::customCss().'
			<div class="pctrip-container">

				<div class="pctrip-header pure_col pure_span_24">
					<img src="'.self::$event->images->large.'">
				</div>
				<div class="pctrip-avatar-container pure_col pure_span_4">
					<div class="pctrip-avatar" href="#" style="background-image: url('.self::$event->images->small.')"></div>
				</div>

				<div class="pctrip-name pure_col pure_span_14">
					<h3>'.self::$event->name.'</h3>
					<p class="pctrip-date">'.self::getDateRange(self::$event->starts_at, self::$event->ends_at).'</p>
				</div>
				<div class="pure_col pure_span_6 pctrip-register">
				'.self::printRegisterButton().'
				</div>


				<div class="pctrip-content pure_col pure_span_24">


					<div class="pctrip-body pure_col pure_span_18">
						<p>'.self::$event->about.'</p>
					</div>

					<div class="pctrip-sidebar pure_col pure_span_6">

						<div class="pctrip-sidebarsection">
              <h4>Share</h4>
              '.\PureCharity\Base\PublicController::sharingLinks(array(), self::$event->name).'
              <a target="_blank" href="'.\PureCharity\Base\PublicController::pcUrl().'/'.self::$event->slug.'">
			          <img src="'. $moduleConfig['resources']['assets']['img'] .'/share-purecharity.png">
			        </a>
            </div>

            '.self::printTicketsArea().'

						<div class="pctrip-sidebarsection">
							<h4>Trip Information</h4>
							<p><strong>Trip Type:</strong> '.self::printTripTypes().'</p>
							'.self::printTripLocation().'
							'.self::printTripTags().'
						</div>

					</div>

				</div>

			</div>

		';
	}

	/**
	 * Print the tickets area
	 *
	 * @since    1.1.4
	 */
	public static function printTicketsArea(){

		if (
			empty(self::$event->registrations_state) ||
			self::$event->registrations_state !== 'open' ||
			empty(self::$event->tickets) ||
			count(self::$event->tickets) === 0
		) { return ''; }

		return '
		<div class="pctrip-sidebarsection">
			<h4>Trip Costs</h4>
			'. self::printTripTickets() .'
		</div>
		';
	}

	/**
	 * Print the country/location
	 *
	 * @since    1.0.0
	 */
	public static function printTripLocation(){
    $html = '';
    if(self::$event->region != ""){
      $html .= "<p><strong>Region:</strong> ".self::$event->region."</p>";
    }

    if(self::$event->location == ""){
      $html .= "<p><strong>Country:</strong> ".self::$event->country."</p>";
    }else{
      $html .= "<p><strong>Location:</strong> ".self::$event->location."</p>";
    }

    return $html;
  }

	/**
	 * Print the register button
	 *
	 * @since    1.0.0
	 */
	public static function printRegisterButton() {

		if (
			empty(self::$event->registrations_state) ||
			self::$event->registrations_state !== 'open' ||
			empty(self::$event->tickets) ||
			count(self::$event->tickets) !== 1
		) { return ''; }

		return '
			<a class="pctrip-pure-button" href="'.self::$event->public_url.'/registrations/new?ticket_id='.self::$event->tickets[0]->id.'">Register</a>
		';
	}

	/**
	 * Print the trip leaders
	 *
	 * @since    1.0.0
	 */
	public static function printTripLeaders(){
		$html = '';
		foreach(self::$event->leaders as $leader){
			$html .= '<p><a href="'.$leader->public_url.'">'.$leader->name.'</a></p>';
		}
		return $html;
	}

	/**
	 * Print the trip tags
	 *
	 * @since    1.0.0
	 */
	public static function printTripTags(){
		$tags = array();
		foreach(self::$event->trip_tags as $tag){
			$tags[] = '<a href="?trip_tag='.$tag.'">'.$tag.'</a>';
		}
		if(count($tags) > 0){
			return '<p><strong>Tags:</strong> '.join(', ', $tags);
		}else{
			return '';
		}
	}

	/**
	 * Print the trip types
	 *
	 * @since    1.0.0
	 */
	public static function printTripTypes(){
		$types = [];

		if (empty(self::$event->types)) {
			return join(
				', ',
				array_unique($types)
			);
		}

		foreach (self::$event->types as $type) {
			$types[] = $type;
		}
		
		return join(
			', ',
			array_unique($types)
		);
	}

	/**
	 * Print the trip tickets
	 *
	 * @since    1.0.0
	 */
	public static function printTripTickets(){

		$tickets = '';

		if (
			empty(self::$event) ||
			empty(self::$event->tickets)
		) {
			return $tickets;
		}

		foreach(self::$event->tickets as $ticket){

			$tickets .= '
				<p class="pctrip-ticket">
					<strong>'.$ticket->name.'</strong><br /><br />
					<span class="pctrip-ticket-price">$'. number_format($ticket->price, 2) .'</span><br /><br />
					'.$ticket->description.'</br>
					'. (count(self::$event->tickets) > 1 ? '<a class="pctrip-pure-button" href="'.$ticket->public_url.'/registrations/new?ticket_id='.$ticket->id.'">Register</a>' : '') .'
				</p>
			';
		}
		return $tickets;
	}


	/**
	 * Calculate date range for a trip
	 *
	 * @since    1.0.0
	 */
  public static function getDateRange($start, $end) {
    $start = strtotime($start);
    $end = strtotime($end);
    $days = ($end - $start) / 3600 / 24;
    if (($days > 31) || date('M',$start) != date('M',$end)) {
      return date(self::DATE_FORMAT, $start) . ' - ' . date(self::DATE_FORMAT, $end);
    } else {
      $parts = preg_split('/([dj])/', self::DATE_FORMAT, -1, PREG_SPLIT_DELIM_CAPTURE);
      $date = '';
      foreach($parts as $part) {
        if ($part == 'd' || $part == 'j') {
          $date .= date($part, $start) . '-' . date($part, $end);
        } else {
          $date .= date($part, $start);
        }
      }
      return $date;
    }
  }

  	public function purecharityTripsFiltering() {

		$filters = !empty($_POST['filters']) ? $_POST['filters'] : false;
  
		$response = [
			'success' => false,
			'listing' => false,
		];

		if (empty($filters)) { $this->returnAjaxResponse(false, $response); }

		if (
			!empty($filters['starts_at']) && 
			$filters['starts_at'] !== '0'
		) {
			$filters['ends_at'] = $filters['starts_at'];
		}

		$filtersPrepared = [];
		foreach ($filters as $key => $value) {
			if (
				strtolower($value) === 'all' ||
				$value === 0 ||
				$value === '0' ||
				$value === ''
			) { continue; }

			if (
				$key === 'starts_at' ||
				$key === 'ends_at'
			) {
				$day = $key === 'starts_at' ? 30 : 1; // Inverting the Start and the End date due to the API bug;
				$value = date('Y-m-'. $day, strtotime($value));
			} else {
				$value = str_replace('-', ' ', $value);
			}

			$filterRelation = $key .'='. strtolower($value);
			if (strpos($value, ' ') !== false) {
				$filterRelation = $key .'="'. strtolower($value) .'"';
			}

			$filtersPrepared[] = $filterRelation;
		}

		$initialQuery = !empty($_POST['initialQuery']) ? $_POST['initialQuery'] : false;
		if (!empty($initialQuery)) {

			$initialQueryArr = explode('&', $initialQuery);

			$filtersPrepared = array_merge(
				$filtersPrepared,
				$initialQueryArr
			);
		}

		$filtersPrepared = implode(' ', $filtersPrepared);

		$shortcode = '[trips '. $filtersPrepared .' grid=true sort=date dir=asc upcoming=true]';

		$response['success'] = true;
		$response['listing'] = do_shortcode($shortcode);
		
		$this->returnAjaxResponse(true, $response);
	}
}