<?php

namespace PureCharity\Fundraisers;

class ShortcodeController extends FundraisersController {
    
    public $moduleConfig;

    private $config;

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

    function __construct($moduleConfig) {

        $this->moduleConfig = $moduleConfig;

        $this->config = [
            'shortcodes' => [
                'fundraisers' => 'fundraisersShortcode',
                'fundraisers_search' => 'fundraisersSearchShortcode',
                'last_fundraisers' => 'lastFundraisersShortcode',
                'fundraiser' => 'fundraiserShortcode',
                'fundraiser_funding_bar' => 'fundraiserFundingBarShortcode',
                'featured_fundraiser' => 'featuredFundraiserShortcode',
            ],
        ];

        $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 fundraisersShortcode($atts) {

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

        $options = shortcode_atts( array (
            'fundraiser' => false,
            'query' => get_query_var('query'),
            'grid' => get_query_var('grid'),
            'title' => get_query_var('title'),
            'campaign' => get_query_var('campaign'),
            'per_page' => get_query_var('per_page'),
            'dir' => get_query_var('dir'),
            'order' => get_query_var('order'),
            'hide_search' => get_query_var('hide_search'),
            'layout' => get_query_var('layout') # [1, 2, 3, 4]
        ), $atts );

        $campaignQuery = (
            !empty($_GET['campaign']) ?
            sanitize_text_field($_GET['campaign']) :
            null
        );

        $passCampaign = true;

        if (
            !empty($campaignQuery) &&
            $campaignQuery !== $options['campaign']
        ) {
            $passCampaign = false;
        }

        $singleFundrainserContainer = '';

        if (
            !empty($_GET['fundraiser']) &&
            $passCampaign
        ) {
            $opt = array();
            $opt['slug'] = $_GET['fundraiser'];
            $opt['title'] = $options['title'];
            $opt['layout'] = $options['layout'];
            $opt['id'] = $_GET['id'] ?? null;

            $singleFundrainserContainer = '
            <div 
                class="pc-single-fundraiser-presentation-container"
                data-fundraiser-slug="'.$_GET['fundraiser'].'"
                data-campaign-id="'.$_GET['campaign'].'"
            >
                <div class="pc-single-fundraiser-presentation-container-loader">
                    <div class="lds-roller"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>
                </div>
                <div class="pc-single-fundraiser-presentation-container-shortcode">
                    <button class="pc-single-fundraiser-presentation-container-shortcode-close-button">
                        <svg xmlns="http://www.w3.org/2000/svg" height="16" width="12" viewBox="0 0 384 512"><!--!Font Awesome Free 6.5.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2023 Fonticons, Inc.--><path d="M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z"/></svg>
                    </button>
                    '. self::fundraiserShortcode($opt) .'
                </div>
            </div>
            ';
        }

        $params = [];

        $paramsMap = [
            'request' => [
                '_page' => 'page',
                'query' => 'query',
            ],
            'options' => [
                'per_page' => 'limit',
                'campaign' => 'campaign_id',
                'order' => 'sort',
                'dir' => 'dir',
                'layout' => 'layout',
                'title' => 'title',
                'hide_search' => 'hide_search',
                'grid' => 'grid',
            ],
        ];

        foreach ($paramsMap as $paramHolder => $paramData) {

            foreach ($paramData as $paramKey => $paramApiKey) {

                if ($paramHolder === 'request') {

                    $value = (
                        !empty($_REQUEST[$paramKey]) ?
                        $_REQUEST[$paramKey] :
                        null
                    );
                } elseif ($paramHolder === 'options') {

                    $value = (
                        !empty($options[$paramKey]) ?
                        $options[$paramKey] :
                        null
                    );
                }

                if (
                    empty($value) ||
                    !empty($params[$paramApiKey])
                ) { continue; }

                $params[$paramApiKey] = $value;
            }
        }

        global $PcPlugin;

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

        $fundraisersModule = $PcPlugin->getModule('fundraisers', 'FundraisersController');
        $publicController = $fundraisersModule->getController('PublicController');

        $externalFundraisers = $apiController->apiCall(
            'externalfundraisers',
            [],
            $params
        );

        $workableData = [
            'fundraisers' => (
                !empty($externalFundraisers) ?
                $externalFundraisers :
                [
                    'external_fundraisers' => [],
                    'meta' => (object)[],
                ]
            ),
            'options' => $options,
        ];

        if (
            empty($workableData['fundraisers']) ||
            empty($workableData['fundraisers']->external_fundraisers)
        ) {

            return (
                $singleFundrainserContainer.
                $publicController::listNotFound()
            );
        }

        $publicController::$fundraisers = $workableData['fundraisers'];
        $publicController::$options = $workableData['options'];

        if (
            !empty($options['grid']) &&
            $options['grid'] === 'true'
        ) {

            return (
                $singleFundrainserContainer.
                $publicController::listingGrid($options)
            );
        }

        return (
            $singleFundrainserContainer.
            $publicController::listing()
        );
    }

    public static function fundraisersSearchShortcode($atts) {
        
        self::handleModuleResource('fundraisers', true);

        $options = shortcode_atts([
            'page_id' => get_query_var('page_id')
        ], $atts);

        global $PcPlugin;
		
		$fundraisersModule = $PcPlugin->getModule('fundraisers', 'FundraisersController');
		$paginatorController = $fundraisersModule->getController('PaginatorController');

        $query_param = $paginatorController::getQueryParam(true);
    
        if ($options['page_id'] != 0 && get_permalink($options['page_id'])) {
            $html = '
            <form class="fundraisers-search-form" action="' . get_permalink($options['page_id']) . '">
                <input type="text" name="query" placeholder="Search for an Adopting Family" value="'.$query_param.'">
                <button type="submit">Search</button>
            </form>';
        } else {
            $html = '';
        }
    
        return $html;
    }

    public static function lastFundraisersShortcode($atts) {

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

        $options = shortcode_atts( array(
            'fundraiser' => false,
            'query' => get_query_var('query'),
            'dir' => get_query_var('dir'),
            'order' => get_query_var('order'),
            'title' => get_query_var('title'),
            'limit' => get_query_var('limit'),
            'layout' => get_query_var('layout') # [1, 2, 3, 4]
        ), $atts );

        $campaignQuery = (
            !empty($_GET['campaign']) ?
            sanitize_text_field($_GET['campaign']) :
            null
        );

        $passCampaign = true;

        if (
            !empty($campaignQuery) &&
            $campaignQuery !== $options['campaign']
        ) {
            $passCampaign = false;
        }

        if (
            !empty($_GET['fundraiser']) &&
            $passCampaign
        ) {

            $opt = array();
            $opt['slug'] = $_GET['fundraiser'];
            $opt['title'] = $options['title'];
            $opt['layout'] = $options['layout'];
            $opt['id'] = $_GET['id'] ?? null;
            return self::fundraiserShortcode($opt);
        } else {
            
            $params = [];

            $paramsMap = [
                'request' => [
                    '_page' => 'page',
                    'query' => 'query',
                ],
                'options' => [
                    'limit' => 'limit',
                    'fundraiser' => 'fundraiser',
                    'order' => 'sort',
                    'dir' => 'dir',
                    'title' => 'title',
                    'layout' => 'layout',
                ],
            ];

            foreach ($paramsMap as $paramHolder => $paramData) {

                foreach ($paramData as $paramKey => $paramApiKey) {

                    if ($paramHolder === 'request') {

                        $value = (
                            !empty($_REQUEST[$paramKey]) ?
                            $_REQUEST[$paramKey] :
                            null
                        );
                    } elseif ($paramHolder === 'options') {

                        $value = (
                            !empty($options[$paramKey]) ?
                            $options[$paramKey] :
                            null
                        );
                    }

                    if (
                        empty($value) ||
                        !empty($params[$paramApiKey])
                    ) { continue; }

                    $params[$paramApiKey] = $value;
                }
            }

            if (
                !empty($params['title']) &&
                $params['title'] === 'owner_name'
            ) {

                $params['sort'] = 'founder';
            }

            global $PcPlugin;

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

            $fundraisersModule = $PcPlugin->getModule('fundraisers', 'FundraisersController');
            $publicController = $fundraisersModule->getController('PublicController');

            $externalFundraisers = $apiController->apiCall(
                'externalfundraisers',
                [],
                $params
            );

            $workableData = [
                'fundraisers' => (
                    !empty($externalFundraisers) ?
                    $externalFundraisers :
                    [
                        'external_fundraisers' => [],
                        'meta' => (object)[],
                    ]
                ),
                'options' => $options,
            ];

            if (
                empty($workableData['fundraisers']) ||
                empty($workableData['fundraisers']->external_fundraisers)
            ) {

                return $publicController::listNotFound();
            }

            $publicController::$fundraisers = $workableData['fundraisers'];
            return $publicController::listingLastGrid();
        }
    }
    
    public static function fundraiserShortcode($atts) {

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

        $options = shortcode_atts( array(
            'slug' => get_query_var('slug'),
            'title' => get_query_var('title'),
            'layout' => get_query_var('layout'),
            'id' => null,
        ), $atts );

        global $PcPlugin;

        $fundraisersModule = $PcPlugin->getModule('fundraisers', 'FundraisersController');
        $publicController = $fundraisersModule->getController('PublicController');
          
        if (empty($options['slug'])) { return $publicController::notFound(); }

        $baseModule = $PcPlugin->getModule('base', 'BaseController');
        $apiController = $baseModule->getController('ApiController');
    
        $fundraiser = $apiController->apiCall(
            'fundraisers',
            ['show'],
            [
                'slug' => $options['slug'],
            ]
        );

        if (
            empty($fundraiser) ||
            (
                empty($fundraiser->fundraiser) &&
                empty($fundraiser->external_fundraisers)
            )
        ) { return $publicController::notFound(); }
        
        if (!empty($fundraiser->fundraiser)) {

            $fundraiser = $fundraiser->fundraiser;
        } else {

            $fundraiser = $fundraiser->external_fundraisers[0];
        }

        $publicController::$fundraiser = $fundraiser;
        $publicController::$options = $options;
    
        return $publicController::show();
    }

    public static function fundraiserFundingBarShortcode($atts) {

        self::handleModuleResource('fundraisers', true);
        
        $options = shortcode_atts( array(
            'fundraiser' => false,
            'standalone_bar' => true
        ), $atts );
        
        if ($options['fundraiser']) {

            global $PcPlugin;

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

            $fundraisersModule = $PcPlugin->getModule('fundraisers', 'FundraisersController');
            $publicController = $fundraisersModule->getController('PublicController');

            $fundraiser = $apiController->apiCall(
                'fundraisers',
                ['show'],
                [
                    'slug' => $options['fundraiser'],
                ]
            );
    
            if (
                empty($fundraiser) ||
                (
                    empty($fundraiser->fundraiser) &&
                    empty($fundraiser->external_fundraisers)
                )
            ) { return $publicController::notFound(); }

            if ($fundraiser) {
                $fundraiser = $fundraiser->fundraiser;
                $publicController::$fundraiser = $fundraiser;
                $publicController::$options = $options;

                return $publicController::singleViewFundingBar();
            } else {
                return $publicController::notFound();
            }
        }
    }

    public static function featuredFundraiserShortcode($atts) {

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

        $options = shortcode_atts( array (
            'slug' => get_query_var('slug'),
            'title' => get_query_var('title'),
            'redirect' => get_query_var('redirect')
          ), $atts );
      
          if ($options['slug']) {

            global $PcPlugin;

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

            $fundraisersModule = $PcPlugin->getModule('fundraisers', 'FundraisersController');
            $publicController = $fundraisersModule->getController('PublicController');

            $fundraiser = $apiController->apiCall(
                'fundraisers',
                ['show'],
                [
                    'slug' => $options['slug'],
                ]
            );

            if (
                empty($fundraiser) ||
                (
                    empty($fundraiser->fundraiser) &&
                    empty($fundraiser->external_fundraisers)
                )
            ) { return $publicController::notFound(); }

            if ($fundraiser) {

              $fundraiser = $fundraiser->fundraiser;
                $publicController::$fundraiser = $fundraiser;
                $publicController::$options = $options;

              return $publicController::featuredFundraiser();
            } else {
              return $publicController::notFound();
            }
          }
    }
}