<?php

namespace FleekDash\Services\AnalyticsTracking;

/**
 * Tracking Helpers
 *
 * Utility methods for analytics tracking operations
 *
 * @package FleekDash\Services\AnalyticsTracking
 */
class TrackingHelpers
{
    /**
     * Get client IP address with proxy support
     *
     * @return string Client IP address
     */
    public static function getClientIP()
    {
        $ip_keys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'];

        foreach ($ip_keys as $key) {
            if (isset($_SERVER[$key])) {
                $ip = $_SERVER[$key];
                if (strpos($ip, ',') !== false) {
                    $ip = explode(',', $ip)[0];
                }
                $ip = trim($ip);
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                    return $ip;
                }
            }
        }

        return $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
    }

    /**
     * Get post data from URL
     *
     * @param string $url URL to extract post data from
     * @return array Post ID and type
     */
    public static function getPostDataFromUrl($url)
    {
        $post_id = function_exists('url_to_postid') ? \call_user_func('url_to_postid', $url) : 0;
        if ($post_id) {
            $post = \get_post($post_id);
            $post_type = is_object($post) && isset($post->post_type) ? $post->post_type : null;
            return [
                'post_id' => $post_id,
                'post_type' => $post_type
            ];
        }

        return ['post_id' => null, 'post_type' => null];
    }

    /**
     * Classify referrer type (direct, search, social, referral)
     *
     * @param string $referrer Referrer URL
     * @param string $referrer_domain Referrer domain
     * @return string Referrer type
     */
    public static function classifyReferrer($referrer, $referrer_domain)
    {
        if (empty($referrer))
            return 'direct';

        $search_engines = ['google.com', 'bing.com', 'yahoo.com', 'duckduckgo.com'];
        $social_networks = ['facebook.com', 'twitter.com', 'linkedin.com', 'instagram.com'];

        foreach ($search_engines as $engine) {
            if (strpos($referrer_domain, $engine) !== false) {
                return 'search';
            }
        }

        foreach ($social_networks as $network) {
            if (strpos($referrer_domain, $network) !== false) {
                return 'social';
            }
        }

        return 'referral';
    }
}

