<?php require_once("./pin/header.php"); ?>
<?php require_once("./pin/navbar.php"); ?>
<?php require_once("./pin/sidebar.php"); ?>
<style>
    .btn-sm svg {
        width: 20px;
        height: 20px;
        stroke: #333;
    }

    .btn-sm:hover {
        background-color: #f1f1f1;
    }

    #usersTable {
        border-collapse: collapse;
        width: 100%;
    }

    #usersTable th,
    #usersTable td {
        border: 1px solid #dee2e6;
        /* Ensure all table cells have a border */
    }
    #usersTable tbody tr:last-child td {
        border-bottom: 2px solid #dee2e6 !important;
        /* Force a visible bottom border */
    }
</style>
<div class="content-page">
    <div class="content" id="scheduledSection">
        <!-- Add User page -->
        <div class="d-flex align-items-center justify-content-between p-3 rounded mt-3">
            <h2 class="m-0">Add User</h2>

            <div class="d-flex align-items-center gap-2">
                <div class="input-group" style="width: 300px;">
                    <input type="text" class="form-control" placeholder="Search...">
                    <span class="input-group-text">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" style="fill: rgba(13, 13, 13, 0.62);">
                            <path d="M10 18a7.952 7.952 0 0 0 4.897-1.688l4.396 4.396 1.414-1.414-4.396-4.396A7.952 7.952 0 0 0 18 10c0-4.411-3.589-8-8-8s-8 3.589-8 8 3.589 8 8 8zm0-14c3.309 0 6 2.691 6 6s-2.691 6-6 6-6-2.691-6-6 2.691-6 6-6z"></path>
                        </svg>
                    </span>
                </div>
                <button class="btn btn-success" id="addNewUser">
                    New User
                </button>
            </div>
        </div>

        <!-- table-->
        <div class="mt-3 p-3 border rounded bg-white">
            <table class="table table-bordered" id="usersTable">
                <thead class="table-light">
                    <tr>
                        <th>User</th>
                        <th>Status</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Role</th>
                        <th>Teams</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Table rows will be added here dynamically-->
                </tbody>
            </table>
        </div>
    </div> <!-- container-fluid -->
</div> <!-- content -->
<?php require_once("./pin/modals.php"); ?>
<?php require_once("./pin/footer.php"); ?>
<script>
    let selectedUserId = '';

    // function to format roles properly
    function formatRoles(roleString) {
        if (!roleString) return ""; // Handle empty or undefined role
        return roleString
            .split(",") // Split by comma
            .map(role => role.replace(/_/g, " ").replace(/\b\w/g, char => char.toUpperCase())) // Replace underscores & capitalize words
            .join(", "); // Join back with commas
    }

    function fetchUsers() {
        $.ajax({
            url: 'https://app.watify.io/server/fetch_users.php',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    let users = response.users;
                    let tableBody = $('#usersTable tbody');
                    tableBody.empty(); // Clear existing rows

                    users.forEach(user => {
                        tableBody.append(`
                            <tr>
                                <td>${user.name}</td>
                                <td><span class="badge bg-success">Online</span></td>
                                <td>${user.email}</td>
                                <td>${user.phone}</td>
                               <td>${formatRoles(user.role)}</td>
                                <td></td> <!-- Teams column, empty for now -->
                                <td>
                                    <div class="d-flex align-items-center gap-2">
                                        <!-- Dropdown-style Button with Menu -->
                                        <div class="dropdown">
                                            <button class="btn btn-sm btn-light border dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" 
                                                     fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                    <path d="M6 9l6 6 6-6"></path>
                                                </svg>
                                            </button>
                                            <ul class="dropdown-menu">
                                               <li>
                                                <a class="dropdown-item edit-user" href="#" 
                                                    data-id="${user.id}" 
                                                    data-name="${user.name}" 
                                                    data-email="${user.email}" 
                                                    data-phone="${user.phone}" 
                                                    data-role="${user.role}">
                                                    Edit
                                                </a>
                                            </li>
                                                <li><a class="dropdown-item delete-user" href="#" data-id="${user.id}">Delete</a></li>
                                            </ul>
                                        </div>

                                        <!-- Three Dots Button (Horizontal Ellipsis) -->
                                        <button class="btn btn-sm btn-light border d-flex align-items-center justify-content-center">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" 
                                                 fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                <circle cx="6" cy="12" r="1"></circle>
                                                <circle cx="12" cy="12" r="1"></circle>
                                                <circle cx="18" cy="12" r="1"></circle>
                                            </svg>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        `);
                    });

                    // Initialize DataTables
                    $('#usersTable').DataTable();
                } else {
                    console.error("Error:", response.message);
                }
            },
            error: function(xhr, status, error) {
                console.error("AJAX Error:", error);
            }
        });
    }
    $(document).ready(function() {
        // Handle Edit and Delete actions
        $(document).on('click', '.edit-user', function() {
            let userName = $(this).data('name'); // Get Name
            let userEmail = $(this).data('email'); // Get Email
            let userPhone = $(this).data('phone'); // Get Phone
            let userRole = $(this).data('role'); // Get Role
            // Split Name into First Name & Last Name (assuming space-separated)
            let nameParts = userName.split(" ");
            let firstName = nameParts[0] || "";
            let lastName = nameParts.slice(1).join(" ") || "";
            selectedUserId = $(this).data('id');
            // Fill modal fields with user data
            $('#firstName').val(firstName);
            $('#lastName').val(lastName);
            $('#emailId').val(userEmail);
            $('#phoneNumber').val(userPhone);

            // Select the correct role in the dropdown
            let selectedRoles = userRole.split(',').map(role => role.trim());
            $('#selectRolesDropDown').val(selectedRoles).change();
            // Show the modal
            $('#saveUserButton').hide();
            $('#updateUserButton').show()
            $("#addUserModal").modal("show"); // open modal 
        });

        $(document).on('click', '.delete-user', function() {
            let userId = $(this).data('id');
            if (confirm('Are you sure you want to delete this user?')) {
                $.ajax({
                    url: 'https://app.watify.io/server/delete_user', 
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        userId: userId,
                    }),
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            alert('User deleted successfully');
                            location.reload(); // Reload page to reflect changes
                        } else {  
                            alert('Error: ' + response.message);
                        }
                    },
                    error: function(xhr, status, error) {
                        alert('Something went wrong, please try again later');
                    }
                });
            }
        });

        // Call fetchUsers when the page loads
        fetchUsers();

        $('#selectRolesDropDown').select2({
            theme: "bootstrap-5",
            width: '100%', // Ensures full width
            placeholder: $(this).data('placeholder'),
            dropdownParent: $('#addUserModal'), // Ensures dropdown appears inside the modal
        });

        document.getElementById("saveUserButton").addEventListener('click', function() {
            let firstName = document.getElementById('firstName').value.trim();
            let lastName = document.getElementById('lastName').value.trim();
            let email = document.getElementById('emailId').value.trim();
            let emailConfirmed = document.getElementById('emailConfirmed').checked;
            let phoneNumber = document.getElementById('phoneNumber').value.trim();
            let phoneConfirmed = document.getElementById('phoneConfirmed').checked;
            let selectedRoles = $('#selectRolesDropDown').val() || [];
            let formData = {
                firstName,
                lastName,
                email,
                phoneNumber,
                roles: selectedRoles // Change key name from selectedRoles to roles
            };
            $.ajax({
                url: 'https://app.watify.io/server/add_new_user',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                dataType: 'json',
                success: function(response) {
                    // console.log('Server Response:', response);
                    if (response.status === 'success') {
                        round_success_noti(response.message);
                        $('#addUserModal').modal('hide');
                    } else {
                        round_error_noti(response.message);
                    }
                },
                error: function(xhr, status, error) {
                    round_error_noti('Something went wrong, Please try again later');
                }
            });

        });
    });
    document.getElementById("addNewUser").addEventListener("click", function() {
        $('#saveUserButton').show();
        $('#updateUserButton').hide()
        $('#firstName').val('');
        $('#lastName').val('');
        $('#emailId').val('');
        $('#phoneNumber').val('');

        // Uncheck checkboxes
        $('#emailConfirmed').prop('checked', false);
        $('#phoneConfirmed').prop('checked', false);

        // Reset dropdown for multiple roles
        $('#selectRolesDropDown').val([]).change();
        $("#addUserModal").modal("show");
    });

    document.getElementById("updateUserButton").addEventListener("click", function() {
        let firstName = document.getElementById('firstName').value.trim();
        let lastName = document.getElementById('lastName').value.trim();
        let email = document.getElementById('emailId').value.trim();
        let emailConfirmed = document.getElementById('emailConfirmed').checked;
        let phoneNumber = document.getElementById('phoneNumber').value.trim();
        let phoneConfirmed = document.getElementById('phoneConfirmed').checked;
        let selectedRoles = $('#selectRolesDropDown').val() || [];

        if (selectedUserId == "") return;

        let userId = selectedUserId;
        let formData = {
            firstName,
            lastName,
            email,
            phoneNumber,
            userId,
            roles: selectedRoles // Change key name from selectedRoles to roles
        };
        $.ajax({
            url: 'https://app.watify.io/server/update_user',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            dataType: 'json',
            success: function(response) {
                console.log('Server Response:', response);
                if (response.status === 'success') {
                    round_success_noti(response.message);
                    fetchUsers();
                    $('#addUserModal').modal('hide');
                } else {
                    round_error_noti(response.message);
                }
            },
            error: function(xhr, status, error) {
                round_error_noti('Something went wrong, Please try again later');
            }
        });
    });
</script>