<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

$api_key     = "106de5fd0d63b2de";
$secret_key  = "NDY1NGE3NjZjYTgzZmE5MTFkOThkODg1MDZjMmE1NTVmOTc2OGJlMzc1MDRmYjNlMDkxODE1MWFiM2JkY2FlNg==";
$sender_name = "Bexa Mikopo";

$data    = json_decode(file_get_contents("php://input"), true);
$phones  = $data['phones']  ?? [];
$message = $data['message'] ?? '';

if (empty($phones) || empty($message)) {
    echo json_encode(["status" => "error", "message" => "Phone numbers and message are required"]);
    exit();
}

function formatPhoneNumber($phone) {
    $p = preg_replace('/\s+/', '', $phone);
    if (preg_match('/^(07|06)[0-9]{8}$/', $p)) {
        return '255' . substr($p, 1);
    } elseif (preg_match('/^(2557|2556)[0-9]{8}$/', $p)) {
        return $p;
    }
    return null;
}

$recipients = [];
foreach ($phones as $i => $entry) {
    $fmt = formatPhoneNumber($entry['dest_addr']);
    if ($fmt) {
        $recipients[] = [
            'recipient_id' => (string)($i + 1),
            'dest_addr'    => $fmt
        ];
    }
}

if (empty($recipients)) {
    echo json_encode(["status" => "error", "message" => "No valid phone numbers found"]);
    exit();
}

$url     = "https://apisms.beem.africa/v1/send";
$headers = [
    "Content-Type: application/json",
    "Authorization: Basic " . base64_encode("$api_key:$secret_key"),
];

$payload = json_encode([
    "source_addr"   => $sender_name,
    "encoding"      => 0,
    "schedule_time" => "",
    "message"       => $message,
    "recipients"    => $recipients
]);

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_HTTPHEADER     => $headers,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $payload,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error    = curl_error($ch);
curl_close($ch);

if ($httpCode === 200) {
    echo json_encode(["status" => "success", "message" => "Messages sent successfully"]);
} else {
    echo json_encode([
        "status"     => "error",
        "message"    => "Failed to send messages",
        "http_code"  => $httpCode,
        "response"   => $response,
        "curl_error" => $error
    ]);
}
