<?php
header("Content-Type: application/json");

$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 to format phone numbers correctly
function formatPhoneNumber($phone) {
    $phone = preg_replace('/\s+/', '', $phone); // Ondoa spaces
    // Inakubalika ikiwa namba inaanza na 06 au 07
    if (preg_match('/^(07|06)[0-9]{8}$/', $phone)) {
        return '255' . substr($phone, 1); // Badilisha mwanzo wa "0" kuwa "255"
    } elseif (preg_match('/^(2557|2556)[0-9]{8}$/', $phone)) {
        return $phone; // Ikiwa tayari iko katika format sahihi
    }
    return null; // Namba si sahihi
}


$recipients = [];
foreach ($phones as $index => $phone) {
    $formattedPhone = formatPhoneNumber($phone['dest_addr']);
    if ($formattedPhone) {
        $recipients[] = ["recipient_id" => strval($index + 1), "dest_addr" => $formattedPhone];
    }
}

// Hakikisha kuna namba za kutuma SMS baada ya kuchuja
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
]);

// Debugging: Print request payload
error_log("Payload Sent: " . $payload);

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

// Debugging: Log API Response and any errors
error_log("Beem API Response: " . $response);
error_log("HTTP Code: " . $httpCode);
if ($error) {
    error_log("cURL Error: " . $error);
}

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
    ]);
}
?>
