<?php
// sms_functions.php

// send_sms_with_all_report_responses.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Assuming 'db_connect.php' and 'sms_api.php' are in the same directory.
// You must ensure 'db_connect.php' contains your actual database connection.
if (!file_exists('db_connect.php')) {
    die("Error: The 'db_connect.php' file was not found. Please ensure it's in the same directory.");
}

// Include the database connection
include 'db_connect.php';

// Replace with your actual Beem API credentials.
// For production, consider using environment variables.
define('BEEM_API_KEY', '4d2495c90cbee253');
define('BEEM_SECRET_KEY', 'MWVkOWQzYWM5Yjg1MmNiNDA2ZGRiODZkODI3ZDQ0OTk4ODBmNzhmYTU5Mzg3YmM5Y2M5Y2ZkN2Q0OGI3ZTJlMw==');

// Set the response header for JSON
header('Content-Type: application/json');

// --- NEW FUNCTIONS ---
/**
 * Fetches the current local SMS balance from the database.
 * @param mysqli $conn The database connection object.
 * @return int The current balance, or 0 if no record is found.
 */
function getLocalSmsBalance($conn) {
    $sql = "SELECT current_balance FROM Kigango_SMS_Balance LIMIT 1";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return (int) $row['current_balance'];
    }
    return 0;
}

/**
 * Decrements the local SMS balance by one after a successful send.
 * @param mysqli $conn The database connection object.
 * @return bool True on success, false on failure.
 */
function updateSmsBalance($conn) {
    $sql = "UPDATE Kigango_SMS_Balance SET current_balance = current_balance - 1 WHERE current_balance > 0 LIMIT 1";
    return $conn->query($sql);
}

/**
 * Logs an SMS record into the SMS_Log table.
 *
 * @param mysqli $conn The database connection object.
 * @param array $logData An associative array of log data.
 * @return bool True on success, false on failure.
 */
function logSms($conn, $logData) {
    // Corrected to handle all parameters and prevent SQL injection.
    $stmt = $conn->prepare("INSERT INTO SMS_Log (recipient_phone, message_content, sent_status, beem_request_id, api_response, sms_category_id, related_contribution_id, authorized_person_id, partner_id, partner_code, monthYear) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    if ($stmt === false) {
        error_log("Prepare failed: " . $conn->error);
        return false;
    }

    $stmt->bind_param("sssssiisiss",
        $logData['recipient_phone'],
        $logData['message_content'],
        $logData['sent_status'],
        $logData['beem_request_id'],
        $logData['api_response'],
        $logData['sms_category_id'],
        $logData['related_contribution_id'],
        $logData['authorized_person_id'],
        $logData['partner_id'],
        $logData['partner_code'],
        $logData['monthYear']
    );

    $result = $stmt->execute();
    if ($result === false) {
        error_log("Execute failed: " . $stmt->error);
    }

    $stmt->close();
    return $result;
}
// --- END OF NEW FUNCTIONS ---

/**
 * Sends an SMS via the Beem API and returns a detailed response.
 *
 * @param string $recipient_phone The recipient's phone number (e.g., '2557XXXXXXXX').
 * @param string $message The message content to be sent.
 * @return array An associative array with the status ('sent' or 'failed'), beem_request_id, and full API response string.
 */
function sendBeemSms($recipient_phone, $message) {
    $api_key = BEEM_API_KEY;
    $secret_key = BEEM_SECRET_KEY;
    
    $postData = array(
        'source_addr' => 'OCOAN',
        'encoding' => 0,
        'schedule_time' => '',
        'message' => $message,
        'recipients' => [
            array('recipient_id' => '1', 'dest_addr' => $recipient_phone)
        ]
    );

    $Url = 'https://apisms.beem.africa/v1/send';

    $ch = curl_init($Url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt_array($ch, array(
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => array(
            'Authorization: Basic ' . base64_encode("$api_key:$secret_key"),
            'Content-Type: application/json'
        ),
        CURLOPT_POSTFIELDS => json_encode($postData)
    ));

    $response = curl_exec($ch);
    $responseData = json_decode($response, true);

    if ($response === FALSE) {
        $error = curl_error($ch);
        curl_close($ch);
        return [
            'status' => 'failed',
            'beem_request_id' => null,
            'api_response' => '{"error_message": "cURL Error: ' . $error . '"}'
        ];
    }
    curl_close($ch);

    $status = 'failed';
    $beem_request_id = null;
    if (isset($responseData['successful']) && $responseData['successful'] > 0) {
        $status = 'sent';
        $beem_request_id = $responseData['request_id'] ?? null;
    }

    return [
        'status' => $status,
        'beem_request_id' => $beem_request_id,
        'api_response' => $response
    ];
}


// --- MAIN API ENDPOINT LOGIC ---
$response = ['success' => false, 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'send_sms') {
    $recipient_phone = $_POST['recipient_phone'] ?? null;
    $message_content = $_POST['message'] ?? null;
    $sms_category_id = isset($_POST['sms_category_id']) ? intval($_POST['sms_category_id']) : null;
    $partner_id = $_POST['partner_id'] ?? null;
    $partner_code = $_POST['partner_code'] ?? null;
    $authorized_person_id = $_POST['authorized_person_id'] ?? '1'; // Assuming a default of user ID 1

    // **Step 1: Check local SMS balance**
    $balance = getLocalSmsBalance($conn);
    if ($balance < 1) {
        $response['message'] = "⚠️ Low Balance! Your available SMS balance is **" . $balance . "**. Please recharge to send SMS. For assistance, contact **+255-653-666-614** or use the payment merchant **M-Pesa**.";
        
        // Log the failed SMS attempt due to low balance
        $logData = [
            'recipient_phone' => $recipient_phone,
            'message_content' => $message_content,
            'sent_status' => 'Failed - Low Balance',
            'beem_request_id' => null,
            'api_response' => 'SMS sending skipped due to low local balance.',
            'sms_category_id' => $sms_category_id,
            'related_contribution_id' => null,
            'authorized_person_id' => $authorized_person_id,
            'partner_id' => $partner_id,
            'partner_code' => $partner_code,
            'monthYear' => date('F Y')
        ];
        logSms($conn, $logData);

        echo json_encode($response);
        exit;
    }

    // **Step 2: Send the SMS via Beem API**
    $send_result = sendBeemSms($recipient_phone, $message_content);

    // **Step 3: Check API status and update balance**
    if ($send_result['status'] === 'sent') {
        updateSmsBalance($conn);
        $response['success'] = true;
        $response['message'] = "SMS sent successfully! Current status: **" . $send_result['status'] . "**";
    } else {
        $response['message'] = "SMS sending failed. Beem API Error: " . ($send_result['api_response'] ?? 'Unknown error.');
    }

    // **Step 4: Log the SMS regardless of the sending status**
    $logData = [
        'recipient_phone' => $recipient_phone,
        'message_content' => $message_content,
        'sent_status' => $send_result['status'],
        'beem_request_id' => $send_result['beem_request_id'],
        'api_response' => $send_result['api_response'],
        'sms_category_id' => $sms_category_id,
        'related_contribution_id' => null,
        'authorized_person_id' => $authorized_person_id,
        'partner_id' => $partner_id,
        'partner_code' => $partner_code,
        'monthYear' => date('F Y')
    ];

    if (!logSms($conn, $logData)) {
        $response['success'] = false; // Override success if logging fails
        $response['message'] .= "<br>Error: Failed to save SMS record to database.";
    }

    echo json_encode($response);
    exit;
}

// Ensure the connection is closed
$conn->close();

?>