<?php

namespace PloverCRM\Common;

/**
 * WordPress Hooks Handler
 * 
 * Registers WordPress hooks and filters
 */
class Hooks
{
    private const COOKIE_PREFIX = 'plover_crm_';
    private const FIRST_TOUCH_QUERY_PARAMS = [
        'utm_id',
        'utm_source',
        'utm_medium',
        'utm_campaign',
        'utm_term',
        'utm_content',
        'gclid',
        'fbclid',
        'msclkid',
        'ttclid',
        'li_fat_id',
        'twclid',
    ];
    private const LAST_TOUCH_QUERY_PARAMS = [
        'utm_source',
        'utm_medium',
        'utm_campaign',
        'utm_term',
        'utm_content',
    ];

    /**
     * Initialize hooks
     */
    public static function init(): void
    {
        // Email generation hooks
        add_filter('fluent_crm/incoming_webhook_data', [self::class, 'handleIncomingWebhookData'], 10);
        add_filter('fluentform/insert_response_data', [self::class, 'handleFluentFormData'], 10);
        add_action('elementor_pro/forms/form_submitted', [self::class, 'handleElementorFormData']);

        // UTM and tracking cookies
        add_action('init', [self::class, 'storeUtmCookies']);

        // Hide internal CRM bridge users from the standard WordPress user list
        // and block direct WordPress login for those bridge accounts.
        add_action('pre_get_users', [CrmUserManager::class, 'shouldHideShadowUsersInQuery']);
        add_filter('wp_authenticate_user', [CrmUserManager::class, 'blockShadowUserLogin'], 10, 1);
    }

    /**
     * Handle incoming webhook data - generate email if empty
     */
    public static function handleIncomingWebhookData($postedData)
    {
        if (empty($postedData['email'])) {
            $postedData['email'] = Utils::generateRandomEmail();
        }
        return $postedData;
    }

    /**
     * Handle Fluent Forms data - generate email if empty
     */
    public static function handleFluentFormData($formData)
    {
        // Only proceed if 'email' field exists in the form
        if (isset($formData['email']) && empty($formData['email'])) {
            if (!empty($formData['phone'])) {
                // Generate email from phone number
                $phone = preg_replace('/\D+/', '', $formData['phone']);
                $formData['email'] = $phone . '@wpr.com';
            } else {
                // Fallback: generate email from IP hash
                $ipAddress = $_SERVER['REMOTE_ADDR'];
                $hashedEmail = sprintf('%u', crc32($ipAddress)) . '@wpr.com';
                $formData['email'] = $hashedEmail;
            }
        }

        return $formData;
    }

    /**
     * Handle Elementor Pro form data - generate email if empty
     */
    public static function handleElementorFormData(): void
    {
        if (isset($_POST['form_fields']['email']) && empty($_POST['form_fields']['email'])) {
            $_POST['form_fields']['email'] = Utils::generateRandomEmail();
        }
    }

    /**
     * Store UTM parameters and tracking data in cookies
     */
    public static function storeUtmCookies(): void
    {
        if (!self::shouldTrackRequest()) {
            return;
        }

        $expiration = time() + 90 * DAY_IN_SECONDS; // 90-day lifetime for attribution
        $currentUrl = self::getCurrentUrl();
        $refererUrl = self::getRefererUrl();
        $refererDomain = self::getExternalRefererDomain($refererUrl);

        foreach (self::FIRST_TOUCH_QUERY_PARAMS as $param) {
            if (!isset($_GET[$param])) {
                continue;
            }

            self::setTrackingCookie(
                self::COOKIE_PREFIX . $param,
                sanitize_text_field(wp_unslash($_GET[$param])),
                $expiration,
                false
            );
        }

        foreach (self::LAST_TOUCH_QUERY_PARAMS as $param) {
            if (!isset($_GET[$param])) {
                continue;
            }

            self::setTrackingCookie(
                self::COOKIE_PREFIX . 'last_' . $param,
                sanitize_text_field(wp_unslash($_GET[$param])),
                $expiration,
                true
            );
        }

        if ($refererDomain) {
            self::setTrackingCookie(
                self::COOKIE_PREFIX . 'referral_domain',
                sanitize_text_field($refererDomain),
                $expiration,
                false
            );

            self::setTrackingCookie(
                self::COOKIE_PREFIX . 'last_referral_domain',
                sanitize_text_field($refererDomain),
                $expiration,
                true
            );
        }

        if ($currentUrl) {
            self::setTrackingCookie(
                self::COOKIE_PREFIX . 'landing_page_first_visit',
                esc_url_raw($currentUrl),
                $expiration,
                false
            );

            self::setTrackingCookie(
                self::COOKIE_PREFIX . 'last_page_url',
                esc_url_raw($currentUrl),
                $expiration,
                true
            );
        }

        $formattedTime = wp_date('Y-m-d H:i:s');

        self::setTrackingCookie(
            self::COOKIE_PREFIX . 'landing_datetime_first_visit',
            $formattedTime,
            $expiration,
            false
        );

        self::setTrackingCookie(
            self::COOKIE_PREFIX . 'last_seen_at',
            $formattedTime,
            $expiration,
            true
        );
    }

    public static function getTrackingCookieKeys(): array
    {
        return [
            self::COOKIE_PREFIX . 'utm_id',
            self::COOKIE_PREFIX . 'utm_source',
            self::COOKIE_PREFIX . 'utm_medium',
            self::COOKIE_PREFIX . 'utm_campaign',
            self::COOKIE_PREFIX . 'utm_term',
            self::COOKIE_PREFIX . 'utm_content',
            self::COOKIE_PREFIX . 'gclid',
            self::COOKIE_PREFIX . 'fbclid',
            self::COOKIE_PREFIX . 'msclkid',
            self::COOKIE_PREFIX . 'ttclid',
            self::COOKIE_PREFIX . 'li_fat_id',
            self::COOKIE_PREFIX . 'twclid',
            self::COOKIE_PREFIX . 'referral_domain',
            self::COOKIE_PREFIX . 'landing_page_first_visit',
            self::COOKIE_PREFIX . 'landing_datetime_first_visit',
            self::COOKIE_PREFIX . 'last_utm_source',
            self::COOKIE_PREFIX . 'last_utm_medium',
            self::COOKIE_PREFIX . 'last_utm_campaign',
            self::COOKIE_PREFIX . 'last_utm_term',
            self::COOKIE_PREFIX . 'last_utm_content',
            self::COOKIE_PREFIX . 'last_referral_domain',
            self::COOKIE_PREFIX . 'last_page_url',
            self::COOKIE_PREFIX . 'last_seen_at',
        ];
    }

    public static function getCurrentUrl(): string
    {
        $host = sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'] ?? ''));
        $requestUri = wp_unslash($_SERVER['REQUEST_URI'] ?? '');

        if (!$host || !$requestUri) {
            return '';
        }

        return esc_url_raw((is_ssl() ? 'https://' : 'http://') . $host . $requestUri);
    }

    public static function getRefererUrl(): string
    {
        if (empty($_SERVER['HTTP_REFERER'])) {
            return '';
        }

        return esc_url_raw(wp_unslash($_SERVER['HTTP_REFERER']));
    }

    public static function getExternalRefererDomain(string $refererUrl): string
    {
        if (!$refererUrl) {
            return '';
        }

        $refererHost = wp_parse_url($refererUrl, PHP_URL_HOST);
        $currentHost = sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'] ?? ''));

        if (!$refererHost || !$currentHost || $refererHost === $currentHost) {
            return '';
        }

        return sanitize_text_field($refererHost);
    }

    private static function shouldTrackRequest(): bool
    {
        if (is_admin() || wp_doing_ajax() || wp_doing_cron()) {
            return false;
        }

        if (defined('REST_REQUEST') && REST_REQUEST) {
            return false;
        }

        $requestMethod = strtoupper(sanitize_text_field(wp_unslash($_SERVER['REQUEST_METHOD'] ?? 'GET')));
        if ($requestMethod !== 'GET') {
            return false;
        }

        $fetchDest = strtolower(sanitize_text_field(wp_unslash($_SERVER['HTTP_SEC_FETCH_DEST'] ?? '')));
        if ($fetchDest !== '' && !in_array($fetchDest, ['document', 'iframe', 'frame'], true)) {
            return false;
        }

        $acceptHeader = strtolower(sanitize_text_field(wp_unslash($_SERVER['HTTP_ACCEPT'] ?? '')));
        if (
            $acceptHeader !== '' &&
            !str_contains($acceptHeader, 'text/html') &&
            !str_contains($acceptHeader, 'application/xhtml+xml')
        ) {
            return false;
        }

        return true;
    }

    private static function setTrackingCookie(string $name, string $value, int $expiration, bool $overwrite): void
    {
        if ($value === '') {
            return;
        }

        if (!$overwrite && isset($_COOKIE[$name]) && $_COOKIE[$name] !== '') {
            return;
        }

        $_COOKIE[$name] = $value;

        if (!headers_sent()) {
            setcookie($name, $value, $expiration, '/', '', is_ssl(), true);
        }
    }
}
