<?php
/**
 * @package edoobox
 */

namespace Edoobox\Legacies;

use Edoobox\Api\ShortcodeApi;
use Edoobox\Base\BaseController;
use Edoobox\Base\Bootstrap;
use Edoobox\Base\DocumentHead;
use Edoobox\Base\GoogleTagManager;
use Edoobox\Base\LogTime;
use Edoobox\Base\Options;
use Edoobox\Base\Settings;
use Edoobox\Helpers\Arr;
use Edoobox\Plugin;
use Edoobox\Requests\Auth;
use Edoobox\Requests\Helpers\Shortcode;
use Edoobox\Requests\Next;
use Edoobox\Requests\NextOffer;
use Edoobox\Requests\Template;

class EdooboxSystem extends BaseController {
    public Auth $auth;
    public array $options = [];
    public int $shortcodeCounter = 0;

    public function __construct() {
        global $post;
        parent::__construct();

        if ( $post && is_singular() && ShortcodeApi::hasShortcode($post) ) {
            add_shortcode(Settings::SHORTCODE_NAME, [$this, 'renderTemplate']);
            add_filter('pre_get_document_title', [$this, 'setDocumentTitle']);
        }
    }

    public function renderTemplate($attr): string {
        global $wp;

        if ( ! $this->hasRequiredAttributes($attr) ) {
            return '<!-- edoobox error: url nicht im shortcode hinterlegt -->';
        }

        $this->auth = new Auth();
        $this->options = Options::get(Settings::SETTINGS_OPTION_NAME, []);
        $shortcut = Arr::get($this->options, 'account_code', '');
        $attributes = Shortcode::getMergedAttributes($attr);
        $typeIsDefault = $this->typeIsDefault($attributes);

        if ( $typeIsDefault ) {
            $template = new Template($attributes);
            $apiResponse = $template->fetch();
        } else {
            $next = new Next($attributes);
            $apiResponse = $next->fetch();
        }

        if ( ! $apiResponse ) {
            return '<!-- edoobox: keine Daten gefunden -->';
        }

        $output = $this->addGlobalVariables();
        $count = $this->shortcodeCounter;
        $this->shortcodeCounter++;
        if ($count === 0) {
            $this->enqueueBootstrap($apiResponse);
        }
        $gtm_id = $apiResponse['api']['data']['footer']['gtm_id'] ?? '';
        GoogleTagManager::set($attributes['gtm'], $gtm_id, $this->pluginURL);

        if ($typeIsDefault) {
            $current_url = home_url(add_query_arg([], $wp->request)) . Settings::PLACEHOLDER_PATH;
            $plugin_url = plugins_url('js' . Settings::PLACEHOLDER_PATH, __FILE__);
            $content_widgets = $apiResponse['api']['data']['content']['widgets'];
            $output = $content_widgets;

            if ( strpos($content_widgets, $current_url) !== false ) {
                $output = str_replace($current_url, $plugin_url, $content_widgets);
            }

            if ( $this->options['design'] !== 'bootstrap' ) {
                $nav_tag = '<nav class="navbar navbar-default navbar-fixed-top" role="navigation">';
                $nav_replacement = '<nav class="navbar navbar-default navbar-fixed-top" role="navigation" style="position: fixed; width: 100%; top: 0; left: 0; z-index: 2;">';
                if ( $count ) {
                    $nav_replacement = '<nav class="navbar navbar-default navbar-fixed-top hidden" role="navigation" style="position: fixed; width: 100%; top: 0; left: 0; z-index: 2;">';
                }

                // Überprüfung und Ersetzung des Nav-Tags
                if ( strpos($output, $nav_tag) !== false ) {
                    $output = str_replace($nav_tag, $nav_replacement, $output);
                }
            }
        } else {
            $offers = Arr::get($apiResponse, 'api.data', []);
            $this->enqueueShortcodeProStyles($attributes);

            if ( $attributes['template'] === 'Table' ) {
                $output .= "<table>";
            }

            foreach ( $offers as $item ) {
                $output .= $this->buildShortcodeProOfferTemplate($apiResponse, $attributes, $item);
            }

            if ( $attributes['template'] === 'Table' ) {
                $output .= "</table>";
            }
        }

        $version = '<!--edoobox version: ' . Settings::PLUGIN_VERSION . '-->';

        if ( ! Arr::get($this->options, BaseController::SETTINGS_SEO_PRIORITY)) {
            $head = new DocumentHead();
            $output = $head->removeOgTagsFromMainContent($output);
        }

        return
            $version .
            $this->addGlobalVariables() .
            LogTime::asHtmlCommentString(4) .
            '<div class="edoobox-plugin edbs-' .
            $count .
            '" data-noframe="' .
            $this->getFrameSetting($attributes, $apiResponse) .
            '"' .
            '" data-count="' . // used in JS to allow for more specific selectors
            $count .
            '" data-language="' .
            Arr::get($attributes, 'language') .
            '" data-shortcut="' .
            $shortcut .
            '" data-url="' .
            Arr::get($attributes, 'url') .
            '">' .
            $output .
            $this->getScriptSetting($apiResponse) .
            '</div>';
    }

    public function setDocumentTitle($title) {
        global $post;
        $attributes = ShortcodeApi::getAttributes($post);
        $template = new Template($attributes);
        return $template->setDocumentTitle($title);
    }

    private function enqueueBootstrap($apiResponse) {
        $hash = Bootstrap::getHash($apiResponse);
        $name = Bootstrap::getName($apiResponse);
        $version = Bootstrap::getVersion($apiResponse);
        Plugin::setBootstrapVersion($version);
        (new Bootstrap($name, $version, $hash))->enqueue();
    }

    private function getFrameSetting($mergedAttributes, $apiResponse): int {
        $needle = getenv('ED_DEV_URL') ? 'edoobox.ch' : 'edoobox.com';
        $hasFrame = ($mergedAttributes['root'] && strpos($apiResponse['provider_url'], $needle));
        return $hasFrame ? 1 : 0;
    }

    private function getScriptSetting($apiResponse): string {
        return '<script type="text/javascript" defer>var ed_permalink = "' . $apiResponse['provider_url'] . '";</script>';
    }

    private function hasRequiredAttributes($attr) {
        return Arr::get($attr, 'url', false);
    }

    private function enqueueShortcodeProStyles(array $attributes) {
        $template = Arr::get($attributes, 'template', 'List');
        if ( $template === 'Table' || $template === 'List' ) {
            wp_enqueue_style('edoobox_shortcode_pro', $this->pluginURL . '/css/edbs-next.css', [], '1.0');
        }
    }

    private function loadCustomShortcodeProTemplate($name) {
        $templates = Options::get('edbs_next_options_templates', [0 => ""]);
        if ( $name === 'default' || ! isset($templates[$name]) ) {
            return false;
        }

        return stripslashes($templates[$name]);
    }

    private function buildShortcodeProOfferTemplate(array $apiResponse, array $attributes, array $item) {
        $offer = new NextOffer($item, $apiResponse);
        $templateName = Arr::get($attributes, 'template', 'List');
        $templateHtml = $this->loadCustomShortcodeProTemplate($templateName);

        $item['start_date'] = $offer->getDateFormatted('start_date');
        $item['end_date'] = $offer->getDateFormatted('end_date');
        $item['deadline'] = $offer->getDateFormatted('deadline');
        $item['image'] = $offer->getImageUrl();
        $item['rewriteUrl'] = $offer->getRewriteUrl();
        $templateEngine = new EdooboxFrontendTemplate();

        if ( $templateHtml ) {
            return $templateEngine->view($templateHtml, $item, false);
        }

        if ( $attributes['template'] === 'Table' ) {
            return $templateEngine->view('shortcode_next_table.html', $item);
        }

        return $templateEngine->view('shortcode_next.html', $item);
    }

    private function typeIsDefault($attributes): bool {
        global $post;
        $defaultPath = parse_url(get_permalink($post->ID), PHP_URL_PATH);
        $currentPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        return Arr::get($attributes, 'type') === 'default' || (Arr::get($attributes, 'type') === 'next' && $currentPath !== $defaultPath);
    }

    private function addGlobalVariables(): string {
        $api_key = get_option('maps_google_api_key', '');
        return "<script type='text/javascript'>window.googleMapsApiKey = ['$api_key']</script>";
    }
}
