<?php
session_start();
header('Content-Type: application/json');

require_once "../include/db.php";

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['positions' => []]);
    exit;
}

$userId = intval($_SESSION['user_id']);

// Get trades that are still "pending" (if you add real-time later)
// For now, return last 3 trades that just closed
$sql = "SELECT * FROM trades WHERE user_id = $userId AND created_at > DATE_SUB(NOW(), INTERVAL 5 MINUTE) ORDER BY created_at DESC LIMIT 3";
$result = mysqli_query($conn, $sql);

$positions = [];
while ($row = mysqli_fetch_assoc($result)) {
    $positions[] = [
        'id' => $row['id'],
        'asset' => $row['asset'],
        'trade_type' => $row['trade_type'],
        'amount' => $row['amount'],
        'status' => $row['status']
    ];
}

echo json_encode(['positions' => $positions]);