<?php
// Ensure that the API connection is available and valid
include 'manager_data.php';

// Connect to MT5 server
if (($error_code = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, MT5_CONNECTION_TIMEOUT, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD)) != MTRetCode::MT_RET_OK) {
    echo json_encode(['error' => "Connection failed with error: " . MTRetCode::GetError($error_code)]);
    exit();
} else {
    // Fetch user logins
    $logins = [];
    $group = ""; // Leave empty to fetch all users or specify a group if needed
    $result = $api->UserLogins($group, $logins);

    if ($result !== MTRetCode::MT_RET_OK) {
        echo json_encode(['error' => "Error fetching user logins: " . MTRetCode::GetError($result)]);
        exit();
    }

    // Prepare an array for the user data to return as JSON
    $user_data = [];

    foreach ($logins as $login) {
        // Fetch account details for each login
        $user = null;
        $result = $api->UserGet($login, $user);
        $user2 = null;
        $result2 = $api->UserAccountGet($login, $user2);

        if ($result !== MTRetCode::MT_RET_OK || $result2 !== MTRetCode::MT_RET_OK) {
            $user_data[] = ['error' => "Error fetching account details for login $login: " . MTRetCode::GetError($result)];
        } else {
            // Extract account details
            $user_data[] = [
                'trade_id' => $login,
                'name' => $user->Name,
                'email' => $user->Email,
                'balance' => $user->Balance,
                'margin' => $user2->MarginFree,
                'group' => $user->Group,
                'leverage' => $user->Leverage,
            ];
        }
    }

    // Return the data as JSON
    echo json_encode($user_data);
}

// Disconnect from MT5 server
$api->Disconnect();
?>
