<?php

namespace PloverCRM\Common;

/**
 * Holds request-scoped webhook tracking context so enrichment can consume it
 * without persisting transport-only payloads as CRM custom fields.
 */
class WebhookContextStore
{
    private static array $context = [];

    public static function remember(array $context): void
    {
        $filteredCookies = [];
        $cookies = is_array($context['cookies'] ?? null) ? $context['cookies'] : [];

        foreach (Hooks::getTrackingCookieKeys() as $key) {
            if (!isset($cookies[$key]) || $cookies[$key] === '') {
                continue;
            }

            $filteredCookies[$key] = self::sanitizeCookieValue($key, $cookies[$key]);
        }

        $referrerUrl = self::sanitizeUrl($context['referrer_url'] ?? '');
        $referrerDomain = (string) ($context['referrer_domain'] ?? '');
        if ($referrerDomain === '' && $referrerUrl !== '') {
            $referrerDomain = Hooks::getExternalRefererDomain($referrerUrl);
        }

        self::$context = [
            'user_ip' => self::sanitizeIp($context['user_ip'] ?? ''),
            'user_agent' => sanitize_text_field((string) ($context['user_agent'] ?? '')),
            'current_url' => self::sanitizeUrl($context['current_url'] ?? ''),
            'referrer_url' => $referrerUrl,
            'referrer_domain' => sanitize_text_field((string) $referrerDomain),
            'cookies' => $filteredCookies,
        ];
    }

    public static function current(): array
    {
        return self::$context;
    }

    public static function has(): bool
    {
        return !empty(self::$context);
    }

    public static function clear(): void
    {
        self::$context = [];
    }

    public static function buildFromRequest(array $payload = []): array
    {
        $payloadCookies = [];
        if (is_array($payload['plover_crm_cookies'] ?? null)) {
            $payloadCookies = $payload['plover_crm_cookies'];
        } elseif (is_array($payload['cookies'] ?? null)) {
            $payloadCookies = $payload['cookies'];
        }

        $referrerUrl = (string) ($payload['plover_crm_referer'] ?? ($payload['referrer_url'] ?? ($payload['referer_url'] ?? Hooks::getRefererUrl())));

        return [
            'user_ip' => (string) ($payload['plover_crm_user_ip'] ?? ($payload['user_ip'] ?? IpHandler::getRealUserIp())),
            'user_agent' => (string) ($payload['plover_crm_user_agent'] ?? ($payload['user_agent'] ?? ($_SERVER['HTTP_USER_AGENT'] ?? ''))),
            'current_url' => (string) ($payload['plover_crm_current_url'] ?? ($payload['current_url'] ?? '')),
            'referrer_url' => $referrerUrl,
            'referrer_domain' => '',
            'cookies' => !empty($payloadCookies) ? $payloadCookies : $_COOKIE,
        ];
    }

    private static function sanitizeIp($ip): ?string
    {
        $ip = trim((string) $ip);
        return $ip !== '' ? $ip : null;
    }

    private static function sanitizeUrl($url): string
    {
        $url = trim((string) $url);
        return $url !== '' ? esc_url_raw($url) : '';
    }

    private static function sanitizeCookieValue(string $key, $value): string
    {
        $value = is_scalar($value) ? (string) $value : '';
        if ($value === '') {
            return '';
        }

        if (str_contains($key, 'page_url')) {
            return esc_url_raw($value);
        }

        return sanitize_text_field($value);
    }
}
