<?php
// Ensure session is started if you want to use it (though JSON is better for AJAX)
// if (session_status() == PHP_SESSION_NONE) {
//     session_start();
// }

include 'db_connect.php'; // Ensure this file correctly connects to your database

// Function to safely get data from POST
function get_safe_post_data($param, $default = '') {
    return isset($_POST[$param]) ? $_POST[$param] : $default; // Removed htmlspecialchars for currency/amounts which are numbers
}

// Function to send JSON response and exit
function send_json_response($status, $message, $conn) {
    // Close the database connection before exiting
    if ($conn && $conn->ping()) {
        $conn->close();
    }
    header('Content-Type: application/json');
    echo json_encode(['status' => $status, 'message' => $message]);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $partner_id = (int)get_safe_post_data('partner_id');
    $partner_code = get_safe_post_data('partner_code');
    $phone_number = get_safe_post_data('phone_number');
    $month_year = get_safe_post_data('month_year');
    $sms_category_id = (int)get_safe_post_data('sms_category_id');
    $message_content = get_safe_post_data('message_content');
    $commitment_amount = (float)get_safe_post_data('commitment_amount');
    $total_paid = (float)get_safe_post_data('total_paid');
    $remaining_amount = (float)get_safe_post_data('remaining_amount');
    $commitment_currency = get_safe_post_data('commitment_currency');

    // Basic validation
    if (empty($partner_id) || empty($partner_code) || empty($phone_number) || empty($month_year) || empty($sms_category_id) || empty($message_content)) {
        send_json_response('error', 'Error: Missing required SMS data.', $conn);
    }

    // --- SMS Sending Logic (Placeholder) ---
    // In a real application, you would replace this with your actual SMS API call.
    // Example: $sms_sent_successfully = send_sms_via_api($phone_number, $message_content);
    $sms_sent_successfully = true; // Simulate success for demonstration
    // --- End SMS Sending Logic ---

    if ($sms_sent_successfully) {
        // Log the SMS in the SMS_Log table
        $log_sql = "INSERT INTO SMS_Log (partner_id, partner_code, phone_number, sms_category_id, message_content, month_year, sent_at, commitment_amount, total_paid, remaining_amount, commitment_currency) VALUES (?, ?, ?, ?, ?, ?, NOW(), ?, ?, ?, ?)";
        $stmt_log = $conn->prepare($log_sql);
        
        if ($stmt_log) {
            // Use 'd' for the amounts (double/float) and 'i' for integer IDs, 's' for strings
            $stmt_log->bind_param("isisssddds", 
                $partner_id, 
                $partner_code, 
                $phone_number, 
                $sms_category_id, 
                $message_content, 
                $month_year, 
                $commitment_amount, 
                $total_paid, 
                $remaining_amount, 
                $commitment_currency
            );
            
            if ($stmt_log->execute()) {
                // SUCCESS: Return JSON
                $stmt_log->close();
                send_json_response('success', 'SMS sent and logged successfully to ' . htmlspecialchars($phone_number) . '.', $conn);
            } else {
                // WARNING: SMS sent, but logging failed.
                $error_message = 'SMS sent, but failed to log: ' . $stmt_log->error;
                $stmt_log->close();
                send_json_response('warning', $error_message, $conn);
            }
        } else {
            // WARNING: SMS sent, but log statement failed to prepare.
            send_json_response('warning', 'SMS sent, but failed to prepare log statement: ' . $conn->error, $conn);
        }
    } else {
        // ERROR: SMS failed to send via API
        send_json_response('error', 'Failed to send SMS to ' . htmlspecialchars($phone_number) . '.', $conn);
    }
} else {
    // If accessed directly without POST
    send_json_response('error', 'Invalid request method.', $conn);
}
// $conn->close() is now inside send_json_response
?>