<?php

require_once 'includes/db_connect.php';
require_once 'includes/termination_router.php';

date_default_timezone_set('Africa/Accra');

// Fetch QUEUED transactions not yet started
$result = $conn->query("
    SELECT * FROM transactions
    WHERE status='QUEUED'
    AND processing_started_at IS NULL
    ORDER BY created_at ASC
    LIMIT 20
");

while ($txn = $result->fetch_assoc()) {

    // Mark as processing start
    $conn->query("
        UPDATE transactions
        SET processing_started_at=NOW()
        WHERE id={$txn['id']}
    ");

    processTransaction($conn, $txn);
}


function processTransaction($conn, $txn)
{
    $countryRow = $conn->query("
        SELECT status
        FROM countries
        WHERE country_code='{$txn['to_country']}'
        LIMIT 1
    ")->fetch_assoc();

    $environment = $countryRow['status'] ?? 'SANDBOX';

    if ($environment === 'SANDBOX') {
        simulateSandbox($conn, $txn);
    } else {
        liveTermination($conn, $txn);
    }
}


function simulateSandbox($conn, $txn)
{
    // Simulate 5–10 second delay
    sleep(rand(5,10));

    // 90% success rate (adjustable)
    $success = rand(1,100) <= 90;

    if ($success) {

        $fakeRef = "SIM-" . time() . rand(100,999);

        $stmt = $conn->prepare("
            UPDATE transactions
            SET status='SETTLED',
                termination_reference=?,
                completed_at=NOW()
            WHERE id=?
        ");
        $stmt->bind_param("si", $fakeRef, $txn['id']);
        $stmt->execute();

        sendFinalSms($conn, $txn, true);

    } else {

        $stmt = $conn->prepare("
            UPDATE transactions
            SET status='FAILED',
                failure_reason='Sandbox simulated failure',
                retry_count=retry_count+1,
                last_attempt=NOW()
            WHERE id=?
        ");
        $stmt->bind_param("i", $txn['id']);
        $stmt->execute();

        sendFinalSms($conn, $txn, false);
    }
}


function sendFinalSms($conn, $txn, $success)
{
    require_once 'ussd_callback.php'; // for send_sms()

    if ($success) {

        $msg = "MADR\n".
               "Transaction Successful\n".
               "Ref: {$txn['reference']}";

        send_sms($txn['sender_msisdn'], $msg);

    } else {

        $msg = "MADR\n".
               "Transaction Failed\n".
               "Ref: {$txn['reference']}";

        send_sms($txn['sender_msisdn'], $msg);
    }
}
