<?php
ob_start();
?>

<main class="container-fluid p-0">
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title fs-6" id="exampleModalLabel">Add User</h3>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="" class="form-label">Email Address</label>
                        <input type="email" id="modal_email" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label for="" class="form-label">Password</label>
                        <input type="text" id="modal_password" class="form-control">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveUserBtn">Save changes</button>
                </div>
            </div>
        </div>
    </div>

    <div class="px-6 px-lg-7 pt-8 border-bottom mb-4">
        <div class="row mb-5">
            <div class="col-12 col-md-6">
                <h2>Users</h2>
            </div>
            <div class="col-12 col-md-6 d-flex justify-content-end">
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">+ Add</button>
            </div>
            <div class="hstack gap-2 ms-auto"></div>
        </div>
    </div>

    <!-- Search Field -->
    <div class="row float-end m-auto d-flex justify-content-end mt-4">
        <div class="px-6 col-md-4">
            <div class="mb-3">
                <input type="text" id="userSearch" class="form-control" placeholder="Search Users...">
            </div>
        </div>
    </div>

    <div class="container">
        <table class="table" id="usersTable">
            <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">Full Name</th>
                    <th scope="col">Email address</th>
                    <th scope="col">Gender</th>
                    <th scope="col">Status</th>
                    <th scope="col">Action</th>
                </tr>
            </thead>
            <tbody id="usersTableBody">
                <tr>
                    <td colspan="6">Loading users...</td>
                </tr>
            </tbody>
        </table>
    </div>

    <div class="py-4 px-6">
        <div class="row align-items-center justify-content-between">
            <div class="col-md-6 d-none d-md-block"></div>
            <div class="col-md-auto">
                <nav aria-label="Page navigation"></nav>
            </div>
        </div>
    </div>
</main>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        const apiUrl = "https://projects.funtashtechnologies.com/gomeetapi/adminpanel/getallusers.php";

        function fetchUsers() {
            $.getJSON(apiUrl, function(response) {
                if (response.Result === "true") {
                    const users = response.Data;
                    const tbody = $("#usersTableBody");
                    tbody.empty();

                    users.forEach((user, index) => {
                        const fullName = `${user.firstname ?? ''} ${user.lastname ?? ''}`.trim();
                        const email = user.email ?? '-';
                        const id = user.id ?? '-';
                        const gender = user.gender ?? '-';
                        const status = (user.status ?? 'unverified').toLowerCase();

                        // Determine button class and label for status
                        const statusBadge = status === 'verified' ?
                            `<button class="btn btn-sm btn-success">Verified</button>` :
                            `<button class="btn btn-sm btn-danger">Not Verified</button>`;

                        tbody.append(`
        <tr>
            <th scope="row">${index + 1}</th>
            <td>${fullName}</td>
            <td>${email}</td>
            <td>${gender}</td>
            <td>${statusBadge}</td>
            <td>
                <a href="user-details.php?id=${id}" class="btn btn-sm btn-primary">View</a>
         <button class="btn btn-sm btn-dark delete-user-btn" data-id="${id}">Delete</button>
            </td>
        </tr>
    `);
                    });

                } else {
                    $("#usersTableBody").html(`<tr><td colspan="6">No users found.</td></tr>`);
                }
            }).fail(() => {
                $("#usersTableBody").html(`<tr><td colspan="6">Failed to load users.</td></tr>`);
            });
        }

        // Fetch on page load
        fetchUsers();

        // Filter
        $("#userSearch").on("keyup", function() {
            const value = $(this).val().toLowerCase();
            $("#usersTableBody tr").filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
            });
        });

        $('#saveUserBtn').on('click', function() {
            const email = $('#modal_email').val().trim();
            const password = $('#modal_password').val().trim();
            const $btn = $(this);

            if (!email || !password) {
                alert("Please enter both email and password.");
                return;
            }

            $btn.prop('disabled', true).text('Saving...');

            fetch("https://projects.funtashtechnologies.com/gomeetapi/adminpanel/adduser.php", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify({
                        email,
                        password
                    })
                })
                .then(res => res.json())
                .then(data => {
                    if (data.Result === "true") {
                        alert("User added successfully.");
                        $('#exampleModal').modal('hide');
                        // Optionally refresh your user list here
                    } else {
                        alert("Error: " + data.ResponseMsg);
                    }
                })
                .catch(() => {
                    alert("Something went wrong.");
                })
                .finally(() => {
                    $btn.prop('disabled', false).text('Save changes');
                    $('#modal_email').val('');
                    $('#modal_password').val('');
                });
        });

        $(document).on('click', '.delete-user-btn', function () {
    const userId = $(this).data('id');

    if (!confirm("Are you sure you want to delete this user?")) return;

    fetch("https://projects.funtashtechnologies.com/gomeetapi/adminpanel/deleteuser.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({ id: userId })
    })
    .then(res => res.json())
    .then(data => {
        if (data.Result === "true") {
            alert("User deleted successfully.");
            fetchUsers(); // Refresh the list
        } else {
            alert("Error: " + data.ResponseMsg);
        }
    })
    .catch(() => {
        alert("Something went wrong while deleting.");
    });
});

    });
</script>

<?php
$content = ob_get_clean();
include '../layouts/master.php';
?>