

<?php $__env->startSection('title', 'Create 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-success text-white">
                    <h5 class="mb-0"><i class="fas fa-plus"></i> Create Delivery Receipt</h5>
                </div>
                <div class="card-body">
                    <form id="receiptForm" action="<?php echo e(route('delivery-receipts.store')); ?>" method="POST">
                        <?php echo csrf_field(); ?>

                        <!-- Invoice Selection -->
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Select Invoice</label>
                                <select class="form-select form-select-lg" name="factory_invoice_id" id="invoiceSelect" required>
                                    <option value="">Choose an invoice...</option>
                                    <?php $__currentLoopData = $invoices; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $invoice): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($invoice->id); ?>"
                                                data-customer="<?php echo e($invoice->customer->name ?? 'N/A'); ?>"
                                                data-ordered-amount="<?php echo e($invoice->total_ordered_amount); ?>">
                                            <?php echo e($invoice->invoice_number); ?> - <?php echo e($invoice->customer->name ?? 'N/A'); ?> ($<?php echo e(number_format($invoice->total_ordered_amount, 2)); ?>)
                                        </option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </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(date('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($man->name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                        </div>

                        <!-- Invoice Details (shown when invoice is selected) -->
                        <div id="invoiceDetails" class="d-none">
                            <div class="card border-primary mb-3">
                                <div class="card-header bg-light">
                                    <h6 class="mb-0">Invoice Details</h6>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <p class="mb-1"><strong>Customer:</strong> <span id="customerName"></span></p>
                                            <p class="mb-1"><strong>Ordered Amount:</strong> $<span id="orderedAmount"></span></p>
                                        </div>
                                        <div class="col-md-8">
                                            <div class="table-responsive">
                                                <table class="table table-sm table-striped">
                                                    <thead class="table-light">
                                                        <tr>
                                                            <th>Item</th>
                                                            <th>Ordered</th>
                                                            <th>Picked</th>
                                                            <th>Deliver</th>
                                                            <th>Price</th>
                                                            <th>Notes</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody id="invoiceItemsBody">
                                                        <!-- Items will be loaded here -->
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </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..."></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> Save 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.index')); ?>" class="btn btn-secondary btn-lg">
                                    <i class="fas fa-times"></i> Cancel
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
let currentInvoiceId = null;

$(document).ready(function() {
    // Invoice selection change handler
    $('#invoiceSelect').on('change', function() {
        const invoiceId = $(this).val();
        const selectedOption = $(this).find('option:selected');

        if (invoiceId) {
            currentInvoiceId = invoiceId;
            $('#customerName').text(selectedOption.data('customer'));
            $('#orderedAmount').text(parseFloat(selectedOption.data('ordered-amount')).toFixed(2));
            $('#invoiceDetails').removeClass('d-none');
            loadInvoiceItems(invoiceId);
        } else {
            currentInvoiceId = null;
            $('#invoiceDetails').addClass('d-none');
        }
    });
});

function loadInvoiceItems(invoiceId) {
    $.get('<?php echo e(route("delivery-receipts.invoice-items", ":id")); ?>'.replace(':id', invoiceId))
        .done(function(data) {
            const tbody = $('#invoiceItemsBody');
            tbody.empty();

            data.items.forEach(item => {
                const row = `
                    <tr>
                        <td>
                            <div class="fw-bold">${item.item_name}</div>
                            <small class="text-muted">${item.sku}</small>
                        </td>
                        <td class="text-center">${item.ordered_quantity}</td>
                        <td class="text-center">
                            <span class="badge bg-info">${item.picked_quantity || 0}</span>
                        </td>
                        <td>
                            <input type="number" class="form-control form-control-sm delivered-qty"
                                   name="items[][factory_invoice_item_id]" value="${item.picked_quantity || item.ordered_quantity}"
                                   min="0" max="${item.picked_quantity || item.ordered_quantity}" required>
                            <input type="hidden" name="items[][delivered_quantity]" class="actual-delivered-qty">
                            <input type="hidden" name="items[][delivered_unit_price]" value="${item.ordered_unit_price}">
                        </td>
                        <td class="text-end">$${parseFloat(item.ordered_unit_price).toFixed(2)}</td>
                        <td>
                            <input type="text" class="form-control form-control-sm"
                                   name="items[][notes]" placeholder="Optional">
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });

            // Update hidden fields when delivered qty changes
            $('.delivered-qty').on('input', function() {
                const $row = $(this).closest('tr');
                const deliveredQty = parseFloat($(this).val()) || 0;
                const unitPrice = parseFloat($(this).siblings('[name*="delivered_unit_price"]').val()) || 0;

                $row.find('.actual-delivered-qty').val(deliveredQty);
            });

            // Trigger initial update
            $('.delivered-qty').trigger('input');
        })
        .fail(function() {
            alert('Failed to load invoice items');
        });
}

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 invoiceId = $('#invoiceSelect').val();
    const deliveryDate = $('[name=delivery_date]').val();
    const deliveredBy = $('[name=delivered_by]').val();

    if (!invoiceId) {
        alert('Please select an invoice');
        $('#invoiceSelect').focus();
        return false;
    }

    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 item has delivery quantity
    let hasItems = false;
    $('.delivered-qty').each(function() {
        if (parseFloat($(this).val()) > 0) {
            hasItems = true;
            return false;
        }
    });

    if (!hasItems) {
        alert('Please enter delivery quantities for at least one item');
        return false;
    }

    return true;
}

function submitForm() {
    $('#saveBtn, #submitBtn').prop('disabled', true);
    $('#saveBtn').html('<i class="fas fa-spinner fa-spin"></i> Saving...');
    $('#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_backup\create.blade.php ENDPATH**/ ?>