<?php
/**
 * Resolves the visitor address from server variables.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Core;

/**
 * Behind a reverse proxy REMOTE_ADDR is the proxy, not the visitor. Reading it
 * directly would give every visitor the same address and let one person's rate
 * limit lock out the whole shop.
 */
final class ClientIp
{
    /**
     * @param array<string,mixed> $server A copy of $_SERVER.
     */
    public static function resolve(array $server): string
    {
        $candidates = [
            'HTTP_CF_CONNECTING_IP',
            'HTTP_X_FORWARDED_FOR',
            'REMOTE_ADDR',
        ];

        foreach ($candidates as $key) {
            if (!isset($server[$key])) {
                continue;
            }

            $value = (string) $server[$key];
            $first = trim(explode(',', $value)[0]);

            if (false !== filter_var($first, FILTER_VALIDATE_IP)) {
                return $first;
            }
        }

        return '';
    }
}
