<?php
/**
 * Bezbedna detekcija transporta i klijentske IP adrese.
 * Proxy zaglavlja se koriste samo kada je neposredni peer eksplicitno pouzdan.
 */

function request_valid_ip(string $value): ?string
{
    $value = trim($value);
    return filter_var($value, FILTER_VALIDATE_IP) !== false ? $value : null;
}

function trusted_proxy_ips(): array
{
    $configured = defined('TRUSTED_PROXY_IPS') && is_array(TRUSTED_PROXY_IPS) ? TRUSTED_PROXY_IPS : [];
    $result = [];
    foreach ($configured as $ip) {
        $valid = request_valid_ip((string)$ip);
        if ($valid !== null) {
            $result[$valid] = true;
        }
    }
    return array_keys($result);
}

function request_remote_ip(): string
{
    return request_valid_ip((string)($_SERVER['REMOTE_ADDR'] ?? '')) ?? '0.0.0.0';
}

function request_is_from_trusted_proxy(): bool
{
    return in_array(request_remote_ip(), trusted_proxy_ips(), true);
}

function request_client_ip(): string
{
    if (request_is_from_trusted_proxy()) {
        foreach (explode(',', (string)($_SERVER['HTTP_X_FORWARDED_FOR'] ?? '')) as $candidate) {
            $valid = request_valid_ip($candidate);
            if ($valid !== null) {
                return $valid;
            }
        }
    }
    return request_remote_ip();
}

function request_is_https(): bool
{
    if ((!empty($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) !== 'off')
        || (int)($_SERVER['SERVER_PORT'] ?? 0) === 443) {
        return true;
    }

    if (!request_is_from_trusted_proxy()) {
        return false;
    }

    $forwardedProto = strtolower(trim(explode(',', (string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? ''))[0] ?? ''));
    return $forwardedProto === 'https' || strtolower((string)($_SERVER['HTTP_X_FORWARDED_SSL'] ?? '')) === 'on';
}

function request_should_use_secure_cookie(): bool
{
    return request_is_https() || (defined('APP_FORCE_SECURE_COOKIE') && APP_FORCE_SECURE_COOKIE === true);
}
