<?php
// ============================================
// SEN RDV SANTÉ+ — Configuration Africa's Talking SMS
// ============================================
define('AT_USERNAME', 'senrdvsanteplus');
define('AT_API_KEY',  'atsk_1f3d4a5376a1463d852bd66d397ea0eddc37117f96313bf94e1f33593e61c8c8c1ad6094');
define('AT_SENDER',   'SenRdvSante'); // vide en attendant approbation Sender ID

// fonction centralisée d'envoi SMS via Africa's Talking
function envoyerSMS(string $telephone, string $message): bool {
    // je formate le numéro en international +221XXXXXXXXX
    $tel = $telephone;
    if (!str_starts_with($tel, '+')) {
        $tel = '+221' . ltrim($tel, '0');
    }

    // je construis le body JSON pour l'endpoint Bulk SMS
    $body = [
        'username'     => AT_USERNAME,
        'message'      => $message,
        'phoneNumbers' => [$tel],
    ];
    if (!empty(AT_SENDER)) {
        $body['senderId'] = AT_SENDER;
    }

    $ch = curl_init('https://api.africastalking.com/version1/messaging/bulk');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            'Accept: application/json',
            'Content-Type: application/json',
            'apiKey: ' . AT_API_KEY,
        ],
        CURLOPT_POSTFIELDS => json_encode($body),
        CURLOPT_TIMEOUT    => 15,
    ]);

    $reponse = curl_exec($ch);
    $erreur  = curl_error($ch);
    curl_close($ch);

    if ($erreur) {
        error_log("SMS erreur cURL: $erreur");
        return false;
    }

    $data = json_decode($reponse, true);
    error_log("SMS réponse AT: $reponse");

    return isset($data['SMSMessageData']['Recipients'][0]['status'])
        && str_contains($data['SMSMessageData']['Recipients'][0]['status'], 'Success');
}