<?php
session_start();
include 'config.php';
include 'manager_data.php';

// Check if user is logged in
if (strlen($_SESSION['clogin']) == 0) {
    echo json_encode(['error' => 'Unauthorized access']);
    exit();
}

// 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: ' . MTRetCode::GetError($error_code)]);
    exit();
}

// 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)]);
    $api->Disconnect();
    exit();
}

// Prepare data for response
$data = [];
foreach ($logins as $login) {
    $user = null;
    $userAccount = null;

    $result = $api->UserGet($login, $user);
    $result2 = $api->UserAccountGet($login, $userAccount);

    if ($result === MTRetCode::MT_RET_OK && $result2 === MTRetCode::MT_RET_OK) {
        $data[] = [
            'login' => $login,
            'name' => $user->Name,
            'email' => $user->Email,
            'balance' => $user->Balance,
            'margin' => $userAccount->MarginFree,
            'group' => $user->Group,
            'leverage' => $user->Leverage
        ];
    }
}

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

// Return data as JSON
echo json_encode($data);
?>
