<?php
// update_sms_status.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Ensure the required files are present
if (!file_exists('db_connect.php')) {
    die("Error: The 'db_connect.php' file was not found. Please ensure it's in the same directory.");
}
if (!file_exists('sms_api.php')) {
    die("Error: The 'sms_api.php' file was not found. Please ensure it's in the same directory.");
}

require_once 'db_connect.php';
require_once 'sms_api.php';

// Log file for the cron job's output
$log_file = __DIR__ . '/cron_log.txt';
function log_message($message) {
    global $log_file;
    file_put_contents($log_file, date('[Y-m-d H:i:s]') . " " . $message . "\n", FILE_APPEND);
}

log_message("Starting SMS status update cron job...");

// Function to check the status of a specific SMS using the Beem API
function getBeemDeliveryStatus($beem_request_id) {
    $api_key = BEEM_API_KEY;
    $secret_key = BEEM_SECRET_KEY;
    $Url = "https://apisms.beem.africa/public/v1/delivery-reports/query?request_id=" . urlencode($beem_request_id);

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

    $response = curl_exec($ch);
    curl_close($ch);
    
    if ($response === FALSE) {
        log_message("cURL Error for request_id $beem_request_id: " . curl_error($ch));
        return ['status' => 'Failed', 'message' => 'cURL Error'];
    }

    $responseData = json_decode($response, true);
    
    // Check for the specific delivery status key in the API response
    if (isset($responseData['data']['attributes']['delivery_status'])) {
        $status = $responseData['data']['attributes']['delivery_status'];
        $final_status = 'Pending'; // Default to Pending

        // Mapping Beem API statuses to your system's statuses
        if ($status === 'DELIVERED') {
            $final_status = 'Delivered';
        } elseif ($status === 'FAILED' || $status === 'EXPIRED') {
            $final_status = 'Failed';
        } elseif ($status === 'SENT' || $status === 'QUEUED') {
            $final_status = 'Sent';
        }

        return ['status' => $final_status, 'message' => $response];
    }

    // If API response doesn't have a status, log it and keep the status as Pending.
    log_message("API Response for request_id $beem_request_id did not contain a delivery status. Raw response: " . $response);
    return ['status' => 'Pending', 'message' => $response];
}

// 1. **FIXED:** Fetch records that have either 'Sent' or 'Pending' status and a valid beem_request_id
// This is the core fix. It now correctly identifies all messages that need a status update.
$sql = "SELECT sms_id, beem_request_id FROM SMS_Log WHERE sent_status IN ('Sent', 'Pending') AND beem_request_id IS NOT NULL";
$result = $conn->query($sql);

if ($result === false) {
    log_message("Database query failed: " . $conn->error);
    $conn->close();
    exit;
}

if ($result->num_rows > 0) {
    log_message("Found " . $result->num_rows . " SMS records to check.");
    
    while ($row = $result->fetch_assoc()) {
        $sms_id = $row['sms_id'];
        $beem_request_id = $row['beem_request_id'];

        log_message("Checking status for SMS ID: $sms_id, Request ID: $beem_request_id");

        // 2. Query the Beem API for the delivery status
        $status_data = getBeemDeliveryStatus($beem_request_id);
        $new_status = $status_data['status'];
        $api_response = $status_data['message'];

        // 3. Update the database if the status is different from the current one
        // This prevents unnecessary database writes for records that are still 'Sent'
        $current_status_sql = "SELECT sent_status FROM SMS_Log WHERE sms_id = ?";
        $current_stmt = $conn->prepare($current_status_sql);
        if ($current_stmt) {
            $current_stmt->bind_param("i", $sms_id);
            $current_stmt->execute();
            $current_result = $current_stmt->get_result();
            $current_row = $current_result->fetch_assoc();
            $current_stmt->close();

            if ($current_row['sent_status'] !== $new_status) {
                $update_sql = "UPDATE SMS_Log SET sent_status = ?, api_response = ? WHERE sms_id = ?";
                $update_stmt = $conn->prepare($update_sql);
                
                if ($update_stmt) {
                    $update_stmt->bind_param("ssi", $new_status, $api_response, $sms_id);
                    if ($update_stmt->execute()) {
                        log_message("Updated SMS ID: $sms_id from '" . $current_row['sent_status'] . "' to '" . $new_status . "'.");
                    } else {
                        log_message("Failed to update SMS ID: $sms_id. Error: " . $update_stmt->error);
                    }
                    $update_stmt->close();
                } else {
                    log_message("Failed to prepare update statement. Error: " . $conn->error);
                }
            } else {
                log_message("Status for SMS ID: $sms_id remains '$new_status'. No update needed.");
            }
        }
    }
} else {
    log_message("No SMS records found with status 'Sent' or 'Pending' to update.");
}

$conn->close();
log_message("Cron job finished.");
?>