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

@await Html.PartialAsync("~/Areas/Inventory/Views/_InventoryPartial.cshtml");
<div id="registerStation">
    <form v-on:submit.prevent="addStation" data-aos="fade-right" id="registerStationForm" v-if="registerStationForm">
        <div class="container register" data-aos="fade-right">
            <div class="row">
                <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 STATION</h3>
                            <div class="row register-form">
                                <div class="col-md-61">

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

                                    @* User ID *@
                                    <div class="form-group row">
                                        <label class="col-sm-4 col-form-label">Station User PIC</label>
                                        <div class="col-sm-8">
                                            <div class="dropdown">
                                                <select class="btn btn-primary dropdown-toggle col-md-10" v-model="selectedUserName" :disabled="currentUser != null" required v-on:change="updateDepartment()">
                                                    <option class="btn-light" value="" disabled selected>Select User</option>
                                                    <option v-for="(technicianUser, index) in users" :key="index" :value="technicianUser.fullname">
                                                        {{ technicianUser.fullname }}
                                                    </option>

                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    @* Department ID *@
                                    <!-- Department Dropdown -->
                                    <div class="form-group row">
                                        <label class="col-sm-4 col-form-label">Department: </label>
                                        <div class="col-sm-8">
                                            <!-- Use a span to keep the same space occupied -->
                                            <span v-if="selectedDepartment">{{ selectedDepartment }}</span>
                                            <span v-else>No department assigned</span>
                                        </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="addStationBtn" :class="['btn', 'col-md-3', 'col-lg-3', 'm-1', 'col-12', registerStationForm ? 'btn-danger' : 'btn-success']" v-on:click="registerStationForm = !registerStationForm"><i :class="['fa', registerStationForm ? 'fa-minus' : 'fa-plus']"></i>&nbsp;{{registerStationForm ? 'Hide Add Station' : 'Show Add Station'}}</button>
        </div>
        <div class="card-body">
            <table class="table table-bordered table-hover table-striped no-wrap" id="stationDatatable" style="width:100%;border-style: solid; border-width: 1px"></table>
        </div>
    </div>
</div>
@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script>
        $(function () {
            app.mount('#registerStation');

            // Attach a click event listener to elements with the class 'btn-success'.
            $('#addStationBtn').on('click', function () {
                // Show the modal with the ID 'addStationModal'.
                $('#registerStationModal').modal('show');
            });
            $('.closeModal').on('click', function () {
                // Show the modal with the ID 'addStationModal'.
                $('.modal').modal('hide');
            });
        });
        const app = Vue.createApp({
            data() {
                return {
                    stationName: null,
                    stationUserPIC: null,
                    departmentId : null,
                    selectedUserName : null,
                    selectedDepartment: null,
                    stations: null,
                    currentUser: null,
                    users : null,
                    registerStationForm: false,
                }
            },
            mounted() {
                this.fetchUsers();
                this.fetchStations();
            },
            methods: {
                async fetchUsers() {
                    try {
                        const response = await fetch(`/IdentityAPI/GetTechnicianUserInformation/`, {
                            method: 'POST',
                        });
                        if (response.ok) {
                            const data = await response.json();
                            this.users = data.technicianUsers;
                        }
                        else {
                            console.error(`Failed to fetch user: ${response.statusText}`);
                        }
                    }
                    catch (error) {
                        console.error('There was a problem with the fetch operation:', error);
                    }
                },
                async fetchStations() {
                    try {
                        const response = await fetch('/InvMainAPI/StationList', {
                            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.stationDatatable) {
                            this.stationDatatable.clear().destroy();
                        }
                        const stations = await response.json();
                        this.stations = stations;

                        if ($.fn.dataTable.isDataTable('#stationDatatable')) {
                            $('#stationDatatable').DataTable().clear().destroy();
                        }
                        this.initiateTable();
                    } catch (error) {
                        console.error('Error fetching stations:', error);
                        this.errorMessage = 'Error: ' + error.message;
                    }
                },
                async addStation() {
                    $('#loadingModal').modal('show');
                    // Create the payload
                    const formData = {
                        StationName: this.stationName,
                        StationPicID: this.stationUserPIC,
                        DepartmentId: this.departmentId,
                    };

                    try {
                        // List of required fields
                        const requiredFields = ['stationName', 'stationUserPIC', 'departmentId'];

                        // Loop through required fields and check if any are null or empty
                        for (let field of requiredFields) {
                            if (this[field] === null || this[field] === '') {
                                alert('Station 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/AddStation', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(formData) // Convert the formData to a JSON string
                        });

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

                        } else {
                            this.fetchStations();
                            this.resetForm();
                        }

                    }
                    catch (error) {
                        console.error('Error:', error);
                        alert('Station Error', `An error occurred: ${error.message}`, 'error');
                    }
                    finally {
                        await new Promise(resolve => {
                            $('#loadingModal').on('shown.bs.modal', resolve);
                        });
                        $('#loadingModal').modal('hide');
                    }
                },
                resetForm() {
                    this.selectedUserName = null;
                    this.selectedDepartment = null;
                    this.stationName = null;
                    this.stationUserPIC = null;
                    this.departmentId = '';
                },
                initiateTable() {
                    self = this;
                    this.stationDatatable = $('#stationDatatable').DataTable({
                        "data": this.stations,
                        "columns": [
                            {
                                "title": "Station Name",
                                "data": "stationName",
                            },
                            {
                                "title": "Station User PIC",
                                "data": "stationPicID",
                            },
                            {
                                "title": "Department ID",
                                "data": "departmentId",
                            },
                            {
                                "title": "Delete",
                                "data": "stationId",
                                "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
                    $('#stationDatatable tbody').on('click', '.delete-btn', function () {
                        const stationId = $(this).data('id');
                        self.deleteStation(stationId);
                    });

                    this.loading = false;
                },
                updateDepartment() {
                    // Find the selected user by their full name
                    const selectedUser = this.users.find(user => user.fullname === this.selectedUserName);
                    if (selectedUser) {
                        this.stationUserPIC = selectedUser.id;
                        this.departmentId = selectedUser.department.departmentId;
                        this.selectedDepartment = selectedUser.department.departmentName; // Set department name
                    }
                },
                async deleteStation(stationId) {
                    if (!confirm("Are you sure you want to delete this station?")) {
                        return;
                    }
                    try {
                        const response = await fetch(`/InvMainAPI/DeleteStation/${stationId}`, {
                            method: 'DELETE',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ stationId })
                        });

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

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