<?php
include 'db_connect.php';
include 'madr_terminate.php';

$baseDelay = 30;  // seconds
$maxRetries = 5;

$txRes = $conn->query("
    SELECT t.*, e.provider 
    FROM transactions t
    LEFT JOIN termination_endpoints e ON e.id=t.endpoint_id AND e.enabled=1
    WHERE t.status='QUEUED'
    AND (t.last_attempt IS NULL OR t.last_attempt <= DATE_SUB(NOW(), INTERVAL POW(2,t.retry_count)*$baseDelay SECOND))
    ORDER BY t.created_at ASC
");

while($tx = $txRes->fetch_assoc()) {
    $txId = $tx['id'];
    $ref  = $tx['reference'];

    if (!$tx['provider']) {
        $conn->query("UPDATE transactions SET status='FAILED' WHERE id=$txId");
        continue;
    }

    $payload = [
        'reference'   => $ref,
        'phone'       => $tx['receiver_msisdn'],
        'amount'      => $tx['send_amount'],
        'recipient'   => $tx['receiver_name'] ?? 'Recipient',
        'sender_name' => 'MADR Sender',
        'from_country'=> $tx['from_country'],
        'to_country'  => $tx['to_country']
    ];

    $result = madr_terminate($tx['to_country'], $tx['provider'], $payload);

    $retryCount = $tx['retry_count'] + 1;
    $status = ($result['status']==='SUCCESS') ? 'SETTLED' : (($retryCount>=$maxRetries)?'FAILED':'QUEUED');

    $conn->query("
        UPDATE transactions
        SET status='$status',
            retry_count=$retryCount,
            last_attempt=NOW(),
            termination_reference='" . $conn->real_escape_string($result['termination_reference'] ?? $result['message']) . "',
            termination_provider='" . $conn->real_escape_string($tx['provider']) . "'
        WHERE id=$txId
    ");
}
