<?php

/**
 * Azure cloud environment helpers for SSO.
 *
 * Centralizes Azure Commercial vs US Government endpoint logic.
 * US Government: login.microsoftonline.us, graph.microsoft.us
 *
 * @package SSO
 */

const SSO_AZURE_ENV_COMMERCIAL = 'commercial';
const SSO_AZURE_ENV_US_GOVERNMENT = 'us_government';
const SSO_AZURE_GRAPH_SCOPE_COMMERCIAL = 'https://graph.microsoft.com/.default';
const SSO_AZURE_GRAPH_SCOPE_US_GOVERNMENT = 'https://graph.microsoft.us/.default';
const SSO_AZURE_GRAPH_BASE_COMMERCIAL = 'https://graph.microsoft.com';
const SSO_AZURE_GRAPH_BASE_US_GOVERNMENT = 'https://graph.microsoft.us';

function sso_azure_environment($tenant_or_env, $reject_invalid = false)
{
    $raw = is_array($tenant_or_env)
        ? (isset($tenant_or_env['azure_environment']) ? $tenant_or_env['azure_environment'] : '')
        : $tenant_or_env;

    if ($raw === null || $raw === '') {
        return SSO_AZURE_ENV_COMMERCIAL;
    }
    $v = trim((string)$raw);
    if ($v === SSO_AZURE_ENV_COMMERCIAL || $v === SSO_AZURE_ENV_US_GOVERNMENT) {
        return $v;
    }
    return $reject_invalid ? null : SSO_AZURE_ENV_COMMERCIAL;
}

function sso_azure_graph_settings($tenant_or_env)
{
    $gov = sso_azure_environment($tenant_or_env) === SSO_AZURE_ENV_US_GOVERNMENT;
    return array(
        'scope' => $gov ? SSO_AZURE_GRAPH_SCOPE_US_GOVERNMENT : SSO_AZURE_GRAPH_SCOPE_COMMERCIAL,
        'base'  => $gov ? SSO_AZURE_GRAPH_BASE_US_GOVERNMENT : SSO_AZURE_GRAPH_BASE_COMMERCIAL,
    );
}

function sso_azure_provider_params(array $tenant)
{
    $params = [
        'clientId'     => isset($tenant['client_id']) ? $tenant['client_id'] : '',
        'clientSecret' => isset($tenant['client_secret']) ? $tenant['client_secret'] : '',
    ];
    if (!empty($tenant['tenant_id'])) {
        $params['tenantId'] = $tenant['tenant_id'];
    }
    $azure_environment = sso_azure_environment($tenant);
    if ($azure_environment === SSO_AZURE_ENV_US_GOVERNMENT) {
        $params['azureEnvironment'] = SSO_AZURE_ENV_US_GOVERNMENT;
    } elseif ($azure_environment === SSO_AZURE_ENV_COMMERCIAL) {
        $params['azureEnvironment'] = SSO_AZURE_ENV_COMMERCIAL;
    }
    return $params;
}
