<?php
/**
 * SmartForex Engine - Active User Positions Fetch Engine
 * Location: public_html/api/positions.php
 */

error_reporting(0);
ini_set('display_errors', 0);

define('DB_HOST', 'localhost');
define('DB_NAME', 'rakshita_relay');
define('DB_USER', 'rakshita_relay');
define('DB_PASS', 'rehman@169');

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (PDOException $e) {
    exit(json_encode([]));
}

session_start();
if (!isset($_SESSION['user_id'])) {
    exit(json_encode([]));
}

$user_id = $_SESSION['user_id'];

header('Content-Type: application/json');

// Fetch all active open positions for the logged-in user
$stmt = $pdo->prepare("SELECT id, symbol, type, leverage, amount, entry_price FROM trades WHERE user_id = ? AND status = 'open' ORDER BY opened_at DESC");
$stmt->execute([$user_id]);
$trades = $stmt->fetchAll();

echo json_encode($trades ? $trades : []);
exit;