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

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

$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;
}

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

$api = $mt5->api; // $api is ready to use

// Get totals (deposit & withdraw from DB)
$stmt = $conn->prepare("
    SELECT 
        COALESCE(SUM(deposit), 0) AS total_deposit,
        COALESCE(SUM(withdraw), 0) AS total_withdraw
    FROM liveaccounts 
    WHERE user_id = ?
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$totalsDB = $stmt->get_result()->fetch_assoc();

// Get active accounts with live MT5 data
$stmt2 = $conn->prepare("SELECT trade_id, account_name, leverage, Balance FROM liveaccounts WHERE user_id = ?");
$stmt2->bind_param("i", $user_id);
$stmt2->execute();
$result2 = $stmt2->get_result();

$activeAccounts = [];
$total_balance = 0; // Initialize total balance

while ($row = $result2->fetch_assoc()) {
    $trade_id = $row['trade_id'];
    $account_name = $row['account_name'];
    $leverage = $row['leverage'];
    $balance_db = $row['Balance']; // fallback in case MT5 fails

    // Fetch live data from MT5
    if (($error_code = $api->UserAccountGet($trade_id, $account)) == MTRetCode::MT_RET_OK) {
        $balance = $account->Balance;
        $floating_profit = $account->Floating; // current profit/loss
        $equity = $balance + $floating_profit;
    } else {
        // fallback to DB values if MT5 fails
        $balance = $balance_db;
        $floating_profit = 0;
        $equity = $balance;
    }

    $activeAccounts[] = [
        "trade_id" => $trade_id,
        "account_name" => $account_name,
        "Balance" => $balance,
        "leverage" => $leverage,
        "total_profit" => $floating_profit,
        "equity" => $equity
    ];

    $total_balance += $equity; // sum total balance
}

// Combine totals
$totals = [
    "total_balance" => $total_balance, // live total balance
    "total_deposit" => $totalsDB['total_deposit'],
    "total_withdraw" => $totalsDB['total_withdraw'],
    "mt5_accounts" => count($activeAccounts)
];

// Get recent transactions (deposit & withdraw)
$stmt3 = $conn->prepare("
    SELECT id, 'Deposit' AS type, deposit AS amount, Registered_Date AS date
    FROM liveaccounts
    WHERE user_id = ? AND deposit > 0
    UNION ALL
    SELECT id, 'Withdrawal' AS type, withdraw AS amount, Registered_Date AS date
    FROM liveaccounts
    WHERE user_id = ? AND withdraw > 0
    ORDER BY date DESC
    LIMIT 5
");
$stmt3->bind_param("ii", $user_id, $user_id);
$stmt3->execute();
$result3 = $stmt3->get_result();
$recentTransactions = [];
while($row = $result3->fetch_assoc()){
    $recentTransactions[] = [
        "id" => $row['id'],
        // 'trade_id' => $row['trade_id'],
        "type" => $row['type'],
        "amount" => $row['amount'],
        "date" => $row['date'],
        "status" => "Completed", // Optional, you can use actual status if available
    ];
}

// Return JSON
echo json_encode([
    "success" => true,
    "totals" => $totals,
    "activeAccounts" => $activeAccounts,
    "recentTransactions" => $recentTransactions
]);
?>
