<?php
function sendSMS($to, $text) {
    // ====== CONFIG ======
    $RC_CLIENT_ID     = 'ada5DLpdFmOeX960PXKKMm';
    $RC_CLIENT_SECRET = '0hqlE7XCJ7sdTrZ7k8TolM0dYlRYklZx4anvW0MOs0Mi';
    $RC_JWT           = 'eyJraWQiOiI4NzYyZjU5OGQwNTk0NGRiODZiZjVjYTk3ODA0NzYwOCIsInR5cCI6IkpXVCIsImFsZyI6IlJTMjU2In0.eyJhdWQiOiJodHRwczovL3BsYXRmb3JtLnJpbmdjZW50cmFsLmNvbS9yZXN0YXBpL29hdXRoL3Rva2VuIiwic3ViIjoiNjMyNDI1MTkwMDQiLCJpc3MiOiJodHRwczovL3BsYXRmb3JtLnJpbmdjZW50cmFsLmNvbSIsImV4cCI6Mzg4OTI3OTgwMSwiaWF0IjoxNzQxNzk2MTU0LCJqdGkiOiJOal9UTjdrZVNlcUIxMTRDUXVxWFNBIn0.YgWKJ97dyfJfUNuIwbUd8tfzdp5Wtql6n219amtvDTEdHhs7-kkLTiaeVmVDuWGk9NXSYxQ4WKTMwRJbSk70xzFryDxk4mKoigOZZxgEBKx-oPCIa7He1QFhNqvuJIY1XI09DmAEg6m2W4H0M6GrR1X33OW1ncCH1VTeWZZ1wc4VZl0Mruzr6VGFDKV4TE5dSNA0k8N5OZJtWsNTitxzwRcEjPB8ZMQiIKbaFdQSRR7mxsZQZSu6lEz6gJfjQOMHr-BUJtHdzRkgoY6njYV3Bb2IV0WaKMxpG-WJNuW647nHhTNeuPK184f8Txxfc1-erXVB7p4WVVLV899ZQ_eusg'; // your JWT
    $RC_SERVER        = 'https://platform.ringcentral.com';
    $FROM_NUMBER      = '+19547081374'; // your RC number

    // Normalize to E.164
    $digits = preg_replace('/\D+/', '', $to);
    if (strlen($digits) === 10) {
        $to = '+1' . $digits;
    } elseif (strlen($digits) === 11 && $digits[0] === '1') {
        $to = '+' . $digits;
    } elseif (!preg_match('/^\+\d{7,15}$/', $to)) {
        return ["error" => "Invalid phone number format: $to"];
    }

    // ====== 1) Get Access Token ======
    $tokenUrl = $RC_SERVER . '/restapi/oauth/token';
    $basicAuth = base64_encode($RC_CLIENT_ID . ':' . $RC_CLIENT_SECRET);
    $tokenPostFields = http_build_query([
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion'  => $RC_JWT
    ]);

    $ch = curl_init($tokenUrl);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Basic ' . $basicAuth,
            'Content-Type: application/x-www-form-urlencoded'
        ],
        CURLOPT_POSTFIELDS     => $tokenPostFields,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 20,
    ]);
    $tokenResp = curl_exec($ch);
    $tokenHttp = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr   = curl_error($ch);
    curl_close($ch);

    if ($tokenResp === false || $tokenHttp >= 400) {
        return ["error" => "Token error (HTTP $tokenHttp)", "details" => $tokenResp ?: $curlErr];
    }

    $tokenData   = json_decode($tokenResp, true);
    $accessToken = $tokenData['access_token'] ?? null;
    if (!$accessToken) {
        return ["error" => "No access_token in response", "raw" => $tokenResp];
    }

    // ====== 2) Send SMS ======
    $smsUrl = $RC_SERVER . '/restapi/v1.0/account/~/extension/~/sms';
    $payload = [
        'from' => ['phoneNumber' => $FROM_NUMBER],
        'to'   => [['phoneNumber' => $to]],
        'text' => $text
    ];

    $ch = curl_init($smsUrl);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . $accessToken,
            'Content-Type: application/json'
        ],
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 20,
    ]);
    $smsResp = curl_exec($ch);
    $smsHttp = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr = curl_error($ch);
    curl_close($ch);

    if ($smsResp === false || $smsHttp >= 400) {
        return ["error" => "SMS error (HTTP $smsHttp)", "details" => $smsResp ?: $curlErr];
    }

    return json_decode($smsResp, true);
}