<?php
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/utils/helpers.php';

// Mock a login
$stmt = $pdo->query("SELECT id, email FROM users LIMIT 1");
$user = $stmt->fetch();

if (!$user) {
    die("No users found.\n");
}

echo "Testing with user: " . $user['email'] . "\n";

// Prepare payload
$payload = [
    'exchange' => 'Binance',
    'amount' => '0.5',
    'currency' => 'BTC',
    'receiverEmail' => $user['email'], // Self-send for test
    'transactionHash' => '0x' . bin2hex(random_bytes(32))
];

// Simulate API call logic (since we can't easily curl localhost from CLI without server running in background, we'll include logic directly or use php-cli to run the file with mocked input if possible, but directly invoking logic is easier for test script)
// Actually, let's just make a CURL request if the server is running (port 8080 was started).
$url = 'http://localhost:8080/api/create-flash-transaction.php';

// We need a token. Let's generate one or find an active session.
$stmt = $pdo->prepare("SELECT session_token FROM sessions WHERE user_id = ? AND expires_at > datetime('now') ORDER BY created_at DESC LIMIT 1");
$stmt->execute([$user['id']]);
$session = $stmt->fetch();

if (!$session) {
    // Create session
    $token = bin2hex(random_bytes(32));
    $stmt = $pdo->prepare("INSERT INTO sessions (id, user_id, session_token, expires_at) VALUES (?, ?, ?, datetime('now', '+1 hour'))");
    $stmt->execute([generateUUID(), $user['id'], $token]);
} else {
    $token = $session['session_token'];
}

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $token,
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo "Response Code: $httpCode\n";
echo "Response Body: $response\n";

if ($httpCode === 200) {
    echo "SUCCESS: Flash transaction created.\n";
    // Check DB
    $data = json_decode($response, true);
    $txId = $data['transaction']['id'];
    $stmt = $pdo->prepare("SELECT * FROM transactions WHERE id = ?");
    $stmt->execute([$txId]);
    $tx = $stmt->fetch();
    echo "DB verification: " . ($tx ? "Found" : "Not Found") . "\n";
    
    // Check Mail Log
    $stmt = $pdo->prepare("SELECT count(*) as count FROM mail_activity WHERE user_id = ? AND created_at > datetime('now', '-1 minute')");
    $stmt->execute([$user['id']]);
    $res = $stmt->fetch();
    echo "Mail Log entries (last 1 min): " . $res['count'] . "\n";
} else {
    echo "FAILED.\n";
}
?>
