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

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

    $tradeid = $_GET['tradeid'];


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();
}

// Fetch user logins
$logins = [];
$group = "";
$result = $api->UserLogins($group, $logins);

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 Master</h2>
        <div class="search-bar">
            <form method="GET" action="">
                <input type="text" id="search-input" name="tradeid" placeholder="Search tradeid..." />
<button type="submit" style='background-color:#2e8b57;color:white;padding:10px;border-radius:10px;border:none;outline:none'><i class="fa fa-search"></i> &nbsp;&nbsp;Search</button>
            </form>
        </div>
        <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>Margin</th>
                        <th>Account</th>
                        <th>Leverage</th>
                        <th>Add Master</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);
                $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->Margin;
                    $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;
                    
                                         // 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;
                    
                    $stmt2 = $dbh->prepare("SELECT * FROM tbl_master WHERE tradeid = :tradeid");
                    $stmt2->bindParam(':tradeid', $tradeid, PDO::PARAM_STR);
                    $stmt2->execute();

                    $is_banned2 = $stmt2->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>$margin</td>";
                    echo "<td>$group</td>";
                    echo "<td>$leverage</td>";
                    
                    if ($is_banned || $is_banned2) {
                        // 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_master.php?tradeid=$login&name=$name&email=$email&balance=$balance&group=$group&leverage=$leverage&loginid=$logined'>
                                <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>

<script>
    document.getElementById('search-input').addEventListener('keyup', function() {
        var input = this.value.toLowerCase();
        var rows = document.querySelectorAll('#client-table tbody tr');
        rows.forEach(function(row) {
            var rowText = row.textContent.toLowerCase();
            row.style.display = rowText.includes(input) ? '' : 'none';
        });
    });
</script>

</body>
</html>

<?php
$api->Disconnect();
?>
