<?php

namespace apexl\Utils\Urls;

class Host
{
    public static function getHost(): string
    {
        $possibleHostSources = array('HTTP_X_FORWARDED_HOST', 'HTTP_HOST', 'SERVER_NAME', 'SERVER_ADDR');
        $sourceTransformations = array(
            "HTTP_X_FORWARDED_HOST" => function ($value): string {
                $elements = explode(',', $value);
                return trim(end($elements));
            }
        );
        $host = '';
        foreach ($possibleHostSources as $source) {
            if (!empty($host)) {
                break;
            }
            if (empty($_SERVER[$source])) {
                continue;
            }
            $host = $_SERVER[$source];
            if (array_key_exists($source, $sourceTransformations)) {
                $host = $sourceTransformations[$source]($host);
            }
        }

        // Remove port number from host
        $host = preg_replace('/:\d+$/', '', (string) $host);

        return trim($host);
    }

    /**
     * Is the current host request under https?
     * @return bool
     */
    public static function isSecure()
    {
        return
            (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
            || $_SERVER['SERVER_PORT'] == 443;
    }

    /**
     * @param $url
     * @return object
     */
    public static function parseURLAsObject($url)
    {
        $urlObject = (object)parse_url((string) $url);
        $query = $urlObject->query ?? null;
        if (!empty($query)) {
            $urlObject->queryParts = (object)[];
            $elements = str_contains((string) $query, '&') ? explode('&', (string) $query) : [$query];
            foreach ($elements as $argString) {
                $args = explode('=', (string) $argString);
                $urlObject->queryParts->{$args[0]} = $args[1];
            }
        }
        if (isset($urlObject->path) && str_contains((string) $urlObject->path, '/')) {
            $urlObject->pathParts = explode('/', (string) $urlObject->path);
        }
        return $urlObject;
    }
}
