<?php
// Fetch token and senderID from sms_settings table
$token = '';
$senderID = '';
$settings_result = $connection->query("SELECT token, senderID FROM sms_settings LIMIT 1");
if ($settings_result && $settings_result->num_rows > 0) {
    $settings = $settings_result->fetch_assoc();
    $token = $settings['token'];
    $senderID = $settings['senderID'];
}

// Handle SMS sending
if (isset($_POST['send_sms'])) {
    $recipients = $_POST['recipients'];
    $message = $_POST['message'];

    // Send SMS using API
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://my.kudisms.net/api/sms',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array(
            'token' => $token,
            'senderID' => $senderID,
            'recipients' => $recipients,
            'message' => $message,
            'gateway' => '2'
        ),
    ));
    $response = curl_exec($curl);
    if ($response === false) {
        $_SESSION['msg'] = "SMS sending failed: " . curl_error($curl);
        $_SESSION['type'] = "error";
        $api_response = "Error: " . curl_error($curl);
    } else {
        $_SESSION['msg'] = "SMS sent successfully.";
        $_SESSION['type'] = "success";
        $api_response = $response;
    }
    curl_close($curl);

    // Save SMS details to DB
    $stmt = $connection->prepare("INSERT INTO sent_sms (senderID, recipients, message, response) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $senderID, $recipients, $message, $api_response);
    $stmt->execute();
    $stmt->close();

    header("Location: send_sms");
    exit();
}

// Fetch sent SMS list
$result = $connection->query("SELECT * FROM sent_sms ORDER BY sent_at DESC");
?>
