<?php

declare(strict_types=1);

namespace FleekDash\Admin\Iframe;

/**
 * Detects FleekDash iframe / protected request context from superglobals and referer.
 *
 * @package FleekDash\Admin\Iframe
 */
final class IframeRequestContext
{
    /**
     * One-time redirect: normalize embed transport params (?protected, ?fleek-compat)
     * to match policy for the canonical wp-admin URL (rules in iframe-classes.ts).
     * Fixes bookmarks, new-tab links, SPA history, and referer-inherited stale state.
     */
    public static function redirectIfEmbedTransportParamsMismatchPolicy(): void
    {
        if (!\is_admin()) {
            return;
        }

        $hasTransportParam =
            (isset($_GET['protected']) && (string) $_GET['protected'] === 'true')
            || (isset($_GET['fleek-compat']) && \is_string($_GET['fleek-compat']) && $_GET['fleek-compat'] !== '');

        if (!$hasTransportParam) {
            return;
        }

        $full = IframeHelpers::getCurrentRequestFullUrl();
        $mode = GeneratedIframeAdminUrlPolicy::resolveModeForAdminUrl($full);
        $needsProtected = GeneratedIframeAdminUrlPolicy::modeRequiresProtectedQueryParam($mode);

        $hasProtected = isset($_GET['protected']) && (string) $_GET['protected'] === 'true';
        $currentCompat = isset($_GET['fleek-compat']) && \is_string($_GET['fleek-compat'])
            ? (string) $_GET['fleek-compat']
            : '';

        $compatMismatch = $currentCompat !== '' && $currentCompat !== $mode;
        $protectedMismatch = $needsProtected !== $hasProtected;

        if (!$compatMismatch && !$protectedMismatch) {
            return;
        }

        $clean = \remove_query_arg(['protected', 'fleek-compat'], $full);
        $clean = \add_query_arg('fleek-compat', $mode, $clean);
        if ($needsProtected) {
            $clean = \add_query_arg('protected', 'true', $clean);
        }

        if ($clean !== $full) {
            \wp_safe_redirect($clean, 302);
            exit;
        }
    }

    /**
     * @deprecated Use redirectIfEmbedTransportParamsMismatchPolicy()
     */
    public static function redirectIfProtectedMustNotApplyToCurrentAdminUrl(): void
    {
        self::redirectIfEmbedTransportParamsMismatchPolicy();
    }

    /**
     * Detect if request is in iframe context (GET or POST referer).
     */
    public static function detectIframeContext(): bool
    {
        if (isset($_GET['fleekdash-frame']) && $_GET['fleekdash-frame'] === '1') {
            return true;
        }

        if (
            isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST'
            && isset($_POST['_wp_http_referer'])
        ) {
            $refererParts = parse_url(wp_unslash((string) $_POST['_wp_http_referer']));
            if (isset($refererParts['query'])) {
                parse_str($refererParts['query'], $params);
                if (isset($params['fleekdash-frame']) && $params['fleekdash-frame'] === '1') {
                    $_GET['fleekdash-frame'] = '1';
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Detect if request is in protected mode (fleek-window protection).
     */
    public static function detectProtectedMode(): bool
    {
        if (isset($_GET['protected']) && $_GET['protected'] === 'true') {
            return true;
        }

        if (
            isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST'
            && isset($_POST['_wp_http_referer'])
        ) {
            $refererParts = parse_url(wp_unslash((string) $_POST['_wp_http_referer']));
            if (isset($refererParts['query'])) {
                parse_str($refererParts['query'], $params);
                if (isset($params['protected']) && $params['protected'] === 'true') {
                    $_GET['protected'] = 'true';
                    return true;
                }
            }
        }

        return false;
    }
}
