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

if (strlen($_SESSION['clogin']) == 0) {
    echo "<script>window.location.href='login.php';</script>";
}

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 "Connection failed with error: " . MTRetCode::GetError($error_code);
    exit();
} else {
    // Fetch user logins for all groups
    $logins = [];
    $group = ""; // Leave empty to fetch all users (no group filter)
    $result = $api->UserLogins($group, $logins);

    if ($result !== MTRetCode::MT_RET_OK) {
        echo "Error fetching user logins: " . MTRetCode::GetError($result);
        exit();
    }
}

// File path to save the data
$file_path = "user_accounts.txt";

// Open file in read-write mode (to check for existing data)
$file = fopen($file_path, "a+");
if (!$file) {
    echo "Error opening file for writing.";
    exit();
}

// Read existing data into an array for duplicate check
$existing_logins = [];
while (($line = fgets($file)) !== false) {
    $data = explode("\t", $line);
    if (count($data) > 1) {
        $existing_logins[] = $data[0]; // Assuming login is the first field
    }
}

// Go back to the start of the file to check and write headers if necessary
rewind($file);

// Write headers only if the file is empty (ftell returns 0 if file pointer is at the start)
if (ftell($file) == 0) {
    fwrite($file, "Login\tName\tEmail\tBalance\tMargin\tGroup\tLeverage\n");
}

?>

<table border="1">
    <thead>
        <tr>
            <th>Login</th>
            <th>Name</th>
            <th>Email</th>
            <th>Balance</th>
            <th>Margin</th>
            <th>Group</th>
            <th>Leverage</th>
        </tr>
    </thead>
    <tbody>
        <?php
        // Display user logins and account details in table format
        if (!empty($logins)) {
            foreach ($logins as $login) {
                // Check if the login is already processed
                if (in_array($login, $existing_logins)) {
                    continue; // Skip duplicate logins
                }

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

                if ($result !== MTRetCode::MT_RET_OK || $result2 !== MTRetCode::MT_RET_OK) {
                    echo "<tr><td colspan='7'>Error fetching account details for login $login: " . MTRetCode::GetError($result) . "</td></tr>";
                } else {
                    // Extract account details
                    $name = $user->Name;
                    $email = $user->Email;
                    $balance = $user->Balance;
                    $margin = $user2->MarginFree;
                    $group = $user->Group;
                    $leverage = $user->Leverage;

                    // Write account details to file
                    $line = "$login\t$name\t$email\t$balance\t$margin\t$group\t$leverage\n";
                    fwrite($file, $line);

                    // Display account details for each login in table
                    echo "<tr>";
                    echo "<td>$login</td>";
                    echo "<td>$name</td>";
                    echo "<td>$email</td>";
                    echo "<td>$balance</td>";
                    echo "<td>$margin</td>";
                    echo "<td>$group</td>";
                    echo "<td>$leverage</td>";
                    echo "</tr>";
                }
            }
        } else {
            echo "<tr><td colspan='7'>No user logins found.</td></tr>";
        }

        // Close the file
        fclose($file);
        ?>
    </tbody>
</table>
