@{
    ViewData["Title"] = "Product Form";
    Layout = "~/Views/Shared/_Layout.cshtml";
    string userId = ViewBag.UserId;
}

@await Html.PartialAsync("~/Areas/Inventory/Views/_InventoryPartial.cshtml")
<div class="row">
    <div id="registerProduct" class="card m-1">
        <div class="row" v-if="addSection == true">
            <form v-on:submit.prevent="addProduct" data-aos="fade-right" >
                <div class="container register" data-aos="fade-right">
                    <div class="row" data-aos="fade-right">
                        <div class="col-md-12">
                            <div class="tab-content" id="myTabContent">
                                <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
                                    <div class="card-header">
                                        <h3 class="register-heading">REGISTRATION PRODUCT</h3>
                                    </div>
                                    <div class="row register-form card-body">
                                        <div class="col-md-6">

                                            @* Product Name *@
                                            <div class="form-group row">
                                                <label for="productName" class="col-sm-3">Product Name:</label>
                                                <div class="col-sm-9">
                                                    <input type="text" id="productName" name="productName" class="form-control" required v-model="productName">
                                                </div>
                                            </div>

                                            @* Product Short Name *@
                                            <div class="form-group row">
                                                <label for="productName" class="col-sm-3">Product Short Name:</label>
                                                <div class="col-sm-9">
                                                    <input type="text" id="productShortName" name="productShortName" class="form-control" maxlength="13" v-model="productShortName" required>
                                                    <p><em><small class="text-danger">* Product short name limited to 13 characters</small></em></p>
                                                </div>
                                            </div>

                                            @* Manufacturer *@
                                            <div class="form-group row">
                                                <label class="col-sm-3">Manufacturer:</label>
                                                <div class="col-sm-9">
                                                    <div class="">
                                                        <select class="btn btn-primary form-select" v-model="manufacturer" required>
                                                            <option class="btn-light" value="" selected disabled>Select Manufacturer</option>
                                                            <option class="btn-light" v-for="(item, index) in manufacturers" :key="item.manufacturerId" :value="item.manufacturerId">{{ item.manufacturerName ?? 'Select Manufacturer' }}</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>

                                            @* Category *@
                                            <div class="form-group row">
                                                <label class="col-sm-3">Category:</label>
                                                <div class="col-sm-9">
                                                    <div class="">
                                                        <select class="btn btn-primary form-select" v-model="category" required>
                                                            <option class="btn-light" value="" selected disabled>Select Category</option>
                                                            <option class="btn-light" v-for="(item, index) in categories" :key="item" :value="item">{{ item ?? 'Select Category'  }}</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>

                                        </div>
                                        <div class="col-md-6">

                                            @* Model No Coding *@
                                            <div class="form-group row">
                                                <label for="modelNo" class="col-sm-3">Model No:</label>
                                                <div class="col-sm-9">
                                                    <input type="text" id="modelNo" name="modelNo" class="form-control" required v-model="modelNo">
                                                </div>
                                            </div>

                                            @* Image Product Coding *@
                                            <div class="form-group row">
                                                <label for="imageProduct" class="col-sm-3">Image:</label>
                                                <div class="col-sm-9">
                                                    <input type="file" id="imageProduct" name="imageProduct" class="form-control" v-on:change="previewImage" accept="image/*" required>
                                                    <br>
                                                    <img v-if="imageSrc" :src="imageSrc" alt="Image Preview" class="img-thumbnail" style="width: 200px; margin-top: 10px;" />
                                                </div>
                                            </div>

                                        </div>
                                        <div class="form-group row">
                                            <div class="col-sm-9 offset-sm-3">
                                                <button type="button" v-on:click="resetForm" class="btn btn-secondary mx-1">Reset</button>
                                                <input type="submit" class="btn btn-primary mx-1">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
            <div class="row">
                <button class="btn btn-danger col-md-3 m-1" v-on:click="addSection = false"><i class="fa fa-minus"></i>&nbsp;Hide Add Product Section</button>
            </div>
        </div>
        <div class="row">
            <button id="addProductBtn" class="btn btn-success col-md-3 m-1" v-show="addSection == false" v-on:click="addSection = true"><i class="fa fa-plus"></i>&nbsp;Show Add Product Section</button>
        </div>
        <div class="row table-responsive">
            <table class="table table-bordered table-hover table-striped no-wrap" id="productDatatable" style="width:100%;border-style: solid; border-width: 1px"></table>
        </div>
    </div>
</div>

@section Scripts {
@{
    await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
<script>
    $(function () {
        app.mount('#registerProduct');
    });
    const app = Vue.createApp({
            data() {
                return {
                    addSection: false,
                    productName: null,
                    manufacturer: '',
                    manufacturers: null,
                    category: '',
                    categories: ["Asset", "Part", "Disposable"],
                    modelNo: null,
                    imageProduct: null,
                    manufactures: [],
                    showOtherManufacturer: false,
                    imageSrc: '',
                    products: null,
                    productDatatable: null,
                    productShortName: null,
                }
        },
        mounted() {
            // Fetch companies, depts, and products from the API
            this.fetchManufactures();
            this.fetchProducts();
        },
        methods: {
            initiateTable() {
                this.productDatatable = $('#productDatatable').DataTable({
                    "data": this.products,
                    "columns": [
                        {   "title": "Product Name", 
                            "data": "productName",
                        },
                        {   "title": "Product Short Name", 
                            "data": "productShortName",
                        },
                        {   "title": "Model Number", 
                            "data": "modelNo",
                        },
                        {   "title": "Manufacturer", 
                            "data": "manufacturer.manufacturerName",
                        },
                        {   "title": "Product Category", 
                            "data": "category",
                        },
                        {   "title": "Product Stock", 
                            "data": "quantityProduct",
                        },
                        {   "title": "Image", 
                            "data": "imageProduct",
                            "render": function (data, type, full, meta) {
                                var image = `<a href="${data}" target="_blank" data-lightbox="image-1">
                                                <img src="${data}" alt="Image" class="img-thumbnail" style="width: 100px; height: 100px;" />
                                            </a>`;
                                return image;
                            },
                        },
                        {   
                            "title": "Delete",
                            "data": "productId",
                            "render": function (data) {
                                    var deleteButton = `<button type="button" class="btn btn-danger delete-btn" data-id="${data}">Delete</button>`;
                                return deleteButton;
                            }, 
                        }

                    ],
                    responsive:true,
                })
                self = this;
                // Attach click event listener to the delete buttons
                $('#productDatatable tbody').on('click', '.delete-btn', function () {
                    const productId = $(this).data('id'); // Get the manufacturer ID from the button
                    self.deleteProduct(productId); // Call the Vue method
                });

                this.loading = false;
            },
            async fetchManufactures() {
                fetch('/InvMainAPI/ManufacturerList', {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(data => {
                    if (data != null && data.length > 0)
                    {
                        this.manufacturers = data;
                    }
                    })
                    .catch(error => {
                        console.error('There was a problem with the fetch operation:', error);
                    });
            },
            async fetchProducts() {
                try {
                    const response = await fetch('/InvMainAPI/ProductList',{
                        method: 'POST'
                    }); // Call the API
                    if (!response.ok) {
                        throw new Error('Failed to fetch products');
                    }
                    this.products = await response.json(); // Store the fetched products
                    this.$nextTick(() => {
                        this.initiateTable()
                    })
                } catch (error) {
                    console.error('Error fetching products:', error);
                }
            },
            async addProduct() {
                // const existingProduct = this.products.find(p => p.modelNo === this.modelNo);
                // if (existingProduct) {
                //     alert(`Product Error: The model number ${this.modelNo} already exists.`, 'error');
                //     return; // Exit early if the modelNo exists
                // }

                // Create the payload
                const formData = {
                    productName: this.productName,
                    productShortName: this.productShortName,
                    manufacturerId: this.manufacturer,
                    category: this.category,
                    modelNo: this.modelNo,
                    imageProduct: this.imageProduct
                };

                try {
                    // List of required fields
                    const requiredFields = ['productName', 'manufacturer', 'category', 'modelNo', 'imageProduct'];

                    // Loop through required fields and check if any are null or empty
                    for (let field of requiredFields) {
                        if (this[field] === null || this[field] === '') {
                            alert('Product Error', `Please fill in required fields: ${field}.`, 'warning');
                            return; // Exit early if validation fails
                        }
                    }

                    // Proceed to send the data as raw JSON string
                    const response = await fetch('/InvMainAPI/AddProduct', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(formData) // Convert the formData to a JSON string
                    });

                    if (!response.ok) {
                        const errorData = await response.json();
                        console.error('Error response:', errorData);
                        this.errorMessage = 'Error: ' + (errorData.message || 'Unknown error');

                    } else {
                        this.products = await response.json();
                        alert('Success!', 'Product form has been successfully submitted.', 'success');
                        this.fillTable(this.products);
                        this.resetForm();
                    }

                } catch (error) {
                    console.error('Error:', error);
                    alert('Product Error', `An error occurred: ${error.message}`, 'error');
                }
            },
            resetForm() {
                this.productName = null;
                this.manufacturer = '';
                this.category = '';
                this.modelNo = null;
                this.imageProduct = null;
                this.imageSrc = '';
                const fileInput = document.getElementById('imageProduct');
                if (fileInput) {
                    fileInput.value = ''; // Clear the file input value
                }
            },

            // Update Select View
            updateManufacturer(manufacturer) {
                this.manufacturer = manufacturer;
                this.showOtherManufacturer = false;
            },
            updateCategory(category) {
                this.category = category;
            },

            // When User Presses Button Other
            toggleOtherInput(type) {
                if (type === 'manufacturer') {
                    this.showOtherManufacturer = true;
                }
            },

            // User Inserting an Image
            previewImage(event) {
                const file = event.target.files[0];

                if (file) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        this.imageSrc = e.target.result; // Show the image preview
                        this.imageProduct = e.target.result.split(',')[1]; // Get Base64 string (remove metadata)
                    };
                    reader.readAsDataURL(file);
                } else {
                    this.imageSrc = '';
                    this.imageProduct = null;
                }
            },
            async deleteProduct(productId) {
                if (!confirm("Are you sure you want to delete this product?")) {
                    return;
                }
                try {
                    const response = await fetch(`/InvMainAPI/DeleteProduct/${productId}`, {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                    });
                    const result = await response.json();

                    if (result.success) {
                        alert(result.message);
                        // Remove the row from DataTables
                        this.productDatatable
                            .row($(`.delete-btn[data-id="${productId}"]`).closest('tr'))
                            .remove()
                            .draw();
                    } else {
                        alert(result.message);
                    }
                } 
                catch (error) {
                    console.error("Error deleting product:", error);
                    alert("An error occurred while deleting the product.");
                }
                finally {
                    this.loading = false;
                }
            },
            fillTable(data){
                if (!this.productDatatable) {
                    console.error("DataTable not initialized");
                    return;
                }
                this.productDatatable.clear();
                this.productDatatable.rows.add(data);
                this.productDatatable.draw();
                this.loading = false;
            },
            
        }
    });
</script>
}
