
@{
    ViewData["Title"] = "Item Movement";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<style>
    @@font-face {
      font-family: 'OCR-A';
      src: url('../assets/fonts/ocraext.ttf');
    }

    .QrPrintFont {
      font-family: 'OCR-A', monospace;
    }
    .table td img {
        display: block !important;
    }


    .text-true {
        color: green;
    }

    .text-false {
        color: red;
    }

    .text-primary {
        color: blue; /* Warna asal untuk 'Receive' */
    }

    .text-warning {
        color: orange; /* Warna oren untuk 'Return' */
    }

    .ms-auto {
        margin-left: auto !important; /* Push Complete/Incomplete to right */
    }


</style>
@await Html.PartialAsync("~/Areas/Inventory/Views/_InventoryPartialUser.cshtml")

<div id="ItemMovement" 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="all">All</option>
                <option value="item">Item</option>
                <option value="station">Station</option>
            </select>
        </div>
    </div>

    <div class="row mb-3" v-if="sortBy === 'item'">
        <h4 class="col-sm-1 col-form-h2" style="min-width:150px;">Search Item:</h4>
        <div class="col-sm-4">
            <input type="text" class="form-control" v-model="searchQuery" placeholder="Search by item code...">
        </div>
    </div>

    <div class="row mb-3" v-if="sortBy === 'station'">
        <h4 class="col-sm-1 col-form-h2" style="min-width:150px;">Search Station:</h4>
        <div class="col-sm-4">
            <input type="text" class="form-control" v-model="searchStation" placeholder="Search by station name...">
        </div>
    </div>

    <div v-if="sortBy === 'all'">
        <div class="row card">
            <div class="card-header">
                <h2>Pending Item Movement</h2>
            </div>
            <div class="card-body">
                <table class="table table-bordered table-hover table-striped no-wrap" id="itemMovementNotCompleteDatatable" style="width:100%;border-style: solid; border-width: 1px"></table>
            </div>
        </div>

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

    <!--------------------------------------------ITEM CATEGORY---------------------------------------------------------------------->
    <div v-if="sortBy === 'item'">
        <div v-for="(group, itemId) in filteredItems" :key="itemId" class="row card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h2>Item : {{ group.uniqueID }}</h2>
                <button class="btn btn-light" v-on:click="toggleCategory(itemId)">
                    <i :class="categoryVisible[itemId] ? 'fas fa-chevron-up' : 'fas fa-chevron-down'"></i> Show Details
                </button>
            </div>

            <!-- Hide all details unless button is clicked -->
            <div v-show="categoryVisible[itemId]" class="card-body">
                <div v-for="(movement, index) in group.movements.sort((a, b) => a.id - b.id).reverse()" :key="movement.id" class="movement-row">
                    <!-- 📌 Show Only Latest Movement -->
                    <div v-if="index === 0" class="row">
                        <strong>Latest Movement</strong>
                        <div class="col-md-12 d-flex flex-wrap align-items-center gap-3 p-2 border-bottom">
                            <!-- Movement Type -->
                            <h3 :class="{'text-primary': movement.toOther === 'On Delivery', 'text-warning': movement.toOther !== 'On Delivery' && movement.action !== 'Assign',
                                         'text-info': movement.action === 'Assign'}"
                                class="flex-shrink-0 text-nowrap"
                                style="max-width:90px; min-width:90px;">

                                {{ movement.action === 'Assign' ? 'Assign' : (movement.toOther === 'On Delivery' ? 'Receive' : 'Return') }}

                            </h3>
 

                            <!-- Send Date -->
                            <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1">
                                <h4 class="fixed-label m-0 text-nowrap">Send Date:</h4>
                                <span class="fixed-value">{{ movement.sendDate }}</span>
                            </div>

                            <!-- Receive Date -->
                            <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1">
                                <h4 class="fixed-label m-0 text-nowrap">Receive Date:</h4>
                                <span class="fixed-value">{{ movement.receiveDate || 'Not arrive' }}</span>
                            </div>

                            <!-- Action -->
                            <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1">
                                <h4 class="fixed-labelStatus m-0 text-nowrap">Action:</h4>
                                <span class="fixed-value">{{ movement.action }}</span>
                            </div>

                            <!-- Status -->
                            <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1">
                                <h4 class="fixed-labelStatus m-0 text-nowrap">Status:</h4>
                                <span class="fixed-value">{{ movement.latestStatus || movement.toOther }}</span>
                            </div>

                            <!-- More Details Button -->
                            <button class="btn btn-info btn-sm ms-auto" v-on:click="toggleDetails(movement.id)">
                                More Details
                            </button>

                            <!-- Completion Status -->
                            <h4 :class="movement.movementComplete == 1 && movement.latestStatus !== 'Ready To Deploy' ? 'text-success' : 'text-danger'"
                                class="text-nowrap ms-3">
                                {{ movement.movementComplete == 1 && movement.latestStatus !== 'Ready To Deploy' ? 'Complete' : (movement.latestStatus === 'Ready To Deploy' ? 'Canceled' : 'Incomplete') }}
                            </h4>

                        </div>

                        <div v-show="detailsVisible[movement.id]" class="col-md-12 mt-2">
                            <div class="row">
                                <div class="col-md-4 text-center">
                                    <!-- Conditionally render Start Icon -->
                                    <i v-if="movement.toOther !== 'On Delivery'" class="fas fa-user fa-2x"></i>
                                    <i v-else class="fas fa-warehouse fa-2x"></i>
                                    <p><strong>Start</strong></p>
                                    <p v-if="movement.toUser !== null"><strong>User:</strong> {{ movement.toUserName }}</p>
                                    <p v-if="movement.toStation !== null"><strong>Station:</strong> {{ movement.toStationName }}</p>
                                    <p v-if="movement.toStore !== null"><strong>Store:</strong> {{ movement.toStoreName }}</p>
                                </div>
                                <div class="col-md-4 text-center">
                                    <p></p>
                                    <i class="fas fa-arrow-right fa-2x"></i>
                                    <p>{{ movement.latestStatus || movement.toOther }}</p>
                                    <p>
                                        <button class="btn btn-info btn-sm ms-auto" v-on:click="remark(movement.remark)">
                                            Remark
                                        </button>
                                    </p>
                                    <p>
                                        <button class="btn btn-info btn-sm ms-auto" v-on:click="consignmentNote(movement.consignmentNote)">
                                            Consignment Note
                                        </button>
                                    </p>
                                </div>
                                <div class="col-md-4 text-center">
                                    <!-- Conditionally render End Icon -->
                                    <i v-if="movement.lastStation" class="fas fa-map-marker-alt"></i>
                                    <i v-v-else-if="movement.toOther !== 'On Delivery'" class="fas fa-warehouse fa-2x"></i>
                                    <i v-else class="fas fa-user fa-2x"></i>
                                    <p><strong>End</strong></p>
                                    <p v-if="movement.lastUser !== null"><strong>User:</strong> {{ movement.lastUserName }}</p>
                                    <p v-if="movement.lastStation !== null"><strong>Station:</strong> {{ movement.lastStationName }}</p>
                                    <p v-if="movement.lastStore !== null"><strong>Store:</strong> {{ movement.lastStoreName }}</p>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

                <!-- 📌 Single View History Button -->
                <button class="btn btn-light w-100 text-left" v-on:click="toggleHistory(itemId)">
                    <i :class="historyVisible[itemId] ? 'fas fa-chevron-up' : 'fas fa-chevron-down'"></i> View History
                </button>

                <div v-show="historyVisible[itemId]" class="history-row">
                    <div v-for="(movement, i) in group.movements.slice(1)" :key="i" class="row mt-2">
                        <div class="col-md-12 d-flex flex-wrap align-items-center gap-3 p-2 border-bottom">
                            <!-- Movement Type -->
                            <h3 :class="{'text-primary': movement.toOther === 'On Delivery', 'text-warning': movement.toOther !== 'On Delivery' && movement.action !== 'Assign',
                                         'text-info': movement.action === 'Assign'}"
                                class="flex-shrink-0 text-nowrap"
                                style="max-width:90px; min-width:90px;">

                                {{ movement.action === 'Assign' ? 'Assign' : (movement.toOther === 'On Delivery' ? 'Receive' : 'Return') }}

                            </h3>

                            <!-- Send Date -->
                            <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1" style="max-width:285px; min-width:285px;">
								<h4 class="fixed-label m-0 text-nowrap">Send Date:</h4>
                                <span class="fixed-value text-truncate">{{ movement.sendDate }}</span>
                            </div>

                            <!-- Receive Date -->
                            <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1" style="max-width:290px; min-width:290px;">
                                <h4 class="fixed-label m-0 text-nowrap">Receive Date:</h4>
                                <span class="fixed-value text-truncate" style="max-width:160px;">{{ movement.receiveDate || 'Not arrive' }}</span>
                            </div>

                            <!-- Action -->
                            <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1" style="max-width:150px; min-width:150px;">
                                <h4 class="fixed-labelStatus m-0 text-nowrap">Action:</h4>
                                <span class="fixed-value text-truncate">{{ movement.action }}</span>
                            </div>

                            <!-- Status -->
                            <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1" style="max-width:160px; min-width:160px;">
                                <h4 class="fixed-labelStatus m-0 text-nowrap">Status:</h4>
                                <span class="fixed-value text-truncate" style="max-width:90px;">{{ movement.latestStatus || movement.toOther }}</span>
                            </div>

                            <!-- More Details Button -->
                            <button class="btn btn-info btn-sm ms-auto"v-on:click="toggleDetails(movement.id)">
                                More Details
                            </button>

                            <!-- Completion Status -->
                            <h4 :class="movement.movementComplete == 1 && movement.latestStatus !== 'Ready To Deploy' ? 'text-success' : 'text-danger'"
                                class="text-nowrap ms-3">
                                {{ movement.movementComplete == 1 && movement.latestStatus !== 'Ready To Deploy' ? 'Complete' : (movement.latestStatus === 'Ready To Deploy' ? 'Canceled' : 'Incomplete') }}
                            </h4>
                        </div>


                        <!-- 📌 Details Section (Hidden by Default) -->
                        <div v-show="detailsVisible[movement.id]" class="col-md-12 mt-2">
                            <div class="row">
                                <div class="col-md-4 text-center">
                                    <!-- Conditionally render Start Icon -->
                                    <i v-if="movement.toOther !== 'On Delivery'" class="fas fa-user fa-2x"></i>
                                    <i v-else class="fas fa-warehouse fa-2x"></i>
                                    <p><strong>Start</strong></p>
                                    <p v-if="movement.toUser !== null"><strong>User:</strong> {{ movement.toUserName }}</p>
                                    <p v-if="movement.toStation !== null"><strong>Station:</strong> {{ movement.toStationName }}</p>
                                    <p v-if="movement.toStore !== null"><strong>Store:</strong> {{ movement.toStoreName }}</p>
                                </div>
                                <div class="col-md-4 text-center">
                                    <p></p>
                                    <i class="fas fa-arrow-right fa-2x"></i>
                                    <p>{{ movement.latestStatus || movement.toOther }}</p>
                                    <p>
                                        <button class="btn btn-info btn-sm ms-auto" v-on:click="remark(movement.remark)">
                                            Remark
                                        </button>
                                    </p>
                                    <p>
                                        <button class="btn btn-info btn-sm ms-auto" v-on:click="consignmentNote(movement.consignmentNote)">
                                            Consignment Note
                                        </button>
                                    </p>
                                </div>
                                <div class="col-md-4 text-center">
                                    <!-- Conditionally render End Icon -->
                                    <i v-if="movement.lastStation" class="fas fa-map-marker-alt"></i>
                                    <i v-else-if="movement.toOther !== 'On Delivery'" class="fas fa-warehouse fa-2x"></i>
                                    <i v-else class="fas fa-user fa-2x"></i>
                                    <p><strong>End</strong></p>
                                    <p v-if="movement.lastUser !== null"><strong>User:</strong> {{ movement.lastUserName }}</p>
                                    <p v-if="movement.lastStation !== null"><strong>Station:</strong> {{ movement.lastStationName }}</p>
                                    <p v-if="movement.lastStore !== null"><strong>Store:</strong> {{ movement.lastStoreName }}</p>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

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


    <!--------------------------------------------STATION CATEGORY---------------------------------------------------------------------->
    <div v-if="sortBy === 'station'">
        <div v-for="(items, station) in filteredStation" :key="stationName" :class="{'bg-light-gray': station === 'Unassign Station', 'bg-white': station !== 'Unassign Station'}"   class="station-category card mt-3">
            <!-- 📌 Station Header -->
            <div class="card-header d-flex justify-content-between align-items-center">
                <h3>{{ station }}</h3>
                <button class="btn btn-light" v-on:click="toggleCategory(station)">
                    <i :class="categoryVisible[station] ? 'fas fa-chevron-up' : 'fas fa-chevron-down'"></i> Show Items
                </button>
            </div>

            <!-- 📌 Show Items Under Each Station -->
            <div v-show="categoryVisible[station]" class="card-body">
                <div v-for="(group, itemId) in items" :key="itemId" class="row card">
                    <!-- 📌 Item Header -->
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h2>Item : {{ group.uniqueID }}</h2>
                        <button class="btn btn-light" v-on:click="toggleCategory(itemId)">
                            <i :class="categoryVisible[itemId] ? 'fas fa-chevron-up' : 'fas fa-chevron-down'"></i> Show Details
                        </button>
                    </div>

                    <!-- 📌 Show Movements for Each Item -->
                    <div v-show="categoryVisible[itemId]" class="card-body">
                        <div v-for="(movement, index) in group.movements.sort((a, b) => a.id - b.id).reverse()" :key="movement.id" class="movement-row">
                            <div v-if="index === 0" class="row">
                                <strong>Latest Movement</strong>
                                <div class="col-md-12 d-flex flex-wrap align-items-center gap-3 p-2 border-bottom">
                                    <h3 :class="{'text-primary': movement.toOther === 'On Delivery', 'text-warning': movement.toOther !== 'On Delivery' && movement.action !== 'Assign',
                                         'text-info': movement.action === 'Assign'}"
                                        class="flex-shrink-0 text-nowrap"
                                        style="max-width:90px; min-width:90px;">

                                        {{ movement.action === 'Assign' ? 'Assign' : (movement.toOther === 'On Delivery' ? 'Receive' : 'Return') }}

                                    </h3>

                                    <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1">
                                        <h4 class="fixed-label m-0 text-nowrap">Send Date:</h4>
                                        <span class="fixed-value">{{ movement.sendDate }}</span>
                                    </div>

                                    <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1">
                                        <h4 class="fixed-label m-0 text-nowrap">Receive Date:</h4>
                                        <span class="fixed-value">{{ movement.receiveDate || 'Not arrive' }}</span>
                                    </div>

                                    <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1">
                                        <h4 class="fixed-labelStatus m-0 text-nowrap">Action:</h4>
                                        <span class="fixed-value">{{ movement.action }}</span>
                                    </div>

                                    <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1">
                                        <h4 class="fixed-labelStatus m-0 text-nowrap">Status:</h4>
                                        <span class="fixed-value">{{ movement.latestStatus || movement.toOther }}</span>
                                    </div>

                                    <button class="btn btn-info btn-sm ms-auto" v-on:click="toggleDetails(movement.id)">
                                        More Details
                                    </button>

                                    <h4 :class="movement.movementComplete == 1 && movement.latestStatus !== 'Ready To Deploy' ? 'text-success' : 'text-danger'" class="text-nowrap ms-3">
                                        {{ movement.movementComplete == 1 && movement.latestStatus !== 'Ready To Deploy' ? 'Complete' : (movement.latestStatus === 'Ready To Deploy' ? 'Canceled' : 'Incomplete') }}
                                    </h4>
                                </div>

                                <div v-show="detailsVisible[movement.id]" class="col-md-12 mt-2">
                                    <div class="row">
                                        <div class="col-md-4 text-center">
                                            <i v-if="movement.toOther !== 'On Delivery'" class="fas fa-user fa-2x"></i>
                                            <i v-else class="fas fa-warehouse fa-2x"></i>
                                            <p><strong>Start</strong></p>
                                            <p v-if="movement.toUser !== null"><strong>User:</strong> {{ movement.toUserName }}</p>
                                            <p v-if="movement.toStation !== null"><strong>Station:</strong> {{ movement.toStationName }}</p>
                                            <p v-if="movement.toStore !== null"><strong>Store:</strong> {{ movement.toStoreName }}</p>
                                        </div>
                                        <div class="col-md-4 text-center">
                                            <i class="fas fa-arrow-right fa-2x"></i>
                                            <p>{{ movement.latestStatus || movement.toOther }}</p>
                                            <p>
                                                <button class="btn btn-info btn-sm ms-auto" v-on:click="remark(movement.remark)">
                                                    Remark
                                                </button>
                                            </p>
                                            <p>
                                                <button class="btn btn-info btn-sm ms-auto" v-on:click="consignmentNote(movement.consignmentNote)">
                                                    Consignment Note
                                                </button>
                                            </p>
                                        </div>
                                        <div class="col-md-4 text-center">
                                            <i v-if="movement.lastStation" class="fas fa-map-marker-alt"></i>
                                            <i v-else-if="movement.toOther !== 'On Delivery'" class="fas fa-warehouse fa-2x"></i>
                                            <i v-else class="fas fa-user fa-2x"></i>
                                            <p><strong>End</strong></p>
                                            <p v-if="movement.lastUser !== null"><strong>User:</strong> {{ movement.lastUserName }}</p>
                                            <p v-if="movement.lastStation !== null"><strong>Station:</strong> {{ movement.lastStationName }}</p>
                                            <p v-if="movement.lastStore !== null"><strong>Store:</strong> {{ movement.lastStoreName }}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 📌 Single View History Button -->
                        <button class="btn btn-light w-100 text-left" v-on:click="toggleHistory(itemId)">
                            <i :class="historyVisible[itemId] ? 'fas fa-chevron-up' : 'fas fa-chevron-down'"></i> View History
                        </button>

                        <div v-show="historyVisible[itemId]" class="history-row">
                            <div v-for="(movement, i) in group.movements.slice(1)" :key="i" class="row mt-2">
                                <div class="col-md-12 d-flex flex-wrap align-items-center gap-3 p-2 border-bottom">
                                    <!-- Movement Type -->
                                    <h3 :class="{'text-primary': movement.toOther === 'On Delivery', 'text-warning': movement.toOther !== 'On Delivery' && movement.action !== 'Assign',
                                         'text-info': movement.action === 'Assign'}" class="flex-shrink-0 text-nowrap" style="max-width:90px; min-width:90px;">
                                         {{ movement.action === 'Assign' ? 'Assign' : (movement.toOther === 'On Delivery' ? 'Receive' : 'Return') }} 
                                    </h3>

                                    <!-- Send Date -->
                                    <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1" style="max-width:285px; min-width:285px;">
                                        <h4 class="fixed-label m-0 text-nowrap">Send Date:</h4>
                                        <span class="fixed-value text-truncate">{{ movement.sendDate }}</span>
                                    </div>

                                    <!-- Receive Date -->
                                    <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1" style="max-width:290px; min-width:290px;">
                                        <h4 class="fixed-label m-0 text-nowrap">Receive Date:</h4>
                                        <span class="fixed-value text-truncate" style="max-width:160px;">{{ movement.receiveDate || 'Not arrive' }}</span>
                                    </div>

                                    <!-- Action -->
                                    <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1" style="max-width:150px; min-width:150px;">
                                        <h4 class="fixed-labelStatus m-0 text-nowrap">Action:</h4>
                                        <span class="fixed-value text-truncate">{{ movement.action }}</span>
                                    </div>

                                    <!-- Status -->
                                    <div class="d-flex flex-wrap align-items-center gap-2 flex-grow-1" style="max-width:160px; min-width:160px;">
                                        <h4 class="fixed-labelStatus m-0 text-nowrap">Status:</h4>
                                        <span class="fixed-value text-truncate" style="max-width:90px;">{{ movement.latestStatus || movement.toOther }}</span>
                                    </div>

                                    <!-- More Details Button -->
                                    <button class="btn btn-info btn-sm ms-auto" v-on:click="toggleDetails(movement.id)">
                                        More Details
                                    </button>

                                    <!-- Completion Status -->
                                    <h4 :class="movement.movementComplete == 1 && movement.latestStatus !== 'Ready To Deploy' ? 'text-success' : 'text-danger'"
                                        class="text-nowrap ms-3">
                                        {{ movement.movementComplete == 1 && movement.latestStatus !== 'Ready To Deploy' ? 'Complete' : (movement.latestStatus === 'Ready To Deploy' ? 'Canceled' : 'Incomplete') }}
                                    </h4>
                                </div>


                                <!-- 📌 Details Section (Hidden by Default) -->
                                <div v-show="detailsVisible[movement.id]" class="col-md-12 mt-2">
                                    <div class="row">
                                        <div class="col-md-4 text-center">
                                            <!-- Conditionally render Start Icon -->
                                            <i v-if="movement.toOther !== 'On Delivery'" class="fas fa-user fa-2x"></i>
                                            <i v-else class="fas fa-warehouse fa-2x"></i>
                                            <p><strong>Start</strong></p>
                                            <p v-if="movement.toUser !== null"><strong>User:</strong> {{ movement.toUserName }}</p>
                                            <p v-if="movement.toStation !== null"><strong>Station:</strong> {{ movement.toStationName }}</p>
                                            <p v-if="movement.toStore !== null"><strong>Store:</strong> {{ movement.toStoreName }}</p>
                                        </div>
                                        <div class="col-md-4 text-center">
                                            <p></p>
                                            <i class="fas fa-arrow-right fa-2x"></i>
                                            <p>{{ movement.latestStatus || movement.toOther }}</p>
                                            <p>
                                                <button class="btn btn-info btn-sm ms-auto" v-on:click="remark(movement.remark)">
                                                    Remark
                                                </button>
                                            </p>
                                            <p>
                                                <button class="btn btn-info btn-sm ms-auto" v-on:click="consignmentNote(movement.consignmentNote)">
                                                    Consignment Note
                                                </button>
                                            </p>
                                        </div>
                                        <div class="col-md-4 text-center">
                                            <!-- Conditionally render End Icon -->
                                            <i v-if="movement.lastStation" class="fas fa-map-marker-alt"></i>
                                            <i v-else-if="movement.toOther !== 'On Delivery'" class="fas fa-warehouse fa-2x"></i>
                                            <i v-else class="fas fa-user fa-2x"></i>
                                            <p><strong>End</strong></p>
                                            <p v-if="movement.lastUser !== null"><strong>User:</strong> {{ movement.lastUserName }}</p>
                                            <p v-if="movement.lastStation !== null"><strong>Station:</strong> {{ movement.lastStationName }}</p>
                                            <p v-if="movement.lastStore !== null"><strong>Store:</strong> {{ movement.lastStoreName }}</p>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>

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

    <!--------------------------------------------REMARK & CONSIGNMENT NOTE CATEGORY---------------------------------------------------------------------->
    <div class="modal fade" id="remarkModal" tabindex="-1" aria-labelledby="remarkModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="remarkModalLabel">Remark</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="remarkContent">
                    <!-- Remark Content Here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="consignmentModal" tabindex="-1" aria-labelledby="consignmentModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="consignmentModalLabel">Consignment Note</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <img v-if="/\.(jpeg|jpg|png|gif)$/i.test(consignmentNoteUrl)" :src="consignmentNoteUrl" class="img-fluid" alt="Consignment Note Image">
                    <iframe v-else-if="/\.pdf$/i.test(consignmentNoteUrl)" :src="consignmentNoteUrl" style="width:100%; height: 80vh;"></iframe>
                    <a v-else class="btn btn-primary">There's no Folder or Picture</a>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
@{
    await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
<script>
    $(function () {
        app.mount('#ItemMovement');
    });
        const app = Vue.createApp({
            data() {
                return {
                    itemMovements: [],
                    itemMovementCompleteDatatable: null,
                    itemMovementNotCompleteDatatable: null,
                    searchQuery: "",
                    searchStation: "",
                    sortBy: "all",
                    historyVisible: {},
                    detailsVisible: {},
                    categoryVisible: {},
                    consignmentNoteUrl: "",
                    stationName: "",
                };
            },
            computed: {
                groupedItems() {
                    return this.itemMovements.reduce((acc, movement) => {
                        if (!acc[movement.itemId]) {
                            acc[movement.itemId] = {
                                uniqueID: movement.uniqueID,
                                movements: [],
                            };
                        }
                        acc[movement.itemId].movements.push(movement);
                        return acc;
                    }, {});
                },
                groupedByStation() {
                    let grouped = {};
                    this.itemMovements.forEach((movement) => {
                        let station = movement.toStationName || movement.lastStationName || "Unassign Station";
                        let itemId = movement.uniqueID;

                        if (!grouped[station]) {
                            grouped[station] = {};
                        }

                        if (!grouped[station][itemId]) {
                            grouped[station][itemId] = { uniqueID: itemId, movements: [] };
                        }

                        grouped[station][itemId].movements.push(movement);
                    });

                    // Sort stations and move "Unassign Station" to the last position
                    let sortedKeys = Object.keys(grouped).sort((a, b) => {
                        if (a === "Unassign Station") return 1; // Move Unassign Station to the end
                        if (b === "Unassign Station") return -1;
                        return a.localeCompare(b); // Normal sorting for other stations
                    });

                    let sortedGrouped = {};
                    sortedKeys.forEach((key) => {
                        sortedGrouped[key] = grouped[key];
                    });

                    return sortedGrouped;
                },
                filteredItems() {
                    if (!this.searchQuery.trim()) {
                        return this.groupedItems;
                    }
                    const searchLower = this.searchQuery.toLowerCase();
                    return Object.fromEntries(
                        Object.entries(this.groupedItems).filter(([_, group]) =>
                            group.uniqueID.toLowerCase().includes(searchLower)
                        )
                    );
                },
                filteredStation() {
                    if (!this.searchStation) {
                        return this.groupedByStation;
                    }

                    let searchQuery = this.searchStation.toLowerCase();
                    let grouped = this.groupedByStation;
                    let filtered = {};

                    Object.keys(grouped).forEach(station => {
                        if (station.toLowerCase().includes(searchQuery)) {
                            filtered[station] = grouped[station];
                        }
                    });

                    return filtered;
                },
            },
            mounted() {
                this.fetchItemMovement();
            },
            methods: {
                remark(remark) {
                    document.getElementById("remarkContent").innerText = remark || "No remark message provide.";
                    let modal = new bootstrap.Modal(document.getElementById("remarkModal"));
                    modal.show();
                },

                consignmentNote(consignmentNote) {
                    if (!consignmentNote) {
                        this.consignmentNoteUrl = "No consignment note available.";
                        new bootstrap.Modal(document.getElementById('consignmentModal')).show();
                        return;
                    }

                    // Pastikan URL betul
                    this.consignmentNoteUrl = consignmentNote;

                    // Tunggu Vue update sebelum buka modal
                    this.$nextTick(() => {
                        new bootstrap.Modal(document.getElementById('consignmentModal')).show();
                    });
                },

                async fetchItemMovement() {
                    try {
                        const response = await fetch("/InvMainAPI/ItemMovementUser", {
                            method: "POST",
                            headers: { "Content-Type": "application/json" },
                        });

                        if (!response.ok) throw new Error("Failed to fetch item movement");

                        const data = await response.json();
                        this.itemMovements = data.map((movement) => ({
                            ...movement,
                            showDetails: false,
                        }));

                        this.renderTables();
                    } catch (error) {
                        console.error("Error fetching item:", error);
                    }
                },

                renderTables() {
                    if (this.sortBy === "all") {
                        this.initAllTables();
                    }
                },
                initAllTables() {
                    if (this.itemMovementNotCompleteDatatable) {
                        this.itemMovementNotCompleteDatatable.destroy();
                    }
                    if (this.itemMovementCompleteDatatable) {
                        this.itemMovementCompleteDatatable.destroy();
                    }

                    this.itemMovementNotCompleteDatatable = $("#itemMovementNotCompleteDatatable").DataTable({
                        data: this.itemMovements.filter((m) => m.movementComplete == 0),
                        columns: [
                            { title: "Unique Id", data: "id" },
                            { title: "Product Code", data: "uniqueID" },
                            { title: "From User", data: "toUserName" },
                            { title: "Last User", data: "lastUserName" },
                            { title: "From Station", data: "toStationName" },
                            { title: "From Store", data: "toStoreName" },
                            { title: "Action", data: "action" },
                            { title: "Start Status", data: "toOther" },
                            { title: "Quantity", data: "quantity" },
                            { title: "Send Date", data: "sendDate" },
                            {
                                title: "Note", 
                                data: "consignmentNote",
                                render: function (data, type, full, meta) {
                                    if (!data) {
                                        return "No Document";
                                    }

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

                                    if (isImage) {
                                        return `<a href="${data}" target="_blank" data-lightbox="image-1">
                                                                <img src="${data}" alt="Image" class="img-thumbnail" style="width: 100px; height: 100px;" />
                                                            </a>`;
                                    }
                                    else if (isPdf) {
                                        return `<a href="${data}" 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>`;
                                    } else {
                                        return `<a href="${data}" target="_blank">Download File</a>`;
                                    }
                                },
                            },
                            { title: "Remark", data: "remark" },
                        ],
                        responsive: true,
                    });

                    this.itemMovementCompleteDatatable = $("#itemMovementCompleteDatatable").DataTable({
                        data: this.itemMovements.filter((m) => m.movementComplete == 1),
                        columns: [
                            { title: "Unique Id", data: "id" },
                            { title: "Product Code", data: "uniqueID" },
                            { title: "From User", data: "toUserName" },
                            { title: "Last User", data: "lastUserName" },
                            { title: "From Station", data: "toStationName" },
                            { title: "Last Station", data: "lastStationName" },
                            { title: "From Store", data: "toStoreName" },
                            { title: "Last Store", data: "lastStoreName" },
                            { title: "Action", data: "action" },
                            { title: "Start Status", data: "toOther" },
                            { title: "Latest Status", data: "latestStatus" },
                            { title: "Qty", data: "quantity" },
                            { title: "Send Date", data: "sendDate" },
                            { title: "Receive Date", data: "receiveDate" },
                            { title: "Note", 
                              data: "consignmentNote",
                              render: function (data, type, full, meta) {
                                    if (!data) {
                                        return "No Document";
                                    }

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

                                    if (isImage) {
                                        return `<a href="${data}" target="_blank" data-lightbox="image-1">
                                                                <img src="${data}" alt="Image" class="img-thumbnail" style="width: 100px; height: 100px;" />
                                                            </a>`;
                                    }
                                    else if (isPdf) {
                                        return `<a href="${data}" 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>`;
                                    } else {
                                        return `<a href="${data}" target="_blank">Download File</a>`;
                                    }
                              },
                            },
                            { title: "Remark", data: "remark" },
                        ],
                        responsive: true,
                    });
                },
                toggleCategory(itemId) {
                    this.categoryVisible[itemId] = !this.categoryVisible[itemId];
                },
                toggleHistory(itemId) {
                    this.historyVisible[itemId] = !this.historyVisible[itemId];
                },
                toggleDetails(movementId) {
                    this.detailsVisible[movementId] = !this.detailsVisible[movementId];
                },
                handleSorting() {
                    this.renderTables();
                },
            },
        });

</script>
}