@{
    ViewData["Title"] = "QR Scanner";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<style scoped>
    .error {
        font-weight: bold;
        color: red;
    }

    .barcode-format-checkbox {
        margin-right: 10px;
        white-space: nowrap;
        display: inline-block;
    }

    select {
        width: 200px; /* Adjust width as needed */
        padding: 5px;
        font-size: 16px;
    }

</style>


@await Html.PartialAsync("~/Areas/Inventory/Views/_InventoryPartialUser.cshtml")
<div id="registerItem" class="row">
    <div class="row card">
        <div class="card-header">
            <button v-if="displayStatus !== null" v-on:click="resetScanner" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Scanner
            </button>
        </div>
        <div class="card-body">

            <select v-if="displayStatus == null" class="form-select" v-model="selectedCameraId" v-on:change="updateCamera">
                <option v-for="device in videoInputDevices" :key="device.deviceId" :value="device.deviceId">
                    {{ device.label || `Camera ${videoInputDevices.indexOf(device) + 1}` }}
                </option>
            </select>

            <div id="registerItem" v-if="displayStatus == null" data-aos="fade-right">
                <p style="text-align:center; padding:10px;">Scan QR Code Here:</p>
                
                <qrcode-stream :constraints="selectedConstraints"
                               :formats="['qr_code']"
                               :track="trackFunctionSelected.value"
                               v-on:camera-on="onCameraReady"
                               v-on:detect="onDecode"
                               v-on:error="onError">
                </qrcode-stream>

                <p class="error">{{ error }}</p>

            </div>
            <!--RECEIVE OR RETURN INTERFACE -->
            <div style="text-align: center; margin: 20px 0;" v-if="displayStatus === 'arrived' && thisItem.currentStationId != null">
                <h2>Item Receive Information :</h2>
                <h3>Station Assign</h3>
            </div>
            <div style="text-align: center; margin: 20px 0;" v-if="displayStatus === 'arrived' && thisItem.currentStationId == null">
                <h2>Item Receive Information :</h2>
                <h3>Self Assign</h3>
            </div>

            <div style="text-align: center; margin: 20px 0;" v-if="displayStatus === 'return' && thisItem.currentStationId != null">
                <h2>Item Return Information :</h2>
                <h3>Station</h3>
            </div>
            <div style="text-align: center; margin: 20px 0;" v-if="displayStatus === 'return' && thisItem.currentStationId == null">
                <h2>Item Return Information :</h2>
                <h3>Self Assign</h3>
            </div>

            <div v-if="displayStatus === 'arrived' || displayStatus === 'return'" style="display: flex; justify-content: center; align-items: center;">

                <div class="col-lg-7 col-11 border rounded p-3 shadow-sm">
                    <div class="row m-3 d-flex align-items-center justify-content-center">
                        <div class="col-lg-7 col-11 border rounded p-3 shadow-sm">
                            <div class="col-12 text-center">
                                <img :src="thisItem.imageProduct" alt="Product Image" class="img-fluid rounded" data-toggle="modal" data-target="#imageModal" style="max-height: 300px;" />
                            </div>
                            <div class="col-12 text-center mt-3">
                                <p class="h4 fw-bold text-primary">{{ thisItem.uniqueID }}</p>
                            </div>
                        </div>
                    </div>

                    <!-- Item Name -->
                    <div class="col-12 mb-3">
                        <p class="h5 fw-bold">
                            <i class="fas fa-tag me-2 text-secondary"></i>Item Name:
                            <span class="text-muted">{{ thisItem.productName }}</span>
                        </p>
                    </div>

                    <!-- Part Number -->
                    <div class="col-12 mb-3">
                        <p class="h5 fw-bold">
                            <i class="fas fa-barcode me-2 text-secondary"></i>Part Number:
                            <span class="text-muted">{{ thisItem.partNumber }}</span>
                        </p>
                    </div>

                    <!-- Serial Number -->
                    <div class="col-12 mb-3">
                        <p class="h5 fw-bold">
                            <i class="fas fa-hashtag me-2 text-secondary"></i>Serial Number:
                            <span class="text-muted">{{ thisItem.serialNumber }}</span>
                        </p>
                    </div>

                    <!-- Station -->
                    <div class="col-12 mb-3">
                        <p class="h5 fw-bold">
                            <i class="fas fa-user-tie me-2 text-secondary"></i>PIC:
                            <span class="text-muted">{{thisItem.currentUserFullName}}</span>
                        </p>
                    </div>

                    <!-- Station -->
                    <div class="col-12 mb-3">
                        <p class="h5 fw-bold">
                            <i class="fas fa-user-tie me-2 text-secondary"></i>Station:
                            <span class="text-muted">{{thisItem.currentStation || 'No Station Deploy (Self Assign)' }}</span>
                        </p>
                    </div>

                    <!--RECIEVE INTERFACE -->
                    <div class="col-12" v-if="displayStatus === 'arrived'">
                        <div class="card shadow-sm border-0">
                            <div class="card-body">
                                <h5 class="card-title mb-4 text-primary">
                                    <i class="fas fa-info-circle me-2"></i>Receiver Information
                                </h5>
                                <ul class="list-group list-group-flush">
                                    <!-- User -->
                                    <li class="list-group-item">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <span class="fw-bold">
                                                <i class="fas fa-user me-2 text-secondary"></i>User:
                                            </span>
                                            <span class="text-muted text-end" style="max-width: 70%; word-wrap: break-word;">
                                                {{ thisItem.currentUser }}
                                            </span>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>

                    <!--RETURN INTERFACE -->
                    <div class="col-12" v-if="displayStatus === 'return'">
                        <div class="card shadow-sm border-0">
                            <div class="card-body">
                                <h5 class="card-title mb-4 text-primary">
                                    <i class="fas fa-info-circle me-2"></i>Sender Information
                                </h5>
                                <ul class="list-group list-group-flush">
                                    <!-- User -->
                                    <li class="list-group-item">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <span class="fw-bold">
                                                <i class="fas fa-user me-2 text-secondary"></i>User:
                                            </span>
                                            <span class="text-muted text-end" style="max-width: 70%; word-wrap: break-word;">
                                                {{ thisItem.currentUser }}
                                            </span>
                                        </div>
                                    </li>

                                </ul>
                            </div>
                        </div>
                    </div>

                </div>

            </div>

            <!--RECIEVE INTERFACE -->
            <form v-on:submit.prevent="updateItemMovement" v-if="displayStatus === 'arrived'" data-aos="fade-right">
                <div class=" register" data-aos="fade-right">
                    <div class="row" data-aos="fade-right">

                        @*Right Side*@
                        <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">
                                    <br><br>

                                    @* Submit and Reset Buttons *@
                                    <div class="form-group row">
                                        <div class="col-sm-8 offset-sm-5">
                                            <button type="button" v-on:click="receiveReturnMessage" class="btn btn-secondary m-1">Return Item</button>
                                            <button type="submit" class="btn btn-primary m-1">Receive Item</button>
                                        </div>
                                    </div>
                                       
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </form>

            <!--RETURN INTERFACE -->
            <form v-on:submit.prevent="" v-if="displayStatus === 'return'" data-aos="fade-right">
                <div class=" register" data-aos="fade-right">
                    <div class="row" data-aos="fade-right">

                        @*Right Side*@
                        <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">
                                    <br><br>
                                    @* Submit and Reset Buttons *@
                                    <div class="form-group row">
                                        <div class="col-sm-8 offset-sm-5">
                                            <button type="submit" v-on:click="ReturnMessage" class="btn btn-primary m-1">Return Item</button>
                                            <button type="submit" v-on:click="StationMessage" class="btn btn-primary m-1">{{ thisItem?.currentStationId == null ? "Deploy Station" : "Change Station" }}</button>
                                        </div>
                                    </div>
                                        
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>

            <!--STATION DEPLOY MESSAGE BOX INTERFACE-->
            <div class="modal fade" id="stationMessage" tabindex="-1" role="dialog" aria-labelledby="stationModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="stationModalLabel">{{ thisItem?.currentStationId == null ? "Deploy Station" : "Change Station" }}</h5>
                            <button type="button" class="close" data-dismiss="modal" v-on:click="closeStationMessageModal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <form v-on:submit.prevent="updateStationItemMovement">

                                <div class="form-group row">
                                    <label class="col-sm-4 col-form-label">Deploy Station : </label>
                                    <div class="col-sm-8">
                                        <select class="btn btn-primary dropdown-toggle col-md-10" v-model="selectedStation">
                                            <option class="btn-light" value="" disabled selected>Select Station</option>
                                            <option v-if="stationList.length === 0" class="btn-light" disabled>No Station Assigned to You</option>
                                            <option class="btn-light" v-for="(station, index) in stationList" :key="index" :value="station.stationId">{{ station.stationName}}</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label class="col-sm-4 col-form-label">Remark:</label>
                                    <div class="col-sm-8">
                                        <input type="text" class="form-control" v-model="remark" />
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label class="col-sm-4 col-form-label">Consignment Note:</label>
                                    <div class="col-sm-8">
                                        <input type="file" class="form-control-file" v-on:change="handleFileUpload" accept="image/png, image/jpeg, application/pdf" />
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-primary">Deploy Station</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!--RETURN MESSAGE BOX INTERFACE-->
            <div class="modal fade" id="returnMessage" tabindex="-1" role="dialog" aria-labelledby="returnModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="returnModalLabel">Return Item</h5>
                            <button type="button" class="close" data-dismiss="modal" v-on:click="closeMessageModal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <form v-on:submit.prevent="returnItemMovement">

                                <div class="form-group row">
                                    <label class="col-sm-4 col-form-label">Remark:</label>
                                    <div class="col-sm-8">
                                        <input type="text" class="form-control" v-model="remark" />
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label class="col-sm-4 col-form-label">Consignment Note:</label>
                                    <div class="col-sm-8">
                                        <input type="file" class="form-control-file" v-on:change="handleFileUpload" accept="image/png, image/jpeg, application/pdf" />
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-primary">Return Item</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!--RECEIVE THEN RETURN INTERFACE -->
            <div class="modal fade" id="returnModal" tabindex="-1" role="dialog" aria-labelledby="returnModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="returnModalLabel">Return Item</h5>
                            <button type="button" class="close" data-dismiss="modal" v-on:click="closeModal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <form v-on:submit.prevent="receiveReturnAPI">

                                <div class="form-group row">
                                    <label class="col-sm-4 col-form-label">Remark:</label>
                                    <div class="col-sm-8">
                                        <input type="text" class="form-control" v-model="remark" />
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label class="col-sm-4 col-form-label">Consignment Note:</label>
                                    <div class="col-sm-8">
                                        <input type="file" class="form-control-file" v-on:change="handleFileUpload" accept="image/png, image/jpeg, application/pdf" />
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-primary">Return Item</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ALREADY RETURN ITEM INTERFACE -->
            <div v-if="displayStatus === 'requestAgain'" class="d-flex justify-content-center align-items-center vh-100">
                <div class="col-lg-10 col-11 border rounded p-5 shadow-lg text-center min-vh-50">
                    <h1 class="text-danger">The item has been register as returned.</h1>
                    <h3 class="text-muted">You need to request this item again to used it legally.</h3>
                </div>
            </div>

            <!-- NOT SIGN IN ITEM INTERFACE -->
            <div v-if="displayStatus === 'differentUser'" class="d-flex justify-content-center align-items-center vh-100">
                <div class="col-lg-10 col-11 border rounded p-5 shadow-lg text-center min-vh-50">
                    <h1 class="text-danger">The item is not assigned to you.</h1>
                    <h3 class="text-muted">You need to request this item to validly use it.</h3>
                </div>
            </div>

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

@section Scripts {

    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script src="~/js/vue-qrcode-reader.umd.js"></script>
   
    <script>

        const app = Vue.createApp({

            data() {
                return {
                    thisItem: null,
                    selectedUser: "",
                    selectedStation: "",
                    stationList: [],
                    displayStatus: null,
                    debounceTime: 500,
                    currentUser: null,
                    movementId: null,
                    currentUserId: null,
                    remark: null,
                    consignmentNote: null,
                    receiveReturn: null,
                    UniqueID: null,
                    InventoryMasterId: null,

                    //QR VARIABLE
                    qrCodeResult: null,
                    debounceTimeout: null,
                    error: "",
                    selectedConstraints: { facingMode: "user" },
                    trackFunctionSelected: { text: 'outline', value: null },
                    barcodeFormats: {
                        qr_code: true,  // Hanya mendukung QR Code
                        code_128: true,
                        ean_13: true
                    },
                    constraintOptions: [
                        { label: "Rear Camera", constraints: { facingMode: "environment" } },
                        { label: "Front Camera", constraints: { facingMode: "user" } }
                    ],
                    videoInputDevices: [],
                    selectedCameraId: null,
                    scanStartTime: null,
                    scanTime: null
                };
            },
            async mounted() {
                this.trackFunctionSelected.value = this.paintOutline;
                await this.fetchUser();
                await Promise.all([
                    this.fetchStation(),
                ]);
            },
            methods: {

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

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

                async updateStationItemMovement() {
                    const requiredFields = ['selectedStation'];

                    for (let field of requiredFields) {
                        if (!this[field]) {
                            alert(`Request Error: Please fill in required field ${field}.`, 'warning');
                            return;
                        }
                    }

                    try {
                        const now = new Date();
                        const formData = {
                            ItemId: this.thisItem.itemID,
                            ToStation: this.thisItem.currentStationId,
                            ToStore: this.thisItem.toStore,
                            ToUser: this.currentUserId,
                            ToOther: "Delivered",
                            SendDate: new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString(),
                            Action: "Assign",
                            Quantity: this.thisItem.quantity,
                            Remark: this.remark,
                            ConsignmentNote: this.consignmentNote,
                            Date: new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString(),
                            LastUser: this.currentUserId,
                            LastStore: this.thisItem.toStore,
                            LastStation: this.selectedStation,
                            LatestStatus: "Delivered",
                            ReceiveDate: new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString(),
                            MovementComplete: true,
                        };

                        const response = await fetch('/InvMainAPI/StationItemMovementUser', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(formData)
                        });

                        if (response.ok) {
                            this.thisItem = await response.json();
                            this.fetchItem(this.thisItem.uniqueID);
                            alert('Success! Item assign to the Station.');
                            $('#stationMessage').modal('hide');
                            this.displayStatus = "return";
                        } else {
                            throw new Error('Failed to submit form.');
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        alert('Inventory PSTW Error: An error occurred.');
                    }
                },

                async updateItemMovement() {

                    if (this.receiveReturn == null) {
                        if (!confirm("Are you sure you already received this item?")) {
                            return false;
                        }
                    }

                    try {
                        const now = new Date();
                        const formData = {
                            Id: this.thisItem.id,
                            LastStore: this.thisItem.toStore,
                            LatestStatus: "Delivered",
                            ReceiveDate: new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString(),
                            MovementComplete: true,
                        };

                        const response = await fetch('/InvMainAPI/UpdateItemMovementUser', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(formData)
                        });

                        if (response.ok) {
                            if (this.receiveReturn == null) {
                                alert('Success! Item has been successfully received.');
                                this.thisItem = await response.json();
                                this.displayStatus = "return";
                                this.fetchItem(this.UniqueID);
                                this.resetForm();
                            } else {
                                this.returnItemMovement();
                            }
                        } else {
                            throw new Error('Failed to submit form.');
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        alert('Inventory PSTW Error: An error occurred.');
                    }
                },

                async returnItemMovement() {

                    if (!confirm("Are you sure you want to return this item?")) {
                        return false;
                    }

                    try {
                        const now = new Date();
                        const formData = {
                            ItemId: this.thisItem.itemID,
                            ToStation: this.thisItem.currentStationId,
                            ToStore: this.thisItem.currentStoreId,
                            ToUser: this.currentUserId,
                            ToOther: "Return",
                            SendDate: new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString(),
                            Action: "StockIn",
                            Quantity: this.thisItem.quantity,
                            Remark: this.remark,
                            ConsignmentNote: this.consignmentNote,
                            Date: new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString(),
                            LastUser: this.InventoryMasterId,
                            LastStore: this.thisItem.toStore,
                            LastStation: this.thisItem.toStation,
                            LatestStatus: null,
                            ReceiveDate: null,
                            MovementComplete: false,
                        };

                        const response = await fetch('/InvMainAPI/ReturnItemMovementUser', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(formData)
                        });

                        if (response.ok) {
                            alert('Success! Item is on the delivery to return to Inventory Master.');
                            this.thisItem = await response.json();
                            $('#returnModal').modal('hide');
                            $('#returnMessage').modal('hide');
                            this.displayStatus = "requestAgain";
                            this.resetForm();
                        } else {
                            throw new Error('Failed to submit form.');
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        alert('Inventory PSTW Error: An error occurred.');
                    }
                },
                async fetchItem(itemid) {
                    try {
                        const response = await fetch('/InvMainAPI/GetItem/' + itemid, {
                            method: 'POST',
                        }
                        );

                        if (response.ok) {

                            this.thisItem = await response.json();
                            this.fetchStore(this.thisItem.toStore);

                            if (this.thisItem.movementId != null && this.thisItem.toOther === "On Delivery" && this.thisItem.latestStatus == null && this.thisItem.currentUserId == this.currentUserId && this.thisItem.movementComplete == 0) {
                                this.displayStatus = "arrived";
                            } else if (this.thisItem.movementId != null && this.thisItem.latestStatus != null && this.thisItem.currentUserId == this.currentUserId && this.thisItem.latestStatus != "Ready To Deploy") {
                                this.displayStatus = "return";
                            } else if (this.thisItem.movementId != null && this.thisItem.toOther === "Return" && this.thisItem.latestStatus == null && this.thisItem.toUser == this.currentUserId) {
                                this.displayStatus = "requestAgain";
                            } else {
                                this.displayStatus = "differentUser";
                                this.thisItem = null;
                            }
                        } else {
                            this.error = 'Qr Code Not Register to the system';  
                        }
                    } catch (error) {
                        console.error('Error fetching item information:', 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');
                        }

                        const data = await response.json();
                        this.stationList = data.filter(station => station.stationPicID === this.currentUserId);
                    } catch (error) {
                        console.error('Error fetching suppliers:', error);
                    }
                },

                async fetchStore(storeId) {
                    try {
                        const response = await fetch('/InvMainAPI/StoreSpecificMaster/' + storeId, {
                            method: 'POST', // Specify the HTTP method
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        });
                        if (!response.ok) {
                            throw new Error('Failed to fetch Store');
                        }

                        const data = await response.json();
                        this.InventoryMasterId = data.userId;

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

                async fetchUser() {
                    try {
                        const response = await fetch(`/IdentityAPI/GetUserInformation/`, {
                            method: 'POST',
                        });
                        if (response.ok) {
                            const data = await response.json();
                            this.currentUser = data?.userInfo || null;
                            this.currentUserId = this.currentUser.id;
                        }
                        else {
                            console.error('Failed to fetch user');
                        }
                    }
                    catch (error) {
                        console.error('There was a problem with the fetch operation:', error);
                    }
                },

                resetScanner() {
                    this.displayStatus = null;
                    this.qrCodeResult = null;
                    this.thisItem = null;
                },

                resetForm() {
                    this.selectedStation = null;
                },

                async receiveReturnAPI() {
                    this.receiveReturn = 1;
                    this.updateItemMovement();
                },

                // Split Url dapatkan unique ID Je
                onDecode(detectedCodes) {
                    if (detectedCodes.length > 0) {
                        this.qrCodeResult = detectedCodes[0].rawValue; // Ambil URL dari rawValue
                        this.UniqueID = this.qrCodeResult.split('/').pop(); // Ambil UniqueID dari URL
                        this.fetchItem(this.UniqueID);
                    }
                },

                //Showing Qr Error
                onError(err) {
                    let message = `[${err.name}]: `;
                    if (err.name === "NotAllowedError") {
                        message += "You have to allow camera accecss.";
                    } else if (err.name === "NotFoundError") {
                        message += "There's no camera detect.";
                    } else if (err.name === "NotReadableError") {
                        message += "You are using camera on the other application.";
                    } else {
                        message += err.message;
                    }
                    this.error = message;
                },

                //Setting Camera to know that camera are turn on or not
                async onCameraReady(videoElement) {

                    const video = document.querySelector("video");

                    const track = video.srcObject.getVideoTracks()[0];

                    if (track && track.getCapabilities) {
                        const capabilities = track.getCapabilities(); // Get camera capabilities

                        if (capabilities.sharpness) {
                            track.applyConstraints({
                                advanced: [{ width: 1280, height: 720 }]
                            }).then(() => {

                                // Step 2: Apply sharpness separately
                                return track.applyConstraints({ advanced: [{ sharpness: 10 }] });
                            }).then(() => {

                                return track.applyConstraints({ advanced: [{ exposureMode: 'continuous' }] });
                            })
                            .then(() => {
                            }).catch(err => console.error("Failed to apply constraints:", err));
    
                        } else {
                            console.warn("⚠️ Sharpness not supported on this camera");
                        }
                    }


                    try {
                        const devices = await navigator.mediaDevices.enumerateDevices();
                        this.videoInputDevices = devices.filter(device => device.kind === 'videoinput');

                        if (this.videoInputDevices.length > 0) {
                            // Keep the selected camera if already chosen
                            if (!this.selectedCameraId) {
                                this.selectedCameraId = this.videoInputDevices[0].deviceId;
                            }

                            this.selectedConstraints = { deviceId: { exact: this.selectedCameraId } };
                        } else {
                            this.error = "No camera detected.";
                        }
                    } catch (err) {
                        this.error = "Error accessing camera: " + err.message;
                    }
                },

                //Update Camera Category
                updateCamera() {
                    this.selectedConstraints = { deviceId: { exact: this.selectedCameraId } };
                },

                //Red box if QR Detect
                paintOutline(detectedCodes, ctx) {
                    for (const detectedCode of detectedCodes) {
                        const [firstPoint, ...otherPoints] = detectedCode.cornerPoints;

                        ctx.strokeStyle = 'red'; // Warna garis merah
                        ctx.lineWidth = 3;

                        ctx.beginPath();
                        ctx.moveTo(firstPoint.x, firstPoint.y);
                        for (const { x, y } of otherPoints) {
                            ctx.lineTo(x, y);
                        }
                        ctx.lineTo(firstPoint.x, firstPoint.y);
                        ctx.closePath();
                        ctx.stroke();
                    }
                },

                //Ni return message
                receiveReturnMessage() {
                    $("#returnModal").modal("show");
                },

                closeModal() {
                    $('#returnModal').modal('hide'); // Manually hide the modal
                },

                ReturnMessage() {
                    $("#returnMessage").modal("show");
                },
                
                closeMessageModal() {
                    $('#returnMessage').modal('hide'); // Manually hide the modal
                },

                StationMessage() {
                    $("#stationMessage").modal("show");
                },

                closeStationMessageModal() {
                    $('#stationMessage').modal('hide'); // Manually hide the modal
                },
            },
        });
        app.component("qrcode-stream", VueQrcodeReader.QrcodeStream);

        app.mount('#registerItem');

        $(function () {
            // Attach event listener to show modal
            $('#addItemBtn').on('click', function () {
                $('#registerItemModal').modal('show');
            });

            // Close modals
            $('.closeModal').on('click', function () {
                $('.modal').modal('hide');
            });
        });
    </script>
}
