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

@await Html.PartialAsync("~/Areas/Inventory/Views/_InventoryPartial.cshtml");
<div id="app">
    <div class="row card">
        <div class="card-header">
            <button id="addManufacturerBtn" class="btn btn-success col-md-3 m-1"><i class="fa fa-plus"></i>&nbsp;Add Manufacturer</button>
        </div>
        <div class="card-body">
            <div v-if="loading">
                <div class="spinner-border text-info" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
            </div>
            <table class="table table-bordered table-hover table-striped no-wrap" id="manufacturerTable" style="width:100%;border-style: solid; border-width: 1px"></table>
        </div>
    </div>
    <div class="modal fade" id="addManufacturerModal" tabindex="-1" role="dialog" aria-labelledby="addManufacturerModalLabel" 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="addManufacturerModalLabel">Add Manufacturer</h5>
                    <button type="button" class="closeModal" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form v-on:submit.prevent="addManufacturer">
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="manufacturerName">Manufacturer Name:</label>
                            <input type="text" class="form-control" id="manufacturerName" v-model="newManufacturer.manufacturerName" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary closeModal" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Save changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
<script>
    const app = Vue.createApp({
        data() {
            return {
                manufacturer: null,
                manufacturerDatatable: null,
                newManufacturer: {
                    manufacturerName: null,
                },
                loading: true,
            }

        },
        mounted() {
            // Fetch companies, depts, and products from the API
            this.fetchManufactures();
            this.initiateTable();
        },
        methods: {
            async fetchManufactures() {
                    fetch('/InvMainAPI/ManufacturerList', {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data != null && data.length > 0) 
                        {
                            this.manufacturer = data;
                        }
                        if (!this.manufacturerDatatable) {
                            this.initiateTable();
                        } else {
                            this.fillTable(data);
                        }
                    })
                    .catch(error => {
                        console.error('There was a problem with the fetch operation:', error);
                    });

            },
            async initiateTable() {
                this.manufacturerDatatable = $('#manufacturerTable').DataTable({
                    "data": this.manufacturer,
                    "columns": [
                        {   "title": "Manufacturer Name", 
                            "data": "manufacturerName",
                        },
                        {   "title": "Delete", 
                            "data": "manufacturerName",
                            "render": function (data, type, full, meta) {
                                    var deleteButton = `<button type="button" class="btn btn-danger delete-btn" data-id="${full.manufacturerId}">Delete</button>`;
                                return deleteButton;
                            },
                            "width": '10%',
                        },
                    ],
                })
                self = this;
                // Attach click event listener to the delete buttons
                $('#manufacturerTable tbody').on('click', '.delete-btn', function () {
                    const manufacturerId = $(this).data('id'); // Get the manufacturer ID from the button
                    self.deleteManufacturer(manufacturerId); // Call the Vue method
                });

                this.loading = false;
            },
            fillTable(data){
                if (!this.manufacturerDatatable) {
                    console.error("DataTable not initialized");
                    return;
                }
                this.manufacturerDatatable.clear();
                this.manufacturerDatatable.rows.add(data);
                this.manufacturerDatatable.draw();
                this.loading = false;
            },
            addManufacturer() {
                    this.loading = true;
                    const existingManufacturer = this.manufacturer != null ? this.manufacturer.find(m => m.manufacturerName.toLowerCase() === this.newManufacturer.manufacturerName.toLowerCase()) : null;
                    if (existingManufacturer) {
                        alert('Manufacturer already exists');
                        return;
                    }
                    fetch('/InvMainAPI/AddManufacturer', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(this.newManufacturer)
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data != null && data.length > 0)
                        {
                            this.manufacturer = data;
                        }
                        this.fillTable(data);
                    })
                    .catch(error => {
                        console.error('There was a problem with the fetch operation:', error);
                    })
                    .finally(() => {
                        $('#preloader').modal('hide');
                        this.newManufacturer.manufacturerName = null;
                    });
            },
            async deleteManufacturer(manufacturerId) {
                if (!confirm("Are you sure you want to delete this manufacturer?")) {
                    return;
                }
                try {
                    const response = await fetch(`/InvMainAPI/DeleteManufacturer/${manufacturerId}`, {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                    });
                    const result = await response.json();

                    if (result.success) {
                        alert(result.message);
                        // Remove the row from DataTables
                        this.manufacturerDatatable
                            .row($(`.delete-btn[data-id="${manufacturerId}"]`).closest('tr'))
                            .remove()
                            .draw();
                    } else {
                        alert(result.message);
                    }
                } 
                catch (error) {
                    console.error("Error deleting manufacturer:", error);
                    alert("An error occurred while deleting the manufacturer.");
                }
                finally {
                    this.loading = false;
                }
            },
        }
        
    });

    $(function () {
        app.mount('#app');

        // Attach a click event listener to elements with the class 'btn-success'.
        $('#addManufacturerBtn').on('click', function () {
            // Show the modal with the ID 'addManufacturerModal'.
            $('#addManufacturerModal').modal('show');
        });
        $('.closeModal').on('click', function () {
            // Show the modal with the ID 'addManufacturerModal'.
            $('#addManufacturerModal').modal('hide');
        });
    });
</script>
}

