

<?php $__env->startSection('title', 'Edit Delivery Receipt'); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-warning text-white">
                    <h5 class="mb-0"><i class="fas fa-edit"></i> Edit Delivery Receipt</h5>
                </div>
                <div class="card-body">
                    <form id="receiptForm" action="<?php echo e(route('delivery-receipts.update', $receipt)); ?>" method="POST">
                        <?php echo csrf_field(); ?>
                        <?php echo method_field('PUT'); ?>

                        <!-- Gate Pass Information (Read-only) -->
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Gate Pass</label>
                                <input type="text" class="form-control" value="<?php echo e($receipt->gatePass->gate_pass_number); ?> - <?php echo e($receipt->gatePass->customer->name ?? 'N/A'); ?>" readonly>
                                <input type="hidden" name="gate_pass_id" value="<?php echo e($receipt->gate_pass_id); ?>">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label fw-bold">Delivery Date</label>
                                <input type="date" class="form-control form-control-lg" name="delivery_date"
                                       value="<?php echo e($receipt->delivery_date->format('Y-m-d')); ?>" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label fw-bold">Delivery Man</label>
                                <select class="form-select form-select-lg" name="delivered_by" required>
                                    <option value="">Select Delivery Man</option>
                                    <?php $__currentLoopData = $deliveryMen; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $man): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($man->id); ?>" <?php echo e($receipt->delivered_by == $man->id ? 'selected' : ''); ?>>
                                            <?php echo e($man->name); ?>

                                        </option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                        </div>

                        <!-- Factory Invoice Overview (shown when gate pass is loaded) -->
                        <div id="factoryInvoiceOverview" class="d-none mb-4">
                            <div class="card border-success">
                                <div class="card-header bg-success text-white">
                                    <h6 class="mb-0"><i class="fas fa-file-invoice"></i> Factory Invoice Items (Originally Ordered)</h6>
                                </div>
                                <div class="card-body">
                                    <div id="factoryInvoiceContent">
                                        <!-- Factory invoice items grouped by customer will be loaded here -->
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Delivery Items Table -->
                        <div id="deliveryItemsSection" class="d-none">
                            <div class="card border-primary">
                                <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                                    <h6 class="mb-0"><i class="fas fa-truck"></i> Delivery Items</h6>
                                    <button type="button" class="btn btn-light btn-sm" id="addDeliveryRowBtn" disabled>
                                        <i class="fas fa-plus"></i> Add Row
                                    </button>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                        <table class="table table-striped" id="deliveryItemsTable">
                                        <thead class="table-dark">
                                            <tr>
                                                    <th>Customer</th>
                                                <th>Item</th>
                                                    <th>Available Qty</th>
                                                    <th>Deliver Qty</th>
                                                <th>Unit Price</th>
                                                <th>Total</th>
                                                <th>Notes</th>
                                                    <th>Actions</th>
                                            </tr>
                                        </thead>
                                            <tbody id="deliveryItemsBody">
                                                <!-- Delivery rows will be loaded here -->
                                        </tbody>
                                        <tfoot class="table-dark">
                                            <tr>
                                                    <th colspan="5" class="text-end">Total Amount:</th>
                                                    <th class="text-end" id="grandTotal">$0.00</th>
                                                    <th colspan="2"></th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Notes -->
                        <div class="row mb-3">
                            <div class="col-12">
                                <label class="form-label fw-bold">Notes</label>
                                <textarea class="form-control" name="notes" rows="3" placeholder="Optional delivery notes..."><?php echo e($receipt->notes); ?></textarea>
                            </div>
                        </div>

                        <!-- Actions -->
                        <div class="row">
                            <div class="col-12 text-end">
                                <button type="button" class="btn btn-success btn-lg me-2" onclick="saveReceipt()" id="saveBtn">
                                    <i class="fas fa-save"></i> Update as Draft
                                </button>
                                <button type="button" class="btn btn-primary btn-lg me-2" onclick="submitReceipt()" id="submitBtn">
                                    <i class="fas fa-paper-plane"></i> Submit for Processing
                                </button>
                                <a href="<?php echo e(route('delivery-receipts.show', $receipt)); ?>" class="btn btn-secondary btn-lg me-2">
                                    <i class="fas fa-times"></i> Cancel
                                </a>
                                <a href="<?php echo e(route('delivery-receipts.index')); ?>" class="btn btn-secondary btn-lg">
                                    <i class="fas fa-arrow-left"></i> Back to List
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
let currentGatePassId = <?php echo e($receipt->gate_pass_id); ?>;
let factoryInvoiceByCustomer = {};
let availableOgpItems = [];
let availableCustomers = [];
let deliveryRowCount = 0;

$(document).ready(function() {
    // Load existing receipt data
    loadReceiptData();

    // Add delivery row button
    $('#addDeliveryRowBtn').on('click', function() {
        addDeliveryRow();
    });
});

function loadReceiptData() {
    $.get(`<?php echo e(url('delivery-receipts/gate-pass')); ?>/${currentGatePassId}/items`)
        .done(function(data) {
            factoryInvoiceByCustomer = data.factory_invoice_by_customer;
            availableOgpItems = data.available_ogp_items;
            availableCustomers = data.customers;

            // Display factory invoice overview
            displayFactoryInvoiceOverview();

            // Show delivery items section
            $('#factoryInvoiceOverview').removeClass('d-none');
            $('#deliveryItemsSection').removeClass('d-none');
            $('#addDeliveryRowBtn').prop('disabled', false);

            // Load existing delivery items
            loadExistingDeliveryItems();
        })
        .fail(function() {
            alert('Failed to load gate pass data');
        });
}

function loadExistingDeliveryItems() {
    const existingItems = <?php echo json_encode($receipt->items, 15, 512) ?>;

    existingItems.forEach(item => {
        addDeliveryRow();

        // Get the last added row
        const lastRow = $('#deliveryItemsBody tr:last');
        const customerSelect = lastRow.find('.delivery-customer');
        const itemSelect = lastRow.find('.delivery-item');
        const qtyInput = lastRow.find('.delivery-qty');
        const priceInput = lastRow.find('.delivery-price');
        const notesInput = lastRow.find('.delivery-notes');

        // Populate the row with existing data
        customerSelect.val(item.customer_account_id);
        itemSelect.val(item.gate_pass_item_id).trigger('change');

        // Wait a bit for the change event to complete, then set quantity
        setTimeout(() => {
            qtyInput.val(item.delivered_quantity);
            priceInput.val(item.delivered_unit_price);
            lastRow.find('.factory-invoice-id').val(item.factory_invoice_id || '');
            if (notesInput.length) notesInput.val(item.notes || '');
            updateRowTotal(lastRow);
        }, 100);
    });
}

function addCustomerSection(customerId, customerName) {
    const sectionId = `customer-section-${customerId}`;
    const sectionHtml = `
        <div class="card border-success mb-3 customer-section" id="${sectionId}">
            <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                <h6 class="mb-0"><i class="fas fa-user"></i> ${customerName}</h6>
                <button type="button" class="btn btn-sm btn-outline-light" onclick="removeCustomerSection('${customerId}')">
                    <i class="fas fa-times"></i> Remove
                </button>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <button type="button" class="btn btn-primary btn-sm" onclick="showAddItemModal('${customerId}')">
                        <i class="fas fa-plus"></i> Add Item from OGP
                    </button>
                </div>
                <div class="table-responsive">
                    <table class="table table-sm table-striped">
                        <thead class="table-light">
                            <tr>
                                <th>Item</th>
                                <th>Factory Invoice Qty</th>
                                <th>Available Qty</th>
                                <th>Deliver Qty</th>
                                <th>Unit Price</th>
                                <th>Notes</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="customer-items-${customerId}">
                            <!-- Items will be added here -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;

    $('#customerSections').append(sectionHtml);
    customerSections[customerId] = {
        name: customerName,
        items: []
    };
}

function removeCustomerSection(customerId) {
    // Return quantities back to available pool
    if (customerSections[customerId]) {
        customerSections[customerId].items.forEach(customerItem => {
            const availableSpan = $(`#available-${customerItem.gate_pass_item_id}`);
            const currentAvailable = parseFloat(availableSpan.text());
            availableSpan.text(currentAvailable + customerItem.delivered_quantity);
        });
    }

    $(`#customer-section-${customerId}`).remove();
    delete customerSections[customerId];
}

function showAddItemModal(customerId) {
    // Create modal for adding items
    const modalHtml = `
        <div class="modal fade" id="addItemModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Add Item from OGP to ${customerSections[customerId].name}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="table-responsive">
                            <table class="table table-sm table-striped">
                                <thead class="table-light">
                                    <tr>
                                        <th>Select</th>
                                        <th>Item</th>
                                        <th>Original Customer</th>
                                        <th>Available Qty</th>
                                        <th>Deliver Qty</th>
                                        <th>Unit Price</th>
                                    </tr>
                                </thead>
                                <tbody id="add-item-body">
                                    <!-- Items will be loaded here -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" onclick="addSelectedItems('${customerId}')">Add Selected Items</button>
                    </div>
                </div>
            </div>
        </div>
    `;

    // Remove existing modal if any
    $('#addItemModal').remove();
    $('body').append(modalHtml);

    // Populate modal with available items
    const tbody = $('#add-item-body');
    tbody.empty();

    gatePassItems.forEach(item => {
        const availableQty = parseFloat($(`#available-${item.id}`).text());
        if (availableQty > 0) {
            const row = `
                <tr>
                    <td>
                        <input type="checkbox" class="form-check-input item-checkbox"
                               data-item-id="${item.id}" data-max-qty="${availableQty}" data-unit-price="${item.unit_price}">
                    </td>
                    <td>${item.item_name}</td>
                    <td>${item.customer_name}</td>
                    <td class="text-center">${availableQty}</td>
                    <td>
                        <input type="number" class="form-control form-control-sm deliver-qty-input"
                               data-item-id="${item.id}" min="0" max="${availableQty}" step="0.01" value="0" disabled>
                    </td>
                    <td class="text-end">$${parseFloat(item.unit_price).toFixed(2)}</td>
                </tr>
            `;
            tbody.append(row);
        }
    });

    // Handle checkbox changes
    $('.item-checkbox').on('change', function() {
        const itemId = $(this).data('item-id');
        const qtyInput = $(`.deliver-qty-input[data-item-id="${itemId}"]`);
        qtyInput.prop('disabled', !$(this).is(':checked'));
        if (!$(this).is(':checked')) {
            qtyInput.val('0');
        }
    });

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

function addSelectedItems(customerId) {
    $('.item-checkbox:checked').each(function() {
        const itemId = $(this).data('item-id');
        const qtyInput = $(`.deliver-qty-input[data-item-id="${itemId}"]`);
        const quantity = parseFloat(qtyInput.val()) || 0;

        if (quantity > 0) {
            const item = gatePassItems.find(i => i.id == itemId);
            if (item) {
                // Check if item already exists in customer section
                const existingItemIndex = customerSections[customerId].items.findIndex(ci => ci.gate_pass_item_id == itemId);

                if (existingItemIndex >= 0) {
                    // Update existing item
                    const existingItem = customerSections[customerId].items[existingItemIndex];
                    const newQuantity = existingItem.delivered_quantity + quantity;
                    updateCustomerItemQuantity(customerId, itemId, newQuantity);
                } else {
                    // Add new item
                    const customerItem = {
                        gate_pass_item_id: itemId,
                        factory_invoice_id: item.factory_invoice_id,
                        item_name: item.item_name,
                        factory_invoice_quantity: item.factory_invoice_quantity,
                        unit_price: item.unit_price,
                        delivered_quantity: quantity,
                        notes: ''
                    };
                    addItemToCustomerSection(customerId, customerItem, true);
                }

                // Update available quantity
                const availableSpan = $(`#available-${itemId}`);
                const currentAvailable = parseFloat(availableSpan.text());
                availableSpan.text(currentAvailable - quantity);
            }
        }
    });

    $('#addItemModal').modal('hide');
}

function addItemToCustomerSection(customerId, item, isFromModal = false) {
    const tbody = $(`#customer-items-${customerId}`);
    const itemId = item.id || item.gate_pass_item_id;
    const rowId = `item-row-${customerId}-${itemId}`;

    // Check if item already exists
    if ($(`#${rowId}`).length > 0) {
        return; // Item already exists
    }

    const maxQty = isFromModal ? item.delivered_quantity : item.picked_quantity;
    const initialQty = isFromModal ? item.delivered_quantity : 0;

    const row = `
        <tr id="${rowId}">
            <td>
                <div class="fw-bold">${item.item_name}</div>
            </td>
            <td class="text-center">${item.factory_invoice_quantity}</td>
            <td class="text-center">
                <span class="badge bg-warning">${maxQty}</span>
            </td>
            <td>
                <input type="number" class="form-control form-control-sm customer-delivered-qty"
                       name="customer_items[${customerId}][][delivered_quantity]" value="${initialQty}"
                       min="0" max="${maxQty}" step="0.01" required
                       data-item-id="${itemId}" data-customer-id="${customerId}">
                <input type="hidden" name="customer_items[${customerId}][][gate_pass_item_id]" value="${itemId}">
                <input type="hidden" name="customer_items[${customerId}][][factory_invoice_id]" value="${item.factory_invoice_id || item.factory_invoice_id}">
                <input type="hidden" name="customer_items[${customerId}][][customer_account_id]" value="${customerId}">
                <input type="hidden" name="customer_items[${customerId}][][delivered_unit_price]" value="${item.unit_price}">
            </td>
            <td class="text-end">$${parseFloat(item.unit_price).toFixed(2)}</td>
            <td>
                <input type="text" class="form-control form-control-sm"
                       name="customer_items[${customerId}][][notes]" placeholder="Optional" value="${item.notes || ''}">
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-danger" onclick="removeItemFromCustomer('${customerId}', '${itemId}')">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `;

    tbody.append(row);

    // Add to customer sections tracking
    if (!customerSections[customerId].items.find(ci => ci.gate_pass_item_id == itemId)) {
        customerSections[customerId].items.push({
            gate_pass_item_id: itemId,
            factory_invoice_id: item.factory_invoice_id || item.factory_invoice_id,
            delivered_quantity: initialQty
        });
    }

    // Handle quantity changes
    $(`.customer-delivered-qty[data-item-id="${itemId}"][data-customer-id="${customerId}"]`).on('change', function() {
        const newQty = parseFloat($(this).val()) || 0;
        updateCustomerItemQuantity(customerId, itemId, newQty);
    });
}

function updateCustomerItemQuantity(customerId, itemId, newQuantity) {
    const itemIndex = customerSections[customerId].items.findIndex(ci => ci.gate_pass_item_id == itemId);
    if (itemIndex >= 0) {
        const oldQuantity = customerSections[customerId].items[itemIndex].delivered_quantity;
        const difference = newQuantity - oldQuantity;

        // Update available quantity
        const availableSpan = $(`#available-${itemId}`);
        const currentAvailable = parseFloat(availableSpan.text());
        availableSpan.text(currentAvailable - difference);

        // Update tracking
        customerSections[customerId].items[itemIndex].delivered_quantity = newQuantity;
    }
}

function removeItemFromCustomer(customerId, itemId) {
    // Return quantity back to available pool
    const itemIndex = customerSections[customerId].items.findIndex(ci => ci.gate_pass_item_id == itemId);
    if (itemIndex >= 0) {
        const quantity = customerSections[customerId].items[itemIndex].delivered_quantity;
        const availableSpan = $(`#available-${itemId}`);
        const currentAvailable = parseFloat(availableSpan.text());
        availableSpan.text(currentAvailable + quantity);

        // Remove from tracking
        customerSections[customerId].items.splice(itemIndex, 1);
    }

    // Remove row
    $(`#item-row-${customerId}-${itemId}`).remove();
}

function displayFactoryInvoiceOverview() {
    const container = $('#factoryInvoiceContent');
    container.empty();

    if (Object.keys(factoryInvoiceByCustomer).length === 0) {
        container.html('<p class="text-muted">No factory invoice items found for this gate pass.</p>');
        return;
    }

    Object.values(factoryInvoiceByCustomer).forEach(customerData => {
        const customerSection = `
            <div class="mb-4">
                <h5 class="text-primary mb-3">
                    <i class="fas fa-user"></i> ${customerData.customer_name}
                </h5>
                <div class="table-responsive">
                    <table class="table table-sm table-striped">
                        <thead class="table-light">
                            <tr>
                                <th>Item</th>
                                <th>Ordered Quantity</th>
                                <th>Unit Price</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${customerData.items.map(item => `
                                <tr>
                                    <td><strong>${item.item_name}</strong></td>
                                    <td class="text-center">${item.ordered_quantity}</td>
                                    <td class="text-end">$${parseFloat(item.unit_price || 0).toFixed(2)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        `;
        container.append(customerSection);
    });
}

function addDeliveryRow() {
    deliveryRowCount++;
    const rowId = `delivery-row-${deliveryRowCount}`;

    // Create customer options
    let customerOptions = '<option value="">Select Customer</option>';
    availableCustomers.forEach(customer => {
        customerOptions += `<option value="${customer.id}">${customer.name}</option>`;
    });

    // Create item options
    let itemOptions = '<option value="">Select Item</option>';
    availableOgpItems.forEach(item => {
        itemOptions += `<option value="${item.id}" data-available="${item.available_quantity}" data-price="${item.unit_price}" data-factory-invoice-id="${item.factory_invoice_id}">${item.item_name} (Available: ${item.available_quantity})</option>`;
    });

    const row = `
        <tr id="${rowId}">
            <td>
                <select class="form-select form-select-sm delivery-customer" name="delivery_items[${deliveryRowCount}][customer_account_id]" required>
                    ${customerOptions}
                </select>
            </td>
            <td>
                <select class="form-select form-select-sm delivery-item" name="delivery_items[${deliveryRowCount}][gate_pass_item_id]" required>
                    ${itemOptions}
                </select>
                <input type="hidden" name="delivery_items[${deliveryRowCount}][factory_invoice_id]" class="factory-invoice-id">
            </td>
            <td class="text-center">
                <span class="badge bg-info available-qty">0</span>
            </td>
            <td>
                <input type="number" class="form-control form-control-sm delivery-qty"
                       name="delivery_items[${deliveryRowCount}][delivered_quantity]"
                       min="0" step="0.01" value="0" required>
            </td>
            <td>
                <input type="number" class="form-control form-control-sm delivery-price"
                       name="delivery_items[${deliveryRowCount}][delivered_unit_price]"
                       min="0" step="0.01" value="0" readonly>
            </td>
            <td class="text-end delivery-total">$0.00</td>
            <td>
                <input type="text" class="form-control form-control-sm delivery-notes"
                       name="delivery_items[${deliveryRowCount}][notes]" placeholder="Optional">
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-danger" onclick="removeDeliveryRow('${rowId}')">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `;

    $('#deliveryItemsBody').append(row);

    // Attach event handlers
    attachRowEventHandlers(rowId);
}

function attachRowEventHandlers(rowId) {
    const row = $(`#${rowId}`);

    // Item selection change
    row.find('.delivery-item').on('change', function() {
        const selectedOption = $(this).find('option:selected');
        const availableQty = selectedOption.data('available') || 0;
        const price = selectedOption.data('price') || 0;
        const factoryInvoiceId = selectedOption.data('factory-invoice-id') || '';

        row.find('.available-qty').text(availableQty);
        row.find('.delivery-price').val(price.toFixed(2));
        row.find('.factory-invoice-id').val(factoryInvoiceId);
        row.find('.delivery-qty').attr('max', availableQty);

        updateRowTotal(row);
    });

    // Quantity and price change
    row.find('.delivery-qty, .delivery-price').on('input', function() {
        updateRowTotal(row);
    });
}

function updateRowTotal(row) {
    const qty = parseFloat(row.find('.delivery-qty').val()) || 0;
    const price = parseFloat(row.find('.delivery-price').val()) || 0;
    const total = qty * price;

    row.find('.delivery-total').text('$' + total.toFixed(2));
    updateGrandTotal();
}

function updateGrandTotal() {
    let grandTotal = 0;
    $('.delivery-total').each(function() {
        const totalText = $(this).text().replace('$', '');
        grandTotal += parseFloat(totalText) || 0;
    });
    $('#grandTotal').text('$' + grandTotal.toFixed(2));
}

function removeDeliveryRow(rowId) {
    $(`#${rowId}`).remove();
    updateGrandTotal();
}

function saveReceipt() {
    if (!validateForm()) return;

    // Set status to draft
    $('<input>').attr({
        type: 'hidden',
        name: 'status',
        value: 'draft'
    }).appendTo('#receiptForm');

    submitForm();
}

function submitReceipt() {
    if (!validateForm()) return;

    if (!confirm('Are you sure you want to submit this receipt for processing? This will create actual customer transactions.')) {
        return;
    }

    // Set status to submitted
    $('<input>').attr({
        type: 'hidden',
        name: 'status',
        value: 'submitted'
    }).appendTo('#receiptForm');

    submitForm();
}

function validateForm() {
    const deliveryDate = $('[name=delivery_date]').val();
    const deliveredBy = $('[name=delivered_by]').val();

    if (!deliveryDate) {
        alert('Please select a delivery date');
        $('[name=delivery_date]').focus();
        return false;
    }

    if (!deliveredBy) {
        alert('Please select a delivery man');
        $('[name=delivered_by]').focus();
        return false;
    }

    // Check if at least one delivery row exists
    if ($('#deliveryItemsBody tr').length === 0) {
        alert('Please add at least one delivery item');
        return false;
    }

    // Check if all delivery rows are properly filled
    let isValid = true;
    $('#deliveryItemsBody tr').each(function() {
        const row = $(this);
        const customer = row.find('.delivery-customer').val();
        const item = row.find('.delivery-item').val();
        const qty = parseFloat(row.find('.delivery-qty').val()) || 0;
        const availableQty = parseFloat(row.find('.available-qty').text()) || 0;

        if (!customer) {
            alert('Please select a customer for all delivery items');
            row.find('.delivery-customer').focus();
            isValid = false;
            return false;
        }

        if (!item) {
            alert('Please select an item for all delivery items');
            row.find('.delivery-item').focus();
            isValid = false;
            return false;
        }

        if (qty <= 0) {
            alert('Please enter a valid delivery quantity for all items');
            row.find('.delivery-qty').focus();
            isValid = false;
            return false;
        }

        if (qty > availableQty) {
            alert('Delivery quantity cannot exceed available quantity');
            row.find('.delivery-qty').focus();
            isValid = false;
            return false;
        }
    });

    return isValid;
}

function submitForm() {
    $('#saveBtn, #submitBtn').prop('disabled', true);
    $('#saveBtn').html('<i class="fas fa-spinner fa-spin"></i> Updating...');
    $('#submitBtn').html('<i class="fas fa-spinner fa-spin"></i> Submitting...');

    $('#receiptForm').submit();
}
</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\delivery-receipts\edit.blade.php ENDPATH**/ ?>