<?php

namespace PloverCRM\Common;

/**
 * IP Handler
 * 
 * Handles IP detection and validation
 */
class IpHandler
{
    /**
     * Get the real user IP address
     */
    public static function getRealUserIp(): string
    {
        $ip = $_SERVER['REMOTE_ADDR'];

        // Check for proxy headers
        $proxy_headers = [
            'HTTP_CF_CONNECTING_IP',    // Cloudflare
            'HTTP_X_REAL_IP',            // Nginx proxy
            'HTTP_X_FORWARDED_FOR',      // Standard proxy header
            'HTTP_CLIENT_IP',            // Some proxies
        ];

        foreach ($proxy_headers as $header) {
            if (!empty($_SERVER[$header])) {
                $potential_ip = $_SERVER[$header];

                // HTTP_X_FORWARDED_FOR can contain multiple IPs
                if (strpos($potential_ip, ',') !== false) {
                    $ips = explode(',', $potential_ip);
                    $potential_ip = trim($ips[0]);
                }

                if (self::isValidIp($potential_ip)) {
                    $ip = $potential_ip;
                    break;
                }
            }
        }

        return $ip;
    }

    /**
     * Validate IP address
     */
    public static function isValidIp(string $ip): bool
    {
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false;
    }
}
