<?php

declare(strict_types=1);

namespace MyCustomizer\WooCommerce\Connector\Controller;

use Exception;
use MyCustomizer\WooCommerce\Connector\Config\MczrConfig;
use MyCustomizer\WooCommerce\Connector\Factory\MczrFactory;
use MyCustomizer\WooCommerce\Connector\Libs\MczrProduct;
use MyCustomizer\WooCommerce\Connector\Libs\MczrSettings;
use Symfony\Component\HttpFoundation\Request;

class MczrIframeController
{
    /** @var bool */
    private $customizerDisplayed = false;
    /** @var MczrFactory */
    private $factory;
    /** @var string|null */
    private $iFrameHook = null;
    /** @var int */
    private $iFrameHookPriority = 0;
    /** @var int|null */
    private $productId = null;
    /** @var MczrProduct */
    private $productToolkit;
    /** @var Request */
    private $request;
    /** @var MczrSettings */
    private $settings;
    /** @var \Twig\Environment */
    private $twig;

    public function __construct()
    {
        $this->factory = new MczrFactory();
        $this->productToolkit = new MczrProduct();
        $this->request = Request::createFromGlobals();
        $this->settings = new MczrSettings();
        $this->twig = $this->factory->getTwig();
    }

    public function init(): void
    {
        $this->iFrameHook = $this->settings->get('iframeHook');
        try {
            $this->iFrameHookPriority = $this->settings->get('iframeHookPriority');
        } catch (Exception $e) {
        }
        \add_action($this->iFrameHook, [$this, 'displayAction'], $this->iFrameHookPriority, 0);
        \add_action('mczrIframe', [$this, 'displayAction'], $this->iFrameHookPriority, 0);
        if (
            $this->iFrameHook != 'woocommerce_before_main_content'
            && $this->iFrameHook != 'woocommerce_after_main_content'
        ) {
            \add_action('woocommerce_before_main_content', [$this, 'displayFallbackAction'], $this->iFrameHookPriority, 0);
            \add_action('woocommerce_after_main_content', [$this, 'displayAction'], $this->iFrameHookPriority, 0);
        }
    }

    public function displayFallbackAction(): void
    {
        $product = \wc_get_product();
        if ('boolean' == gettype($product)) {
            return;
        }

        if (!$product->is_type('mczr')) {
            return;
        }

        if (\is_archive() || \is_search()) {
            return;
        }

        $this->productId = $product->get_id();

        $allowed_html = [
            'div' => [
                'id' => [],
            ]
        ];

        echo \wp_kses($this->twig->render('Iframe/displayFallback.html.twig'), $allowed_html);
    }

    /**
     * @throws Exception
     */
    public function displayAction(): void
    {
        if ($this->customizerDisplayed) {
            return;
        }
        $product = \wc_get_product();
        if ('boolean' == gettype($product)) {
            return;
        }

        if (!$product->is_type('mczr')) {
            return;
        }

        if (\is_archive() || \is_search()) {
            return;
        }

        // Check for the mandatory mczrShopId option
        if (!$this->settings->get('shopId')) {
            throw new Exception('Shop id is not defined. Please, connect the shop in MyCustomizer admin prior to access this page.');
        }

        $productId = ($product->get_id());
        $settings = $this->settings->getAll();
        $baseCustomizerUrl = str_replace('{{brand}}', $settings['brand'], MczrConfig::getConfig()['customizerUrlPattern']);
        $defaultProductName = \get_post_meta($productId, 'mczrStartingPoint', true);
        $designId = $this->request->query->get('designId');
        $token = $this->request->query->get('token');
        $lang = \get_bloginfo('language');
        $vars = [
            'settings' => $settings,
            'iframeSrc' => "{$baseCustomizerUrl}/customize/startingpoint/$defaultProductName?shopid={$settings['shopId']}&lang=$lang",
        ];
        if ($designId) {
            $vars['iframeSrc'] = "{$baseCustomizerUrl}/customize/design/$designId?shopid={$settings['shopId']}&lang=$lang";
        }
        if ($token) {
            $vars['iframeSrc'] .= "&token=$token";
        }
        $vars['iframeSrc'] .= '&storeProductUrl=' . $this->productToolkit->buildProductUrl($productId);
        $vars['product'] = [
            'id' => $product->get_id(),
        ];
        $allowed_html = [
            'iframe' => [
                'id' => [],
                'class' => [],
                'data-product-id' => [],
                'height' => [],
                'frameBorder' => [],
                'width' => [],
                'src' => [],
                'allow' => [],
                'title' => [],
            ],
            'script' => [],
            'style' => [],
        ];
        if (
            \current_filter() === 'woocommerce_after_main_content'
            && !$this->customizerDisplayed
            && $this->productId == $product->get_id()
        ) {
            echo \wp_kses($this->twig->render('Iframe/displayScript.html.twig', $vars), $allowed_html);
        } elseif (
            !$this->customizerDisplayed
            && \current_filter() === $this->iFrameHook
        ) {
            $this->customizerDisplayed = true;
            echo \wp_kses($this->twig->render('Iframe/display.html.twig', $vars), $allowed_html);
        }
    }
}
