<?php
// talksasa.php

// Sanitize and get the GET parameters
$message   = isset($_GET['message']) ? trim($_GET['message']) : '';
$phone     = isset($_GET['phone']) ? trim($_GET['phone']) : '';
$sender_id = isset($_GET['senderid']) ? trim($_GET['senderid']) : '';
$api_param = isset($_GET['api']) ? trim($_GET['api']) : '';

// Validate required parameters
if (empty($message) || empty($phone) || empty($sender_id) || empty($api_param)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Missing required parameters.']);
    exit;
}

// Extract API token from api param (format: 138|your_token)
list($account_id, $api_token) = explode('|', $api_param, 2);

// API Endpoint
$url = 'https://bulksms.talksasa.com/api/v3/sms/send';

// Setup the payload
$data = [
    'recipient' => $phone,
    'sender_id' => $sender_id,
    'type'      => 'plain',
    'message'   => $message,
];

// Initialize cURL
$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $api_token",
    'Content-Type: application/json',
    'Accept: application/json',
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

// Execute the request
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
    echo json_encode(['status' => 'error', 'message' => curl_error($ch)]);
} else {
    http_response_code($http_code);
    echo $response;
}

curl_close($ch);
?>