<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Service;

use Paysera\PrestashopPayments\Form\PaymentSettingsDataConfiguration;
use Paysera\PrestashopPayments\Provider\SettingsProvider;
use Paysera\PrestashopPayments\Provider\UrlProvider;
use Twig\Environment;

if (!defined('_PS_VERSION_')) {
    exit;
}

class PopupBridgeRenderer
{
    private const POPUP_FALLBACK_COOKIE = 'paysera_popup_fallback';

    public function __construct(
        private SettingsProvider $settingsProvider,
        private UrlProvider $urlProvider,
        private Environment $twig,
        private CmsToolsFacade $cmsToolsFacade
    ) {
    }

    public function redirect(string $url, object $cookie): void
    {
        $html = $this->renderPopupBridgeIfNeeded($url, $cookie);

        if ($html !== null) {
            echo $html;

            exit;
        }

        $this->cmsToolsFacade->redirect($url);
    }

    public function renderPopupBridgeIfNeeded(string $redirectUrl, object $cookie): ?string
    {
        if (!$this->isPopupWindowMode($cookie)) {
            return null;
        }

        return $this->render($redirectUrl);
    }

    public function isPopupWindowMode(object $cookie): bool
    {
        if ($this->isPopupFallbackActive($cookie)) {
            $this->clearPopupFallbackCookie($cookie);

            return false;
        }

        return $this->settingsProvider->getPaymentWindowMode()
            === PaymentSettingsDataConfiguration::PAYMENT_WINDOW_MODE_NEW_WINDOW;
    }

    public function render(string $redirectUrl): string
    {
        $shopBaseUrl = $this->urlProvider->getShopBaseUrl();
        $parentOrigin = rtrim($shopBaseUrl, '/');

        return $this->twig->render('popup_bridge.html.twig', [
            'redirectUrl' => $redirectUrl,
            'parentOrigin' => $parentOrigin,
        ]);
    }

    private function isPopupFallbackActive(object $cookie): bool
    {
        return isset($cookie->{self::POPUP_FALLBACK_COOKIE})
            && $cookie->{self::POPUP_FALLBACK_COOKIE} === '1';
    }

    private function clearPopupFallbackCookie(object $cookie): void
    {
        unset($cookie->{self::POPUP_FALLBACK_COOKIE});
        $cookie->write();
    }
}
