@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "Role Administration";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<p>
    @* <a asp-action="UserCreate">Create New</a> *@
</p>
<div id="app">
    <div class="row">
        <div class="col-md-12 col-lg-12">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">Role List</h4>
                    <div class="row">
                        <div class="col-md-6 col-lg-6">
                            <form class="form-group" v-on:submit.prevent="addRole">
                                <label class="form-label">Role Name</label>
                                <input type="text" class="form-control" placeholder="Role Name" v-model="newRoleName" v-on:input="newRoleName=sentenceCapitalization($event)" required>
                                <textarea class="form-control" placeholder="Role Description" v-model="newRoleDescription" v-on:input="newRoleDescription=sentenceCapitalization($event)"></textarea>
                                <button type="submit" class="btn btn-primary m-1">Add</button>
                            </form>
                        </div>
                    </div>
                    <div class="col-md-12 col-lg-12">
                        <div>
                            <table class="table table-bordered table-hover table-striped no-wrap align-middle" id="roleDatatable" style="width:100%;border-style: solid; border-width: 1px"></table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- MODAL -->
    <div class="modal fade" id="confirm-dialog" tabindex="-1" role="dialog" aria-labelledby="confirm-dialog-title" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="confirm-dialog-title">Confirmation</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close" v-on:click="hideModal">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div v-if="selectedRole">
                    <div class="modal-body">
                        <p>Are you sure you want to delete role {{ selectedRole.roleName }}?</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal" v-on:click="hideModal">Cancel</button>
                        <input type="hidden" id="delete-id">
                        <a id="confirmButton" href="#" class="btn btn-danger" v-on:click="confirmDelete(selectedRole)">Confirm</a>
                    </div>
                </div>
                <div v-else><p>Loading...</p></div>
            </div>
        </div>
    </div>
</div>
@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script>

        $(function () {
            app.mount('#app');
        });

        const app = Vue.createApp({
            data() {
                return {
                    userList: null,
                    roleList: null,
                    selectedRole: null,
                    roleDatatable: null,
                    newRoleName: null,
                    newRoleDescription: null,
                };
            },
            mounted() {
                this.fetchRoles();
            },
            methods: {
                async fetchRoles() {
                    fetch('/RoleAPI/GetRoleList', {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(data => {
                            this.roleList = data.length ? data : [];
                            this.$nextTick(() => {
                                if (this.roleDatatable != null) {
                                    this.roleDatatable.clear().destroy();
                                }
                            this.initiateTable();
                            });
                    })
                    .catch(error => {
                        console.error('There was a problem with the fetch operation:', error);
                    });
                },
                deleteRole(roleId, roleName) {
                    this.selectedRole = { id: roleId, roleName: roleName }; // Set selected user
                    console.log(this.selectedRole);
                    $('#confirm-dialog').modal('show'); // Show the modal

                },
                async confirmDelete(selectedRole) {
                    try{
                        var response = await fetch('/RoleAPI/DeleteRole/' + selectedRole.id, {
                            method: 'DELETE',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                        });
                        if (response.ok) {
                            this.roleList = this.roleList.filter(role => role.id !== selectedRole.id);
                            this.$nextTick(() => {
                                if (this.roleDatatable != null) {
                                    this.roleDatatable.clear().destroy();
                                }
                                this.initiateTable();
                            });
                        }
                        else {
                            console.error('Failed to delete role');
                        }

                        this.hideModal();

                    }
                    catch (error) {
                        console.error('There was a problem with the fetch operation:', error);
                    }
                },
                hideModal() {
                    $('#confirm-dialog').modal('hide');
                },
                async initiateTable() {
                    self = this;
                    this.roleDatatable = $('#roleDatatable').DataTable({
                        "data": self.roleList,
                        "columns": [
                            {
                                "title": "Role",
                                "data": "name",
                            },
                            {
                                "title": "Description",
                                "data": "description",
                            },
                            {
                                "title": "Delete",
                                "data": "id",
                                "render": function (data, type, row, meta) {
                                    if(row.name != "Inventory Master"){
                                        var deleteButton = `<button type="button" class="btn btn-danger delete-btn" data-id="${data}" data-name="${row.name}">Delete</button>`;
                                    }
                                    else{
                                        var deleteButton = ""
                                    }
                                    return deleteButton;
                                },
                            }
                        ],
                        responsive: true,
                        order: [[5, 'asc']],
                    })

                    // Attach click event listener to the delete button
                    $('#roleDatatable tbody').on('click', '.delete-btn', function () {
                        const roleId = $(this).data('id');
                        const roleName = $(this).data('name');
                        self.deleteRole(roleId, roleName);
                    });

                    this.loading = false;
                },
                async addRole() {
                    try
                    {
                        const response = await fetch(`/RoleAPI/AddRole`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                newRoleName: this.newRoleName,
                                newRoleDescription: this.newRoleDescription
                            })
                        });

                        if (!response.ok) {
                            throw new Error('Failed to add role');
                        }
                        const data = await response.json();
                        console.log('Role updated successfully');
                    }
                    catch (error) {
                        const errorResponse = await response.json();
                        console.error('Failed to add role:', errorResponse.message);
                    }

                    this.fetchRoles();
                },
                sentenceCapitalization(event) {
                    const value = event.target.value.trimStart();
                    return value.charAt(0).toUpperCase() + value.slice(1);
                },
            }
        })
    </script>
}
