<?php
// -------------------- Config --------------------
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

// -------------------- Include Files --------------------
include_once __DIR__ . "/config.php";
include_once __DIR__ . "/connection.php";

// -------------------- Fetch Accounts + MT5 Equity --------------------
try {
    $query = "SELECT Registered_Date, account_name, trade_id, email, trader_pwd, invester_pwd, leverage 
              FROM liveaccounts ORDER BY Registered_Date DESC";

    $stmt = $conn->prepare($query);
    $stmt->execute();
    $result = $stmt->get_result();

    // Connect to MT5
    $mt5 = new MT5Connection();
    if (!$mt5->connect()) {
        echo json_encode([
            "success" => false,
            "message" => "Failed to connect to MT5",
            "error_code" => $mt5->lastError()
        ]);
        exit;
    }

    $accounts = [];

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

        $login = intval($row["trade_id"]);
        $accountInfo = new MTAccount();
        $equity = 0;

        $ret = $mt5->api->UserAccountGet($login, $accountInfo);

        if ($ret === MTRetCode::MT_RET_OK) {
            $equity = floatval($accountInfo->Equity);
        }

        $row["equity"] = $equity;
        $accounts[] = $row;
    }

    echo json_encode([
        "success" => true,
        "total_accounts" => count($accounts),
        "data" => $accounts
    ], JSON_PRETTY_PRINT);

} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Exception occurred",
        "error" => $e->getMessage()
    ]);
}
