<?php
/**
 * Dynamics 365 OAuth helpers (email receive only — no helpdesk dependency).
 */

function getAccessToken($config)
{
    if (empty($config['tenant_id']) || empty($config['client_id']) || empty($config['client_secret'])) {
        return null;
    }

    $tenantId = $config['tenant_id'];
    $clientId = $config['client_id'];
    $clientSecret = $config['client_secret'];
    $orgUrl = $config['orgUrl'] ?? $config['resource'] ?? '';

    $tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token";
    $data = http_build_query([
        'grant_type' => 'client_credentials',
        'client_id' => $clientId,
        'client_secret' => $clientSecret,
        'scope' => "$orgUrl/.default",
    ]);

    $ch = curl_init($tokenUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
    $response = curl_exec($ch);
    curl_close($ch);

    $tokenData = json_decode($response, true);
    if (empty($tokenData['access_token'])) {
        error_log('Dynamics token retrieval failed: ' . $response);
        return null;
    }

    return $tokenData['access_token'];
}

function loadDynamicsConfig($conn, $db)
{
    $result = mysqli_query($conn, "SELECT client_id, client_secret, tenant_id, url, scope FROM $db.tbl_dynamic_connection LIMIT 1");
    if (!$result || !($row = mysqli_fetch_assoc($result))) {
        return null;
    }

    return [
        'client_id' => $row['client_id'],
        'client_secret' => $row['client_secret'],
        'tenant_id' => $row['tenant_id'],
        'resource' => $row['url'],
        'orgUrl' => $row['url'],
        'scope' => $row['scope'],
    ];
}
