<?php

namespace PureCharity\Sponsorships;

class ShortcodeController extends SponsorshipsController {
    
    public $moduleConfig;

    private $config;

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

    function __construct($moduleConfig) {

        $this->moduleConfig = $moduleConfig;

        $this->config = [
            'shortcodes' => [
                'sponsorships' => 'sponsorshipsShortcode',
                'sponsorship' => 'sponsorshipChildShortcode',
                'sponsorship_child' => 'sponsorshipChildShortcode',
            ],
        ];

        $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 sponsorshipsShortcode($atts) {
        // Set up and retrieve attributes
        $options = shortcode_atts( array(
            'status' => false,
            'per_page' => false,
            'reject' => false
        ), $atts );
  
      $sponsorship_id = (string) $atts["program_id"];

      self::handleModuleResource('sponsorships', true);
  
      if (isset($_GET['sponsorship'])) {
        // In case it's a single child view
        return self::sponsorshipChildShortcode(['sponsorship' => $_GET['sponsorship']]);
      } else if($sponsorship_id){
        $filters = '';
        $age = '';
        $gender = '';
        $location = '';
  
        // Check for any filters, validating and sanitizing along the way
        // Append valid filters to $filters
        if (isset($_GET['gender'])) {
          $gender = ucfirst(strtolower($_GET['gender']));
  
          if ($gender == 'Male' || $gender == 'Female') {
            $filters = '&gender='. $gender;
          }
        }
  
        $range1 = $range2 = $range3 = $range4 = '';
  
        if (isset($_GET['age'])) {
          $age = $_GET['age'];
          if (preg_match('/[0-9-]*/', $_GET['age'])) {
            // Split the age
            $ages = explode('-', $_GET['age']);
  
            if (isset($ages[0]) && isset($ages[1])) {
              $filters .= '&min_age='. $ages[0];
            }
  
            if (isset($ages[0]) && !isset($ages[1])) {
              $filters .= '&max_age='. $ages[0];
            }
  
            if (isset($ages[1])) {
              $filters .= '&max_age='. $ages[1];
            }
          }
        }
  
        if (isset($_GET['country'])) {
          $filters .= '&country='. urlencode(sanitize_text_field($_GET['country']));
        }
  
        if (isset($_GET['query'])) {
          $filters .= '&search_filter='. urlencode(sanitize_text_field($_GET['query']));
        }
  
        if (!empty($_GET['location'])) {
          $filters .= '&location='. urlencode(sanitize_text_field($_GET['location']));
        }
  
        if($options['reject']){
          $filters .= '&reject='.$options['reject'];
        }
  
        if ($status = $options['status']) {
          $filters .= '&status='. $status;
        }
  
        if (isset($_GET['_page'])) {
          $filters .= '&page='. (int) $_GET['_page'];
        }
  
        $full_filters = $filters;
  
        if ($limit = $options['per_page']) {
          $filters .= '&limit='. (int) $limit;
        }
  
        $fullFiltersLimit = '&limit='. $limit;
        if (!empty($fullFiltersLimit)) {
          $full_filters .= $fullFiltersLimit;
        }
  
        // Prepare the Script Initiator
        $script = '
        <div 
          class="js-sponshorships-lazy-loaded" 
          data-url="sponsorships?sponsorship_program_id='. $sponsorship_id . $filters .'"
          data-full-url="sponsorships?sponsorship_program_id='. $sponsorship_id . $full_filters .'"
          data-ajax-url="'. admin_url('admin-ajax.php') .'"
        >
          <div class="lds-roller"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>
        </div>';
        return $script;
      }
    }

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

      self::handleModuleResource('sponsorships', true);
  
      if ($options['sponsorship']) {
        global $PcPlugin;

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

        $sponsorshipsModule = $PcPlugin->getModule('sponsorships', 'SponsorshipsController');
        $publicController = $sponsorshipsModule->getController('PublicController');

        $sponsorship = $apiController->apiCall(
          'sponsorships',
          [$options['sponsorship']],
          []
        );

        $publicController::$sponsorship = $sponsorship->sponsorship;

        return $publicController::single();
      }
    }
}