<?php
// Database connection using mysqli
include('connection.php');



// Get account name from query string
$accountName = $_GET['account_name'] ?? '';

if ($accountName) {
    // Get account ID from account name
    $stmt = $conn->prepare('SELECT account_id FROM rr_410_accounts WHERE account_name = ?');
    $stmt->bind_param('s', $accountName);
    $stmt->execute();
    $stmt->bind_result($accountId);
    $stmt->fetch();
    $stmt->close();

    if ($accountId) {
        // Get trade data for the account
        $stmt = $conn->prepare('
            SELECT 
                h.trade_id,
                c.coin_name,
                d.direction,
                h.leverage,
                h.percents,
                h.close_date
            FROM rr_410_history_input h
            JOIN rr_410_coin c ON h.coin_id = c.coin_id
            JOIN rr_410_direction d ON h.direction_id = d.direction_id
            WHERE h.account_id = ?
            order by trade_id desc
        ');
        $stmt->bind_param('i', $accountId);
        $stmt->execute();
        $result = $stmt->get_result();

        $tradeHistory = [];

        // Fetch all rows
        while ($row = $result->fetch_assoc()) {
            $tradeHistory[] = $row;
        }

        $stmt->close();

        // Return the data as JSON
        echo json_encode($tradeHistory);
    } else {
        echo json_encode(['error' => 'Account not found']);
    }
} else {
    echo json_encode(['error' => 'No account name provided']);
}

// Close the database connection
$conn->close();
?>
