<?php
// SMS sending API
require_once '../includes/db.php';

header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    $phone = $input['phone'] ?? '';
    $message = $input['message'] ?? '';

    if (!$phone || !$message) {
        echo json_encode(['success' => false, 'message' => 'Missing parameters']);
        exit;
    }

    // Send SMS using Onfon Media Bulk SMS API
    $apiKey = getSetting('sms_api_key');
    $senderId = getSetting('sms_sender_id');

    if (!$apiKey) {
        echo json_encode(['success' => false, 'message' => 'SMS API key not configured']);
        exit;
    }

    // Onfon Media Bulk SMS API integration
    $url = 'https://api.onfonmedia.co.ke/v1/sms/SendBulkSMS'; // Replace with actual endpoint

    $data = [
        'api_key' => $apiKey,
        'sender_id' => $senderId,
        'message' => $message,
        'phone' => $phone
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey // Assuming Bearer token
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $result = json_decode($response, true);

    if ($httpCode == 200 && isset($result['success']) && $result['success']) {
        echo json_encode(['success' => true, 'message' => 'SMS sent successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to send SMS: ' . ($result['message'] ?? 'Unknown error')]);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}
?>