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

include(__DIR__ . "/includes/db_connect.php");

// --------------------------------------------------
// SEND SMS FUNCTION (same as USSD)
// --------------------------------------------------
function send_sms($phone, $message) {
    if (substr($phone, 0, 1) === '0') {
        $phone = '233' . substr($phone, 1);
    }

    $arkeselApiKey = "OmlmMERVeHJOdHhhT3BMUDQ=";
    $arkeselUrl = "https://sms.arkesel.com/sms/api";

    $queryParams = http_build_query([
        "action" => "send-sms",
        "api_key" => $arkeselApiKey,
        "to" => $phone,
        "from" => "Tekpulse",
        "sms" => $message
    ]);

    $ch = curl_init("$arkeselUrl?$queryParams");
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
    ]);

    curl_exec($ch);
    curl_close($ch);
}

// --------------------------------------------------
// FETCH LATEST QUEUED TRANSACTION
// --------------------------------------------------
$q = $conn->query("
    SELECT *
    FROM transactions
    WHERE status='QUEUED'
    ORDER BY created_at DESC
    LIMIT 1
");

if ($q->num_rows == 0) {
    exit("❌ No QUEUED transaction found.");
}

$tx = $q->fetch_assoc();

// --------------------------------------------------
// MARK AS SETTLED
// --------------------------------------------------
$conn->query("
    UPDATE transactions
    SET
        status='SETTLED',
        retry_count = retry_count + 1,
        last_attempt = NOW(),
        completed_at = NOW()
    WHERE id = {$tx['id']}
");

// --------------------------------------------------
// SEND SETTLEMENT SMS
// --------------------------------------------------
$senderMsg =
    "Mobex ADR\n".
    "Your transfer of GHS {$tx['send_amount']} was successful.\n".
    "Ref: {$tx['reference']}";

send_sms($tx['sender_msisdn'], $senderMsg);

$recipientMsg =
    "Mobex ADR\n".
    "You have received {$tx['receive_amount']}.\n".
    "From: {$tx['sender_msisdn']}\n".
    "Ref: {$tx['reference']}";

send_sms($tx['receiver_msisdn'], $recipientMsg);

echo "✅ Transaction {$tx['reference']} SETTLED successfully and SMS sent.";
