<?php 
include 'header-link.php'; 

// Ensure that the connection is available
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "
SELECT s.*, COALESCE(b.amount, 0) AS amount 
FROM student s
LEFT JOIN balance b ON s.userid = b.userid 
ORDER BY s.userid DESC
";

// Execute query and get the results
$result = $con->query($sql);

if (!$result) {
    die("Query failed: " . $con->error);
}

$students = [];
while ($row = $result->fetch_assoc()) {
    $students[] = $row;
}

// Handle delete request
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_id'])) {
    $delete_id = $_POST['delete_id'];
    
    // Prepare delete query with parameter binding for security
    $delete_sql = "DELETE FROM student WHERE id = ?";
    $stmt = $con->prepare($delete_sql);
    $stmt->bind_param("i", $delete_id);
    
    if ($stmt->execute()) {
        header("Location: user-info.php"); 
        exit();
    } else {
        echo "Error deleting user: " . $stmt->error;
    }
    $stmt->close();
}
?>

<main>
    <section>
        <div class="container mt-2 pb-5">
            <div class="row justify-content-center">
                <div class="col-md-6">
                    <div class="card custom-card">
                        <div class="card-body">
                            <div class="text-center">
                                <i class="profile-icon fa-duotone fa-solid fa-users"></i>
                            </div>

                            <h6 class="card-title text-center my-3">User List</h6>

                            <!-- Search input field -->
                            <input type="text" class="form-control mb-4" id="searchInput" placeholder="Search User..." onkeyup="filterOffers()">

                            <!-- User List -->
                            <div class="offer-list" id="offerList">
                                <?php foreach ($students as $student): ?>
                                    <div class="offer-card mb-5 p-3" data-sim="<?php echo $student['userid']; ?>">
                                        <div class="row">
                                            <div class="col">
                                                <small class="fw-bold">User Name: <?php echo htmlspecialchars($student['username']); ?></small><br>
                                                <small>Mobile: <?php echo htmlspecialchars($student['number']); ?></small><br>
                                                <small> Join Date: <?php echo htmlspecialchars($student['entry_date']); ?> </small>
                                            </div>
                                            <div class="col text-end">
                                                <small>Password: <?php echo htmlspecialchars($student['password']); ?></small><br>
                                                <small>PIN: <?php echo htmlspecialchars($student['pin']); ?></small><br>
                                                <small class="fw-bold">Balance: <?php echo htmlspecialchars(number_format($student['amount'])); ?></small>
                                            </div>
                                        </div>

                                        <div class="d-grid text-center">
                                            <!-- Delete Form -->
                                            <form action="" method="POST" style="display:inline;">
                                                <input type="hidden" name="delete_id" value="<?php echo $student['id']; ?>">
                                                <button type="submit" class="btn custom-button w-50 mx-auto" onclick="return confirm('Do you want to delete this user?')"> 
                                                    <i class="font fa-solid fa-trash"></i> Delete
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</main>

<script>
// JavaScript function for live search filtering
function filterOffers() {
    const searchInput = document.getElementById('searchInput').value.toLowerCase();
    const offerCards = document.querySelectorAll('.offer-card');

    offerCards.forEach(card => {
        const offerText = Array.from(card.querySelectorAll('small')).map(small => small.textContent.toLowerCase()).join(' ');

        if (offerText.includes(searchInput)) {
            card.style.display = '';
        } else {
            card.style.display = 'none';
        }
    });
}
</script>

</body>
</html>
