<?php
// check_test.php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/kindamba.php';

$tid = $_SERVER['argv'][1] ?? @file_get_contents('last_test_id.txt');
if (!$tid) {
    echo "Usage: php check_test.php [transaction_id]\n";
    exit;
}

$adminStmt = $pdo->query("SELECT api_key FROM users WHERE id = 1 LIMIT 1");
$publicKey = $adminStmt->fetchColumn() ?: KINDAMBA_PUBLIC_KEY;

echo "Checking status for transaction ID: $tid...\n";
echo "Using Public Key: " . substr($publicKey, 0, 10) . "...\n";

$result = kindamba_verify_status($tid, $publicKey);

echo "HTTP Code: " . $result['code'] . "\n";
echo "Response: " . json_encode($result['data'], JSON_PRETTY_PRINT) . "\n";

$data = $result['data'];
$rawStatus = strtolower($data['data']['status'] ?? $data['status'] ?? 'pending');
echo "\nMapped Raw Status: $rawStatus\n";

if ($rawStatus === 'completed' || $rawStatus === 'success' || $rawStatus === 'successful') {
    echo "RESULT: SUCCESS! This should trigger a redirect in the frontend.\n";
} else if ($rawStatus === 'pending' || $rawStatus === 'initiated' || $rawStatus === 'processing') {
    echo "RESULT: STILL PENDING (Check your phone for USSD Prompt).\n";
} else {
    echo "RESULT: FAILED/CANCELLED ($rawStatus)\n";
}
