@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "Company & Department Administration";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="app">
    <div class="row">
        <div class="card-header">
            <button id="addCompDeptBtn" class="btn btn-success col-md-3 col-lg-3 m-1 col-12"><i class="fa fa-plus"></i>&nbsp;Add Company & Department</button>
        </div>
        <div class="col-md-12 col-lg-12">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">Company And Department</h4>
                    <div class="col-md-12 col-lg-12">
                        <div>
                            <table class="table table-bordered table-hover table-striped no-wrap" id="userDatatable" style="width:100%;border-style: solid; border-width: 1px"></table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ADD COMPANY DEPARTMENT MODAL -->
    <div class="modal fade" id="registerCompDept" tabindex="-2" role="dialog" aria-labelledby="addCompDeptModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addCompDeptModalLabel">Add Item</h5>
                    <button type="button" class="closeModal" data-dismiss="modal" aria-label="Close" v-on:click="showItemModal=false">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="container-fluid">
                        <form v-on:submit.prevent="addCompanyDepartment" data-aos="fade-right">
                            <div class="register" data-aos="fade-right">
                                <div class="row" data-aos="fade-right">
                                    <div class="col-md-12">
                                        <h3 class="register-heading">REGISTER COMPANY & DEPARTMENT</h3>
                                        <div class="row register-form d-flex justify-content-center">
                                            <div class="col-md-9">
                                                <!-- Company Input -->
                                                <div class="form-group row">
                                                    <label class="col-sm-3 col-form-label">Company:</label>
                                                    <div class="col-sm-4">
                                                        <input type="text" class="form-control col-md-10" v-model="company" required>
                                                    </div>

                                                    <!-- Add Department -->
                                                    <div class="col-sm-4">
                                                        <button type="button"
                                                                class="btn f-icon d-flex align-items-center text-success"
                                                                style="height: 36px; width: auto"
                                                                v-on:click="departments.push({ departmentName: '', departmentCode: '' })">
                                                            <i class="fas fa-plus-square fa-lg"></i>&ensp;Add Department
                                                        </button>

                                                        <span class="text-danger">*Click to add more department</span>
                                                    </div>
                                                </div>

                                                <!-- Department Inputs -->
                                                <div class="form-group row">
                                                    <span class="text-danger">*Department code only accept 2 alphabets character. This code will be use for the item identification</span>
                                                    <label class="col-sm-3 col-form-label">Department:</label>
                                                    <div class="col-sm-8">
                                                        <div class="row mb-2 align-items-center" v-for="(department, index) in departments" :key="index">
                                                            <div class="col-10">
                                                                <input type="text" class="form-control"
                                                                       v-model="departments[index].departmentName"
                                                                       placeholder="Department Name"
                                                                v-on:input="updateUppercase($event, index, 'departmentName')"
                                                                       required>

                                                                <input type="text" class="form-control"
                                                                       minlength="2" maxlength="2" pattern="[a-zA-Z]{2}"
                                                                       v-model="departments[index].departmentCode"
                                                                       placeholder="Department Code"
                                                                v-on:input="updateUppercase($event, index, 'departmentCode')"
                                                                       required>
                                                            </div>
                                                            <div class="col-2">
                                                                <button type="button" class="btn btn-danger" v-on:click="removeDepartment(index)">
                                                                    Remove
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        @* Submit and Reset Buttons *@
                                        <div class="row">
                                            <div class="col-sm-8 col-md-12 d-flex justify-content-center">
                                                <button type="button" v-on:click="resetDetails()" class="btn btn-secondary m-1">Reset</button>
                                                <button type="submit" class="btn btn-primary m-1" :disabled="departments.length == 0">Submit</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- DELETE 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="selectedModule">
                    <div class="modal-body">
                        <p>Are you sure you want to delete module {{ selectedModule.moduleName }}?</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(selectedModule)">Confirm</a>
                    </div>
                </div>
                <div v-else><p>Loading...</p></div>
            </div>
        </div>
    </div>
</div>
@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script>
        const app = Vue.createApp({
            data() {
                return {
                    userList: null,
                    selectedModule: null,
                    compDeptList: null,
                    company: null,
                    departments: [{
                        departmentName: '',
                        departmentCode: '',
                    }],
                    compDeptDatatable: null,
                };
            },
            watch: {
                // departments: {
                //     handler() {
                //         // Code to be executed when the 'departments' data property changes
                //         console.log(this.departments);
                //     },
                //     deep: true, // Watch nested changes inside the departments array
                // },
            },
            mounted() {
                this.fetchCompDept();
            },
            methods: {
                async fetchCompDept() {
                    fetch('/AdminAPI/GetDepartmentWithCompanyList', {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(data => {
                        // console.log(data)
                        this.compDeptList = data ? data : [];
                        if (this.compDeptDatatable != null) {
                            this.compDeptDatatable.clear().destroy();
                        }
                        this.initiateTable();
                    })
                    .catch(error => {
                        console.error('There was a problem with the fetch operation:', error);
                    });
                },
                editCompDept(compDept) {
                    // Check if the user ID exists
                    if (module.settingId) {
                        // Redirect the user to the edit user page
                        window.location.href = 'ModuleSetting/' + module.settingId;
                    } else {
                        console.error('Module ID not found');
                    }
                },
                deleteCompDept(compDept) {
                    this.selectedModule = module; // Set selected user
                    $('#confirm-dialog').modal('show'); // Show the modal

                    // console.log(this.selectedModule);
                },
                confirmDelete(compDept) {
                    fetch(`/ModuleAPI/DeleteModule/${module.settingId}`, {
                        method: 'POST'
                    })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Failed to delete module');
                            }
                            // Remove the deleted user from the userData array
                            const index = this.moduleData.findIndex(u => u.settingId === module.settingId);
                            if (index !== -1) {
                                alert("Module deleted successfully");
                                this.moduleData.splice(index, 1);
                            }
                            this.hideModal(); // Hide the modal after deletion
                        })
                        .catch(error => {
                            console.error('Failed to delete module with status:', error);
                        });
                },
                hideModal() {
                    $('#confirm-dialog').modal('hide');
                },
                initiateTable() {
                    self = this;
                    // Flatten the data to create rows for each department
                    var flatData = [];
                    self.compDeptList.forEach(function (company) {
                        company.departments.forEach(function (department) {
                            flatData.push({
                                companyId: company.companyId,
                                companyName: company.companyName,
                                departmentName: department.departmentName,
                                departmentCode: department.departmentCode
                            });
                        });
                    });
                    this.compDeptDatatable = $('#userDatatable').DataTable({
                        "data": flatData,
                        "columns": [
                            {
                                "title": "Company Name",
                                "data": "companyName",
                                "visible": false,
                            },
                            {
                                "title": "Department Name",
                                "data": "departmentName",
                            },
                            {
                                "title": "Department Code",
                                "data": "departmentCode",
                            },
                            {
                                "title": "Delete",
                                "data": "companyId",
                                "render": function (data) {
                                    var deleteButton = `<button type="button" class="btn btn-danger delete-btn" data-id="${data}">Delete</button>`;
                                    return deleteButton;
                                },
                            }
                        ],
                        "rowGroup": {
                            "dataSrc": "companyName"  // Group rows by the companyName column
                        },
                        responsive: true,
                        ordering: false,
                    })

                    // Attach click event listener to the delete buttons
                    $('#itemDatatable tbody').on('click', '.delete-btn', function () {
                        const itemId = $(this).data('id');
                        self.deleteItem(itemId);
                    });

                    $('#itemDatatable tbody').on('click', '.print-btn', function () {
                        const itemId = $(this).data('id');
                        var $row = $(this).closest('tr'); // get the row containing the button
                        var imageSrc = $row.find('img').attr('src'); // find the img element in the row and get its src
                        // console.log(imageSrc);
                        self.printItem(itemId, imageSrc);
                    });

                    this.loading = false;
                },
                async addCompanyDepartment() {
                    try {
                        // Show the loading modal
                        $('#loadingModal').modal('show');

                        // Perform the fetch request
                        const response = await fetch('/AdminAPI/AddCompanyDepartment', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                Company: this.company,
                                Department: this.departments,
                            }),
                        });

                        // Check if the response is OK
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.message);
                        }

                        const data = await response.json();
                        this.fetchCompDept();
                        $('#registerCompDept').modal('hide');
                        alert("Company and department successfully added");
                    }
                    catch (error) {
                        console.error('Failed to add company and department:', error);
                        alert(error.message);
                    }
                    finally {
                        await new Promise(resolve => {
                            $('#loadingModal').on('shown.bs.modal', resolve);
                        });
                        $('#loadingModal').modal('hide');
                    }
                },
                removeDepartment(index) {
                    this.departments.splice(index, 1);
                },
                updateUppercase(event, index, key) {
                    this.departments[index][key] = event.target.value.toUpperCase();

                    if (key === 'departmentCode') {
                        //check if the code is already exist from compdeptlist[index1].departments[index2].departmentCode
                        for (let index1 = 0; index1 < this.compDeptList.length; index1++) {
                            for (let index2 = 0; index2 < this.compDeptList[index1].departments.length; index2++) {
                                if (this.departments[index].departmentCode === this.compDeptList[index1].departments[index2].departmentCode) {
                                    alert("Department Code already exist");
                                    this.departments[index].departmentCode = '';
                                    break;
                                }
                            }
                        }
                    }
                },
                resetDetails(){
                    this.company = null;
                    this.departments = [{
                        departmentName: '',
                        departmentCode: '',
                    }];
                }
            }
        })

        $(function () {
            app.mount('#app');
            $('#addCompDeptBtn').on('click', function () {
                $('#registerCompDept').modal('show');
            });
            $('.closeModal').on('click', function () {
                $('.modal').modal('hide');
            });
        });
    </script>
}
