<?php
/**
 * whp_panel_url($query) — returns the absolute URL to the WHP panel for
 * the given query string (no leading '?').
 *
 * Resolution order (first non-empty wins):
 *   1. /docker/whp/settings.json -> hostname
 *        Set by the Server Settings page (Hostname field). This is the
 *        canonical source.
 *   2. /docker/whp/settings.json -> panel_domain
 *        Optional override for installs where the panel is reachable at
 *        a different host/port than the system hostname (e.g. staging
 *        behind an IP:port). Must be set by hand; there's no UI for it.
 *   3. gethostname() if it looks like an FQDN (contains a dot).
 *   4. '#' as a last resort; emails still send but the button won't
 *      navigate, and a warning is logged.
 *
 * WHP listens on 8443 (HTTPS) and 8080 (HTTP), not on 443/80. The helper
 * appends the appropriate default port when the configured hostname does
 * not already include one. If the configured value starts with http:// or
 * https://, that scheme/port combination is used verbatim (escape hatch
 * for installs fronted by a reverse proxy that uses 443 publicly).
 */

// Default ports the WHP panel listens on, per scheme.
if (!defined('WHP_PORT_HTTPS')) define('WHP_PORT_HTTPS', 8443);
if (!defined('WHP_PORT_HTTP'))  define('WHP_PORT_HTTP',  8080);

if (!function_exists('whp_panel_url')) {

    function whp_panel_url(string $query = ''): string {
        static $cached = null;
        if ($cached === null) {
            $raw = '';
            $settingsFile = '/docker/whp/settings.json';
            if (is_readable($settingsFile)) {
                $settings = json_decode((string)file_get_contents($settingsFile), true) ?: [];
                foreach (['hostname', 'panel_domain'] as $key) {
                    $candidate = trim((string)($settings[$key] ?? ''));
                    if ($candidate !== '') { $raw = $candidate; break; }
                }
            }
            if ($raw === '') {
                $hn = gethostname();
                if ($hn && strpos($hn, '.') !== false) {
                    $raw = $hn;
                }
            }
            if ($raw === '') {
                error_log('whp_panel_url: no hostname in /docker/whp/settings.json (set it via Server Settings → Server Hostname)');
                $cached = '#';
            } else {
                $cached = whp_panel_url_normalize($raw);
            }
        }
        if ($cached === '#') {
            return '#';
        }
        $path = '/index.php';
        return $query === '' ? $cached . $path : $cached . $path . '?' . ltrim($query, '?');
    }

    /**
     * Turn a raw hostname value into a base URL ending in no trailing slash.
     *
     * Accepted inputs:
     *   whp01.cloud-hosting.io          -> https://whp01.cloud-hosting.io:8443
     *   whp01.cloud-hosting.io:8443     -> https://whp01.cloud-hosting.io:8443  (port kept, default scheme https)
     *   192.168.1.105:8080              -> http://192.168.1.105:8080            (explicit port that matches http default)
     *   https://panel.example.com       -> https://panel.example.com            (scheme respected, no port added)
     *   https://panel.example.com:9000  -> https://panel.example.com:9000
     */
    function whp_panel_url_normalize(string $raw): string {
        $raw = trim($raw);
        $lower = strtolower($raw);
        // Explicit scheme wins: use verbatim, don't add a port.
        if (strpos($lower, 'http://') === 0 || strpos($lower, 'https://') === 0) {
            return rtrim($raw, '/');
        }
        // Strip any leading '//' a user might have entered.
        $host = ltrim($raw, '/');
        // Pick scheme. If a port suffix is present and equals WHP_PORT_HTTP,
        // go http; otherwise https (covers bare hostnames and :8443).
        $scheme = 'https';
        $defaultPort = WHP_PORT_HTTPS;
        if (preg_match('/:(\d+)$/', $host, $m)) {
            $port = (int)$m[1];
            // Heuristic: port 80 or the WHP http port → http. Everything else → https.
            if ($port === 80 || $port === WHP_PORT_HTTP) {
                $scheme = 'http';
            }
            // Keep the explicit port in the host string; don't re-append.
            return $scheme . '://' . $host;
        }
        return $scheme . '://' . $host . ':' . $defaultPort;
    }
}
