<?php
/**
 * BeemSms — thin client for the Beem Africa v1 send-sms API.
 * Docs: https://docs.beem.africa/#/send-sms
 *
 * We use HTTP Basic auth (api_key : secret_key). One recipient per call;
 * batching is a Beem Enterprise feature we don't need at Pacific scale.
 *
 * On success returns {ok:true, message_id:"..."}; on failure returns
 * {ok:false, msg:"..."} — the caller (Outbox::dispatchPendingSms) handles
 * retries and status transitions.
 */
class BeemSms
{
    private string $apiKey;
    private string $secretKey;
    private string $senderId;
    private string $endpoint = 'https://apisms.beem.africa/v1/send';

    public function __construct()
    {
        $this->apiKey    = defined('BEEM_API_KEY')    ? (string)BEEM_API_KEY    : '';
        $this->secretKey = defined('BEEM_SECRET_KEY') ? (string)BEEM_SECRET_KEY : '';
        $this->senderId  = defined('BEEM_SENDER_ID')  ? (string)BEEM_SENDER_ID  : 'PACIFIC';
    }

    public function send(string $msisdn, string $message): array
    {
        if ($this->apiKey === '' || $this->secretKey === '') {
            return ['ok' => false, 'msg' => 'Beem API keys not configured.'];
        }
        // Beem expects recipients as {recipient_id, dest_addr} — dest_addr WITHOUT + prefix.
        $dest = ltrim($msisdn, '+');
        $payload = json_encode([
            'source_addr'   => $this->senderId,
            'schedule_time' => '',
            'encoding'      => 0,
            'message'       => $message,
            'recipients'    => [['recipient_id' => 1, 'dest_addr' => $dest]],
        ], JSON_UNESCAPED_SLASHES);

        $ch = curl_init($this->endpoint);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $payload,
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'Authorization: Basic ' . base64_encode($this->apiKey . ':' . $this->secretKey),
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_CONNECTTIMEOUT => 8,
        ]);
        $resp = curl_exec($ch);
        $http = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $err  = curl_error($ch);
        curl_close($ch);

        if ($resp === false)  return ['ok' => false, 'msg' => "cURL: {$err}"];
        if ($http < 200 || $http >= 300) return ['ok' => false, 'msg' => "HTTP {$http}: " . mb_substr((string)$resp, 0, 200)];

        $data = json_decode((string)$resp, true);
        // Beem success:  {"successful":true,"request_id":123,"code":100,"message":"..."}
        // Beem failure:  {"code":101,"message":"invalid credentials"} (or similar)
        if (is_array($data) && !empty($data['successful'])) {
            return ['ok' => true, 'message_id' => (string)($data['request_id'] ?? '')];
        }
        return ['ok' => false, 'msg' => 'Beem: ' . (is_array($data) ? ($data['message'] ?? json_encode($data)) : (string)$resp)];
    }
}
