<?php

class NetworkHelper
{
    /**
     * @param bool $verifyNameBelongsToServer if this parameter is set to true,
     * then function performs DNS lookup to verify server name's IP address matches server's IP address
     * @return string
     * @throws ResponseException
     */
    public static function getServerUrl(bool $verifyNameBelongsToServer): string
    {
        $serverName = $_SERVER['SERVER_NAME'];
        $serverIP = $_SERVER['SERVER_ADDR']; // The server's actual IP address
        $port = key_exists('SERVER_PORT', $_SERVER) && !in_array($_SERVER['SERVER_PORT'], [443, 80]) ? ':' . $_SERVER['SERVER_PORT'] : '';

        if ($verifyNameBelongsToServer) {
            // Perform a DNS lookup to get the IP address of the server name
            $resolvedIPs = gethostbynamel($serverName);

            // Check if the resolved IP matches the server's IP
            if ($resolvedIPs === false || !in_array($serverIP, $resolvedIPs)) {
                throw new ResponseException(
                    'The server name does not belong to this server',
                    Response::BADREQUEST
                );
            }
        }
        return 'https://' . $serverName . $port;
    }
}
