<?php
namespace EasyChat\Library\Messenger;





final class SmsInstallationScope {
    public static function create(string $site_url, string $session_token): string {
        $site_url = trim($site_url);
        $session_token = trim($session_token);
        if ($site_url === '' || $session_token === '') {
            return '';
        }

        $endpoint = self::canonicalEndpoint($site_url);
        if ($endpoint === '') {
            return '';
        }

        return substr(hash('sha256', "v1\0" . $endpoint . "\0" . $session_token), 0, 32);
    }

    public static function currentSiteUrl(): string {
        if (function_exists('easychat_public_base_url')) {
            return (string)easychat_public_base_url();
        }

        return defined('HTTP_SERVER') ? (string)HTTP_SERVER : '';
    }

    private static function canonicalEndpoint(string $site_url): string {
        $parts = parse_url(trim($site_url));
        if (!is_array($parts)) {
            return '';
        }

        $scheme = strtolower((string)($parts['scheme'] ?? ''));
        $host = strtolower((string)($parts['host'] ?? ''));
        if ($scheme === '' || $host === '') {
            return '';
        }

        $port_number = isset($parts['port']) ? (int)$parts['port'] : -1;
        $default_port = ($scheme === 'https' && $port_number === 443)
            || ($scheme === 'http' && $port_number === 80);
        $port = $port_number < 0 || $default_port ? '' : ':' . $port_number;
        $path = rtrim((string)($parts['path'] ?? '/'), '/');
        if ($path === '') {
            $path = '/';
        }

        return $scheme . '://' . $host . $port . $path;
    }
}
