<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include "config.php"; 
include "connection.php"; // MT5 connection class

$data = json_decode(file_get_contents("php://input"), true);
$user_id = $data['user_id'] ?? 0;

if (!$user_id) {
    echo json_encode(["success" => false, "message" => "Missing user id"]);
    exit;
}

// MT5 connect
$mt5 = new MT5Connection();
if (!$mt5->connect()) {
    echo json_encode([
        "success" => false,
        "message" => "MT5 connection failed, error: " . $mt5->lastError()
    ]);
    exit;
}

$api = $mt5->api;

// Fetch ALL accounts including demo
$stmt = $conn->prepare("
    SELECT trade_id, account_name, leverage, Balance, account_type 
    FROM liveaccounts 
    WHERE user_id = ?
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$accounts = [];

while ($row = $result->fetch_assoc()) {

    $trade_id      = $row['trade_id'];
    $account_name  = $row['account_name'];
    $leverage      = $row['leverage'];
    $account_type  = $row['account_type'];
    $balance_db    = (float)$row['Balance'];

    $balance = $balance_db;
    $floating_profit = 0;
    $equity = $balance_db;

    // Try fetching live MT5 data (including demo)
    try {
        if (($err = $api->UserAccountGet($trade_id, $accData)) == MTRetCode::MT_RET_OK) {
            $balance = (float)$accData->Balance;
            $floating_profit = (float)($accData->Floating ?? 0);
            $equity = $balance + $floating_profit;
        }
    } catch (Throwable $e) {
        // fallback to DB values
        $balance = $balance_db;
        $floating_profit = 0;
        $equity = $balance;
    }

    $accounts[] = [
        "trade_id"      => $trade_id,
        "account_name"  => $account_name,
        "account_type"  => $account_type,
        "leverage"      => $leverage,
        "Balance"       => $balance,
        "floating_profit" => $floating_profit,
        "equity"        => $equity
    ];
}

echo json_encode([
    "success" => true,
    "accounts" => $accounts
]);
?>
