@{
    ViewData["Title"] = "User Form";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@await Html.PartialAsync("~/Areas/Inventory/Views/_InventoryPartial.cshtml");
<div id="registerSupplier">
    <form v-on:submit.prevent="addSupplier" data-aos="fade-right" id="registerSupplierForm" v-if="registerSupplierForm">
        <div class="container register" data-aos="fade-right">
            <div class="row">
                @*Right Side*@
                <div class="col-md-9 register-rights" data-aos="fade-right">
                    <div class="tab-content" id="myTabContent" data-aos="fade-right">
                        <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab" data-aos="fade-right">
                            <h3 class="register-heading">REGISTRATION SUPPLIER</h3>
                            <div class="row register-form">
                                <div class="col-md-61">

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

                                    @* Supplier Gender *@
                                    <div class="form-group row">
                                        <label class="col-sm-3">Supplier Address:</label>
                                        <div class="col-sm-9">
                                            <div class="dropdown">
                                                <textarea type="text" id="supplierAddress" name="supplierAddress" class="form-control" required v-model="supplierAddress"></textarea>
                                            </div>
                                        </div>
                                    </div>

                                    @* Supplier PIC *@
                                    <div class="form-group row">
                                        <label class="col-sm-3">Supplier PIC:</label>
                                        <div class="col-sm-9">
                                            <input type="email" id="supplierPIC" name="supplierPIC" class="form-control" v-model="supplierPIC">
                                        </div>
                                    </div>

                                    @* Supplier Email *@
                                    <div class="form-group row">
                                        <label class="col-sm-3">Supplier Email:</label>
                                        <div class="col-sm-9">
                                            <input type="email" id="supplierEmail" name="supplierEmail" class="form-control" v-model="supplierEmail">
                                        </div>
                                    </div>

                                    @* Supplier Number Phone *@
                                    <div class="form-group row">
                                        <label class="col-sm-3">Supplier Phone Number:</label>
                                        <div class="col-sm-9">
                                            <input type="tel" id="supplierPhoneNo" name="supplierPhoneNo" class="form-control" v-model="supplierPhoneNo">
                                        </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 m-1">Reset</button>
                                        <button type="submit" class="btn btn-primary m-1">Submit</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
    <div class="row card">
        <div class="card-header">
            <button id="addSupplierBtn" :class="['btn', 'col-md-3', 'col-lg-3', 'm-1', 'col-12', registerSupplierForm ? 'btn-danger' : 'btn-success']" v-on:click="registerSupplierForm = !registerSupplierForm"><i :class="['fa', registerSupplierForm ? 'fa-minus' : 'fa-plus']"></i>&nbsp;{{registerSupplierForm ? 'Hide Add Supplier' : 'Show Add Supplier'}}</button>
        </div>
        <div class="card-body">
            <table class="table table-bordered table-hover table-striped no-wrap" id="supplierDatatable" style="width:100%;border-style: solid; border-width: 1px"></table>
        </div>
    </div>
</div>
@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script>
        $(function () {
                app.mount('#registerSupplier');

                // Attach a click event listener to elements with the class 'btn-success'.
                $('#addSupplierBtn').on('click', function () {
                    // Show the modal with the ID 'addManufacturerModal'.
                    $('#registerSupplierModal').modal('show');
                });
                $('.closeModal').on('click', function () {
                    // Show the modal with the ID 'addManufacturerModal'.
                    $('.modal').modal('hide');
                });
        });
         const app = Vue.createApp({
            data() {
                return {
                    supplierCompName : null,
                    supplierEmail : null,
                    supplierAddress : null,
                    supplierPhoneNo : null,
                    supplierPIC : null,
                    suppliers: null,
                    supplierDatatable: null,
                    gender: ["Male", "Female", "Helicopter"],
                    registerSupplierForm: false
                }
            },
            mounted(){
                this.fetchSuppliers();
            },
            methods: {
                async fetchSuppliers() {
                    try {
                        const response = await fetch('/InvMainAPI/SupplierList', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        });

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

                        if (this.itemDatatable) {
                            this.itemDatatable.clear().destroy();
                        }
                        this.initiateTable();
                    } catch (error) {
                        console.error('Error fetching suppliers:', error);
                        this.errorMessage = 'Error: ' + error.message;
                    }
                },
                async addSupplier() {
                    $('#loadingModal').modal('show');
                    // Create the payload
                    const formData = {
                        supplierCompName: this.supplierCompName,
                        supplierAddress: this.supplierAddress,
                        supplierPIC: this.supplierPIC,
                        supplierEmail: this.supplierEmail,
                        supplierPhoneNo: this.supplierPhoneNo,
                    };

                    try {
                        // List of required fields
                        const requiredFields = ['supplierCompName', 'supplierAddress'];

                        // 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/AddSupplier', {
                            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 {
                            alert('Success!', 'Supplier form has been successfully submitted.', 'success');
                            this.fetchSuppliers();
                            this.resetForm();
                        }

                    } 
                    catch (error) {
                        console.error('Error:', error);
                        alert('Product Error', `An error occurred: ${error.message}`, 'error');
                    }
                    finally {
                        await new Promise(resolve => {
                            $('#loadingModal').on('shown.bs.modal', resolve);
                        });
                        $('#loadingModal').modal('hide');
                    }
                },
                resetForm() {
                    this.supplierCompName = null;
                    this.supplierAddress = null;
                    this.supplierEmail = null;
                    this.supplierPhoneNo = null;
                    this.supplierPIC = null;
                },
                initiateTable() {
                    self = this;
                    this.supplierDatatable = $('#supplierDatatable').DataTable({
                        "data": this.suppliers,
                        "columns": [
                            {
                                "title": "Supplier Company Name",
                                "data": "supplierCompName",
                            },
                            {
                                "title": "Supplier Address",
                                "data": "supplierAddress",
                            },
                            {
                                "title": "Company PIC",
                                "data": "supplierPIC",
                            },
                            {
                                "title": "Supplier Email",
                                "data": "supplierEmail",
                            },
                            {
                                "title": "Supplier Phone No",
                                "data": "supplierPhoneNo",
                            },
                            {
                                "title": "Delete",
                                "data": "supplierId",
                                "render": function (data) {
                                    var deleteButton = `<button type="button" class="btn btn-danger delete-btn" data-id="${data}">Delete</button>`;
                                    return deleteButton;
                                },
                            }
                        ],
                        responsive: true,

                    })

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

                    this.loading = false;
                },
                async deleteSupplier(supplierId) {
                    if (!confirm("Are you sure you want to delete this supplier?")) {
                        return;
                    }
                    try {
                        const response = await fetch(`/InvMainAPI/DeleteSupplier/${supplierId}`, {
                            method: 'DELETE',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ supplierId })
                        });

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

                        this.fetchSuppliers();
                    } catch (error) {
                        console.error('Error deleting supplier:', error);
                        this.errorMessage = 'Error: ' + error.message;
                    }
                }
            }
        });
    </script>
}