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

// Retrieve account_name from the GET request
$account_name = $_GET['account_name'] ?? null;
$profile_id = $_GET['profile_id'] ?? null;



// Step 1: Get account_id from rr_410_accounts based on account_name
$account_query = "SELECT account_id FROM rr_410_accounts WHERE account_name = ? AND profile_id = ?";
$stmt = $conn->prepare($account_query);
$stmt->bind_param("si", $account_name,$profile_id);
$stmt->execute();
$result = $stmt->get_result();
$account_data = $result->fetch_assoc();

if (!$account_data) {
    echo json_encode(['error' => 'Account not found']);
    http_response_code(404);
    exit;
}

$account_id = $account_data['account_id'];

// Step 2: Get coin_id and coinpair_id from rr_410_history_input based on account_id
$history_query = "SELECT coin_id, coinpair_id FROM rr_410_history_input WHERE account_id = ?";
$stmt = $conn->prepare($history_query);
$stmt->bind_param("i", $account_id);
$stmt->execute();
$result = $stmt->get_result();

$coin_ids = [];
$coinpair_ids = [];
while ($row = $result->fetch_assoc()) {
    $coin_ids[] = $row['coin_id'];
    $coinpair_ids[] = $row['coinpair_id'];
}

// Convert IDs to unique lists to avoid duplicate lookups
$coin_ids = array_unique($coin_ids);
$coinpair_ids = array_unique($coinpair_ids);

// Step 3: Fetch coin names from rr_410_coin based on coin_ids
if (!empty($coin_ids)) {
    $placeholders = implode(',', array_fill(0, count($coin_ids), '?'));
    $coin_query = "SELECT coin_name FROM rr_410_coin WHERE coin_id IN ($placeholders)";
    $stmt = $conn->prepare($coin_query);
    $stmt->bind_param(str_repeat('i', count($coin_ids)), ...$coin_ids);
    $stmt->execute();
    $result = $stmt->get_result();

    $coins = [];
    while ($row = $result->fetch_assoc()) {
        $coins[] = $row['coin_name'];
    }
} else {
    $coins = [];
}

// Step 4: Fetch coinpair names from rr_410_coinpair based on coinpair_ids
if (!empty($coinpair_ids)) {
    $placeholders = implode(',', array_fill(0, count($coinpair_ids), '?'));
    $coinpair_query = "SELECT coinpair_name FROM rr_410_coinpair WHERE coinpair_id IN ($placeholders)";
    $stmt = $conn->prepare($coinpair_query);
    $stmt->bind_param(str_repeat('i', count($coinpair_ids)), ...$coinpair_ids);
    $stmt->execute();
    $result = $stmt->get_result();

    $coinpairs = [];
    while ($row = $result->fetch_assoc()) {
        $coinpairs[] = $row['coinpair_name'];
    }
} else {
    $coinpairs = [];
}

// Step 5: Return data as JSON
echo json_encode(['coins' => $coins, 'coinpairs' => $coinpairs]);

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