

<?php $__env->startSection('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 text-primary">📦 Transfer Order (Material)</h3>

        
        <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-100 fw-semibold" id="createTO" disabled>
                    ➕ Create Transfer Order
                </button>
            </div>
        </div>

        
        <div id="skeletonContainer">
            <?php 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>
            <?php endfor; ?>
        </div>

        
        <div id="itemContainer" class="d-none"></div>
    </div>

    <!-- Create Transfer Order Modal -->
    <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;">

                <!-- Header -->
                <div class="modal-header text-white"
                    style="background:#9FCBE6; border-top-left-radius:1rem; border-top-right-radius:1rem;">
                    <h5 class="modal-title fw-semibold">Create Transfer Order (TO)</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"
                        aria-label="Close"></button>
                </div>

                <!-- Body -->
                <div class="modal-body p-4">
                    <form id="toForm">
                        <!-- ===== HEADER SECTION ===== -->
                        <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">
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">No. Series</label>
                                    <select id="to_noSeries" class="form-select">
                                        <option value="TO.RBC" selected>RBC</option>
                                        <option value="TO.CI">CI</option>
                                    </select>
                                </div>

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

                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">Business Unit</label>
                                    <select id="to_businessUnit" class="form-select" disabled>
                                        <option value="RBC" selected>Regent Bali Canggu</option>
                                    </select>
                                </div>

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

                                <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" selected>Food Central</option>
                                    </select>
                                </div>

                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">Transfer To</label>
                                    <select id="to_transferTo" class="form-select">
                                        <option value="RBC.2040" selected>Pastry</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- ===== ITEM SECTION ===== -->
                        <div class="border rounded-3 p-3 bg-light">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h6 class="fw-semibold text-primary mb-0">Item Lines</h6>
                            </div>

                            <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>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
$(document).ready(function() {
    const itemContainer = $('#itemContainer');
    const skeletonContainer = $('#skeletonContainer');
    const createTOButton = $('#createTO');
    const selectedItemsTable = $('#selectedItems');
    let allData = [];
    let selectedItems = [];

    // === Fetch Data ===
    $.get("<?php echo e(route('bc.combined-stock')); ?>", function(data) {
        if (data && data.items) {
            allData = data.items;
            renderItems(allData);
        } else {
            itemContainer.html('<p class="text-center text-muted mt-4">No data found</p>');
        }
        skeletonContainer.hide();
        itemContainer.removeClass('d-none');
    });

    // === Render Item Cards ===
    function renderItems(items) {
        itemContainer.empty();
        if (!items.length) {
            itemContainer.html('<p class="text-center text-muted mt-4">No items found</p>');
            return;
        }

        items.forEach(item => {
            const isChecked = selectedItems.some(sel => sel.Item_No === item.Item_No);
            const card = $(`
                <div class="card mb-3 shadow-sm border-0 rounded-4 px-3 py-3 item-card" data-itemno="${item.Item_No}">
                    <div class="d-flex align-items-center justify-content-between">
                        <div class="d-flex align-items-center gap-3">
                            <label class="custom-checkbox">
                                <input type="checkbox" class="form-check-input select-item" value="${item.Item_No}" ${isChecked ? 'checked' : ''}>
                                <span class="checkmark"></span>
                            </label>
                            <div>
                                <h6 class="fw-bold mb-0">${item.Description}</h6>
                                <small class="text-muted">No: ${item.Item_No}</small>
                            </div>
                        </div>
                        <div class="text-end">
                            <span class="badge bg-${item.Inventory <= 0 ? 'danger' : 'success'} rounded-pill px-3 py-2">
                                Stock: ${item.Inventory}
                            </span>
                            <div class="text-muted small mt-1">${item.Replenishment_System || '-'}</div>
                        </div>
                    </div>
                </div>
            `);
            itemContainer.append(card);
        });
    }

    // === Checkbox persist selection ===
    $(document).on('change', '.select-item', function() {
        const itemNo = $(this).val();
        if (this.checked) {
            const item = allData.find(i => i.Item_No === itemNo);
            if (item && !selectedItems.some(sel => sel.Item_No === item.Item_No)) {
                selectedItems.push(item);
            }
        } else {
            selectedItems = selectedItems.filter(i => i.Item_No !== itemNo);
        }
        updateSelectedItems();
    });

    // === Update selected items in modal (dengan select UoM) ===
    function updateSelectedItems() {
        const tbody = selectedItemsTable.find('tbody');
        tbody.empty();

        selectedItems.forEach(item => {
            // Pastikan UoM dalam bentuk array
            const uoms = Array.isArray(item.UoM) && item.UoM.length > 0 ? item.UoM : ['-'];

            // Buat opsi dropdown
            const uomOptions = uoms.map(u => `<option value="${u}">${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">
                            ${uomOptions}
                        </select>
                    </td>
                </tr>
            `);
        });

        createTOButton.prop('disabled', selectedItems.length === 0);
    }

    // === Open Modal ===
    createTOButton.on('click', function() {
        updateSelectedItems();
        $('#toModal').modal('show');
    });

    // === Search & Filter (client-side, persistent selection) ===
    $('#searchInput, #filterSelect').on('input change', function() {
        const keyword = $('#searchInput').val().toLowerCase();
        const filter = $('#filterSelect').val();
        const filtered = allData.filter(i =>
            i.Description.toLowerCase().includes(keyword) &&
            (!filter || i.Replenishment_System === filter)
        );
        renderItems(filtered);
    });
});
</script>
    <script>
        $(document).ready(function() {
            const selectedItemsTable = $('#selectedItems');

            // === Event Submit Transfer Order ===
            $('#toForm').on('submit', async function(e) {
                e.preventDefault();

                const csrfToken = $('meta[name="csrf-token"]').attr('content');
                const $submitBtn = $('#toForm button[type="submit"]');
                $submitBtn.prop('disabled', true);

                // --- Ambil data header ---
                const headerData = {
                    noSeries: $('#to_noSeries').val(),
                    transSpec: $('#to_transSpec').val(),
                    businessUnit: $('#to_businessUnit').val(),
                    department: $('#to_department').val(),
                    transferFromCode: $('#to_transferFrom').val(),
                    transfertoCode: $('#to_transferTo').val(),
                };

                // --- Ambil data items dari tabel (pastikan tbody) ---
                const lines = [];
                $('#selectedItems tbody tr').each(function() {
                    const itemNo = $(this).find('.item-no').text().trim();
                    const desc = $(this).find('.item-desc').text().trim();
                    const qty = parseFloat($(this).find('.item-qty').val()) || 0;
                    const uomCode = $(this).find('.item-uom').val() || '';

                    if (itemNo && qty > 0) {
                        lines.push({
                            itemNo,
                            description: desc,
                            quantity: qty,
                            uomCode,
                        });
                    }
                });


                if (lines.length === 0) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'No Items Selected',
                        text: 'Please add at least one item before submitting.',
                        background: '#FFF8F3',
                        confirmButtonColor: '#7DC5E3',
                    });
                    $submitBtn.prop('disabled', false);
                    return;
                }

                // === Step 1: Proses Simpan Header + Lines ===
                Swal.fire({
                    title: 'Processing Transfer Order...',
                    html: '<b>Creating Header and Items...</b>',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    },
                    background: '#FFF8F3',
                    color: '#333',
                });

                try {
                    const response = await $.ajax({
                        url: "<?php echo e(route('bc.store-transfer')); ?>",
                        method: 'POST',
                        contentType: 'application/json',
                        dataType: 'json',
                        headers: {
                            'X-CSRF-TOKEN': csrfToken
                        },
                        data: JSON.stringify({
                            ...headerData,
                            lines: lines
                        }),
                    });

                    if (response.status !== 'success') {
                        throw new Error(response.message || 'Failed to create Transfer Order.');
                    }

                    Swal.close();
                    Swal.fire({
                        icon: 'success',
                        title: 'Transfer Order Complete!',
                        html: `
                    <div class="text-start">
                        <p class="mb-1">Header <b>${response.header?.no || '-'}</b> created successfully.</p>
                        <p class="mb-1">Total lines: <b>${response.lines?.length || 0}</b></p>
                    </div>
                `,
                        background: '#F0FFF0',
                        confirmButtonColor: '#7DC5E3',
                    });

                    // Reset form dan modal
                    $('#toForm')[0].reset();
                    $('#selectedItems tbody').empty();
                    $('#toModal').modal('hide');

                } catch (err) {
                    Swal.close();
                    Swal.fire({
                        icon: 'error',
                        title: 'Error Creating Transfer Order',
                        text: err.message || 'Failed to process transfer order.',
                        background: '#FFF0F0',
                        confirmButtonColor: '#E67C73',
                    });
                } finally {
                    $submitBtn.prop('disabled', false);
                }
            });
        });
    </script>




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

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

            100% {
                background-position: 200% 0;
            }
        }

        .custom-checkbox {
            position: relative;
            cursor: pointer;
        }

        .custom-checkbox input {
            opacity: 0;
            position: absolute;
        }

        .custom-checkbox .checkmark {
            width: 22px;
            height: 22px;
            border-radius: 6px;
            border: 2px solid #9c9997;
            display: inline-block;
            transition: all 0.3s ease;
        }

        .custom-checkbox input:checked+.checkmark {
            background-color: #74b9ff;
            border-color: #0984e3;
            box-shadow: 0 0 5px rgba(9, 132, 227, 0.5);
        }

        .item-card:hover {
            background-color: #fff3e9;
            transform: scale(1.01);
            transition: all 0.2s ease-in-out;
        }
    </style>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\agusy\OneDrive\Dokumen\Kerjaan\Pastry\resources\views/items.blade.php ENDPATH**/ ?>