<?php

namespace PureCharity\Sponsorships;

use \stdClass;

class PublicController extends SponsorshipsController {

    public $moduleConfig;

    public static $sponsorship;
    public static $sponsorships;
    public static $sponsorshipsFull;

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

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

	/**
	 * Register the stylesheets for the Client.
	 *
	 * @since 1.0.0
	 */
	public function enqueueStyles() 
	{
        if (self::moduleResourceExists('sponsorships')) {
            wp_enqueue_style(
                'purecharity-plugin-sponsorhips-public', 
                $this->moduleConfig['resources']['styles'] .'public/sponsorships.css', 
                [], 
                $this->version, 
                'all'
            );

            $options = get_option( 'purecharity_plugin_sponsorship_settings' );

            // Allow the user to select a stylesheet theme
            if(isset($options['plugin_style'])){
                switch ($options['plugin_style']) {
                case 'pure-sponsorships-option2':
                    $pureStyle = 'pure-sponsorships-option2';
                    break;
                case 'pure-sponsorships-option3':
                    $pureStyle = 'pure-sponsorships-option3';
                    break;
                default:
                    $pureStyle = 'pure-sponsorships-option1';
                }
            }else{
                $pureStyle = 'pure-sponsorships-option1';
            }

            wp_enqueue_style( 'pure-sponsorships-style', $this->moduleConfig['resources']['styles'] .'public/'. $pureStyle .'.css',  );

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

	/**
	 * Register the JavaScript for the Client.
	 *
	 * @since 1.0.0
	 */
	public function enqueueScripts($hook) 
	{
        
        if (self::moduleResourceExists('sponsorships')) {
		    wp_enqueue_script('pure-sponsorships-selects-js', $this->moduleConfig['resources']['scripts'] .'public/jquery.simpleselect.js', $this->version, false);
        }
	}

	/**
	 * Listing entry for a single sponsorship.
	 *
	 * @since 1.0.0
	 */
    public static function listing() {
        $options = get_option( 'purecharity_plugin_sponsorship_settings' );
        $html = self::customCss();
        $html .= '<div class="pcsponsor-container pc-listing-view">';
        $html .= self::searchInput();

        $html .= '<div class="pcsponsor-filters">';
        $html .= self::ageFilter();
        $html .= self::genderFilter();
        $html .= self::locationFilter();
        $html .= self::resetFilter();
        $html .= '</div>';
        $programSponsorships = (array) self::$sponsorships->sponsorships;
        foreach($programSponsorships as $sponsorship){
            (array) $sponsorship;
            $html .= '
                <div class="pcsponsor-item sponsorship_'.$sponsorship->id.'">
                    <a href="?sponsorship='.$sponsorship->id.'">
                        <div class="pcsponsor-image" style="background-image: url('.$sponsorship->images->small.');">
                            '. ($sponsorship->is_sponsored ? '<p class="pcsponsor-full">Fully Sponsored</p>' : '') .'
                        </div>
                        <div class="pcsponsor-content">
                            '.self::lowerListingContent($sponsorship, $options).'
                        </div>
                    </a>
                </div>
            ';
        }

        $html .= '</div>';

        global $PcPlugin;

        $sponsorshipsModule = $PcPlugin->getModule('sponsorships', 'SponsorshipsController');
        $paginatorController = $sponsorshipsModule->getController('PaginatorController');

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

		if(!isset($options['hide_powered_by'])){
            $baseModule = $PcPlugin->getModule('base', 'BaseController');
			$basePublicController = $baseModule->getController('PublicController');

			$html .= $basePublicController::poweredBy();
		}

        return $html;
    }

    /**
	 * Single child view.
	 *
	 * @since 1.0.0
	 */
    public static function single() {

        $options = get_option( 'purecharity_plugin_sponsorship_settings' );
        $html = self::customCss();

        if(isset($options['plugin_style']) && $options['plugin_style'] == 'pure-sponsorships-option3'){
            $html .= '
                <div class="pcs-rounded pc-single-view">

                    <div class="info">
                        '.self::renderSlots(0).'
                        <h1>'.self::$sponsorship->name.'</h1>
                        '.self::renderAge().'
                        '.self::renderDescription().'
                        '.self::renderAboutSection('pure-about').'
                        '.self::renderCustomFields().'
                    </div>

                    <div class="pictures">

                        <div class="control left">
                            <a href="#"> < </a>
                        </div>

                        <div class="album">
                            <div class="rail">
                                <div class="picture" style="background-image: url('.self::$sponsorship->images->small.');">
                                </div>
                            </div>
                            <ul class="controls">
                                <li class="active"><a href="#picture-1"></a></li>
                                <li><a href="#picture-2"></a></li>
                            </ul>
                            <div class="pcsponsor-single-select pc-third-view">
                                '.self::renderSponsorOptions().'
                            </div>
                        </div>

                        <div class="control right">
                            <a href="#"> > </a>
                        </div>
                    </div>
                </div>

                <div class="pcs-navigation">
                    '.self::lowerLinks().'
                </div>
            ';

        }else{
            $html .= '
                <div class="pcsponsor-single-container pc-single-view">
                    <p class="pcsponsorships-return"><a href="#" onclick="javascript:history.go(-1); return false;">&#10094; Return to Sponsorship List</a></p>

                    <div class="pcsponsor-single-image">
                        <img src="'.self::$sponsorship->images->small.'" loading="lazy" alt="'.self::$sponsorship->name.'"/>
                    </div>
                    <div class="pcsponsor-single-content">
                        <div class="pcsponsor-single-info">
                            <h4>'.self::$sponsorship->name.'</h4>
                            '.self::renderSlots(1).'
                        </div>
                        <div class="pcsponsor-single-desc">
                            '.self::renderAge().'
                            '.self::renderDescription().'
                            '.self::renderAboutSection('pure-about').'
                            <p>'.self::renderCustomFields().'</p>
                        </div>
                        <div class="pcsponsor-single-select">
                            '.self::renderSponsorOptions().'
                        </div>
                    </div>
            ';
        }

        if (empty($options['hide_powered_by'])) {
            global $PcPlugin;
			$baseModule = $PcPlugin->getModule('base', 'BaseController');
			$basePublicController = $baseModule->getController('PublicController');

			$html .= $basePublicController::poweredBy();
        }

        return $html;
    }

    /**
	 * Renders slots.
	 *
	 * @since 1.0.0
	 */
    public static function renderSlots($template=0){
        $total_available = self::$sponsorship->sponsors_goal;
        $taken = self::$sponsorship->quantity_taken;
        if((int)$taken > (int)$total_available){ $taken = $total_available; }

        $html = '';
        if((int)$total_available > 1){
            if($template == 0){
                $html .= '<div class="slots">
                            <ul class="no-padding">'.self::theBullets(self::$sponsorship).'</ul>
                            '. self::sponsorshipSlotsText() .'
                          </div>';
            }else{
                $html .= '<ul class="pcsponsor-status-buttons pcsponsor-single-status-buttons">
                           '.self::theBullets(self::$sponsorship).'
                          </ul>
                           '. self::sponsorshipSlotsText();
            }
        }
        return $html;
    }

    /**
	 * Renders the description.
	 *
	 * @since 1.0.0
	 */
    public static function renderDescription(){
        $html = '';
        if(!empty(self::$sponsorship->description)){
            $html = '<p class="pure-desc">
                    '.self::$sponsorship->description.'
                     </p>';
        }
        return $html;
    }

  /**
	 * Renders the age display.
	 *
	 * @since 1.0.0
	 */

	public static function renderAge(){
    $html = '';
    if(!empty(self::$sponsorship->age)){
      $html = '<p class="pure-desc"><small>
                 <strong>Age:</strong> '.self::$sponsorship->age.'
              </small></p>';
    }
    return $html;
	}

  /**
	 * Renders the about optional section.
	 *
	 * @since 1.0.0
	 */
	public static function renderAboutSection($class=''){
		$html = '';
		if(!empty(self::$sponsorship->about)){
			$html = '<p class="'.$class.'">'.self::$sponsorship->about.'</p>';
		}
		return $html;
	}

	/**
	 * Renders the lower content of the listing options.
	 *
	 * @since 1.0.0
	 */
    public static function lowerListingContent($sponsorship, $options){
        $total_available = $sponsorship->sponsors_goal;

        $available = $sponsorship->sponsors_goal - $sponsorship->quantity_taken;
        if($available < 0){ $available = 0; }

        $components = array();
        $components['title'] = '<h4>'.$sponsorship->name.'</h4>';
        if((int)$total_available > 1){
            $components['bullets'] = '<ul class="pcsponsor-status-buttons">'.self::theBullets($sponsorship).'</ul>';
            $components['info'] = '<p class="pcsponsor-status">
                                    '.$available.' of '.$total_available.'
                                    '.self::pluralize($total_available, 'Sponsorship').'
                                    Available
                                   </p>';
        }else{
            $components['bullets'] = '';
            $components['info'] = (($sponsorship->is_sponsored && (isset($options['plugin_style']) && $options['plugin_style'] == 'pure-sponsorships-option3')) ? '<p>Sponsored</p>' : '');
        }
        if(isset($options['plugin_style']) && $options['plugin_style'] == 'pure-sponsorships-option3'){
            return $components['title'].$components['info'].$components['bullets'];
        }else{
            return $components['title'].$components['bullets'].$components['info'];
        }
    }

    /**
	 * Generates the reset filter CTA.
	 *
	 * @since 1.0.0
	 */
    public static function resetFilter(){
        return '<button id="pc-reset-filters" type="button">Reset filters</button>';
    }

    /**
	 * Generates the age filter.
	 *
	 * @since 1.0.0
	 */
    public static function ageFilter(){
        $options = get_option( 'purecharity_plugin_sponsorship_settings' );
        if(isset($options["age_filter"])){
            return '<select data-type="age" name="age">
                <option value="0">Select Age</option>
                <option '. ( (isset($_GET['age']) && $_GET['age'] == '0-4') ? 'selected' : '') .' value="0-4">0-4</option>
                <option '. ( (isset($_GET['age']) && $_GET['age'] == '5-8') ? 'selected' : '') .' value="5-8">5-8</option>
                <option '. ( (isset($_GET['age']) && $_GET['age'] == '9-12') ? 'selected' : '') .' value="9-12">9-12</option>
                <option '. ( (isset($_GET['age']) && $_GET['age'] == '13-99') ? 'selected' : '') .' value="13-99">13+</option>
            </select>';
        }
    }

    /**
	 * Generates the age filter.
	 *
	 * @since 1.0.0
	 */
    public static function genderFilter(){
        $options = get_option( 'purecharity_plugin_sponsorship_settings' );
        if(isset($options["gender_filter"])){
            return '<select data-type="gender" name="gender">
                <option value="0">Select Gender</option>
                <option '. ( (isset($_GET['gender']) && $_GET['gender'] == 'Male') ? 'selected' : '') .' >Male</option>
                <option '. ( (isset($_GET['gender']) && $_GET['gender'] == 'Female') ? 'selected' : '') .' >Female</option>
            </select>';
        }
    }

    /**
	 * Generates the age filter.
	 *
	 * @since 1.0.0
	 */
    public static function locationFilter(){
        $options = get_option( 'purecharity_plugin_sponsorship_settings' );
        if(isset($options["gender_filter"])){ 
            $html = "";

            // Grab the locations for the filter
            $locations = self::getLocationsFromCache();

            if (empty($locations)) {
                $programSponsorships_full = (array) self::$sponsorshipsFull->sponsorships;

                foreach($programSponsorships_full as $sponsorship) {

                    if (!empty($locations[$sponsorship->location])) { continue; }

                    $locations[$sponsorship->location] = true;
                }
                asort($locations);
                
                $locationsCachedState = self::setLocationsCache(
                    $locations
                );
            }

            $html .= '<select data-type="location" name="location">';
            $html .= '<option value="0">Select Country</option>';
            foreach ($locations as $location => $val) {
                $html .= '<option '. ( (isset($_GET['location']) && $_GET['location'] == $location) ? 'selected' : '') .'>'. $location .'</option>';
            }
            $html .= '</select>';
            return $html;
        }
    }

    /**
	 * Generates the bullets for the sponsorship.
	 *
	 * @since 1.0.0
	 */
    public static function theBullets($sponsorship){
        $total_available = $sponsorship->sponsors_goal;
        $taken = $sponsorship->quantity_taken;
        if((int)$taken > (int)$total_available){ $taken = $total_available; }

        $html = '';
        if((int)$total_available > 1){
            for ($i = 1; $i <= $total_available; $i++) {
                $klass = ($i <= $taken) ? 'pcsponsor-taken' : '';
            $html .= '<li class="'. $klass .'"></li>';
            }
        }
        return $html;

    }



    /**
	 * 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' );
        $pf_settings = get_option( 'purecharity_plugin_sponsorship_settings' );

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

        $scripts = '
            <style>
                .single-sponsorship .ps-taken,
                .single-sponsorship .simpleselect .placeholder,
                .single-sponsorship .styledButton ,
                .pcs-rounded .info .slots ul li.taken,
                .pure-button { background: '. $color .' !important; color: #FFF !important; }
                .pcsponsorships-return a,
                .pcs-rounded .info .slots ul li.pcsponsor-taken,
                .pcs-navigation a span
                .single-sponsorship a { color: '. $color .' !important; }
            </style>
        ';

        return $scripts;
    }


    /**
	 * Renders the available sponsorships slot for the single view. Returns blank if there is only one.
	 *
	 * @since 1.0.0
	 */
    public static function sponsorshipSlotsText(){

        $total_available = (int)self::$sponsorship->sponsors_goal;

        $available = self::$sponsorship->sponsors_goal - self::$sponsorship->quantity_taken;
        if($available < 0){ $available = 0; }

        $html = '';

        if($total_available > 1 && $available > 0){
            $html = '
            <span>
                '.$available.' of '.$total_available.'
                '.self::pluralize($total_available, 'Sponsorship').'
                Available
            </span>
            ';
        }elseif($total_available > 1 && $available == 0){
            $html = '<span>Fully Sponsored</span>';
        }elseif($available == 0){
            $html = '<span>Sponsored</span>';
        }

        return $html;
    }


    /**
	 * Renders the lower links for the single kid view when using layout option 3.
	 *
	 * @since 1.0.0
	 */
    public static function lowerLinks(){
        $options = get_option( 'purecharity_plugin_sponsorship_settings' );

        $permalink = get_permalink();
        $go_back = htmlspecialchars($permalink);

        $html = '';
        if(isset($options['show_back_link'])){
            $html .= '<a href="'. $go_back .'" class="back"><span> < </span>Back</a>';
        }

        if(isset($options['show_more_link']) && !empty($options['more_link'])){
            $html .= '<a href="'. $options['more_link'] .'" class="learn-more">Learn more about sponsorships <span> > </span></a>';
        }

        return $html;
    }

    /**
	 * Renders the custom fields for the single kid view.
	 *
	 * @since 1.0.0
	 */
    public static function renderCustomFields(){
        $options = get_option( 'purecharity_plugin_sponsorship_settings' );
        $fields_config = explode(";", $options['allowed_custom_fields']);

        $custom_fields = Array();
        foreach($fields_config as $key => $value){
            $parts = explode('|', $value);
            $custom_fields[$parts[0]] = @$parts[1];
        }


        $html = '';
        foreach($custom_fields as $key => $value){
            if(isset(self::$sponsorship->custom_fields->$key)){
                $html .= "<b>".$value."</b>: ".self::$sponsorship->custom_fields->$key."<br />";
            }
        }

        if($html != ''){
            $exp = explode(' ', self::$sponsorship->name);
            $return = "<h4>about ".$exp[0]."</h4><p>$html</p>";
        }else{
            $return = '';
        }

        return $return;
    }

    /**
	 * Renders the sponsor options for the single kid view.
	 *
	 * @since 1.0.0
	 */
    public static function renderSponsorOptions(){

        $options = get_option( 'purecharity_plugin_sponsorship_settings' );

        $available = self::$sponsorship->sponsors_goal - self::$sponsorship->quantity_taken;
        if($available < 0){ $available = 0; }

        global $PcPlugin;

        $baseModule = $PcPlugin->getModule('base', 'BaseController');
        $publicController = $baseModule->getController('PublicController');

        $html = '<form method="get" action="'.$publicController::pcUrl().'/sponsorships/'. self::$sponsorship->id .'/fund" class="pcsponsor-fund-form">';

        if((int)self::$sponsorship->sponsors_goal > 1 && $available > 0){
            $html .= '<select id="sponsorship_supporter_shares" name="amount">';
            $html .= '<option>Choose Sponsorship Level</option>';
            for ($i = 1 ; $i <= $available ; $i++) {
                $termName = 'Sponsorship';
                if ($i > 1) {
                    $termName = 'Sponsorships';
                }
                $html .= '<option value="'. (self::$sponsorship->funding_per * $i) .'.00">'. $i .' '. $termName .' - $'. (self::$sponsorship->funding_per * $i) .'.00 Monthly</option>';
            }
            $html .= '</select>';
        }else{
            $html .= '<input type="hidden" name="amount" value="'.self::$sponsorship->funding_per.'" />';
        }
        if($available > 0){
            $html .= '<a class="pure-button submit" href="#">Sponsor</a>';
        }
        $html .= '</form>';
        return $html;
    }

    /**
	 * Global search input.
	 *
	 * @since 1.0.0
	 */
    public static function searchInput(){

        $options = get_option( 'purecharity_plugin_sponsorship_settings' );

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

            $html = '
                <div class="sp-filtering">
                    <form method="get">
                        <fieldset class="livefilter sp-livefilter">
                            <legend>
                                <label for="livefilter-input">
                                    <strong>Search Sponsorships:</strong>
                                </label>
                            </legend>
                            <input id="livefilter-input" class="sp-livefilter-input" value="'.@$_GET['query'].'" name="query" type="text">
                            <button class="sp-filtering-button" type="submit">Filter</button>
                            '. (@$_GET['query'] != '' ? '<a href="#" onclick="$(this).prev().prev().val(\'\'); $(this).parents(\'form\').submit(); return false;">Clear filter</a>' : '') .'
                        </fieldset>
                    </form>
                </div>
            ';
        }else{
            $html = '';
        }
        return $html;
    }

	public function sniffRequests(){
		global $wp;
		if(isset($wp->query_vars['__api'])){
			$this->handleRequest();
			exit;
		}
	}

	protected function handleRequest(){
		global $wp;
		$sponsorship_slug = $wp->query_vars['sponsorship_slug'];
		if(!$sponsorship_slug)
			$this->sendResponse('Please tell what sponsorship to send.');

		// API CALL
		$base_plugin = new Purecharity_Wp_Base();
		$sponsorships = $base_plugin->api_call('sponsorships?sponsorship_program_id='. $sponsorship_slug );

		$custom_fields = Array();
		foreach($sponsorships->sponsorships[0]->custom_fields as $key => $value){
			$custom_fields[$key] = implode(' ', preg_split('/(?=[A-Z])/',$key));
		}

		if($sponsorships)
			$this->sendResponse('200 OK', json_encode($custom_fields));
		else
			$this->sendResponse('Something went wrong');
	}

	protected function sendResponse($msg, $custom_fields = ''){
		$response['message'] = $msg;
		if($custom_fields)
			$response['custom_fields'] = $custom_fields;
			header('content-type: application/json; charset=utf-8');
	    echo json_encode($response)."\n";
	    exit;
	}

	public function addQueryVars($vars){
		$vars[] = '__api';
		$vars[] = 'sponsorship_slug';
		return $vars;
	}

	public function ssForceTemplate() {
		try{
			$options = get_option( 'purecharity_plugin_sponsorship_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 sponsorshipsLazyLoading() {

        $params = ['url', 'fullUrl'];
        $data = [];

        $response = '';

        if (empty($_POST)) {

            $this->returnAjaxResponse(false, $response);
        }

        foreach ($_POST as $key => $value) {
            if (!in_array($key, $params)) { continue; }

            $data[$key] = $value;
        }

        if (
            empty($data['url']) ||
            empty($data['fullUrl'])
        ) {
            
            $this->returnAjaxResponse(false, $response);
        }

        // Sponsorships Listing Cache
        $shouldCache = false;

        $urlsCombined = implode('###', [
            $data['url'],
            $data['fullUrl']
        ]);

        $sponsorshipsCache = (
            empty($_POST['bypassCache']) ?
            $this->getSponsorshipsFromCache($urlsCombined) :
            false
        );

        if (empty($sponsorshipsCache)) {
            $shouldCache = true;

            // Grab the sponsorships
            $sponsorships = $this->getListing($data['url']);
            $sponsorshipsFull = $this->getListing($data['fullUrl']);

            self::$sponsorships = $sponsorships;
            self::$sponsorshipsFull = $sponsorshipsFull;

            $listing = $this->listing();
        } else {
            $listing = $sponsorshipsCache['listing'];
            $currentTimestamp = date('Ymd');

            if ($currentTimestamp !== $sponsorshipsCache['timestamp']) {
                $listing .= '<script id="sponsorshipRecacheTrigger" type="application/javascript"></script>';
            }
        }

        if (!empty($shouldCache)) {
            $cacheResult = $this->setSponsorshipsCache($urlsCombined, $listing);
        }

        $this->returnAjaxResponse(true, $listing);
    }

    public function getSponsorshipsFromCache($urlsCombined) {

        $result = false;

        $sponsorshipsCacheDir = (wp_get_upload_dir())['basedir'] .'/pc-sponsorships-cache/';
      
        if (!file_exists($sponsorshipsCacheDir)) { return $result; }
      
        $urlBinary = md5($urlsCombined);
      
        $sponsorshipsCacheFile = $urlBinary .'.json';
      
        $sponsorshipsCachePath = $sponsorshipsCacheDir . $sponsorshipsCacheFile;
      
        if (!file_exists($sponsorshipsCachePath)) { return $result; }
      
        $sponsorships = json_decode(file_get_contents($sponsorshipsCachePath), true);
        
        $result = $sponsorships;
      
        return $result;
    }

    public function getListing($url) {
        $baseModule = $this->getModule('base', 'BaseController');
        $apiController = $baseModule->getController('ApiController');

        // $basePlugin = new Purecharity_Wp_Base();
        $apiEndpoint = explode('?', $url)[0];
        $queryStr = explode('?', $url)[1];
        parse_str($queryStr, $query);
      
        // Flip Location filter to the Country filter instead
        $query['country'] = $query['location'];
        unset($query['location']);
      
        $sponsorshipIds = explode(',', $query['sponsorship_program_id']);
      
        $result = new \stdClass;
        $result->sponsorships = [];
        $result->meta = new \stdClass;
      
        if (empty($sponsorshipIds)) { return $result; }
      
        $countSponsorships = (
          !empty($query['activePrograms']) ?
          $query['activePrograms'] :
          count($sponsorshipIds)
        );
      
        $limit = intval($query['limit'] / $countSponsorships);
        
        $originalLimit = $query['limit'];
        
        $query['limit'] = $limit;
    
        foreach ($sponsorshipIds as $index => $sponsorshipId) {
          if (empty($sponsorshipId)) { continue; }
      
          $query['sponsorship_program_id'] = $sponsorshipId;
         
          $sponsorships = $apiController->apiCall(
            $apiEndpoint,
            [],
            $query
          );
      
          if (!empty($sponsorships->sponsorships)) {
            $result->sponsorships = array_merge(
              $result->sponsorships,
              $sponsorships->sponsorships,
            );
      
            if (count($sponsorships->sponsorships) < $limit) {
              $countSponsorships -= 1;  
            }
          } else {
            $countSponsorships -= 1;
          }
      
          $result->meta = $sponsorships->meta;
        }
      
        $allSponsorships = count($result->sponsorships);
        if (
          $allSponsorships < $originalLimit &&
          $countSponsorships > 0
        ) {
      
          if (strpos($url, 'activePrograms') === false) {
            $url .= '&activePrograms='. $query['activePrograms'];
          }
      
          $url = str_replace('&activePrograms='. $query['activePrograms'], '&activePrograms='. $countSponsorships, $url);
          $result = $this->getListing($url);
        }

        return $result;
    }

    public function setSponsorshipsCache($urlsCombined, $listing) {
        $result = false;

        $sponsorshipsCacheDir = (wp_get_upload_dir())['basedir'] .'/pc-sponsorships-cache/';
      
        if (!file_exists($sponsorshipsCacheDir)) {
          $cacheDirCreation = mkdir($sponsorshipsCacheDir, 0775);
        }
      
        $urlBinary = md5($urlsCombined);
      
        $sponsorshipsCacheFile = $urlBinary .'.json';
      
        $sponsorshipsCachePath = $sponsorshipsCacheDir . $sponsorshipsCacheFile;
      
        $cacheObject = [
          'timestamp' => date('Ymd'),
          'listing' => $listing,
        ];
      
        $fileContent = json_encode($cacheObject);
        $filePath = $sponsorshipsCachePath;

        try {
            $fileDescriptor = fopen($filePath, 'w');
            
            if ($fileDescriptor) {
                fwrite($fileDescriptor, $fileContent);
                fclose($fileDescriptor);
            }
        } catch (\Exception $error) {
            // Do nothing
        }
      
        $result = $cacheObject;
        return $result;
    }

    public static function getLocationsFromCache() {
        $result = [];
      
        $sponsorshipsLocationsCacheDir = (wp_get_upload_dir())['basedir'] .'/pc-sponsorships-locations-cache/';
      
        if (!file_exists($sponsorshipsLocationsCacheDir)) {
          return $result;
        }
      
        $url = wp_get_referer();
        $pageId = url_to_postid($url);
      
        $sponsorshipsLocationsCacheFile = (
          'locations-'.
          $pageId .
          '.json'
        );
      
        $sponsorshipsLocationsCachePath = $sponsorshipsLocationsCacheDir . $sponsorshipsLocationsCacheFile;
      
        if (!file_exists($sponsorshipsLocationsCachePath)) {
          return $result;
        }
      
        $locations = json_decode(file_get_contents($sponsorshipsLocationsCachePath), true);
        
        $result = $locations;
        
        return $result;
    }

    public static function setLocationsCache($locations) {
        $result = false;
      
        $url = wp_get_referer();
        $pageId = url_to_postid($url);
      
        $sponsorshipsLocationsCacheDir = (wp_get_upload_dir())['basedir'] .'/pc-sponsorships-locations-cache/';
      
        if (!file_exists($sponsorshipsLocationsCacheDir)) {
          $cacheDirCreation = mkdir($sponsorshipsLocationsCacheDir, 0755);
        }
      
        $sponsorshipsLocationsCacheFile = (
          'locations-'.
          $pageId .
          '.json'
        );
      
        $sponsorshipsLocationsCachePath = $sponsorshipsLocationsCacheDir . $sponsorshipsLocationsCacheFile;
        
        $fileContent = json_encode($locations);
        $filePath = $sponsorshipsLocationsCachePath;
      
        try {
            $fileDescriptor = fopen($filePath, 'w');

            if ($fileDescriptor) {
                fwrite($fileDescriptor, $fileContent);
                fclose($fileDescriptor);
            }
        } catch (\Exception $error) {
            // Do nothing
        }
      
        $result = true;
        return $result;
    }
}