<?php
function brq_send_sms(string $to, string $message, string $senderId = 'UOFG', array $opts = []): array {
    $API_BASE  = 'https://dash.brqsms.com/api/http/sms/send';
    $API_TOKEN = '11|lztDoMxzMfbkuNAL8nCFAGdftW0CtkrHxiU0qIBAbf1c0331';
    $LOG_FILE  = __DIR__ . '/logs/sms.log';

    // Normalize: digits only, full intl; many gateways dislike '+'
    $to = preg_replace('/\D+/', '', $to);
    if (!preg_match('/^\d{8,20}$/', $to)) {
        return _sms_fail('Invalid phone number after normalization', 0, null, $LOG_FILE);
    }

    $payload = [
        'recipient'  => $to,
        'sender_id'  => $senderId,
        'message'    => $message,
        'api_token'  => $API_TOKEN,
        'unicode'    => '1', // Arabic
    ];

    // 1) Try JSON POST (what their validator likely expects)
    $jsonResult = _brq_http($API_BASE, 'POST', json_encode($payload, JSON_UNESCAPED_UNICODE), [
        'Content-Type: application/json',
        'Accept: application/json',
        'User-Agent: BRQ-SMS-Client/1.1'
    ]);

    if (_looks_ok($jsonResult)) {
        return _log_and_return($jsonResult, $LOG_FILE, $to, $senderId, 'json');
    }

    // 2) Fallback: form-encoded POST
    $formResult = _brq_http($API_BASE, 'POST', http_build_query($payload, '', '&', PHP_QUERY_RFC3986), [
        'Content-Type: application/x-www-form-urlencoded',
        'Accept: application/json',
        'User-Agent: BRQ-SMS-Client/1.1'
    ]);
    if (_looks_ok($formResult)) {
        return _log_and_return($formResult, $LOG_FILE, $to, $senderId, 'form');
    }

    // 3) Fallback: GET (as their sample URL shows)
    $url = $API_BASE . '?' . http_build_query($payload, '', '&', PHP_QUERY_RFC3986);
    $getResult = _brq_http($url, 'GET', null, [
        'Accept: application/json',
        'User-Agent: BRQ-SMS-Client/1.1'
    ]);
    return _log_and_return($getResult, $LOG_FILE, $to, $senderId, 'get');
}

function _brq_http(string $url, string $method, ?string $body, array $headers): array {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_HTTPHEADER     => $headers,
    ]);
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body ?? '');
    }
    $respBody = curl_exec($ch);
    $errno    = curl_errno($ch);
    $errstr   = curl_error($ch);
    $status   = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $json = null;
    if (is_string($respBody)) {
        $json = json_decode($respBody, true);
    }
    $ok = ($errno === 0 && $status >= 200 && $status < 300 && _gateway_success($json, $respBody));

    return [
        'ok'       => $ok,
        'status'   => $status,
        'errno'    => $errno,
        'error'    => $errstr,
        'body'     => $respBody,
        'response' => $json,
    ];
}

function _gateway_success($json, $raw) {
    // Consider success if JSON has status 'success' or 'ok'
    if (is_array($json) && isset($json['status'])) {
        $s = strtolower((string)$json['status']);
        return in_array($s, ['success','ok','sent','queued'], true);
    }
    // If not JSON, a non-empty raw 2xx might still be success—be conservative:
    return false;
}

function _looks_ok(array $r): bool {
    if ($r['errno'] !== 0) return false;
    if ($r['status'] < 200 || $r['status'] >= 300) return false;
    // Must not contain the "recipient field is required" error:
    if (is_string($r['body']) && stripos($r['body'], 'recipient field is required') !== false) return false;
    return _gateway_success($r['response'], $r['body']);
}

function _log_and_return(array $r, string $file, string $to, string $sender, string $mode): array {
    _sms_log($file, [
        'ts'      => date('c'),
        'ok'      => $r['ok'],
        'status'  => $r['status'],
        'errno'   => $r['errno'],
        'error'   => $r['error'],
        'to'      => $to,
        'sender'  => $sender,
        'mode'    => $mode,
        'body'    => is_string($r['body']) ? substr($r['body'], 0, 1000) : $r['body'],
        'note'    => $r['ok'] ? 'Delivered to gateway' : 'Gateway indicated failure',
    ]);
    return $r;
}

function _sms_log(string $file, array $row): void {
    try {
        if (!is_dir(dirname($file))) @mkdir(dirname($file), 0775, true);
        @file_put_contents($file, json_encode($row, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
    } catch (\Throwable $e) { /* ignore logging errors */ }
}
function _sms_fail(string $msg, int $status = 0, $body = null, string $logFile = null): array {
    if ($logFile) _sms_log($logFile, ['ts'=>date('c'), 'ok'=>false, 'status'=>$status, 'error'=>$msg, 'body'=>$body]);
    return ['ok'=>false, 'status'=>$status, 'errno'=>0, 'error'=>$msg, 'body'=>$body, 'response'=>null];
}
