@{
    ViewData["Title"] = "Dashboard";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div  class="container" id="invAdmin">
    <div class="row">
        <div class="text-center">
            <p><h1 class="display-4">Reporting Dashboard</h1></p>
            <p v-show="currentUserCompanyDept.departmentName"><h2 class="display-6">Store: {{ currentUserCompanyDept.departmentName }}</h2></p>
        </div>
    </div>
    <div class="row card">
        <div class="card-header">
            <h3 class="card-title">Report Filter</h3>
        </div>
        <div class="card-body">
            <div v-if="reportData">
                <div class="row justify-content-center">
                    <div class="col-3">
                        <div class="row col-10">
                            <h4>Department</h4>
                            <multiselect v-model="selectedDepartment" :options="compDeptList" :multiple="true" group-values="departments" group-label="companyName"
                                         :group-select="true" placeholder="Seach Department" track-by="departmentId" label="departmentName">
                            </multiselect> 
                            <div class=""><button class="btn btn-danger" v-on:click="selectedDepartment = []">Clear</button></div>
                        </div>
                    </div>
                    <div class="col-3">
                        <div class="row col-10">
                            <h4>Category</h4>
                            <multiselect v-model="selectedCategory" :options="categoryList" :multiple="true" placeholder="Seach Category">
                            </multiselect>
                            <div class=""><button class="btn btn-danger" v-on:click="selectedCategory = []">Clear</button></div>
                        </div>
                    </div>
                    <div class="col-3">
                        <div class="row col-10">
                            <h4>Product</h4>
                            <multiselect v-model="selectedItem" :options="selectedCategory.length == 0 && selectedDepartment.length == 0 ? productList : filteredProduct " :multiple="true" placeholder="Seach Product" track-by="productId" label="productName">
                            </multiselect> 
                            <div class=""><button class="btn btn-danger" v-on:click="selectedItem = []">Clear</button></div>
                        </div>
                    </div>
                    <div class="col-3">
                        <div class="row col-10">
                            <h4>Date filter</h4>
                            <vue-date-picker v-model="selectedMonth" month-picker range></vue-date-picker>
                            <div class=""><button class="btn btn-danger" v-on:click="selectedMonth = []">Clear</button></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row card">
        <div class="card-header">
            <h3 class="card-title">Inventory Report</h3>
        </div>
        <div class="card-body">
            <div v-if="reportData">
                <div class="row justify-content-center">
                    <div class="col-3">
                        <h4>Statistic</h4>
                        <p>Total Number of Item Registered: {{ reportData.itemCountRegistered }}</p>
                        <p>Total Number of Item Still in Stock: {{ reportData.itemCountStillInStock }}</p>
                    </div>
                    <div class="col-3">
                        <h4>Item Registered </h4>
                        <p>This Month: {{ reportData.itemCountRegisteredThisMonth }}</p>
                        <p>Last Month: {{ reportData.itemCountRegisteredLastMonth }}</p>
                    </div>
                    <div class="col-3">
                        <h4>Item Stock Out </h4>
                        <p>This Month: {{ reportData.itemCountStockOutThisMonth }}</p>
                        <p>Last Month: {{ reportData.itemCountStockOutLastMonth }}</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@section Scripts {
@{
    await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
<script>
    $(function () {
            app.mount('#invAdmin');
            $('.closeModal').on('click', function () {
                // Show the modal with the ID 'addManufacturerModal'.
                $('.modal').modal('hide');
            });
    });
    const app = Vue.createApp({
        components: {
            'multiselect': window.VueMultiselect.default,
            VueDatePicker,
        },
        data() {
            return {
                currentUser: null,
                currentUserCompanyDept: {
                    departmentName: null,
                    departmentId: null
                },
                reportData: null,
                compDeptList: {},
                productList: {},
                categoryList:['Asset', 'Part', 'Disposable'],
                monthList: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                filteredProduct: [],
                selectedMonth: [],
                selectedDepartment: [],
                selectedItem: [],
                selectedCategory: []
            }
        },
        mounted() {
            this.fetchUser();
            this.fetchProductList();
            this.fetchDepartmentsCompaniesList();
        },
        watch: {
            //watch selectedDepartment. when selectedDepartment is changed, if selectedCategory is null filter productList based on selectedDepartment only. otherwise filter the productList based on selectedDepartment and selectedCategory
            selectedDepartment() {
                this.filterProducts();
            },
            selectedCategory() {
                this.filterProducts();
            }
        },
        methods: {
            async fetchUser() {
                try {
                    const response = await fetch(`/IdentityAPI/GetUserInformation/`, {
                        method: 'POST',
                    });
                    if (response.ok) {
                        const data = await response.json();
                        this.currentUser = data?.userInfo || null;
                        const companyDeptData = await this.currentUser.department;
                        const userRole = this.currentUser.role;
                        if(userRole == "SuperAdmin" || userRole == "SystemAdmin"){
                            this.currentUserCompanyDept = {departmentId : 0, departmentName : "All"}
                            this.fetchInventoryReport(0);
                        }
                        else{
                            this.currentUserCompanyDept = companyDeptData;
                            this.fetchInventoryReport(0);
                        }
                    }
                    else {
                        console.error(`Failed to fetch user: ${response.statusText}`);
                    }
                }
                catch (error) {
                    console.error('There was a problem with the fetch operation:', error);
                }
            },
            async fetchInventoryReport(deptId){
                try {
                    const response = await fetch(`/ReportingAPI/GetInventoryReport/` + deptId, {
                        method: 'POST',
                    });
                    if (response.ok) {
                        const data = await response.json();
                        this.reportData = data;
                    }
                    else {
                        console.error(`Failed to fetch user: ${response.statusText}`);
                    }
                }
                catch (error) {
                    console.error('There was a problem with the fetch operation:', error);
                }
            },
            async fetchDepartmentsCompaniesList(){
                try {
                        const response = await fetch(`/AdminAPI/GetDepartmentWithCompanyList/`, {
                        method: 'POST',
                    });
                    if (response.ok) {
                        const data = await response.json();
                        this.compDeptList = data;
                    }
                    else {
                        console.error(`Failed to fetch company & department list: ${response.statusText}`);
                    }
                }
                catch (error) {
                    console.error('There was a problem with the fetch operation:', error);
                }
            },
            async fetchProductList(){
                try {
                        const response = await fetch(`/InvMainAPI/ItemList/`, {
                        method: 'POST',
                    });
                    if (response.ok) {
                        const data = await response.json();
                        this.productList = data;
                    }
                    else {
                        console.error(`Failed to fetch item list: ${response.statusText}`);
                    }
                }
                catch (error) {
                    console.error('There was a problem with the fetch operation:', error);
                }
            },
            filterProducts() {
                const selectedDepartmentIds = this.selectedDepartment.map(department => department.departmentId);
                const selectedCategory = this.selectedCategory;
                if (selectedDepartmentIds.length === 0 && selectedCategory.length === 0) {
                    // No filters applied
                    this.filteredProduct = this.productList;
                } 
                else if (selectedDepartmentIds.length === 0) {
                    // Filter by category only
                    this.filteredProduct = this.productList.filter(product =>
                        selectedCategory.includes(product.category)
                    );
                } 
                else if (selectedCategory.length === 0) {
                    // Filter by department only
                    this.filteredProduct = this.productList.filter(product =>
                        selectedDepartmentIds.includes(product.departmentId)
                    );
                } 
                else {
                    // Filter by both department and category
                    this.filteredProduct = this.productList.filter(product =>
                        selectedDepartmentIds.includes(product.departmentId) &&
                        selectedCategory.includes(product.category)
                    );
                }
            }   
        },
    });
</script>
}