

<?php $__env->startSection('title', 'Good Received Notes (GRN)'); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Good Received Notes (GRN)</h4>
                    <div class="card-tools">
                        <button type="button" class="btn btn-success me-2" data-bs-toggle="modal" data-bs-target="#createGrnModal">
                            <i class="fas fa-plus"></i> Create New GRN
                        </button>
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#filterModal">
                            <i class="fas fa-filter"></i> Filter
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped" id="grnTable">
                            <thead>
                                <tr>
                                    <th>GRN Number</th>
                                    <th>QC Number</th>
                                    <th>PO Number</th>
                                    <th>Vendor</th>
                                    <th>Status</th>
                                    <th>Received Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Data loaded via AJAX -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Filter Modal -->
<div class="modal fade" id="filterModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Filter GRNs</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <label for="filterStatus" class="form-label">Status</label>
                        <select class="form-select" id="filterStatus">
                            <option value="">All Status</option>
                            <option value="pending_qc">Pending QC</option>
                            <option value="accepted">Accepted</option>
                            <option value="rejected">Rejected</option>
                            <option value="partial">Partial</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label for="filterQcNumber" class="form-label">QC Number</label>
                        <input type="text" class="form-control" id="filterQcNumber" placeholder="Search QC Number">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="applyFilter">Apply Filter</button>
            </div>
        </div>
    </div>
</div>

<!-- Create GRN Modal -->
<div class="modal fade" id="createGrnModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Create GRN from QC</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label for="qcNumberSearch" class="form-label">Search QC Number *</label>
                        <select class="form-select" id="qcNumberSearch" required>
                            <option value="">Search QC Number...</option>
                        </select>
                        <small class="form-text text-muted">Search by QC number to load QC data</small>
                    </div>
                    <div class="col-md-6">
                        <label for="grnNumber" class="form-label">GRN Number</label>
                        <input type="text" class="form-control" id="grnNumber" readonly>
                        <small class="form-text text-muted">Auto-generated GRN number</small>
                    </div>
                </div>

                <!-- QC Details -->
                <div id="qcDetails" class="row mb-3" style="display: none;">
                    <div class="col-12">
                        <div class="card bg-light">
                            <div class="card-body">
                                <h6 class="card-title">QC Details</h6>
                                <div class="row">
                                    <div class="col-md-3">
                                        <strong>QC Number:</strong> <span id="qcNumber"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <strong>IGP Number:</strong> <span id="igpNumber"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <strong>PO Number:</strong> <span id="poNumber"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <strong>Vendor:</strong> <span id="vendorName"></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- QC Items Table -->
                <div id="qcItemsSection" class="mb-3" style="display: none;">
                    <h6>QC Items for GRN Creation</h6>
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped" id="qcItemsTable">
                            <thead class="table-dark">
                                <tr>
                                    <th>Item</th>
                                    <th>UOM</th>
                                    <th>IGP Qty</th>
                                    <th>Accepted Qty</th>
                                    <th>Warehouse</th>
                                    <th>Bin</th>
                                    <th>Include in GRN</th>
                                </tr>
                            </thead>
                            <tbody id="qcItemsBody">
                                <!-- Items will be loaded here -->
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Remarks -->
                <div class="row">
                    <div class="col-12">
                        <label for="remarks" class="form-label">Remarks</label>
                        <textarea class="form-control" id="remarks" rows="2" placeholder="Enter any additional remarks"></textarea>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="createGrnBtn" disabled>Create GRN</button>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('plugin-styles'); ?>
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/select2/select2.min.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.css')); ?>">
<style>
    .form-control[readonly] {
        background-color: #f8f9fa !important;
        border-color: #dee2e6 !important;
        color: #495057 !important;
        cursor: not-allowed !important;
    }

    .table th {
        font-size: 0.875rem;
        font-weight: 600;
    }

    .table td {
        font-size: 0.875rem;
        vertical-align: middle;
    }

    .checkbox-irreversible {
        cursor: pointer;
    }

    .checkbox-irreversible:checked {
        background-color: #198754;
        border-color: #198754;
    }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('plugin-scripts'); ?>
<script src="<?php echo e(asset('theme/vendors/select2/select2.min.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/datatables.net/dataTables.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.js')); ?>"></script>
<script>
$(document).ready(function() {
    // Initialize DataTable
    const grnTable = $('#grnTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '<?php echo e(route("grns.index")); ?>',
            data: function(d) {
                d.status = $('#filterStatus').val();
                d.qc_number = $('#filterQcNumber').val();
            }
        },
        columns: [
            { data: 'grn_number', name: 'grn_number' },
            { data: 'qc.qc_number', name: 'qc.qc_number' },
            { data: 'po_number', name: 'po_number', orderable: false, searchable: false },
            { data: 'vendor_name', name: 'vendor_name', orderable: false, searchable: false },
            { data: 'status_badge', name: 'status', orderable: false, searchable: false },
            { data: 'received_date', name: 'received_date' },
            { data: 'actions', name: 'actions', orderable: false, searchable: false }
        ],
        order: [[5, 'desc']]
    });

    // Apply filter
    $('#applyFilter').on('click', function() {
        grnTable.ajax.reload();
        $('#filterModal').modal('hide');
    });

    // Reset filter modal
    $('#filterModal').on('hidden.bs.modal', function() {
        $('#filterStatus').val('');
        $('#filterQcNumber').val('');
    });

    // Create GRN Modal functionality
    $('#createGrnModal').on('show.bs.modal', function() {
        generateGrnNumber();
        loadQcNumbers();
    });

    // Initialize QC Number Select2
    $('#qcNumberSearch').select2({
        theme: 'bootstrap-5',
        placeholder: 'Search QC Number...',
        allowClear: true,
        width: '100%',
        ajax: {
            url: '<?php echo e(route("api.qc.search")); ?>',
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return {
                    q: params.term || ''
                };
            },
            processResults: function(data) {
                return {
                    results: data.map(function(item) {
                        return {
                            id: item.id,
                            text: item.qc_number,
                            qc_number: item.qc_number,
                            igp_number: item.igp?.gate_pass_number,
                            po_number: item.purchaseOrder?.po_number,
                            vendor_name: item.purchaseOrder?.vendor?.name
                        };
                    })
                };
            },
            cache: true
        }
    });

    // QC selection change
    $('#qcNumberSearch').on('change', function() {
        const qcId = $(this).val();
        if (qcId) {
            const selectedOption = $(this).find('option:selected');
            $('#qcNumber').text(selectedOption.data('qc-number'));
            $('#igpNumber').text(selectedOption.data('igp-number'));
            $('#poNumber').text(selectedOption.data('po-number'));
            $('#vendorName').text(selectedOption.data('vendor-name'));
            $('#qcDetails').show();

            // Load QC items
            loadQcItems(qcId);
        } else {
            $('#qcDetails').hide();
            $('#qcItemsSection').hide();
            $('#createGrnBtn').prop('disabled', true);
        }
    });

    // Load QC items
    function loadQcItems(qcId) {
        $.ajax({
            url: `<?php echo e(url('api/qc')); ?>/${qcId}`,
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    renderQcItems(response.data.qc_items);
                    $('#qcItemsSection').show();
                    $('#createGrnBtn').prop('disabled', false);
                } else {
                    toastr.error('Failed to load QC items');
                }
            },
            error: function() {
                toastr.error('Error loading QC items');
            }
        });
    }

    // Render QC items table
    function renderQcItems(items) {
        const tbody = $('#qcItemsBody');
        tbody.empty();

        items.forEach((item, index) => {
            if (item.accepted_qty > 0) { // Only show accepted items
                const row = `
                    <tr data-item-index="${index}">
                        <td>
                            <input type="hidden" name="items[${index}][item_id]" value="${item.item_id}">
                            <input type="hidden" name="items[${index}][purchase_order_item_id]" value="${item.purchase_order_item_id}">
                            <input type="hidden" name="items[${index}][uom_id]" value="${item.uom_id}">
                            <input type="hidden" name="items[${index}][unit_code]" value="${item.unit_code}">
                            <input type="hidden" name="items[${index}][quantity_received]" value="${item.accepted_qty}">
                            <input type="hidden" name="items[${index}][warehouse_id]" value="${item.warehouse_id}">
                            <input type="hidden" name="items[${index}][bin_id]" value="${item.bin_id}">
                            <strong>${item.item.name}</strong>
                        </td>
                        <td>${item.unit_code}</td>
                        <td class="text-end">${item.igp_qty}</td>
                        <td class="text-end">${item.accepted_qty}</td>
                        <td>${item.warehouse?.name || 'N/A'}</td>
                        <td>${item.bin?.code || 'N/A'}</td>
                        <td class="text-center">
                            <input type="checkbox" class="form-check-input checkbox-irreversible"
                                   name="items[${index}][include]" value="1"
                                   onchange="handleCheckboxChange(this, ${index})">
                        </td>
                    </tr>
                `;
                tbody.append(row);
            }
        });
    }

    // Create GRN button click
    $('#createGrnBtn').on('click', function() {
        if (!validateGrnForm()) {
            return;
        }

        const formData = collectGrnFormData();

        $.ajax({
            url: '<?php echo e(route("api.grn.store")); ?>',
            method: 'POST',
            data: formData,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    toastr.success('GRN created successfully!');
                    grnTable.ajax.reload();
                    $('#createGrnModal').modal('hide');
                } else {
                    toastr.error(response.message || 'Failed to create GRN');
                }
            },
            error: function(xhr) {
                const errors = xhr.responseJSON?.errors;
                if (errors) {
                    Object.keys(errors).forEach(field => {
                        toastr.error(errors[field][0]);
                    });
                } else {
                    toastr.error('Error: ' + (xhr.responseJSON?.message || 'Unknown error occurred'));
                }
            }
        });
    });
});

// Generate GRN number
function generateGrnNumber() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    $('#grnNumber').val(`GRN-${year}${month}${day}-${random}`);
}

// Handle checkbox change (irreversible)
window.handleCheckboxChange = function(checkbox, itemIndex) {
    if (checkbox.checked) {
        // Show confirmation
        if (confirm('This action will update warehouse stock and cannot be reverted. Continue?')) {
            checkbox.disabled = true; // Make it irreversible
            checkbox.classList.add('irreversible');
        } else {
            checkbox.checked = false;
            return;
        }
    }
};

// Validate GRN form
function validateGrnForm() {
    const qcId = $('#qcNumberSearch').val();
    if (!qcId) {
        toastr.error('Please select a QC number first.');
        return false;
    }

    let hasSelectedItems = false;
    $('.checkbox-irreversible:checked').each(function() {
        hasSelectedItems = true;
        return false; // break loop
    });

    if (!hasSelectedItems) {
        toastr.error('Please select at least one item to include in GRN.');
        return false;
    }

    return true;
}

// Collect GRN form data
function collectGrnFormData() {
    const formData = {
        qc_id: $('#qcNumberSearch').val(),
        grn_number: $('#grnNumber').val(),
        remarks: $('#remarks').val(),
        items: []
    };

    $('.checkbox-irreversible:checked').each(function() {
        const row = $(this).closest('tr');
        const item = {
            item_id: row.find('input[name$="[item_id]"]').val(),
            purchase_order_item_id: row.find('input[name$="[purchase_order_item_id]"]').val(),
            uom_id: row.find('input[name$="[uom_id]"]').val(),
            unit_code: row.find('input[name$="[unit_code]"]').val(),
            quantity_received: row.find('input[name$="[quantity_received]"]').val(),
            warehouse_id: row.find('input[name$="[warehouse_id]"]').val(),
            bin_id: row.find('input[name$="[bin_id]"]').val()
        };
        formData.items.push(item);
    });

    return formData;
}
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\habibcables-ERP\resources\views\grns\index.blade.php ENDPATH**/ ?>