<?php
// sms_brq.php
//
// BRQ SMS simple sender using cURL (GET request).
// Docs style: https://dash.brqsms.com/api/http/sms/send?... (as provided)

function brq_send_sms(string $recipientE164, string $message, string $senderId = 'UOFG'): array
{
    // Load token from environment for safety
    $apiToken = getenv('BRQ_SMS_TOKEN'); // set it in your vhost/Apache: SetEnv BRQ_SMS_TOKEN "11|xxxxx..."
    if (!$apiToken) {
        return ['ok' => false, 'error' => 'Missing BRQ_SMS_TOKEN env variable.'];
    }

    // Basic recipient sanitization: keep + and digits only
    $recipientE164 = preg_replace('/[^\d+]/', '', $recipientE164 ?? '');
    if ($recipientE164 === '' || strlen(preg_replace('/\D/', '', $recipientE164)) < 8) {
        return ['ok' => false, 'error' => 'Invalid recipient phone number.'];
    }

    // Build endpoint with RFC3986 encoding
    $endpoint = 'https://dash.brqsms.com/api/http/sms/send';
    $query = http_build_query([
        'recipient' => $recipientE164,        // e.g. +2499xxxxxxx or 31612345678
        'sender_id' => $senderId,             // must be allowed by your BRQ account
        'message'   => $message,              // keep it short: many routes are 160 GSM chars per segment
        'api_token' => $apiToken,
    ], '', '&', PHP_QUERY_RFC3986);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $endpoint . '?' . $query,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        // OPTIONAL: follow redirects just in case
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 3,
        // Safe defaults for production
        CURLOPT_HTTPHEADER     => [
            'Accept: application/json',
            'User-Agent: UOFG-Portal/1.0',
        ],
    ]);

    $body = curl_exec($ch);
    $errno = curl_errno($ch);
    $err   = curl_error($ch);
    $http  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($errno) {
        return ['ok' => false, 'error' => 'cURL error: ' . $err];
    }

    // Try to parse JSON; if not JSON, return raw body
    $json = json_decode($body, true);
    if ($json !== null) {
        // Heuristic: many gateways return { success: true/false, message_id: "...", ... }
        $success = (isset($json['success']) && $json['success']) || $http >= 200 && $http < 300;
        return ['ok' => $success, 'http' => $http, 'response' => $json];
    }

    // Fallback for non-JSON responses
    $ok = ($http >= 200 && $http < 300);
    return ['ok' => $ok, 'http' => $http, 'response_raw' => $body];
}
