@extends('layouts.app')
@section('title', 'Transfer Order')

@section('content')
    <div class="container-fluid py-4" id="transfer-page" style="min-height:100vh; background-color:#fffaf7;">

        <h3 class="text-center mb-4 fw-bold" style="color:#2b3e55">📦 Transfer Order (Material)</h3>


        <!-- ===================== FILTER & SEARCH ===================== -->
        <div class="row mb-3 justify-content-center">
            <div class="col-md-4 mb-2">
                <input type="text" id="searchInput" class="form-control shadow-sm" placeholder="🔍 Search item...">
            </div>
            <div class="col-md-3 mb-2">
                <select id="filterSelect" class="form-select shadow-sm">
                    <option value="">All Replenishment Systems</option>
                    <option value="Transfer">Transfer</option>
                    <option value="Purchase">Purchase</option>
                    <option value="Production">Production</option>
                </select>
            </div>
            <div class="col-md-2 mb-2 text-center">
                <button class="btn btn-primary w-auto fw-semibold" id="createTO" disabled>
                    ➕ Create Transfer Order
                </button>
            </div>
        </div>
        <!-- ===================== NAVIGATION LOCATION ===================== -->
        <ul class="nav nav-tabs mb-3" id="locationTabs" style="border-color:#d1d1d1;">
            <!-- Filled by JS -->
        </ul>
        <!-- Skeleton Loader -->
        <div id="skeletonContainer">
            @for ($i = 0; $i < 6; $i++)
                <div class="card mb-3 shadow-sm p-3 border-0 rounded-4 skeleton-card">
                    <div class="placeholder-glow">
                        <div class="placeholder col-1 me-3" style="height: 24px;"></div>
                        <div class="placeholder col-3" style="height: 24px;"></div>
                        <div class="placeholder col-2 ms-auto" style="height: 24px;"></div>
                    </div>
                </div>
            @endfor
        </div>

        <!-- ===================== TABLE PER LOKASI ===================== -->
        <div id="locationTabContent"></div>
    </div>

    <!-- Floating Button -->
    <button id="createTOstick"
        class="btn btn-primary fw-semibold shadow-lg d-flex align-items-center justify-content-center floating-btn"
        title="Create Transfer Order" disabled>
        ➕
    </button>

    <!-- ===================== MODAL CREATE TO ===================== -->
    <div class="modal fade" id="toModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content border-0 shadow-sm" style="border-radius: 1rem;">
                <div class="modal-header text-white" style="background:#9FCBE6;">
                    <h5 class="modal-title fw-semibold">Create Transfer Order</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"
                        aria-label="Close"></button>
                </div>

                <div class="modal-body p-4">
                    <form id="toForm">

                        <!-- HEADER -->
                        <div class="border rounded-3 p-3 mb-4 bg-light">
                            <h6 class="fw-semibold text-primary mb-3">Header Information</h6>

                            <div class="row g-3">

                                <!-- NO SERIES -->
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">No. Series</label>
                                    <select id="to_noSeries" class="form-select" disabled>
                                        <option value="TO.RBC" selected>RBC</option>
                                    </select>
                                </div>

                                <!-- TRANSFER SPEC -->
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">Transfer Spec</label>
                                    <select id="to_transSpec" class="form-select">
                                        <option value="TO.EXT BU" selected>Transfer Antar Business Unit</option>
                                        <option value="ST. ORDER" selected>Transfer Internal Business Unit</option>
                                    </select>
                                </div>

                                <!-- LOCATION (ACTIVE LOCATION AUTO) -->
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">Location</label>
                                    <input id="to_location" class="form-control" disabled>
                                </div>

                                <!-- TRANSFER FROM -->
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">Transfer From</label>
                                    <select id="to_transferFrom" class="form-select">
                                        <option value="CI.1010">Food Central (CI.1010)</option>
                                        <option value="CI.1011">Butcher (CI.1011)</option>
                                        <option value="CI.1012">Pastry & Bakery (CI.1012)</option>
                                        <option value="CI.1020">Operational (CI.1020)</option>
                                        <option value="CI.3000">Maintenance (CI.3000)</option>
                                    </select>
                                </div>

                                <!-- TRANSFER TO -->
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">Transfer To</label>
                                    <select id="to_transferTo" class="form-select">
                                        <option value="RBC.2100">2100</option>
                                        <option value="RBC.2110">2110</option>
                                        <option value="RBC.2120">2120</option>
                                        <option value="RBC.2130">2130</option>
                                        <option value="RBC.2140">2140</option>
                                    </select>
                                </div>

                                <!-- DEPARTMENT -->
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">Department</label>
                                    <input type="text" id="to_department" class="form-control">
                                </div>

                                <!-- TRANSFER TYPE -->
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">Transfer Type</label>
                                    <select id="to_transferType" class="form-select">
                                        <option value="BEVERAGE">BEVERAGE</option>
                                        <option value="MARKET LIST">MARKET LIST</option>
                                        <option value="OTHER">OTHER</option>
                                    </select>
                                </div>

                                <!-- BUSINESS UNIT (NEW) -->
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">Business Unit</label>
                                    <input type="text" id="to_businessUnit" value="RBC" class="form-control"
                                        disabled>
                                </div>

                            </div>
                        </div>




                        <!-- ITEM LINES -->
                        <div class="border rounded-3 p-3 bg-light">
                            <h6 class="fw-semibold text-primary mb-3">Item Lines</h6>

                            <table class="table align-middle" id="selectedItems">
                                <thead class="table-light">
                                    <tr>
                                        <th>Item No</th>
                                        <th>Description</th>
                                        <th>Qty</th>
                                        <th>UoM</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>

                        <div class="d-grid mt-4">
                            <button class="btn text-white fw-semibold" type="submit" style="background-color:#7DC5E3;">
                                <i class="bi bi-arrow-repeat me-1"></i>
                                Create TO
                            </button>
                        </div>

                    </form>
                </div>

            </div>
        </div>
    </div>
   @push('scripts')
<style>
/* ===== SORT ICON ===== */
.sort-icon-mini {
    width: 7px;
    height: 7px;
    border-right: 2px solid #666;
    border-bottom: 2px solid #666;
    position: absolute;
    right: 6px;
    top: 50%;
    translate: 0 -50%;
    opacity: .3;
    transform: rotate(45deg);
    transition: .18s;
}
.sort-icon-mini.asc { opacity: 1; transform: rotate(225deg); }
.sort-icon-mini.desc { opacity: 1; transform: rotate(45deg); }

/* ===== TABLE ===== */
.small-table th,
.small-table td {
    font-size: 12px !important;
    white-space: nowrap;
    color: #2b3e55;
}

/* ===== TAB ACTIVE (SAMA DENGAN TABLE HEADER) ===== */
.nav-link.active-custom {
    color: #000000 !important;
    background-color: #f3e8d2 !important; /* sama seperti table-light */
    border-radius: 6px;
    border: 1px solid #e6d5c3;
    font-weight: 700;
}

/* ===== FLOATING BUTTON ===== */
.floating-btn {
    position: fixed;
    bottom: 24px;
    right: 24px;
    width: 56px;
    height: 56px;
    border-radius: 50%;
    z-index: 1050;
    font-size: 1.5rem;
    transition: all 0.25s ease;
}
.floating-btn:hover { transform: scale(1.08); }

/* Skeleton loader */
.skeleton-card .placeholder {
    border-radius: 10px;
    background: linear-gradient(90deg, #f0ece9 25%, #f6f3f1 50%, #f0ece9 75%);
    animation: shimmer 1.5s infinite;
}
@keyframes shimmer {
    0% { background-position: -200% 0; }
    100% { background-position: 200% 0; }
}
</style>


<script>
document.addEventListener("DOMContentLoaded", function() {

    // ===================================================================
    // GLOBAL VAR
    // ===================================================================
    const skeleton = $('#skeletonContainer');
    const tabs     = $('#locationTabs');
    const tabContent = $('#locationTabContent');

    let LOCATION_MAP  = {};
    let LOCATION_KEYS = [];
    window.activeLocation = null;
    window.selectedItemsPerLocation = {};

    function safeLoc(loc) {
        return String(loc).replace(/\./g, "_");
    }

    // ===================================================================
    // FETCH COMBINED STOCK
    // ===================================================================
    $.get("{{ route('bc.combined-stock') }}", function(res) {

        if (!res || !res.items) {
            tabContent.html(`<p class="text-center text-muted">No data.</p>`);
            return;
        }

        LOCATION_MAP  = res.items;
        LOCATION_KEYS = Object.keys(LOCATION_MAP);

        if (!LOCATION_KEYS.length) {
            tabContent.html(`<p class="text-center text-muted">Empty results.</p>`);
            return;
        }

        window.activeLocation = LOCATION_KEYS[0];

        buildTabs();
        buildTables();
        renderTable(window.activeLocation);

        skeleton.hide();
    });

    // ===================================================================
    // BUILD TABS
    // ===================================================================
    function buildTabs() {
        tabs.empty();

        LOCATION_KEYS.forEach((loc, idx) => {

            const li = $(`
                <li class="nav-item">
                    <a class="nav-link ${idx === 0 ? 'active-custom' : ''}"
                       data-loc="${loc}" style="cursor:pointer; font-weight:600;">
                        ${loc}
                    </a>
                </li>
            `);

            li.on("click", function() {

                const selectedLoc = $(this).find("a").data("loc");
                window.activeLocation = selectedLoc;

                tabs.find(".nav-link").removeClass("active-custom");
                $(this).find(".nav-link").addClass("active-custom");

                tabContent.children().addClass("d-none");
                const safe = safeLoc(selectedLoc);
                $(`#tbl-${safe}`).removeClass("d-none");

                if (!window.selectedItemsPerLocation[selectedLoc]) {
                    window.selectedItemsPerLocation[selectedLoc] = [];
                }

                updateButtons();
                renderTable(selectedLoc);
            });

            tabs.append(li);
        });
    }

    // ===================================================================
    // BUILD TABLE STRUCTURES
    // ===================================================================
    function buildTables() {

        tabContent.empty();

        LOCATION_KEYS.forEach(loc => {

            const safe = safeLoc(loc);
            const visible = loc === window.activeLocation ? "" : "d-none";

            tabContent.append(`
                <div id="tbl-${safe}" class="${visible}">
                    <table class="table table-hover small-table">
                        <thead class="table-light header-${safe}">
                            <tr>
                                <th>#</th>
                                <th>Item No</th>
                                <th>Description</th>
                                <th>Min Stock</th>
                                <th>Max Stock</th>
                                <th>Inventory</th>
                                <th>Status</th>
                                <th>UoM</th>
                                <th>Unit Cost</th>
                                <th>Total Cost</th>
                            </tr>
                        </thead>
                        <tbody class="tbody-${safe}"></tbody>
                    </table>
                </div>
            `);
        });

        setTimeout(initSortingHeaders, 80);
    }

    // ===================================================================
    // RENDER TABLE
    // ===================================================================
    function renderTable(loc) {

        const safe = safeLoc(loc);
        const table = $(`.tbody-${safe}`);
        table.empty();

        const rows = LOCATION_MAP[loc] || [];

        if (!rows.length) {
            table.append(`<tr><td colspan="10" class="text-center text-muted">No items</td></tr>`);
            return;
        }

        rows.forEach(item => appendRow(loc, item, table));
    }

    // ===================================================================
    // APPEND ROW
    // ===================================================================
    function appendRow(loc, item, table) {

        const checked = (window.selectedItemsPerLocation[loc] || [])
            .some(i => i.Item_No === item.Item_No) ? "checked" : "";

        const html = `
            <tr>
                <td><input type="checkbox" class="chk" data-item="${item.Item_No}" ${checked}></td>
                <td>${item.Item_No}</td>
                <td>${item.Description}</td>
                <td>${Number(item.Minimum_Stock).toLocaleString()}</td>
                <td>${Number(item.Maximum_Inventory).toLocaleString()}</td>
                <td>${Number(item.Inventory).toLocaleString()}</td>
                <td>
                    ${ item.Inventory < item.Minimum_Stock
                        ? `<span class="badge bg-danger">Need</span>`
                        : `<span class="badge bg-success">OK</span>`
                    }
                </td>
                <td>${item.Base_UoM}</td>
                <td>${Number(item.Unit_Cost).toLocaleString()}</td>
                <td>${Number(item.Total_Cost).toLocaleString()}</td>
            </tr>
        `;

        const row = $(html);

        // Checkbox handler
        row.find(".chk").on("change", function() {
            const code = $(this).data("item");
            const list = window.selectedItemsPerLocation[loc] || [];

            if (this.checked) {
                const found = LOCATION_MAP[loc].find(i => i.Item_No === code);
                if (found) list.push(found);
            } else {
                const idx = list.findIndex(i => i.Item_No === code);
                if (idx >= 0) list.splice(idx, 1);
            }

            window.selectedItemsPerLocation[loc] = list;
            updateButtons();
        });

        table.append(row);
    }

    // ===================================================================
    // ENABLE / DISABLE CREATE TO BUTTON
    // ===================================================================
    function updateButtons() {
        const list = window.selectedItemsPerLocation[window.activeLocation] || [];
        $("#createTO").prop("disabled", list.length === 0);
        $("#createTOstick").prop("disabled", list.length === 0);
    }

    // ===================================================================
    // SEARCH ENGINE
    // ===================================================================
    document.getElementById("searchInput").addEventListener("input", function() {

        const q = this.value.toLowerCase().trim();
        const loc = window.activeLocation;

        let rows = LOCATION_MAP[loc] || [];

        if (q.length > 0) {
            rows = rows.filter(r =>
                (r.Item_No ?? "").toLowerCase().includes(q) ||
                (r.Description ?? "").toLowerCase().includes(q)
            );
        }

        renderSortedTable(loc, rows);
    });

    // ===================================================================
    // SORTING ENGINE
    // ===================================================================
    let currentSortField = null;
    let currentSortDir   = "asc";

    const SORT_MAP = {
        1: "item",
        2: "desc",
        3: "min",
        4: "max",
        5: "inv",
        6: "status",
        7: "uom",
        8: "unitCost",
        9: "totalCost"
    };

    function getValue(item, f) {
        switch (f) {
            case "item": return item.Item_No || "";
            case "desc": return item.Description || "";
            case "min": return Number(item.Minimum_Stock || 0);
            case "max": return Number(item.Maximum_Inventory || 0);
            case "inv": return Number(item.Inventory || 0);
            case "status": return item.Inventory < item.Minimum_Stock ? 0 : 1;
            case "uom": return item.Base_UoM || "";
            case "unitCost": return Number(item.Unit_Cost || 0);
            case "totalCost": return Number(item.Total_Cost || 0);
        }
        return "";
    }

    function sortCurrentTable() {

        const loc = window.activeLocation;
        let rows = LOCATION_MAP[loc] || [];

        rows = [...rows].sort((a, b) => {
            const A = getValue(a, currentSortField);
            const B = getValue(b, currentSortField);

            if (A < B) return currentSortDir === "asc" ? -1 : 1;
            if (A > B) return currentSortDir === "asc" ? 1 : -1;
            return 0;
        });

        renderSortedTable(loc, rows);
    }

    function renderSortedTable(loc, rows) {
        const safe = safeLoc(loc);
        const table = $(`.tbody-${safe}`);
        table.empty();
        rows.forEach(item => appendRow(loc, item, table));
    }

    function updateSortIcons() {
        document.querySelectorAll(".sort-icon-mini").forEach(i => i.classList.remove("asc","desc"));
        if (!currentSortField) return;

        const active = document.querySelector(`th[data-field="${currentSortField}"] .sort-icon-mini`);
        if (active) active.classList.add(currentSortDir);
    }

    // ===================================================================
    // INITIALIZE SORTING HEADERS
    // ===================================================================
    function initSortingHeaders() {

        LOCATION_KEYS.forEach(loc => {

            const safe = safeLoc(loc);

            document.querySelectorAll(`#tbl-${safe} thead th`).forEach((th, i) => {

                if (i === 0) return;

                th.dataset.field = SORT_MAP[i];

                if (!th.querySelector(".sort-icon-mini")) {
                    th.style.position = "relative";
                    th.insertAdjacentHTML("beforeend", `<span class="sort-icon-mini"></span>`);
                }

                th.onclick = () => {
                    const f = th.dataset.field;

                    if (currentSortField === f) {
                        currentSortDir = currentSortDir === "asc" ? "desc" : "asc";
                    } else {
                        currentSortField = f;
                        currentSortDir   = "asc";
                    }

                    updateSortIcons();
                    sortCurrentTable();
                };
            });
        });
    }
});
</script>

<!-- ===================================================================
CREATE TRANSFER ORDER MODAL + SUBMIT
=================================================================== -->
<script>
$(document).ready(function() {

    const selectedItemsTable = $('#selectedItems');

    // ==================================================
    // BUKA MODAL CREATE TO
    // ==================================================
    function openCreateTOModal() {

        const loc = window.activeLocation;
        const list = window.selectedItemsPerLocation[loc] || [];

        const tbody = selectedItemsTable.find('tbody');
        tbody.empty();

        list.forEach(item => {

            const uoms = Array.isArray(item.UoM) && item.UoM.length > 0
                ? item.UoM.map(u => u.Code)
                : [item.Base_UoM];

            const options = uoms.map(u =>
                `<option value="${u}" ${u === item.Base_UoM ? "selected" : ""}>${u}</option>`
            ).join("");

            tbody.append(`
                <tr>
                    <td class="item-no">${item.Item_No}</td>
                    <td class="item-desc">${item.Description}</td>
                    <td><input type="number" class="form-control form-control-sm item-qty" value="1" min="1"></td>
                    <td><select class="form-select form-select-sm item-uom">${options}</select></td>
                </tr>
            `);
        });

        $('#toModal').modal('show');
    }

    $("#createTO").on("click", openCreateTOModal);
    $("#createTOstick").on("click", openCreateTOModal);

    // ==================================================
    // SUBMIT CREATE TO
    // ==================================================
    $('#toForm').on('submit', async function(e) {
        e.preventDefault();

        const csrf = $('meta[name="csrf-token"]').attr('content');
        const loc = window.activeLocation;
        const list = window.selectedItemsPerLocation[loc] || [];

        const headerData = {
            noSeries: $('#to_noSeries').val(),
            transSpec: $('#to_transSpec').val(),
            transType: $('#to_transferType').val(),
            transferFromCode: $('#to_transferFrom').val(),
            transfertoCode: $('#to_transferTo').val(),
            businessUnit: $('#to_businessUnit').val(),
            department: $('#to_department').val()
        };
        console.log(headerData);
        const lines = [];
        $('#selectedItems tbody tr').each(function() {
            lines.push({
                itemNo: $(this).find('.item-no').text().trim(),
                description: $(this).find('.item-desc').text().trim(),
                quantity: Number($(this).find('.item-qty').val()),
                uomCode: $(this).find('.item-uom').val()
            });
        });

        if (!lines.length) {
            Swal.fire({ icon:'warning', title:'No Items', text:'Select at least one item.' });
            return;
        }

        Swal.fire({
            title: 'Processing...',
            text: 'Creating Transfer Order...',
            allowOutsideClick: false,
            didOpen: () => Swal.showLoading()
        });

        try {
            const res = await $.ajax({
                url: "{{ route('bc.store-transfer') }}",
                method: "POST",
                contentType:'application/json',
                dataType:'json',
                headers:{ 'X-CSRF-TOKEN': csrf },
                data: JSON.stringify({ ...headerData, lines })
            });

            Swal.close();
            Swal.fire({ icon:'success', title:'Transfer Order Created!', text:"Success." });

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

        } catch(err) {
            Swal.close();
            Swal.fire({ icon:'error', title:'Failed', text: err.responseJSON?.message || 'Error' });
        }
    });
});
</script>

<!-- ===================================================================
AUTO-UPDATE DEPARTMENT
=================================================================== -->
<script>
document.addEventListener("DOMContentLoaded", () => {

    const DEPT_MAP = {
        "RBC.2100":"2100", "RBC.2110":"2110", "RBC.2120":"2120",
        "RBC.2130":"2130", "RBC.2140":"2140"
    };

    $('#toModal').on('shown.bs.modal', function() {

        document.getElementById("to_location").value = window.activeLocation || "RBC.2100";

        const cur = $("#to_transferTo").val();
        $("#to_department").val(DEPT_MAP[cur] || "");

        $("#to_transferTo").trigger("change");
    });

    $(document).on("change", "#to_transferTo", function() {
        $("#to_department").val(DEPT_MAP[$(this).val()] || "");
    });

});
</script>
@endpush


@endsection
