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

// Simulate a transfer request
function testTransfer($pdo) {
    echo "--- Testing Crypto Transfer Logic ---\n";

    // 1. Get a sender (Admin)
    $senderId = 1; // Assuming admin is ID 1
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$senderId]);
    $sender = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$sender) {
        die("Sender not found.\n");
    }
    echo "Sender: " . $sender['email'] . "\n";

    // 2. Create a dummy recipient
    $recipientEmail = 'recipient_' . time() . '@test.com';
    $recipientWallet = '0x' . bin2hex(random_bytes(20));
    $stmt = $pdo->prepare("INSERT INTO users (email, password, role, wallet_address) VALUES (?, ?, 'user', ?)");
    $stmt->execute([$recipientEmail, 'hashedpassword', $recipientWallet]);
    $recipientId = $pdo->lastInsertId();
    echo "Created Recipient: $recipientEmail ($recipientWallet)\n";

    // 3. Ensure Sender has balance
    $symbol = 'BTC';
    $amount = 0.5;
    
    // Seed sender funds
    $stmt = $pdo->prepare("INSERT OR REPLACE INTO user_assets (user_id, symbol, name, balance, color, icon) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$senderId, $symbol, 'Bitcoin', 10.0, 'orange', 'btc']); 
    echo "Seeded Sender with 10 BTC.\n";

    // 4. Simulate the API logic directly (since we can't easily mock HTTP request in this CLI script without full auth headers setup, we'll verify logic by replicating the core DB transaction steps or calling a local function if we refactored. 
    // For end-to-end of the API file itself, we need a valid JWT.
    // Instead, let's verify the DB state updates using similar logic to the API to confirm schema works.)
    
    echo "Simulating Transfer of $amount BTC...\n";

    try {
        $pdo->beginTransaction();

        // Debit Sender
        $stmt = $pdo->prepare("UPDATE user_assets SET balance = balance - ? WHERE user_id = ? AND symbol = ?");
        $stmt->execute([$amount, $senderId, $symbol]);

        // Credit Recipient
        $stmt = $pdo->prepare("INSERT INTO user_assets (user_id, symbol, name, balance, color, icon) VALUES (?, ?, ?, ?, ?, ?)");
        // Since sqlite upsert syntax might vary, let's use simple insert for this new user
        $stmt->execute([$recipientId, $symbol, $symbol, $amount, 'gray', 'coins']);

        // Log Transaction
        $txId = generateUUID();
        $txHash = '0x' . bin2hex(random_bytes(32));
        $stmt = $pdo->prepare("INSERT INTO transactions (id, sender_id, receiver_id, amount, symbol, status, tx_hash) VALUES (?, ?, ?, ?, ?, 'completed', ?)");
        $stmt->execute([$txId, $senderId, $recipientId, $amount, $symbol, $txHash]);

        $pdo->commit();
        echo "Transfer Logic Executed Successfully.\n";

        // Verify Balances
        $stmt = $pdo->prepare("SELECT balance FROM user_assets WHERE user_id = ? AND symbol = ?");
        $stmt->execute([$senderId, $symbol]);
        $newSenderBal = $stmt->fetchColumn();
        echo "Sender New Balance: $newSenderBal (Expected 9.5)\n";

        $stmt = $pdo->prepare("SELECT balance FROM user_assets WHERE user_id = ? AND symbol = ?");
        $stmt->execute([$recipientId, $symbol]);
        $recipientBal = $stmt->fetchColumn();
        echo "Recipient Balance: $recipientBal (Expected 0.5)\n";
        
        // Verify Transaction Record
        $stmt = $pdo->prepare("SELECT * FROM transactions WHERE id = ?");
        $stmt->execute([$txId]);
        $tx = $stmt->fetch();
        if ($tx) {
            echo "Transaction Record Found: " . $tx['tx_hash'] . "\n";
        } else {
            echo "Transaction Record NOT Found.\n";
        }

    } catch (Exception $e) {
        $pdo->rollBack();
        echo "Transfer Failed: " . $e->getMessage() . "\n";
    }
}

testTransfer($pdo);
