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

// Mock a login to get a valid user
$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'] . " (ID: " . $user['id'] . ")\n";

// Prepare payload
$payload = [
    'exchange' => 'Binance',
    'amount' => '0.5',
    'currency' => 'BTC',
    'receiverEmail' => 'external_test_' . time() . '@example.com', // Test external email
    'transactionHash' => '0x' . bin2hex(random_bytes(32))
];

// Determine API URL (assuming default port 8080 as per package.json php:dev)
$url = 'http://localhost:8080/backend/api/create-flash-transaction.php';

// Get or Create 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) {
    $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'];
}

echo "Sending request to $url...\n";

$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 || $httpCode === 201) {
    $data = json_decode($response, true);
    if (isset($data['success']) && $data['success']) {
        echo "SUCCESS: API call successful.\n";
        
        // Verify DB Transaction
        $txId = $data['transaction']['id'];
        $stmt = $pdo->prepare("SELECT * FROM transactions WHERE id = ?");
        $stmt->execute([$txId]);
        $tx = $stmt->fetch();
        echo "DB Transaction Verification: " . ($tx ? "Found (ID: $txId)" : "Not Found") . "\n";
        if ($tx) {
             echo "Receiver ID in DB: " . $tx['receiver_id'] . " (Should match User ID " . $user['id'] . " for external email fallback)\n";
        }

        // Verify Mail Log
        // Check for recent mail log for this user
        $stmt = $pdo->prepare("SELECT * FROM mail_activity WHERE user_id = ? ORDER BY created_at DESC LIMIT 1");
        $stmt->execute([$user['id']]);
        $mail = $stmt->fetch();
        
        echo "Mail Log Verification:\n";
        if ($mail) {
            echo " - ID: " . $mail['id'] . "\n";
            echo " - Subject: " . $mail['subject'] . "\n";
            echo " - Status: " . $mail['status'] . "\n";
            echo " - Created: " . $mail['created_at'] . "\n";
            // Verify timestamp is recent (within last minute)
            $mailTime = strtotime($mail['created_at']);
            if (time() - $mailTime < 60) {
                echo "RESULT: Email logged successfully recently.\n";
            } else {
                echo "RESULT: Email log found but old.\n";
            }
        } else {
            echo "RESULT: No mail log found.\n";
        }
    } else {
        echo "FAILED: API returned success=false. Message: " . ($data['message'] ?? 'Unknown') . "\n";
    }
} else {
    echo "FAILED: HTTP Code $httpCode\n";
}
?>
