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

<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">Update Compulsory Details</h4>
                    <div class="col-md-12 col-lg-12">
                        <div>
                            <p><h5>User ID: @Model?.Id</h5></p>
                            <p><h5>User Name: @Model?.UserName</h5></p>
                            <div class="row">
                                <form v-on:submit.prevent="updateInfo">
                                    <div class="col-md-6 col-lg-6">
                                        <div class="form-group">
                                            <label for="company">Company</label>
                                            <select id="company" name="company" class="form-select" v-model="selectedCompany">
                                                <option value="" selected>Select Company</option>
                                                <option v-for="(company, index) in companyList" :key="index" :value="company.companyName">{{ company.companyName }}</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6 col-lg-6">
                                        <div class="form-group">
                                            <label for="department">Department</label>
                                            <select id="department" name="department" class="form-select" v-model="selectedDepartment">
                                                <option value="" selected>Select Department</option>
                                                <option v-for="(department, index) in departmentList" :key="index" :value="department.departmentId">{{ department.departmentName }}</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6 col-lg-6">
                                        <div class="form-group">
                                            <button class="btn btn-primary" type="submit">Update</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script>
        const app = Vue.createApp({
            data() {
                return {
                    userList: null,
                    selectedModule: null,
                    companyList: null,
                    company: '',
                    selectedDepartment: '',
                    selectedCompany: '',
                };
            },
            mounted() {
                this.fetchCompanies();
            },
            computed: {
                // Computed property to dynamically update departmentList based on selectedCompany
                departmentList() {
                    // If selectedCompany is empty, return an empty array to prevent errors
                    if (!this.selectedCompany) {
                        this.selectedDepartment = ''
                        return [];
                    }

                    const selectedCompanyObj = this.companyList.find(c => c.companyName === this.selectedCompany);
                    // Ensure that the selected company exists before accessing its departments
                    return selectedCompanyObj ? selectedCompanyObj.departments : [];
                },
            },
            methods: {
                async fetchCompanies() {
                    try {
                        const response = await fetch('/IdentityAPI/CompanyDepartmentList', {
                            method: 'POST', // Specify the HTTP method
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        });
                        if (!response.ok) {
                            throw new Error('Failed to fetch companies');
                        }

                        this.companyList = await response.json();

                    } catch (error) {
                        console.error('Error fetching products:', error);
                    }
                },
                async updateInfo() {
                    if (!this.selectedDepartment) {
                        alert("Please select a valid department.");
                        return;
                    }
                    const uid = @Model?.Id;
                    try {
                        // Show the loading modal
                        $('#loadingModal').modal('show');
                        const payload = {
                            departmentId: this.selectedDepartment,
                        };
                        // Perform the fetch request
                        const response = await fetch(`/IdentityAPI/UserComptDeptAssignment/${uid}`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(payload),
                        });

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

                        const data = await response.json();
                        window.location.href = data.redirectUrl;
                        alert("Company and department successfully added");
                    }
                    catch (error) {
                        console.error('Failed to add company and department:', error);
                        const message = error.message || "An unexpected error occurred. Please try again.";
                        alert(message);
                    }
                    finally {
                        await new Promise(resolve => {
                            $('#loadingModal').on('shown.bs.modal', resolve);
                        });
                        $('#loadingModal').modal('hide');
                    }
                },
            }
        })

        $(function () {
            app.mount('#app');
        });
    </script>
}
