
<?php $__env->startSection('content'); ?>

<div class="container py-4" style="background:#FFF8F0; border-radius:14px;">
    <!-- ========================= -->
    <!-- HEADER -->
    <!-- ========================= -->
    <div class="d-flex align-items-center justify-content-between mb-4">
        <div>
            <h2 class="fw-bold mb-0" style="color:#183647;">Transfer Orders</h2>
            <div class="small text-muted">Logistics & Inventory Movements</div>
        </div>

        <div class="d-flex gap-2 align-items-center">
            <input id="searchInput" class="form-control form-control-sm" placeholder="Search TO number..."
                style="min-width:260px; background:#fff; border-radius:12px;" />
            <button id="refreshBtn" class="btn btn-sm" title="Refresh"
                style="background:#F2E6DA; color:#5a3e2b; border-radius:10px;">⟳</button>
        </div>
    </div>

    <!-- ========================= -->
    <!-- TABLE WRAPPER -->
    <!-- ========================= -->
    <div class="table-responsive shadow-sm rounded-3 bg-white p-3" style="overflow-x:auto;">
        <table class="table mb-0 align-middle" id="toTable" style="font-size:13px;">
            <thead style="background:#FAEBD7; border-radius:8px; white-space:nowrap;">
                <tr>
                    <th class="sortable" data-field="index"># <span class="sort-icon"></span></th>
                    <th class="sortable" data-field="no">TO No <span class="sort-icon"></span></th>
                    <th class="sortable" data-field="noSeries">No Series <span class="sort-icon"></span></th>
                    <th class="sortable" data-field="from">Transfer From <span class="sort-icon"></span></th>
                    <th class="sortable" data-field="to">Transfer To <span class="sort-icon"></span></th>
                    <th class="sortable" data-field="bu">Business Unit <span class="sort-icon"></span></th>
                    <th class="sortable" data-field="postingDate">Posting Date <span class="sort-icon"></span></th>
                    <th class="sortable" data-field="shipmentDate">Shipment <span class="sort-icon"></span></th>
                    <th class="sortable" data-field="status">Status <span class="sort-icon"></span></th>

                    
                </tr>
            </thead>
            <tbody id="toTbody">
                <!-- rows injected dynamically -->
            </tbody>
        </table>

        <div id="pagination" class="mt-3"></div>
    </div>
</div>


<!-- ========================= -->
<!-- STYLES -->
<!-- ========================= -->
<style>
    body { background: #F0FAFF; }

    .to-row {
        transition: background .18s ease, transform .18s ease;
    }

    .to-row:hover {
        background: #FFF7EE;
        transform: translateY(-3px);
    }

    .status-success, .status-released, .status-open {
        padding: .35rem .55rem;
        border-radius: 8px;
    }
    .status-success { background:#E6F9EF; color:#0f5132; }
    .status-released { background:#D5ECFF; color:#063970; }
    .status-open { background:#FFF1F0; color:#842029; }

    .line-row { display:none; background:#FFF8F0 !important; }

    .line-box {
        background:#FFF3E7;
        border-radius:10px;
        padding:12px;
        border:1px solid #F1D7C4;
    }

    .skeleton-box {
        background:linear-gradient(90deg,#eee 25%,#ddd 50%,#eee 75%);
        background-size:200% 100%;
        animation:skeleton 1.4s infinite;
        border-radius:4px;
    }

    @keyframes skeleton {
        0%{background-position:200% 0;}
        100%{background-position:-200% 0;}
    }

    .pagination {
        display:flex;
        justify-content:center;
        gap:6px;
    }

    .page-item .page-link {
        border-radius:8px;
        padding:.35rem .65rem;
        background:#FFF8F0;
        color:#183647;
        border:none;
        transition:.2s;
    }

    .page-item.active .page-link {
        background:#FFD6A5;
        color:#1F4A63;
        transform:scale(1.15);
    }

    .page-link:hover {
        background:#FFE8C1;
        transform:scale(1.1) translateY(-2px);
    }

    .sortable {
        cursor: pointer;
        position: relative;
        padding-right: 20px;
        user-select: none;
    }

    .sort-icon {
        width: 8px;
        height: 8px;
        border-right: 2px solid #888;
        border-bottom: 2px solid #888;
        position: absolute;
        right: 5px;
        top: 50%;
        translate: 0 -50%;
        opacity: .35;
        transform: rotate(45deg);
        transition: .18s;
    }

    .sort-icon.asc { transform: rotate(225deg); opacity: 1; }
    .sort-icon.desc { transform: rotate(45deg); opacity: 1; }
</style>


<!-- ========================= -->
<!-- JS -->
<!-- ========================= -->
<script>
document.addEventListener('DOMContentLoaded', async () => {

    const qs = s => document.querySelector(s);
    const qsa = s => Array.from(document.querySelectorAll(s));

    let allData = [];
    let filteredData = null;
    let currentPage = 1;
    const PAGE_SIZE = 20;

    let sortField = "postingDate";
    let sortDir = "desc";

    function showSkeleton() {
        let html = "";
        for (let i = 0; i < 6; i++) {
            html += `
            <tr>
                <td colspan="10">
                    <div class="d-flex gap-3 p-2">
                        <div class="skeleton-box" style="width:60px;height:20px;"></div>
                        <div class="skeleton-box flex-grow-1" style="height:20px;"></div>
                        <div class="skeleton-box" style="width:80px;height:20px;"></div>
                    </div>
                </td>
            </tr>`;
        }
        qs('#toTbody').innerHTML = html;
    }

    async function fetchTO() {
        showSkeleton();
        try {
            const res = await fetch(`<?php echo e(route('bc.transfer.with-lines')); ?>`);
            const json = await res.json();

            if (json.status === "success") {
                allData = json.data;

                // ==============================
                // DEFAULT SORT: postingDate DESC
                // ==============================
                allData.sort((a, b) => new Date(b.postingDate) - new Date(a.postingDate));

                currentPage = 1;
                renderTable();
                updateSortIcons();
            }
        } catch (e) {
            qs('#toTbody').innerHTML =
                `<tr><td colspan="10" class="text-center text-danger py-4">Error fetching data</td></tr>`;
        }
    }

    function renderLines(lines) {
        if (!lines || lines.length === 0) {
            return `<div class="p-2 text-muted">No lines found.</div>`;
        }

        return `
        <div class="line-box">
            <table class="table table-sm mb-0">
                <thead>
                    <tr>
                        <th>Line No</th>
                        <th>Item No</th>
                        <th>Description</th>
                        <th>Qty</th>
                        <th>UoM</th>
                        <th>Shipment</th>
                    </tr>
                </thead>
                <tbody>
                    ${lines.map(l => `
                        <tr>
                            <td>${l.lineNo}</td>
                            <td>${l.itemNo}</td>
                            <td>${l.desc ?? '-'}</td>
                            <td>${l.quantity}</td>
                            <td>${l.uomCode}</td>
                            <td>${l.shipmentDate || '-'}</td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>`;
    }

    function renderRow(r, index) {
        let statusClass = "status-open";
        if (r.status === "Released") statusClass = "status-released";
        if (r.status === "success") statusClass = "status-success";

        return `
        <tr class="to-row">
            <td>${index}</td>
            <td>
                <div class="fw-semibold">${r.no}</div>
                <a href="#" class="small text-primary show-lines">Show lines ▾</a>
            </td>
            <td>${r.noSeries}</td>
            <td>${r.transferFromCode}</td>
            <td>${r.transfertoCode}</td>
            <td>${r.businessUnit}</td>
            <td>${r.postingDate}</td>
            <td>${r.shipmentDate ?? '-'}</td>
            <td><span class="${statusClass}">${r.status}</span></td>

            
        </tr>

        <tr class="line-row">
            <td colspan="10">${renderLines(r.Lines)}</td>
        </tr>
        `;
    }

    function doSort(data) {
        return [...data].sort((a, b) => {
            let A, B;

            switch (sortField) {
                case "index": A = 0; B = 0; break;
                case "no": A = a.no; B = b.no; break;
                case "noSeries": A = a.noSeries; B = b.noSeries; break;
                case "from": A = a.transferFromCode; B = b.transferFromCode; break;
                case "to": A = a.transfertoCode; B = b.transfertoCode; break;
                case "bu": A = a.businessUnit; B = b.businessUnit; break;
                case "status": A = a.status; B = b.status; break;
                case "postingDate":
                    A = new Date(a.postingDate);
                    B = new Date(b.postingDate);
                    break;
                case "shipmentDate":
                    A = new Date(a.shipmentDate || '1900-01-01');
                    B = new Date(b.shipmentDate || '1900-01-01');
                    break;
                default: A = ""; B = "";
            }

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

    function renderTable() {
        const base = filteredData || allData;

        const sorted = doSort(base);

        const total = sorted.length;
        const start = (currentPage - 1) * PAGE_SIZE;
        const slice = sorted.slice(start, start + PAGE_SIZE);

        qs('#toTbody').innerHTML = slice.map((r, i) =>
            renderRow(r, start + i + 1)
        ).join("");

        attachLineToggles();
        renderPagination(total);
    }

    function updateSortIcons() {
        qsa(".sort-icon").forEach(i => i.classList.remove("asc", "desc"));

        const active = qs(`th[data-field="${sortField}"] .sort-icon`);
        if (active) active.classList.add(sortDir === "asc" ? "asc" : "desc");
    }

    qsa(".sortable").forEach(th => {
        th.addEventListener("click", () => {
            const field = th.dataset.field;

            if (sortField === field) {
                sortDir = (sortDir === "asc" ? "desc" : "asc");
            } else {
                sortField = field;
                sortDir = "asc";
            }

            updateSortIcons();
            renderTable();
        });
    });

    function renderPagination(total) {
        const pages = Math.ceil(total / PAGE_SIZE);
        if (pages <= 1) {
            qs('#pagination').innerHTML = "";
            return;
        }

        let html = `<ul class="pagination">`;

        for (let i = 1; i <= pages; i++) {
            html += `
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" data-page="${i}">${i}</a>
            </li>`;
        }

        html += `</ul>`;
        qs('#pagination').innerHTML = html;

        qsa('#pagination .page-link').forEach(btn => {
            btn.onclick = () => {
                currentPage = parseInt(btn.dataset.page);
                renderTable();
            };
        });
    }

    function attachLineToggles() {
        qsa('.show-lines').forEach(btn => {
            btn.onclick = e => {
                e.preventDefault();
                const row = btn.closest('tr');
                const next = row.nextElementSibling;
                next.style.display = next.style.display === "none" ? "table-row" : "none";
            };
        });
    }

    qs('#searchInput').addEventListener('input', e => {
        const q = e.target.value.toLowerCase().trim();

        if (!q) {
            filteredData = null;
            currentPage = 1;
            renderTable();
            return;
        }

        filteredData = allData.filter(r =>
            r.no.toLowerCase().includes(q) ||
            r.transferFromCode.toLowerCase().includes(q) ||
            r.transfertoCode.toLowerCase().includes(q)
        );

        currentPage = 1;
        renderTable();
    });

    qs('#refreshBtn').onclick = fetchTO;

    await fetchTO();
});
</script>

<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\jimmy\Documents\hotelstocks\resources\views/transferheader.blade.php ENDPATH**/ ?>