<?php

namespace PureCharity\Trips;

class ShortcodeController extends TripsController {
    
    public $moduleConfig;

    private $config;

    public static $classPath = '\PureCharity\Trips\ShortcodeController';

    function __construct($moduleConfig) {

        $this->moduleConfig = $moduleConfig;

        $this->config = [
            'shortcodes' => [
                'trips' => 'tripsShortcode',
                'trip' => 'tripShortcode',
                'trips_filters' => 'tripsFiltersShortcode',
            ],
        ];

        $this->init();
    }

    public function init() {

        $this->registerShortcodes();
    }

    public function registerShortcodes() {

        if (empty($this->config['shortcodes'])) { return false; }

        foreach ($this->config['shortcodes'] as $shortcodeId => $shortcodeMethod) {

            if (
                empty($shortcodeId) ||
                empty($shortcodeMethod)
            ) { continue; }
              
            add_shortcode(
                $shortcodeId,
                [
                  self::$classPath,
                  $shortcodeMethod
                ]
            );
        }
    }

    public static function tripsShortcode($atts) {

        self::handleModuleResource('trips', true);

      $opts = shortcode_atts( array(
        'limit'         => 10,
        'country'       => get_query_var('country'),
        'region'        => get_query_var('region'),
        'cause'         => get_query_var('cause'),
        'starts_at'     => get_query_var('starts_at'),
        'ends_at'       => get_query_var('ends_at'),
        'past'          => get_query_var('past'),
        'upcoming'      => get_query_var('upcoming'),
        'past_events'   => get_query_var('past_events'),
        'include_past'  => get_query_var('include_past'),
        'grid'          => get_query_var('grid'),
        'tag'           => get_query_var('tag'),
        'sort'          => get_query_var('sort'),
        'dir'           => get_query_var('dir'),
        'trip_tag'      => (isset($_GET['trip_tag']) ? $_GET['trip_tag'] : get_query_var('trip_tag')),
        'query'         => (isset($_GET['query']) ? $_GET['query'] : get_query_var('query')),
        'page'          => (isset($_GET['_page']) ? $_GET['_page'] : get_query_var('_page'))
      ), $atts );
  
      //$opts['ends_at'] = self::is_past($opts['past']);
  
      if(!empty($opts['upcoming']) && $opts['upcoming'] != 'false' && !$opts['include_past']){
        $opts['upcoming'] = 'true';
      }
      if($opts['include_past'] == 'true'){
        unset($opts['upcoming']);
      }
  
      $tripId = (
        !empty($_GET['trip']) ?
        intval($_GET['trip']) :
        false
      );

      if(!empty($tripId)){

        return self::tripShortcode([
            'trip' => $tripId,
        ]);
      } else {

        global $PcPlugin;

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

        $tripsModule = $PcPlugin->getModule('trips', 'TripsController');
        $publicController = $tripsModule->getController('PublicController');

        $filteredOpts = self::filteredOpts(
            $opts,
            [
                // 'query' => 'search_filter',
            ]
        );
        
        $query = http_build_query(
            $filteredOpts
        );

        $events = $apiController->apiCall(
            'events',
            [],
            $filteredOpts
        );

        $html = '<div class="js-trips" data-shortcode-initial-query="'. $query .'"><pc-listing>[LISTING]</pc-listing></div>';

        if ($events && count($events->events) > 0) {
          
          $publicController::$events = $events;

          if($opts['grid']){
            $listing = $publicController::listingGrid();
          }else{
            $listing = $publicController::listing();
          }
        } else {
          $listing = $publicController::listNotFound();
        }

        $html = str_replace(
          [
            '[LISTING]',
          ],
          [
            $listing
          ],
          $html
        );

        return $html;
      }
    }

    public static function tripShortcode($atts) {
        $options = shortcode_atts( array(
            'trip' => false
        ), $atts );

        self::handleModuleResource('trips', true);

        global $PcPlugin;

        $tripsModule = $PcPlugin->getModule('trips', 'TripsController');
        $publicController = $tripsModule->getController('PublicController');

        if (
            empty($options) ||
            empty($options['trip'])
        ) {
            return $publicController::notFound();
        }
            
        $baseModule = $PcPlugin->getModule('base', 'BaseController');
        $apiController = $baseModule->getController('ApiController');

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

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

		$event = $eventResult['event'];

        if (empty($event)) {
            return $publicController::notFound();
        }

        $publicController::$event = $event;

        return $publicController::show();
    }

    public static function tripsFiltersShortcode($atts) {

        if (!empty($_GET['trip'])) { return ''; }

        global $PcPlugin;

        $baseModule = $PcPlugin->getModule('base', 'BaseController');
        $configurationController = $baseModule->getController('ConfigurationController');

        $filters = $configurationController::$filters;

        $filtersLabelToKeyMap = [
            'region' => 'region',
            'country' => 'country',
            'leave-date' => 'starts_at',
            'trip-type' => 'tag',
        ];

        $labels = [
            'filterBy' => __('Filter By', 'wordpress'),
            'filterTrips' => __('Filter Trips', 'wordpress'),
            'applyFilters' => __('Apply Filters', 'wordpress'),
            'resetFilters' => __('Reset Filters', 'wordpress'),
        ];
        
        $html = '
        <h3 class="from-md">'. $labels['filterBy'] .':</h3>
        <button type="button" class="pc-filter-button pc-trips-trigger for-mobile js-filter-button">'. $labels['filterTrips'] .'</button>
        <div class="pc-filters-mobile mobile js-filters">
            [FILTERS]
            [LIVESEARCH]
            [PAGENUMBER]
            <button type="button" class="pc-submit-filters js-submit-filters">'. $labels['applyFilters'] .'</button>
            <button type="button" class="pc-reset-filters js-reset-filters">'. $labels['resetFilters'] .'</button>
        </div>
        ';

        $filterHtml = '
        <div class="pc-filter" data-filter="[FILTER_KEY]">
            <button type="button" class="pc-filter-button js-filter-button">[FILTER_LABEL] <i></i></button>
            <div class="pc-filter-options js-filter-options" style="display: none;">
            [OPTIONS]
            </div>
        </div>
        ';

        $filterOptionHtml = '
        <div class="pc-option-container">
            <input type="radio" name="[FILTER_KEY]" id="option-[OPTION_ID]" value="[OPTION_VALUE]" class="pc-filter-option" [CHECKED]>
            <label for="option-[OPTION_ID]">
            <span>
                [OPTION_LABEL]
            </span>
            </label>
        </div>
        ';

        $filtersStack = [];
        foreach ($filters as $filterKey => $filterOptions) {

            $optionsStack = [];

            if (!empty($filterOptions)) {
                foreach ($filterOptions as $optionKey => $option) {
                    $singleOptionDynamicSetup = [
                        'option_value' => $filterKey !== 'region' ? $option : $optionKey,
                        'option_id' => uniqid(),
                        'option_label' => str_replace('-', ' ', $option),
                        'filter_key' => $filtersLabelToKeyMap[$filterKey],
                        'checked' => '',
                    ];

                    if (
                        empty($singleOptionDynamicSetup['option_value']) ||
                        $singleOptionDynamicSetup['option_value'] === '0' ||
                        $singleOptionDynamicSetup['option_value'] === 'all'
                    ) {
                        $singleOptionDynamicSetup['checked'] = 'checked="checked"';
                    }

                    $optionHtml = $filterOptionHtml;

                    foreach ($singleOptionDynamicSetup as $key => $value) {
                        $optionHtml = str_replace('['. strtoupper($key) .']', $value, $optionHtml);
                    }

                    $optionsStack[] = $optionHtml;
                }
            }

            $singleFilterDynamicSetup = [
                'filter_key' => $filtersLabelToKeyMap[$filterKey],
                'filter_label' => str_replace('-', ' ', $filterKey),
                'options' => implode('', $optionsStack),
            ];

            $singleFilterHtml = $filterHtml;

            foreach ($singleFilterDynamicSetup as $key => $value) {
                $singleFilterHtml = str_replace('['. strtoupper($key) .']', $value, $singleFilterHtml);
            }

            $filtersStack[] = $singleFilterHtml;
        }

        global $PcPlugin;

        $tripsModule = $PcPlugin->getModule('trips', 'TripsController');
        $publicController = $tripsModule->getController('PublicController');

        $htmlTagsFinal = [
            'filters' => implode('', $filtersStack),
            'liveSearch' => $publicController::liveSearch(),
            'pageNumber' => $publicController::pageNumber(),
        ];

        foreach ($htmlTagsFinal as $tagKey => $tagValue) {

            $tag = strtoupper('['. $tagKey .']');
            $html = str_replace(
                $tag,
                $tagValue,
                $html
            );
        }

        return $html;
    }

    public static function filteredOpts($opts = [], $convertKeyMap = []) {

        $filteredOpts = [];

        foreach ($opts as $key => $value) {
            
            $keyUsable = (
                !empty($key) &&
                !empty($convertKeyMap[$key]) ?
                $convertKeyMap[$key] :
                $key
            );

            if (
                empty($keyUsable) ||
                isset($filteredOpts[$keyUsable]) ||
                empty($value)
            ) { continue; }

            $filteredOpts[$keyUsable] = $value;
        }

        return $filteredOpts;
    }
}