<?php
include('connection.php');

$profileId = $_GET['profile_id'] ?? '';
$accountName = $_GET['account_name'] ?? '';
$coinName = $_GET['coin_name'] ?? '';
$direction = $_GET['direction'] ?? '';
$percentage = $_GET['percentage'] ?? '';

if ($accountName && $profileId) {
    $stmt = $conn->prepare('SELECT account_id FROM rr_410_accounts WHERE account_name = ? AND profile_id = ?');
    $stmt->bind_param('si', $accountName, $profileId);
    $stmt->execute();
    $stmt->bind_result($accountId);
    $stmt->fetch();
    $stmt->close();

    if ($accountId) {
        $query = '
            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 = ?
        ';

        $params = [$accountId];
        $types = 'i';

        if ($coinName) {
            $query .= ' AND c.coin_name LIKE ?';
            $params[] = '%' . $coinName . '%';
            $types .= 's';
        }
        if ($direction) {
            $query .= ' AND d.direction_id = ?';
            $params[] = $direction;
            $types .= 'i';
        }
        if ($percentage === 'positive') {
            $query .= ' AND h.percents >= 0';
        } elseif ($percentage === 'negative') {
            $query .= ' AND h.percents < 0';
        }

        $query .= ' ORDER BY h.trade_id DESC';
        $stmt = $conn->prepare($query);

        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();

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

        $stmt->close();
        echo json_encode($tradeHistory);
    } else {
        echo json_encode(['error' => 'Account not found']);
    }
} else {
    echo json_encode(['error' => 'No account name provided']);
}

$conn->close();
?>
