@{
    ViewData["Title"] = "Product Request";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@await Html.PartialAsync("~/Areas/Inventory/Views/_InventoryPartial.cshtml")

<style>
    .dropdown {
        position: relative;
        width: 100%;
    }

    .dropdown-toggle-box {
        display: flex;
        align-items: center;
        border: 1px solid #ddd;
        border-radius: 5px;
        overflow: hidden;
    }

        .dropdown-toggle-box input {
            flex: 1;
            border: none;
            padding: 8px;
        }

    .dropdown-btn {
        border: none;
        background-color: #007bff;
        color: white;
        padding: 8px 12px;
        cursor: pointer;
    }

    .dropdown-content {
        position: absolute;
        width: 100%;
        max-height: 200px;
        overflow-y: auto;
        background: #fff;
        border: 1px solid #ddd;
        z-index: 10;
    }

        .dropdown-content option {
            padding: 10px;
            cursor: pointer;
            display: block;
        }

            .dropdown-content option:hover {
                background-color: #f1f1f1;
            }

    .modal-body img {
        max-width: 100%; /* Ensure it fits the modal */
        max-height: 150px; /* Adjust max height */
        display: block;
        margin: auto;
    }

</style>
<div id="requestProduct" class="row">
    <div class="row mb-3">
        <h2 for="sortSelect" class="col-sm-1 col-form-h2" style="min-width:150px;">Sort by:</h2>
        <div class="col-sm-4">
            <select id="sortSelect" class="form-control" v-model="sortBy" v-on:change="handleSorting">
                <option value="tech">Technician</option>
                <option value="master">Inventory Master</option>
            </select>
        </div>
    </div>

    <div v-show="sortBy === 'master'">
        <div class="row card">
            <div class="card-header">
                <h2>Outgoing Requests to Other Stores</h2>
                <button id="addRequestBtn" class="btn btn-success col-md-3 col-lg-3 m-1 col-12"
                        v-on:click="showRequestModal = true">
                    <i class="fa fa-plus"></i>&nbsp;Add Request
                </button>

            </div>
            <div class="card-body">
                <table class="table table-bordered table-hover table-striped no-wrap" id="requestMasterDatatable" style=" width:100%;border-style: solid; border-width: 1px"></table>
            </div>
        </div>

        <div class="row card">
            <div class="card-header">
                <h2>Incoming Requests from Other Inventory Masters</h2>
            </div>
            <div class="card-body">
                <table class="table table-bordered table-hover table-striped no-wrap" id="requestOtherMasterDatatable" style=" width:100%;border-style: solid; border-width: 1px"></table>
            </div>
        </div>

        <div class="row card">
            <div class="card-header">
                <h2>Complete Request Master</h2>
            </div>
            <div class="card-body">
                <table class="table table-bordered table-hover table-striped no-wrap" id="settledrequestMasterDatatable" style=" width:100%;border-style: solid; border-width: 1px"></table>
            </div>
        </div>
    </div>

    <div v-show="sortBy === 'tech'">
        <div class="row card">
            <div class="card-header">
                <h2>Pending Request</h2>
            </div>
            <div class="card-body">
                <table class="table table-bordered table-hover table-striped no-wrap" id="requestDatatable" style=" width:100%;border-style: solid; border-width: 1px"></table>
            </div>
        </div>

        <div class="row card">
            <div class="card-header">
                <h2>Complete Request</h2>
            </div>
            <div class="card-body">
                <table class="table table-bordered table-hover table-striped no-wrap" id="settledrequestDatatable" style=" width:100%;border-style: solid; border-width: 1px"></table>
            </div>
        </div>
    </div>

    <div class="modal fade" id="rejectModal" tabindex="-1" role="dialog" aria-labelledby="rejectRequestModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="rejectRequestModalLabel">Reject Request</h5>
                    <button type="button" class="closeModal" data-dismiss="modal" aria-label="Close" v-on:click="showRequestModal=false">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="container-fluid">
                        <form v-on:submit.prevent="rejectRequest" data-aos="fade-right">
                            @* <div class=" register" data-aos="fade-right"> *@
                                <div  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">
                                                <h3 class="register-heading">REJECT REQUEST</h3>
                                                <div class="row register-form">
                                                    <div class="col-md-12">

                                                        <div class="form-group row">
                                                            @* <label class="col-sm-4 col-form-label hidden-label">Request Id</label> *@
                                                            <div class="col-sm-8">
                                                                <div class="dropdown">
                                                                    <input type="text" id="currentrequestID" name="currentrequestID" v-model="currentrequestID" class="form-control" hidden />
                                                                </div>
                                                            </div>
                                                        </div>

                                                        <div class="form-group row">
                                                            <label class="col-sm-4 col-form-label">Remark</label>
                                                            <div class="col-sm-8">
                                                                <div class="dropdown">
                                                                    <input type="text" id="rejectremark" name="rejectremark" v-model="rejectremark" class="form-control" required />
                                                                </div>
                                                            </div>
                                                        </div>

                                                        @* Submit and Reset Buttons *@
                                                        <div class="form-group row">
                                                            <div class="col-sm-8 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">Submit</button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="approveModal" tabindex="-1" role="dialog" aria-labelledby="approveRequestModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="approveRequestModalLabel">Approve Request</h5>
                    <button type="button" class="closeModal" data-dismiss="modal" aria-label="Close" v-on:click="showRequestModal=false">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="container-fluid">
                        <form v-on:submit.prevent="approveRequest" data-aos="fade-right">
                            @* <div class=" register" data-aos="fade-right"> *@
                            <div 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">
                                                <h3 class="register-heading">APPROVE REQUEST</h3>
                                                <div class="row register-form">
                                                    <div class="col-md-12">

                                                        <div class="form-group row">
                                                            @* <label class="col-sm-4 col-form-label hidden-label">Request Id</label> *@
                                                            <div class="col-sm-8">
                                                                <div class="dropdown">
                                                                    <input type="text" id="currentrequestID" name="currentrequestID" v-model="currentrequestID" class="form-control" hidden />
                                                                </div>
                                                            </div>
                                                        </div>

                                                        <div class="form-group row">
                                                            <label class="col-sm-4 col-form-label">Remark</label>
                                                            <div class="col-sm-8">
                                                                <div class="dropdown">
                                                                    <input type="text" id="approveremark" name="approveremark" v-model="approveremark" class="form-control" required />
                                                                </div>
                                                            </div>
                                                        </div>

                                                        @* Submit and Reset Buttons *@
                                                        <div class="form-group row">
                                                            <div class="col-sm-8 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">Submit</button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="requestModal" tabindex="-1" role="dialog" aria-labelledby="addRequestModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addRequestModalLabel">Add Request</h5>
                    <button type="button" class="closeModal" data-dismiss="modal" aria-label="Close" v-on:click="showRequestModal=false">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="container-fluid">
                        <form v-on:submit.prevent="addRequestMaster" data-aos="fade-right">
                            <div class="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">
                                                <h3 class="register-heading">PRODUCT REQUEST</h3>
                                                <div class="row register-form">
                                                    <div class="col-md-13">

                                                        <!-- Product Name -->
                                                        <div class="form-group row">
                                                            <label class="col-sm-2 col-form-label">Product</label>
                                                            <div class="col-sm-8">
                                                                <div class="dropdown" v-click-outside="closeDropdown">
                                                                    <!-- Button + Input dalam satu box -->
                                                                    <div class="dropdown-toggle-box" v-on:click="dropdownOpen = !dropdownOpen">
                                                                        <input type="text" class="form-control" v-model="searchQuery"
                                                                               placeholder="Search product..." v-on:focus="dropdownOpen = true" v-on:click.stop />
                                                                        <button type="button" class="btn btn-primary dropdown-btn" v-on:click.stop="dropdownOpen = !dropdownOpen">
                                                                            ▼
                                                                        </button>
                                                                    </div>

                                                                    <!-- Dropdown list -->
                                                                    <div v-if="dropdownOpen" class="dropdown-content" v-on:click.stop>
                                                                        <div v-for="(item, index) in filteredProducts"
                                                                             :key="index" class="dropdown-item" v-on:mousedown.prevent="selectProduct(item)">
                                                                            {{ item.productName + ' (' + item.modelNo + ')' }}
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>

                                                        <!-- Category Dropdown -->
                                                        <div class="form-group row">
                                                            <label class="col-sm-2 col-form-label">Category:</label>
                                                            <div class="col-sm-8">
                                                                <input type="text" id="category" name="category" v-model="showProduct.category" class="form-control" readonly />
                                                            </div>
                                                        </div>

                                                        <!-- Image Product Dropdown-->
                                                        <div class="form-group row align-items-center">
                                                            <label for="imageProduct" class="col-sm-2 col-form-label">Product Image: </label>
                                                            <div class="col-sm-8">
                                                                <img v-if="showProduct.imageProduct" :src="showProduct.imageProduct" alt="Product Image" class="img-fluid" data-toggle="modal" data-target="#imageModal" />
                                                                <input type="hidden" id="imageProduct" name="imageProduct" v-model="showProduct">
                                                            </div>
                                                        </div>

                                                        <!-- Modal -->
                                                        <div class="modal fade" id="imageModal" tabindex="-1" role="dialog" aria-labelledby="imageModalLabel" aria-hidden="true">
                                                            <div class="modal-dialog modal-lg" role="document">
                                                                <div class="modal-content">
                                                                    <div class="modal-header">
                                                                        <h5 class="modal-title" id="imageModalLabel">Product Image</h5>
                                                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                                            <span aria-hidden="true">&times;</span>
                                                                        </button>
                                                                    </div>
                                                                    <div class="modal-body">
                                                                        <img :src="showProduct.imageProduct" alt="Product Image" class="img-fluid">
                                                                    </div>
                                                                    <div class="modal-footer">
                                                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>

                                                        <!-- Quantity Input -->
                                                        <div class="form-group row d-flex align-items-center">
                                                            <label class="col-sm-2 col-form-label">Quantity:</label>
                                                            <div class="col-sm-8">
                                                                <input type="number" class="form-control" v-model="quantity" required />
                                                            </div>
                                                        </div>

                                                        @* Get the Item from who store *@
                                                        <div class="form-group row">
                                                            <label class="col-sm-2 col-form-label">Request From Store : </label>
                                                            <div class="col-sm-8">
                                                                <div class="dropdown">
                                                                    <select class="btn btn-primary dropdown-toggle col-md-12" v-model="fromStoreItem" required>
                                                                        <option class="btn-light" value="" selected disabled>Select Store</option>
                                                                        <option class="btn-light" v-for="(item, index) in stores" :key="item" :value="item.id">{{ item.storeName ?? 'Select Store'  }}</option>
                                                                    </select>
                                                                </div>
                                                            </div>
                                                        </div>

                                                        <!-- Give Item to where store -->
                                                        <div class="form-group row">
                                                            <label class="col-sm-2 col-form-label">Send To Store : </label>
                                                            <div class="col-sm-8">
                                                                <div class="dropdown">
                                                                    <select class="btn btn-primary dropdown-toggle col-md-12" data-toggle="dropdown" aria-expanded="false" v-model="assignStoreItem" required>
                                                                        <option class="btn-light" value="" disabled selected>Select Store</option>
                                                                        <option v-if="storeUser.length === 0" class="btn-light" disabled>No Store Assigned to You</option>
                                                                        <option class="btn-light" v-for="(item, index) in storeUser" :key="index" :value="item.id">
                                                                            {{ item.storeName }}
                                                                        </option>
                                                                    </select>
                                                                </div>
                                                            </div>
                                                        </div>

                                                        <!-- Remark Input (Wider) -->
                                                        <div class="form-group row d-flex align-items-center">
                                                            <label class="col-sm-2 col-form-label">Remark:</label>
                                                            <div class="col-sm-8">
                                                                <input type="text" class="form-control col-md-10" v-model="remark" />
                                                            </div>
                                                        </div>

                                                        <!-- Document/Picture Input -->
                                                        <div class="form-group row d-flex align-items-center">
                                                            <label class="col-sm-2 col-form-label">Document/Picture:</label>
                                                            <div class="col-sm-8">
                                                                <input type="file" id="document" name="document" class="form-control-file" v-on:change="handleFileUpload" accept="image/png, image/jpeg, application/pdf" />
                                                            </div>
                                                        </div>


                                                        @* Submit and Reset Buttons *@
                                                        <div class="form-group row">
                                                            <div class="col-sm-8 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>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script>
        $(function () {
            app.mount('#requestProduct');

            // Attach a click event listener to elements with the class 'btn-success'.
            $('#addRequestBtn').on('click', function () {
                // Show the modal
                $('#requestModal').modal('show');
            });
            $('.closeModal').on('click', function () {
                // Show the modal 
                $('.modal').modal('hide');
            });
            $('.submit-button').on('click', function () {
                // Show the modal
                $('#rejectModal').modal('hide');
                $('#approveModal').modal('hide');
            });
        });
        const app = Vue.createApp({
            data() {
                return {
                    requestID : null,
                    userId : null,
                    stationId : null,
                    productId : null,
                    remark: "",
                    document: null,
                    quantity: 0,
                    status: "",
                    requestDate : null,
                    approvalDate : null,
                    productCategory: "",
                    fromStoreItem : "",
                    assignStoreItem : "",
                    stores: null,
                    sortBy: "tech",
                    productName: null,
                    productCategory: null,
                    stations: [],
                    selectedProduct: "",
                    selectedStation: "",
                    selectedCategory: "",
                    selectedStore: "",
                    showRequestModal: false,
                    showRejectModal: false,
                    showApproveModal: false,
                    loading: false,
                    request: [],
                    currentUser: null,
                    currentUserId: null,
                    currentrequestID: "",
                    rejectremark: "",
                    approveremark: "",
                    storeUser: "",
                    searchQuery: "",
                    dropdownOpen: false, 
                    showRequestModal: false,
                }
            }, 
            async mounted() {
                this.fetchProducts();
                this.fetchStation();
                await this.fetchUser();

                // Wait for fetchStoreSpecific to complete before calling fetchStore
                await this.fetchStoreSpecific(this.currentUserId);
                await Promise.all([
                    await this.fetchRequest(),
                    await this.fetchStore(),
                ]);
            },
            watch: {
                showRequestModal(newVal) {
                    if (newVal) {
                        $('#requestModal').modal('show');
                    } else {
                        $('#requestModal').modal('hide');
                    }
                }
            },
            computed: {
                showProduct() {
                    if (!this.productId) {
                        return []; // No company selected, return empty list
                    }
                    const product = this.products.find(c => c.productId === this.productId);

                    this.productCategory = product.category;

                    return product ? product : {};
                },
                filteredProducts() {
                    return this.products.filter(item =>
                        item.productName.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
                        item.modelNo.toLowerCase().includes(this.searchQuery.toLowerCase())
                    );
                }
            },
            methods: {

                async addRequestMaster() {
                    try {
                        const requiredFields = ['productId', 'quantity', 'fromStoreItem', 'assignStoreItem'];

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

                        this.userId = this.currentUser.id;
                        this.status = "Requested";

                        const now = new Date();
                        this.requestDate = new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString();


                        // Prepare data as JSON (No file upload)
                        const requestDatas = {
                            ProductId: this.productId,
                            StationId: this.stationId,
                            UserId: this.userId,
                            ProductCategory: this.productCategory,
                            RequestQuantity: this.quantity,
                            remarkUser: this.remark || '',
                            remarkMasterInv: '',
                            status: this.status,
                            requestDate: this.requestDate,
                            approvalDate: null,
                            fromStoreItem: this.fromStoreItem,
                            assignStoreItem: this.assignStoreItem,
                            Document: this.document
                        };

                        $('.modal').modal('hide');

                        // Proceed to send the data to the API
                        const response = await fetch('/InvMainAPI/AddRequestMaster', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                // 'Authorization': `Bearer ${this.token}`
                            },
                            body: JSON.stringify(requestDatas)
                        });
                        if (response.ok) {
                            // If the form submission was successful, display a success message
                            alert('Success!', 'Request form has been successfully submitted.', 'success');
                            const requestItem = await response.json();
                            this.items.push(requestItem);
                            this.resetForm();
                            this.fetchRequest();

                        } else {
                            throw new Error('Failed to submit form.');
                        }

                    } catch (error) {
                        console.error('Error:', error);

                        // Displaying error message
                        alert('Inventory PSTW Error', `An error occurred: ${error.message}`, 'error');
                    }
                },

                async addRequest() {
                    try {
                            const requiredFields = ['stationId', 'productId', 'quantity', 'productCategory'];

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

                        // Proceed to send the data to the API
                        const response = await fetch('/InvMainAPI/AddRequest', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                // 'Authorization': `Bearer ${this.token}`
                            },
                            body: JSON.stringify(formData)
                        });
                        if (response.ok) {
                            // If the form submission was successful, display a success message
                            alert('Success!', 'Request form has been successfully submitted.', 'success');
                            const requestItem = await response.json();
                            this.items.push(requestItem);

                            this.fetchRequest();

                        } else {
                            throw new Error('Failed to submit form.');
                        }

                    } catch (error) {
                        console.error('Error:', error);

                        // Displaying error message
                        alert('Inventory PSTW Error', `An error occurred: ${error.message}`, 'error');
                    }

                },

                initiateTable() {
                    self = this;

                    function renderActionButtons(data, type, row) {
                        var actiontButtons = `<div class="row" style="padding: 5px;"> <button type="button" class="btn btn-success approve-btn" data-id="${data}">Approve</button></div> <div class="row" style="padding: 5px;"><button type="button" class="btn btn-danger reject-btn" data-id="${data}">Reject</button></div>`;
                        return actiontButtons;
                    }
                    function renderDocument(data, type, full, meta) {
                        if (!data) {
                            return "No Document";
                        }

                        var imageSrc = full.productImage;
                        // Check if the document is an image based on file extension
                        var isImage = /\.(jpeg|jpg|png|gif)$/i.test(imageSrc);
                        var isPdf = /\.pdf$/i.test(imageSrc);
                        // var imageSrc = full.productImage;  Fallback to data if imgsrc is unavailable

                        if (isImage) {
                            return `    <div class="row"><td>${data}</td></div>
                                                                        <a href="${imageSrc}" target="_blank" data-lightbox="image-1">
                                                                            <img src="${imageSrc}" alt="Image" class="img-thumbnail" style="width: 100px; height: 100px;" />
                                                                        </a>`;
                        }
                        else if (isPdf) {
                            return `<div class="row"><td>${data}</td></div>
                                                                <a href="${imageSrc}" target="_blank">
                                                                    <img src="https://upload.wikimedia.org/wikipedia/commons/8/87/PDF_file_icon.svg"
                                                                        alt="PDF Document" class="img-thumbnail"
                                                                        style="width: 50px; height: 50px;" />
                                                                    <br>View PDF
                                                                </a>`;
                        }
                    }

                    this.requestDatatable = $('#requestDatatable').DataTable({
                        "data": this.items.filter(item => item.status === "Requested" && item.assignStoreItem == null),
                        "columns": [
                            { "title": "Request ID", "data": "requestID" },
                            { "title": "Action", "data": "requestID", "render": renderActionButtons, "className": "align-middle" },
                            { "title": "Product", "data": "productName", "render": renderDocument },
                            { "title": "Requested by User", "data": "userName" },
                            { "title": "Requested by Station", "data": "stationName" },
                            { "title": "Product Category", "data": "productCategory" },
                            { "title": "Request Quantity", "data": "requestQuantity" },
                            { "title": "Document/Picture", "data": "document", "render": renderDocument },
                            { "title": "User Remark", "data": "remarkUser" },
                            { "title": "Status", "data": "status" },
                            { "title": "Request Date", "data": "requestDate" },
                            { "title": "Approval Date", "data": "approvalDate" }
                        ],
                        responsive: true,
                        drawCallback: function (settings) { }
                    });

                    this.settledrequestDatatable = $('#settledrequestDatatable').DataTable({
                        "data": this.items.filter(item => item.status !== "Requested" && item.assignStoreItem == null),
                        "columns": [
                            { "title": "Request ID", "data": "requestID" },
                            { "title": "Product", "data": "productName", "render": renderDocument },
                            { "title": "Requested by User", "data": "userName" },
                            { "title": "Requested by Station", "data": "stationName" },
                            { "title": "Product Category", "data": "productCategory" },
                            { "title": "Request Quantity", "data": "requestQuantity" },
                            { "title": "Document/Picture", "data": "document", "render": renderDocument },
                            { "title": "User Remark", "data": "remarkUser" },
                            { "title": "InvMaster Remark", "data": "remarkMasterInv" },
                            { "title": "Status", "data": "status" },
                            { "title": "Request Date", "data": "requestDate" },
                            { "title": "Approval Date", "data": "approvalDate" }
                        ],
                        responsive: true
                    });
                    this.requestMasterDatatable = $('#requestMasterDatatable').DataTable({
                        "data": this.items.filter(item => item.assignStoreItem != null && item.status == "Requested" && item.userId == this.currentUserId),
                        "columns": [
                            { "title": "Request ID", "data": "requestID" },
                            { "title": "Product", "data": "productName", "render": renderDocument },
                            { "title": "From Store", "data": "fromStoreItem" },
                            { "title": "Assign Store", "data": "assignStoreItem" },
                            { "title": "Product Category", "data": "productCategory" },
                            { "title": "Request Quantity", "data": "requestQuantity" },
                            { "title": "Document/Picture", "data": "document", "render": renderDocument },
                            { "title": "Remark", "data": "remarkUser" },
                            { "title": "Status", "data": "status" },
                            { "title": "Request Date", "data": "requestDate" },
                            { "title": "Approval Date", "data": "approvalDate" },
                            {
                                "title": "Delete", "data": "requestID",
                                "render": function (data) {
                                    var deleteButton = `<button type="button" class="btn btn-danger delete-btn" data-id="${data}">Delete</button>`;
                                    return deleteButton;
                                },
                                "className": "align-middle",
                            }
                        ],
                        responsive: true,
                        drawCallback: function (settings) { }
                    });
                    this.requestOtherMasterDatatable = $('#requestOtherMasterDatatable').DataTable({
                        "data": this.items.filter(item => item.status == "Requested" && this.storeUser.some(store => store.id === item.fromStoreItem)),
                        "columns": [
                            { "title": "Request ID", "data": "requestID" },
                            { "title": "Action", "data": "requestID", "render": renderActionButtons, "className": "align-middle" },
                            { "title": "Product", "data": "productName", "render": renderDocument },
                            { "title": "Requested by User", "data": "userName" },
                            { "title": "From Store", "data": "fromStoreItem" },
                            { "title": "Assign Store", "data": "assignStoreItem" },
                            { "title": "Product Category", "data": "productCategory" },
                            { "title": "Request Quantity", "data": "requestQuantity" },
                            { "title": "Document/Picture", "data": "document", "render": renderDocument },
                            { "title": "User Remark", "data": "remarkUser" },
                            { "title": "Status", "data": "status" },
                            { "title": "Request Date", "data": "requestDate" },
                            { "title": "Approval Date", "data": "approvalDate" }
                        ],
                        responsive: true
                    });
                    this.settledrequestMasterDatatable = $('#settledrequestMasterDatatable').DataTable({
                        "data": this.items.filter(item => item.status != "Requested" && item.assignStoreItem != null),
                        "columns": [
                            { "title": "Request ID", "data": "requestID" },
                            { "title": "Product", "data": "productName", "render": renderDocument },
                            { "title": "Requested by User", "data": "userName" },
                            { "title": "From Store", "data": "fromStoreItem" },
                            { "title": "Assign Store", "data": "assignStoreItem" },
                            { "title": "Product Category", "data": "productCategory" },
                            { "title": "Request Quantity", "data": "requestQuantity" },
                            { "title": "Document/Picture", "data": "document", "render": renderDocument },
                            { "title": "User Remark", "data": "remarkUser" },
                            { "title": "Status", "data": "status" },
                            { "title": "Request Date", "data": "requestDate" },
                            { "title": "Approval Date", "data": "approvalDate" }
                        ],
                        responsive: true
                    }); 
                    
                    // Attach event listeners
                    $('#requestDatatable tbody').on('click', '.reject-btn', function () {
                        const requestID = $(this).data('id');
                        self.rejectRequestModal(requestID);
                    });

                    $('#requestDatatable tbody').on('click', '.approve-btn', function () {
                        const requestID = $(this).data('id');
                        self.approveRequestModal(requestID);
                    });

                    // Attach event listeners
                    $('#requestOtherMasterDatatable tbody').on('click', '.reject-btn', function () {
                        const requestID = $(this).data('id');
                        self.rejectRequestModal(requestID);
                    });

                    $('#requestOtherMasterDatatable tbody').on('click', '.approve-btn', function () {
                        const requestID = $(this).data('id');
                        self.approveRequestModal(requestID);
                    });

                    $('#requestMasterDatatable tbody').off('click', '.delete-btn');

                    $('#requestMasterDatatable tbody').on('click', '.delete-btn', function () {
                        const requestID = $(this).data('id');
                        self.deleteRequestItem(requestID);
                    });

                    this.loading = false;

                },

                async fetchRequest() {
                    try {
                            const response = await fetch('/InvMainAPI/ItemRequestList', {
                            method: 'GET', // Specify the HTTP method
                            headers: {
                                'Content-Type': 'application/json', // Set content type
                            }
                        });

                        if (!response.ok) {
                            throw new Error('Failed to fetch item');
                        }
                        this.items = await response.json();

                        if (this.requestDatatable) {
                            this.requestDatatable.clear().destroy();
                        }
                        if (this.settledrequestDatatable) {
                            this.settledrequestDatatable.clear().destroy();
                        }
                        if (this.requestMasterDatatable) {
                            this.requestMasterDatatable.clear().destroy();
                        }
                        if (this.requestOtherMasterDatatable) {
                            this.requestOtherMasterDatatable.clear().destroy();
                        }
                        if (this.settledrequestMasterDatatable) {
                            this.settledrequestMasterDatatable.clear().destroy();
                        }
                        this.initiateTable();
                    }
                    catch (error) {
                        console.error('Error fetching item:', error);
                    }
                },

                async fetchProducts() {
                    try {
                        // const token = localStorage.getItem('token'); // Get the token from localStorage
                        const response = await fetch('/InvMainAPI/ProductList', {
                            method: 'POST', // Specify the HTTP method
                            headers: {
                                'Content-Type': 'application/json', // Set content type
                                // 'Authorization': `Bearer ${token}` // Include the token in the headers
                            }
                        });

                        if (!response.ok) {
                            throw new Error('Failed to fetch products');
                        }

                        this.products = await response.json();
                    }
                    catch (error) {
                        console.error('Error fetching products:', error);
                    }
                },

                async fetchStation() {
                    try {
                        const response = await fetch('/InvMainAPI/StationList', {
                            method: 'POST', // Specify the HTTP method
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        });
                        if (!response.ok) {
                            throw new Error('Failed to fetch suppliers');
                        }
                        this.stations = await response.json(); // Get the full response object

                    } catch (error) {
                        console.error('Error fetching suppliers:', error);
                    }
                },
                async fetchStore() {
                    try {
                        const response = await fetch('/InvMainAPI/StoreList/', {
                            method: 'POST', // Specify the HTTP method
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        });
                        if (!response.ok) {
                            throw new Error('Failed to fetch suppliers');
                        }

                        const data = await response.json();
                        this.stores = data.filter(store =>
                            !this.storeUser.some(userStore => userStore.id === store.id)
                        );


                    } catch (error) {
                        console.error('Error fetching suppliers:', error);
                    }
                },
                async fetchStoreSpecific(currentUserId) {
                    try {
                        const response = await fetch('/InvMainAPI/StoreSpecificMasterList/' + currentUserId, {
                            method: 'POST', // Specify the HTTP method
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        });
                        if (!response.ok) {
                            throw new Error('Failed to fetch store');
                        }
                        this.storeUser = await response.json(); // Get the full response object

                    } catch (error) {
                        console.error('Error fetching suppliers:', error);
                    }
                },
                async fetchUsers() {
                    try {
                        const response = await fetch('/InvMainAPI/UserList', {
                            method: 'POST', // Specify the HTTP method
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        });
                        if (!response.ok) {
                            throw new Error('Failed to fetch suppliers');
                        }
                        this.users = await response.json(); // Get the full response object

                    } catch (error) {
                        console.error('Error fetching suppliers:', error);
                    }
                },


                // FRONT END FUNCTIONS
                //----------------------//
                //Calculate Total Price
                convertCurrency() {
                    const total = this.DefaultPrice * this.currencyRate;
                    this.convertPrice = total.toFixed(2);
                    this.DefaultPrice = this.DefaultPrice
                        // .replace(/[^0-9.]/g, '') // Remove non-numeric characters except decimal points
                        // .replace(/(\..*)\..*/g, '$1') // Allow only one decimal point
                        // .replace(/^(\d*\.\d{0,2})\d*$/, '$1'); // Limit to two decimal places

                },
                calculateWarrantyEndDate() {
                    // Check if DODate and warranty are valid
                    if (!this.DODate || isNaN(Date.parse(this.DODate))) {
                        this.EndWDate = null;
                        return;
                    }

                    const DODates = new Date(this.DODate);
                    const warrantyMonth = parseInt(this.warranty);

                    // Ensure warranty is a valid number
                    if (!isNaN(warrantyMonth)) {
                        DODates.setMonth(DODates.getMonth() + warrantyMonth);
                        this.EndWDate = DODates.toISOString().split('T')[0];
                    } else {
                        this.EndWDate = null;
                    }
                },
                async approveRequest() {
                    // if (!confirm("Are you sure you want to approve this request?")) {
                    //     return;
                    // }

                    const formData = {
                            RemarkMasterInv: this.rejectremark,

                        };

                        let requestID = this.currentrequestID;
                    try {
                        const response = await fetch(`/InvMainAPI/ApproveRequest/${requestID}`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(formData)

                        });
                        const result = await response.json();

                        if (result.success) {
                            alert(result.message);

                            //static update
                            const row = $(`.approve-btn[data-id="${requestID}"]`).closest('tr');
                            let rowData = this.requestDatatable.row(row).data();

                            // Update the status and remark
                            rowData.status = "Approved";

                            // Remove row from requestDatatable
                            this.requestDatatable.row(row).remove().draw();

                            // Add updated row to settledrequestDatatable
                            this.settledrequestDatatable.row.add(rowData).draw();


                        } else {
                            alert(result.message);
                        }
                    }
                    catch (error) {
                        console.error("Error approving request:", error);
                            // alert("An error occurred while approving the request.");
                    }
                    finally {
                        this.loading = false;
                    }
                },

                async rejectRequest() {

                        const formData = {
                            RemarkMasterInv: this.rejectremark,
                            
                        };

                        let requestID = this.currentrequestID;

                    try {

                        const response = await fetch(`/InvMainAPI/RejectRequest/${requestID}`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                // 'Authorization': `Bearer ${this.token}`
                            },
                            body: JSON.stringify(formData)
                            
                        });
                        if (response.ok) {
                            // If the form submission was successful, display a success message
                            // alert('Success!', 'Request has been Rejected.', 'success');

                            const row = $(`.approve-btn[data-id="${requestID}"]`).closest('tr');
                            let rowData = this.requestDatatable.row(row).data();

                            // Update the status and remark
                            rowData.status = "Rejected";
                            rowData.remarkMasterInv = this.rejectremark;

                            // Remove row from requestDatatable
                            this.requestDatatable.row(row).remove().draw();

                            // Add updated row to settledrequestDatatable
                            this.settledrequestDatatable.row.add(rowData).draw();


                        } else {
                            throw new Error('Failed to submit form.');
                        }

                    } catch (error) {
                        console.error('Error:', error);

                        // Displaying error message
                        alert('Inventory PSTW Error', `An error occurred: ${error.message}`, 'error');
                    }
                    finally {
                        this.loading = false;
                    }
                },
                async rejectRequestModal(requestID, remark) {

                    this.currentrequestID = requestID;
                    this.rejectremark = remark;


                    $(`#rejectModal`).modal('show');

                    
                },
                async approveRequestModal(requestID, remark) {

                    this.currentrequestID = requestID;
                    this.approveremark = remark;


                    $(`#approveModal`).modal('show');


                },
                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;
                            this.currentUserCompanyDept = companyDeptData;
                            this.selectedCompany = companyDeptData?.companyId || "";
                            this.selectedDepartment = companyDeptData?.departmentId || "";
                            this.currentUserId = this.currentUser.id;
                        }
                        else {
                            console.error(`Failed to fetch user: ${response.statusText}`);
                        }
                    }
                    catch (error) {
                        console.error('There was a problem with the fetch operation:', error);
                    }
                },

                closeDropdown() {
                    this.dropdownOpen = false; // Tutup dropdown
                },

                selectProduct(item) {
                    this.selectedProduct = item;
                    this.productId = item.productId;
                    this.searchQuery = item.productName + " (" + item.modelNo + ")";
                    this.dropdownOpen = false;
                },

                closeModal() {
                    this.showRequestModal = false;
                },

                handleFileUpload(event) {
                    const file = event.target.files[0];

                    if (file) {
                        const reader = new FileReader();
                        reader.onload = (e) => {
                            this.document = e.target.result.split(',')[1]; // Get Base64 string (remove metadata)
                        };
                        reader.readAsDataURL(file);
                    } else {
                        this.document = null;
                    }
                },

                resetForm() {
                    this.searchQuery = "";
                    this.stationId = "";
                    this.productId = "";
                    this.remark = "";
                    this.document = null;
                    this.quantity = 0;
                    this.status = "";
                    this.requestDate = null;
                    this.approvalDate = null;
                    this.productCategory = "";
                    this.fromStoreItem = "",
                    this.assignStoreItem = "",

                    this.productName = null;
                    this.selectedProduct = "";
                    this.selectedStation = "";
                    this.selectedCategory = "";
                    this.loading = false;
                    this.rejectremark = "";
                },

                async deleteRequestItem(requestID) {
                    if (!confirm("Are you sure you want to delete this request?")) {
                        return false;
                    }
                    try {
                        const response = await fetch(`/InvMainAPI/DeleteRequest/${requestID}`, {
                            method: 'DELETE',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                        });
                        const result = await response.json();

                        if (result.success) {
                            alert(result.message);

                            if ($.fn.dataTable.isDataTable('#requestMasterDatatable')) {
                                const table = $('#requestMasterDatatable').DataTable();
                                table.row($(`.delete-btn[data-id="${requestID}"]`).closest('tr')).remove().draw();
                            }

                            this.request = this.request.filter(req => req.requestID !== requestID);
                        } else {
                            alert(result.message);
                        }
                    }
                    catch (error) {
                        console.error("Error deleting item:", error);
                        alert("An error occurred while deleting the item.");
                    }
                    finally {
                        this.loading = false;
                    }
                },

                handleSorting() {
                    if (this.requestDatatable) {
                        this.requestDatatable.clear().destroy();
                    }
                    if (this.settledrequestDatatable) {
                        this.settledrequestDatatable.clear().destroy();
                    }
                    if (this.requestMasterDatatable) {
                        this.requestMasterDatatable.clear().destroy();
                    }
                    if (this.requestOtherMasterDatatable) {
                        this.requestOtherMasterDatatable.clear().destroy();
                    }
                    if (this.settledrequestMasterDatatable) {
                        this.settledrequestMasterDatatable.clear().destroy();
                    }
                    this.initiateTable();
                },
            },
            directives: {
                clickOutside: {
                    beforeMount(el, binding) {
                        el.clickOutsideEvent = (event) => {
                            // Make sure the click is outside the element
                            if (!el.contains(event.target) && el !== event.target) {
                                binding.value?.(); // Call the function to close the modal
                            }
                        };
                        setTimeout(() => {
                            document.body.addEventListener("click", el.clickOutsideEvent);
                        }, 0); // Delay to avoid triggering immediately when opening
                    },
                    beforeUnmount(el) {
                        document.body.removeEventListener("click", el.clickOutsideEvent);
                    }
                }
            }

        });
    </script>
}