<?php 
require_once("header.php");

// ==================== DELETE USER =====================
if (isset($_GET['del'])) {
    $id = $_GET['del'];
    $stmt = $pdo->prepare("DELETE FROM logins WHERE id = ?");
    $stmt->execute([$id]);
    $success = "User deleted successfully.";
}

// ==================== TOGGLE LOCK PROFIT =====================
if (isset($_GET['toggle_id'])) {
    $id = intval($_GET['toggle_id']);
    $stmt = $pdo->prepare("SELECT switch FROM logins WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        $newSwitch = ($row['switch'] > 0) ? 0 : 1;
        $stmtUpdate = $pdo->prepare("UPDATE logins SET switch = ? WHERE id = ?");
        $stmtUpdate->execute([$newSwitch, $id]);
    }
    header("Location: adminverify.php");
    exit();
}
?>

<div class="main-panel">
    <div class="content bg-light">
        <div class="page-inner">
            <div class="mt-2 mb-4">
                <h1 class="title1 text-dark"><?php echo $domain_name ?> users list</h1>
            </div>

            <div class="mb-5 row">
                <div class="col-md-12">
                    <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." class="form-control mb-3">

                    <div class="table-responsive">
                        <table id="myTable" class="table table-hover text-dark">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Client Name</th>
                                    <th>Username</th>
                                    <th>A/c Bal.</th>
                                    <th>Capital</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th>Status</th>
                                    <th>Date registered</th>
                                    <th>Deposit</th>
                                    <th>Withdraw</th>
                                    <th>Lock Profit</th>
                                    <th>Details</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody id="userslisttbl">
                                <?php
                                $ordersStmt = $pdo->query("SELECT * FROM logins WHERE ip > 0");
                                $ordersres = $ordersStmt->fetchAll();

                                foreach ($ordersres as $row) {
                                    echo "<tr>
                                        <td>{$row['id']}</td>
                                        <td>{$row['fullname']}</td>
                                        <td>{$row['username']}</td>
                                        <td>&#36;{$row['balance']}</td>
                                        <td>&#36;{$row['ibalance']}</td>
                                        <td><a href='mailto:{$row['email']}'>{$row['email']}</a></td>
                                        <td>{$row['phone']}</td>";

                                    // Status badge
                                    $statusBadge = [
                                        0 => "<span class='badge badge-info'>NOT ACTIVE</span>",
                                        1 => "<span class='badge badge-primary'>ONGOING</span>",
                                        2 => "<span class='badge badge-danger'>LOSING</span>",
                                        3 => "<span class='badge badge-warning'>DORMANT</span>",
                                        4 => "<span class='badge badge-warning'>ONHOLD</span>",
                                        5 => "<span class='badge badge-danger'>BLOCKED</span>",
                                        6 => "<span class='badge badge-success'>COMPLETED</span>"
                                    ];
                                    echo "<td>{$statusBadge[$row['status']]}</td>";

                                    // Date diff
                                    $diff = date_diff(date_create("now"), date_create($row['date']));
                                    echo "<td>Created {$diff->format('%a days ago')}</td>";

                                    // Deposit & Withdraw links
                                    $depositLink = ($row['confirm'] == 1) ? "<a href='udeposit.php?id={$row['id']}' style='color: green;'>DEPOSIT</a>" : "<a href='udeposit.php?id={$row['id']}' style='color: black;'>DEPOSIT</a>";
                                    $withdrawLink = ($row['confirmPAY'] == 1) ? "<a href='uwithdraw.php?id={$row['id']}' style='color: green;'>WITHDRAW</a>" : "<a href='uwithdraw.php?id={$row['id']}' style='color: black;'>WITHDRAW</a>";
                                    echo "<td>{$depositLink}</td>";
                                    echo "<td>{$withdrawLink}</td>";

                                    // Lock Profit button
                                    $lockText = ($row['switch'] > 0) ? "OPEN" : "LOCK";
                                    $btnColor = ($row['switch'] > 0) ? "green" : "black";
                                    echo "<td><a href='adminverify.php?toggle_id={$row['id']}' class='lock-btn' style='color: {$btnColor};'>{$lockText}</a></td>";

                                    // Details and Delete buttons
                                    echo "<td><a class='btn btn-secondary btn-sm' href='userdatails.php?id={$row['id']}'>Details</a></td>";
                                    echo "<td><button class='btn btn-danger btn-sm del-btn' data-id='{$row['id']}'>DEL..</button></td>";
                                    echo "</tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- SweetAlert & jQuery -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
// Confirm Lock Profit toggle
$('.lock-btn').click(function(e){
    e.preventDefault();
    const url = $(this).attr('href');
    const btnText = $(this).text();

    Swal.fire({
        title: 'Are you sure?',
        text: "You want to " + btnText + " this user's profit!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, proceed!',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            // Send AJAX request
            $.get(url, function(response) {
                // After the toggle is done, reload the current page
                window.location.href = 'adminverify.php';
            });
        }
    });
});


// Confirm Delete
$('.del-btn').click(function(){
    var id = $(this).data('id');
    Swal.fire({
        title: 'Are you sure?',
        text: "This action cannot be undone!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, delete!',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = 'adminverify.php?del=' + id;
        }
    });
});

// Search function
function myFunction() {
    var input = document.getElementById("myInput");
    var filter = input.value.toUpperCase();
    var table = document.getElementById("myTable");
    var tr = table.getElementsByTagName("tr");
    for (var i = 1; i < tr.length; i++) {
        var td = tr[i].getElementsByTagName("td")[1];
        if (td) {
            var txtValue = td.textContent || td.innerText;
            tr[i].style.display = (txtValue.toUpperCase().indexOf(filter) > -1) ? "" : "none";
        }
    }
}
</script>


<?php 
require_once("footer.php"); ?>