<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");
ini_set('display_errors', 1);
error_reporting(E_ALL);

include "config.php";
include "connection.php";

$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 = new MT5Connection();
if (!$mt5->connect()) {
    echo json_encode(["success" => false, "message" => "MT5 connection failed"]);
    exit;
}
$api = $mt5->api;

// ----------------------
// Fetch all live accounts
// ----------------------
$stmt = $conn->prepare("SELECT trade_id FROM liveaccounts WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$accounts = $stmt->get_result();

$live_trades = [];
$total_equity = 0;
$total_lot = 0;
$total_profit = 0;

while ($acc = $accounts->fetch_assoc()) {
    $trade_id = (int)$acc['trade_id'];

    // Fetch account equity
    if ($api->UserAccountGet($trade_id, $account) == MTRetCode::MT_RET_OK) {
        $equity = (float)($account->Balance + ($account->Floating ?? 0));
        $total_equity += $equity;
    }

    // Fetch open trades only
    if ($api->PositionGetTotal($trade_id, $total_positions) == MTRetCode::MT_RET_OK && $total_positions > 0) {

        $positions = [];
        if ($api->PositionGetPage($trade_id, 0, $total_positions, $positions) == MTRetCode::MT_RET_OK) {

            foreach ($positions as $pos) {

                $lot = round(($pos->Volume ?? 0) * 0.0001, 2);
                $profit = $pos->Profit ?? 0;

                $live_trades[] = [
                    "trade_id" => $trade_id,
                    "Symbol" => $pos->Symbol ?? null,
                    "Action" => ($pos->Action == 1 ? "Sell" : "Buy"),
                    "Volume" => $lot,
                    "OpenPrice" => $pos->PriceOpen ?? 0,
                    "CurrentPrice" => $pos->PriceCurrent ?? 0,
                    "Profit" => $profit,
                    "TimeCreate" => gmdate("Y-m-d H:i:s", $pos->TimeCreate)
                ];

                $total_lot += $lot;
                $total_profit += $profit;
            }
        }
    }
}

$mt5->api->Disconnect();

echo json_encode([
    "success" => true,
    "total_equity" => $total_equity,
    "total_lot" => $total_lot,
    "total_profit_loss" => $total_profit,
    "live_trades_count" => count($live_trades),
    "live_trades" => $live_trades
]);
exit;
?>
