<?php
/**
 * API - Get Active Trades (Binary & CFD)
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// Start session if not started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/Auth.php';

if (!auth()->isUserLoggedIn()) {
    jsonError('Unauthorized', 401);
}

$userId = auth()->getUserId();
$isDemo = !empty($_GET['is_demo']);

// Get all active trades (both binary pending and CFD open)
$trades = dbFetchAll(
    "SELECT t.*, a.name as asset_name, a.icon_color, a.asset_type 
     FROM trades t 
     LEFT JOIN assets a ON t.asset_id = a.id 
     WHERE t.user_id = :uid AND t.result IN ('pending', 'open') AND t.is_demo = :demo
     ORDER BY t.start_time DESC",
    ['uid' => $userId, 'demo' => $isDemo ? 1 : 0]
);

jsonSuccess('Active trades retrieved', ['trades' => $trades]);
