<?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';

// --- 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 not 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 attempt to the database.
 * @param mysqli $conn The database connection object.
 * @param array $logData The data to be logged.
 * @return bool True on success, false on failure.
 */
function logSms($conn, $logData) {
    $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 notification using the Beem API and returns a detailed result.
 * @param string $recipient The phone number to send the SMS to.
 * @param string $message The message content.
 * @return array A structured array with the sending status, request ID, and API response.
 */
function sendBeemSms($recipient, $message) {
    $api_key = '4d2495c90cbee253';
    $secret_key = 'MWVkOWQzYWM5Yjg1MmNiNDA2ZGRiODZkODI3ZDQ0OTk4ODBmNzhmYTU5Mzg3YmM5Y2M5Y2ZkN2Q0OGI3ZTJlMw==';
    $source_addr = 'OCOAN';

    $postData = array(
        'source_addr' => $source_addr,
        'encoding' => 0,
        'schedule_time' => '',
        'message' => $message,
        'recipients' => [
            array(
                'recipient_id' => '1',
                'dest_addr' => $recipient
            )
        ]
    );

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

    $ch = curl_init($url);
    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),
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0
    ));

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

    $responseData = json_decode($response, true);
    $result = [
        'status' => 'Failed',
        'beem_request_id' => null,
        'api_response' => $response,
        'error_message' => 'Unknown error.'
    ];

    if ($httpCode == 200 && isset($responseData['successful']) && $responseData['successful'] === true) {
        $result['status'] = 'Sent';
        $result['beem_request_id'] = $responseData['request_id'] ?? null;
        $result['error_message'] = null;
    } else {
        $result['error_message'] = 'HTTP Code ' . $httpCode . ' Response: ' . $response;
        error_log('Beem SMS API Error: ' . $result['error_message']);
    }

    return $result;
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['partner_id'])) {
    $response = ['status' => 'error', 'message' => 'Invalid request.'];
    $partner_id = $_POST['partner_id'];
    
    // Fetch partner details from the database
    $stmt = $conn->prepare("SELECT partner_name, partner_code, phone_number1 FROM Partners WHERE partner_id = ?");
    $stmt->bind_param("i", $partner_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $partner = $result->fetch_assoc();
        $partner_name = $partner['partner_name'];
        $partner_code = $partner['partner_code'];
        $phone_number = $partner['phone_number1'];
        $authorized_person_id = '1'; // Assuming a static user for now
        $sms_category_id = 3; // Assuming 3 is the correct category for this type of message

        // Construct the message
        $sms_message = "Nguvu ya Omega, ndugu {$partner_name}, umesajiliwa kwenye Haleluya TV partner na namba yako ni: {$partner_code}";

        // --- NEW SMS LOGIC ---
        $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' => $phone_number,
                'message_content' => $sms_message,
                '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;
        }

        // Send the SMS via Beem API
        $send_result = sendBeemSms($phone_number, $sms_message);

        // Check the status of the API call before proceeding
        if ($send_result['status'] === 'Sent') {
            // Deduct the balance only on a successful API send
            updateSmsBalance($conn);
            $response['status'] = 'success';
            $response['message'] = "SMS sent successfully! Current status: **" . $send_result['status'] . "**";
        } else {
            // If API send failed, set the response and do not deduct balance
            $response['status'] = 'error';
            $response['message'] = "SMS sending failed. Beem API Error: " . ($send_result['error_message'] ?? 'Unknown error.');
        }

        // Log the SMS regardless of the sending status
        $logData = [
            'recipient_phone' => $phone_number,
            'message_content' => $sms_message,
            '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')
        ];

        // Attempt to log the data.
        if (!logSms($conn, $logData)) {
            $response['status'] = 'error';
            $response['message'] .= "<br>Error: Failed to save SMS record to database.";
        }
        // --- END OF NEW SMS LOGIC ---

    } else {
        $response['message'] = 'Partner not found.';
    }
    
    $stmt->close();
    $conn->close();
    echo json_encode($response);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request.']);
}
?>