‰PNG

   IHDR         ôxÔú   sBIT|dˆ   	pHYs  Ä  Ä•+   tEXtSoftware www.inkscape.org›î<  ,àtEXtComment 
<?php
// Turn off error output to screen so we don't break the JSON response
ini_set('display_errors', 0);
error_reporting(E_ALL);

session_start();
require_once('includes/connect.php');
require_once('includes/functions.php');

header('Content-Type: application/json');

// 1. Check Authentication
if (!isset($_SESSION['Email'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit();
}

$user = GetMember1($_SESSION['Email']);
if (!$user) {
    echo json_encode(['status' => 'error', 'message' => 'User not found']);
    exit();
}

$userId = $user['ID'];
$openTrades = [];
$closedTrades = [];

try {
    // 2. Query the trades table securely
    $stmt = $conn->prepare("SELECT id, commodity, trade_type, trade_amount, entry_price, close_price, pnl, status, created_at FROM trades WHERE user_id = ? ORDER BY created_at DESC");
    
    if ($stmt) {
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();

        // 3. Sort trades into Open and Closed arrays
        while ($row = $result->fetch_assoc()) {
            if ($row['status'] === 'OPEN') {
                $openTrades[] = $row;
            } else {
                $closedTrades[] = $row;
            }
        }
        $stmt->close();
        
        // 4. Send the data back to the JavaScript
        echo json_encode([
            'status' => 'success',
            'open_trades' => $openTrades,
            'closed_trades' => $closedTrades
        ]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Database query failed']);
    }
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'System error']);
}
?>