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

echo "--- STARTING FLASH ENDPOINT TEST ---\n";

// 1. Get an active user session
$stmt = $pdo->query("SELECT s.session_token, u.email, u.id FROM sessions s JOIN users u ON s.user_id = u.id WHERE s.expires_at > datetime('now') LIMIT 1");
$session = $stmt->fetch();

if (!$session) {
    // Create a new session for a user
    $stmt = $pdo->query("SELECT id, email FROM users LIMIT 1");
    $user = $stmt->fetch();
    if (!$user) {
        die("No users found to test with.\n");
    }
    $token = createSession($user['id']);
    $session = ['session_token' => $token, 'email' => $user['email'], 'id' => $user['id']];
}

$token = $session['session_token'];
$email = $session['email'];

echo "Using User: $email\n";
echo "TokenPrefix: " . substr($token, 0, 10) . "...\n";

// 2. Prepare Payload
$payload = [
    'exchange' => 'Binance',
    'amount' => '0.5',
    'currency' => 'BTC',
    'receiverEmail' => 'kvng@catgroup.uk', // Real test email
    'senderEmail' => $email,
    'transactionHash' => '0x' . bin2hex(random_bytes(32)),
    'walletAddress' => '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa',
    'network' => 'Bitcoin'
];

// 3. Send Request
$ch = curl_init('http://localhost:8080/backend/api/create-flash-transaction.php'); // URL seems correct based on file struct, but maybe served from root?
// Let's try to infer if 8080 is root c:\Users\c0d3_\fcorex
// If so, it should be http://localhost:8080/backend/api/create-flash-transaction.php
// Wait, the 404 said /backend/api/create-flash-transaction.php was not found.
// Maybe the php server was started inside backend? Or src?
// Let's try http://localhost:8080/api/create-flash-transaction.php assuming backend mapped to api?
// Actually, earlier the user had issues with /api/api/ paths. 
// Let's try to just run the file directly via CLI simulation since we have the token logic.
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 "HTTP Code: $httpCode\n";
echo "Response: $response\n";

if ($httpCode === 200) {
    echo "SUCCESS: Endpoint executed successfully.\n";
    // Check mail log
    $stmt = $pdo->prepare("SELECT * FROM mail_activity WHERE recipient_email = ? ORDER BY created_at DESC LIMIT 1");
    $stmt->execute(['kvng@catgroup.uk']);
    $log = $stmt->fetch();
    if ($log) {
        echo "Mail Log Found: " . $log['status'] . "\n";
    } else {
        echo "WARNING: No mail log found for recipient.\n";
    }
} else {
    echo "FAILED: API returned error.\n";
}
