

<?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">
                    <?php if($errors->any()): ?>
                        <div class="alert alert-danger">
                            <h6>Please fix the following errors:</h6>
                            <ul class="mb-0">
                                <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <li><?php echo e($error); ?></li>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </ul>
                        </div>
                    <?php endif; ?>

                    <form id="receiptForm" action="<?php echo e(route('delivery-receipts.store')); ?>" method="POST">
                        <?php echo csrf_field(); ?>

                        <!-- Gate Pass Selection -->
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Select Gate Pass</label>
                                <select class="form-select form-select-lg" name="gate_pass_id" id="gatePassSelect" required>
                                    <option value="">Choose a gate pass...</option>
                                    <?php $__currentLoopData = $gatePasses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $gatePass): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($gatePass->id); ?>"
                                                data-customer="<?php echo e($gatePass->customer->name ?? 'N/A'); ?>"
                                                data-gate-pass-number="<?php echo e($gatePass->gate_pass_number); ?>">
                                            <?php echo e($gatePass->gate_pass_number); ?>

                                        </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>

                        <!-- Factory Invoice Overview (shown when gate pass is selected) -->
                        <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>

                        <!-- Invoice Sections (will be populated dynamically) -->
                        <div id="customerSections">
                            <!-- Factory invoice sections with delivery items will be added here -->
                        </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">
                                <a href="<?php echo e(route('delivery-receipts.index')); ?>" class="btn btn-secondary me-2">
                                    <i class="fas fa-times"></i> Cancel
                                </a>
                                
                                <button type="button" class="btn btn-success" id="submitBtn" onclick="submitReceipt()">
                                    <i class="fas fa-paper-plane"></i> Submit Receipt
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="submitReceiptModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-paper-plane text-success me-2"></i>
                    Submit Receipt
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                Are you sure you want to submit this receipt for processing?
                <br>
                <small class="text-danger">
                    This will create actual customer transactions.
                </small>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    Cancel
                </button>

                <button type="button" class="btn btn-success" id="modalSubmitReceiptBtn">
                    Yes, Submit
                </button>
            </div>

        </div>
    </div>
</div>

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

<?php $__env->startPush('styles'); ?>
<style>
.delivery-total {
    font-weight: bold;
    color: #28a745;
}

.is-invalid {
    border-color: #dc3545;
}

.invalid-feedback {
    color: #dc3545;
    font-size: 0.875rem;
    margin-top: 0.25rem;
}
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
$(document).ready(function() {
    // Gate pass selection change handler
    $('#gatePassSelect').on('change', function() {
        const gatePassId = $(this).val();

        if (gatePassId) {
            loadGatePassData(gatePassId);
        } else {
            $('#factoryInvoiceOverview').addClass('d-none');
            $('#customerSections').empty();
        }
    });
});

// Global variables to store data
let factoryInvoices = [];
let availableOgpItems = [];
let availableCustomers = [];

function loadGatePassData(gatePassId) {
    $.get(`<?php echo e(url('delivery-receipts/gate-pass')); ?>/${gatePassId}/items`)
        .done(function(data) {
            factoryInvoices = data.factory_invoices || [];
            availableOgpItems = data.available_ogp_items || [];
            availableCustomers = data.customers || [];

            // Display factory invoice overview
            displayFactoryInvoiceOverview();

            // Display factory invoices with delivery sections
            displayFactoryInvoices();

            // Show the containers
            $('#factoryInvoiceOverview').removeClass('d-none');
        })
        .fail(function() {
            alert('Failed to load gate pass data');
        });
}

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

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

    factoryInvoices.forEach(invoiceData => {
        const invoiceSection = `
            <div class="mb-4">
                <h5 class="text-primary mb-3">
                    <i class="fas fa-user"></i> ${invoiceData.customer_name} - Invoice ${invoiceData.invoice_number}
                </h5>
                <div class="table-responsive">
                    <table class="table table-sm table-striped">
                        <thead class="table-light">
                            <tr>
                                <th>Item</th>
                                <th>Picked Quantity</th>
                                <th>Available Quantity</th>
                                <th>Unit Price</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${invoiceData.items.map(item => `
                                <tr>
                                    <td><strong>${item.item_name}</strong></td>
                                    <td class="text-center"><span class="badge bg-info">${item.picked_quantity}</span></td>
                                    <td class="text-center"><span class="badge bg-success">${item.available_quantity}</span></td>
                                    <td class="text-end">$${parseFloat(item.unit_price).toFixed(2)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        `;
        container.append(invoiceSection);
    });
}

function displayFactoryInvoices() {
    const container = $('#customerSections');

    if (factoryInvoices.length === 0) {
        container.html('<div class="alert alert-info">No factory invoices found for this gate pass.</div>');
        return;
    }

    factoryInvoices.forEach(invoiceData => {
        // Create invoice section for each factory invoice
        const invoiceSection = `
            <div class="card border-primary mb-4 invoice-section" data-invoice-id="${invoiceData.factory_invoice_id}">
                <div class="card-header bg-primary text-white">
                    <h6 class="mb-0">
                        <i class="fas fa-user"></i>
                        ${invoiceData.customer_name} - Invoice ${invoiceData.invoice_number}
                    </h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered delivery-table" id="delivery-table-${invoiceData.factory_invoice_id}">
                            <thead class="table-dark">
                                <tr>
                                    <th>Item</th>
                                    <th>Picked Qty</th>
                                    <th>Deliver Qty</th>
                                    <th>Unit Price</th>
                                    <th>Total</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="delivery-body-${invoiceData.factory_invoice_id}">
                                <!-- Pre-populate with originally ordered items -->
                                ${invoiceData.items.map((item, index) => `
                                    <tr id="row-${invoiceData.factory_invoice_id}-${index}" data-customer-id="${invoiceData.customer_id}" data-invoice-id="${invoiceData.factory_invoice_id}">
                                        <td>
                                            <strong>${item.item_name}</strong>
                                            <input type="hidden" name="customer_items[${invoiceData.customer_id}][${index}][gate_pass_item_id]" value="${item.gate_pass_item_id || ''}">
                                            <input type="hidden" name="customer_items[${invoiceData.customer_id}][${index}][factory_invoice_id]" value="${invoiceData.factory_invoice_id}">
                                        </td>
                                        <td class="text-center">
                                            <span class="badge bg-info">${item.picked_quantity}</span>
                                        </td>
                                        <td>
                                            <input type="number" class="form-control form-control-sm delivery-qty"
                                                   name="customer_items[${invoiceData.customer_id}][${index}][delivered_quantity]"
                                                   min="0" max="${item.available_quantity}" step="0.01" value="0" required>
                                        </td>
                                        <td>
                                            <input type="number" class="form-control form-control-sm delivery-price"
                                                   name="customer_items[${invoiceData.customer_id}][${index}][delivered_unit_price]"
                                                   min="0" step="0.01" value="${item.unit_price}" readonly required>
                                        </td>
                                        <td class="text-end delivery-total">$0.00</td>
                                        <td>
                                            <button type="button" class="btn btn-danger btn-sm" onclick="removeRow('row-${invoiceData.factory_invoice_id}-${index}')">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                    <button type="button" class="btn btn-success btn-sm mt-2"
                            onclick="addDeliveryRow('${invoiceData.customer_id}', '${invoiceData.factory_invoice_id}')">
                        <i class="fas fa-plus"></i> Add Delivery Item
                    </button>
                </div>
            </div>
        `;
        container.append(invoiceSection);
    });

    // Attach event handlers to existing rows
    $('.delivery-qty, .delivery-price').on('input', function() {
        updateRowTotal($(this).closest('tr'));
    });
}

function addDeliveryRow(customerId, invoiceId) {
    const tbody = $(`#delivery-body-${invoiceId}`);
    const rowCount = tbody.find('tr').length;
    const rowId = `delivery-row-${invoiceId}-${rowCount}`;

    const row = `
        <tr id="${rowId}" data-customer-id="${customerId}" data-invoice-id="${invoiceId}">
            <td>
                <select class="form-select form-select-sm delivery-item" name="customer_items[${customerId}][${rowCount}][gate_pass_item_id]" required>
                    <option value="">Select Item</option>
                    ${availableOgpItems.map(item =>
                        `<option value="${item.id}" data-available="${item.available_quantity}" data-price="${item.unit_price}" data-item-id="${item.item_id}">${item.item_name} (Available: ${item.available_quantity})</option>`
                    ).join('')}
                </select>
                <input type="hidden" name="customer_items[${customerId}][${rowCount}][factory_invoice_id]" value="${invoiceId}">
            </td>
            <td class="text-center">
                <span class="badge bg-secondary">Added</span>
            </td>
            <td>
                <input type="number" class="form-control form-control-sm delivery-qty"
                       name="customer_items[${customerId}][${rowCount}][delivered_quantity]"
                       min="0" step="0.01" value="0" required>
            </td>
            <td>
                <input type="number" class="form-control form-control-sm delivery-price"
                       name="customer_items[${customerId}][${rowCount}][delivered_unit_price]"
                       min="0" step="0.01" value="0" required>
            </td>
            <td class="text-end delivery-total">$0.00</td>
            <td>
                <button type="button" class="btn btn-sm btn-danger" onclick="removeRow('${rowId}')">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `;

    tbody.append(row);
    attachRowEventHandlers(rowId, customerId);
}

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

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

        row.find('.delivery-price').val(price.toFixed(2));
        row.find('.delivery-qty').attr('max', maxQty);

        updateRowTotal(row);
    });

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

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

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));
}


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

    if (!gatePassId) {
        alert('Please select a gate pass');
        $('#gatePassSelect').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 quantity > 0
    let hasItems = false;
    $('.delivery-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 saveReceipt() {
    if (!validateForm()) return;

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

    submitForm();
}

function submitReceipt() {

    if (!validateForm()) return;

    // show modal instead of confirm()
    const modal = new bootstrap.Modal(
        document.getElementById('submitReceiptModal')
    );

    modal.show();
}

$('#modalSubmitReceiptBtn').on('click', function () {

    // disable button to prevent double click
    $(this)
        .prop('disabled', true)
        .html('<i class="fas fa-spinner fa-spin me-1"></i> Processing...');

    // disable main button too
    $('#submitBtn').prop('disabled', true);

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

    // submit form
    $('#receiptForm').submit();
});


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/create.blade.php ENDPATH**/ ?>