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

// Check if the user is logged in
if (strlen($_SESSION['clogin']) == 0) {
    echo "<script>window.location.href='login.php';</script>";
    exit();
}

// Include necessary files
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();
}

$mastertrade = $_GET['mastertrade'];

// Fetch user logins only when a tradeid is provided
$logins = [];
$group = ""; // Leave empty to fetch all users or specify a group if needed

if (isset($_GET['tradeid']) && !empty($_GET['tradeid'])) {
    // Only search for the entered tradeid
    $tradeid = $_GET['tradeid'];
    $result = $api->UserLogins($group, $logins);

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

?>

<!DOCTYPE html>
<html>
<head>
    <?php include 'style.php'; ?>
</head>
<body>

<?php include 'header.php'; ?>

<?php
$sql = "SELECT * FROM tbl_manager";
$query = $dbh->prepare($sql);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_OBJ);
$cnt = 1;
if ($query->rowCount() > 0) {
    foreach ($results as $result) {
        $loginid = htmlentities($result->login);
    }
}
?>

<div class="topnav" style="background-color:transparent">
    <a href="manager.php" class="split"><i class="fa fa-users"></i> &nbsp;&nbsp;Manager</a>
    <a href="master.php" class="split" style="background-color:#ff6c2c;border-radius:20px"><i class="fa fa-line-chart"></i> &nbsp;&nbsp;Master</a>
    <a href="index.php" class="split" ><i class="fa fa-user"></i> &nbsp;&nbsp;Profiles</a>
</div>

<div class="container">
    <div class="table-container">
        <h2 style="text-align:center; color: #fff;">Add Slave For (<?php echo $_GET['mastertrade'];?>)</h2>
        <!-- Search Bar -->
        <div class="search-bar">
            <form method="GET" action="">
                <!-- Search bar for Trade ID -->
                <input type="text" id="search-input" name="tradeid" placeholder="Search Trade ID..." value="<?= isset($tradeid) ? htmlspecialchars($tradeid) : ''; ?>" />

                <!-- Hidden input for mastertrade, if not set, use the value from the URL or session -->
                <?php
                // Retain the mastertrade value, either from the GET parameter or the session
                $mastertrade_value = isset($_GET['mastertrade']) ? $_GET['mastertrade'] : (isset($_SESSION['mastertrade']) ? $_SESSION['mastertrade'] : '');
                ?>
                <input type="hidden" name="mastertrade" value="<?= htmlspecialchars($mastertrade_value); ?>">

       
            <button type="submit" style="padding:10px;border-radius:5px;background-color:blue;color:white;width:100px">Search</button>
       
            </form>
        </div>

        <!-- Table -->
        <div style="overflow-x:auto;">
            <table id="client-table">
                <thead>
                    <tr>
                        <th>Trade ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Balance</th>
                        <th>Account</th>
                        <th>Leverage</th>
                        <th>Add Slave</th>
                    </tr>
                </thead>
               <tbody>
    <?php
    if (isset($tradeid) && !empty($tradeid)) {
        // Fetch user logins and check for the matching tradeid
        $match_found = false;

        foreach ($logins as $login) {
            if ($login == $tradeid) {
                // Fetch account details for the matching Trade ID
                $user = null;
                $result = $api->UserGet($login, $user);

                if ($result !== 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;
                    $group = $user->Group;
                    $leverage = $user->Leverage;

                    // Check if tradeid exists in tbl_copytrade
                    $stmt = $dbh->prepare("SELECT * FROM tbl_copytrade WHERE mastertrade = :tradeid OR copytrade = :tradeid");
                    $stmt->bindParam(':tradeid', $tradeid, PDO::PARAM_STR);
                    $stmt->execute();

                    $is_banned = $stmt->rowCount() > 0;

                    // Display account details for the matching Trade ID
                    echo "<tr>";
                    echo "<td>$login</td>";
                    echo "<td>$name</td>";
                    echo "<td>$email</td>";
                    echo "<td>$balance</td>";
                    echo "<td>$group</td>";
                    echo "<td>$leverage</td>";
                    
                    if ($is_banned) {
                        // If tradeid is in mastertrade or copytrade, show ban icon
                        echo "<td><i class='fa fa-ban' style='color:red;font-size:25px'></i></td>";
                    } else {
                        // If tradeid is not in mastertrade or copytrade, show add slave link
                        echo "<td><a href='insert_slave.php?mastertradeid=$mastertrade&slavetradeid=$login&name=$name&email=$email&balance=$balance&group=$group&leverage=$leverage&loginid=$loginid'>
                                <i class='fa fa-plus-circle' style='color:#00f541;font-size:25px'></i>
                              </a></td>";
                    }

                    echo "</tr>";
                }
                $match_found = true;
            }
        }

        if (!$match_found) {
            echo "<tr><td colspan='7'>No matching Trade ID found.</td></tr>";
        }
    } else {
        echo "<tr><td colspan='7'>Please enter a Trade ID to search.</td></tr>";
    }
    ?>
</tbody>

            </table>
        </div>
    </div>
</div>

</body>
</html>

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