@extends('layouts.app')

@section('title', 'Create Delivery Receipt')

@section('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">
                    @if ($errors->any())
                        <div class="alert alert-danger">
                            <h6>Please fix the following errors:</h6>
                            <ul class="mb-0">
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    <form id="receiptForm" action="{{ route('delivery-receipts.store') }}" method="POST">
                        @csrf

                        <!-- 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>
                                    @foreach($gatePasses as $gatePass)
                                        <option value="{{ $gatePass->id }}"
                                                data-customer="{{ $gatePass->customer->name ?? 'N/A' }}"
                                                data-gate-pass-number="{{ $gatePass->gate_pass_number }}">
                                            {{ $gatePass->gate_pass_number }}
                                            {{-- - {{ $gatePass->customer->name ?? 'N/A' }} --}}
                                        </option>
                                    @endforeach
                                </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="{{ 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>
                                    @foreach($deliveryMen as $man)
                                        <option value="{{ $man->id }}">{{ $man->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <!-- Items Table (shown when gate pass is selected) -->
                        <div id="itemsSection" class="d-none">
                            <div class="card border-primary">
                                <div class="card-header bg-primary text-white">
                                    <h6 class="mb-0"><i class="fas fa-truck"></i> Delivery Items</h6>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-striped" id="itemsTable">
                                            <thead class="table-dark">
                                                <tr>
                                                    <th>Item</th>
                                                    <th>Customer</th>
                                                    <th>Ordered Qty</th>
                                                    <th>Available Qty</th>
                                                    <th>Deliver Qty</th>
                                                    <th>Unit Price</th>
                                                    <th>Total</th>
                                                </tr>
                                            </thead>
                                            <tbody id="itemsBody">
                                                <!-- Items will be loaded here -->
                                            </tbody>
                                        </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..."></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="{{ 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>
@endsection

@push('styles')
<style>
.is-invalid {
    border-color: #dc3545 !important;
    box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25) !important;
}

.invalid-feedback {
    display: block;
    color: #dc3545;
    font-size: 0.875rem;
    margin-top: 0.25rem;
}
</style>
@endpush

@push('scripts')
<script>
$(document).ready(function() {
    // Gate pass selection change handler
    $('#gatePassSelect').on('change', function() {
        const gatePassId = $(this).val();

        if (gatePassId) {
            loadGatePassItems(gatePassId);
            $('#itemsSection').removeClass('d-none');
        } else {
            $('#itemsSection').addClass('d-none');
            $('#itemsBody').empty();
        }
    });
});

function loadGatePassItems(gatePassId) {
    $.get(`{{ url('delivery-receipts/gate-pass') }}/${gatePassId}/items`)
        .done(function(data) {
            const tbody = $('#itemsBody');
            tbody.empty();

            data.items.forEach((item, index) => {
                const row = `
                    <tr>
                        <td><strong>${item.item_name}</strong></td>
                        <td>${item.customer_name}</td>
                        <td class="text-center">${item.ordered_quantity}</td>
                        <td class="text-center">${item.available_quantity}</td>
                        <td>
                            <input type="hidden" name="items[${index}][gate_pass_item_id]" value="${item.gate_pass_item_id}">
                            <input type="hidden" name="items[${index}][factory_invoice_id]" value="${item.factory_invoice_id || ''}">
                            <input type="hidden" name="items[${index}][delivered_unit_price]" value="${item.unit_price}">
                            <input type="number" class="form-control delivery-qty"
                                   name="items[${index}][delivered_quantity]"
                                   min="0" max="${item.available_quantity}" step="0.01" value="0" required>
                        </td>
                        <td class="text-end">$${parseFloat(item.unit_price).toFixed(2)}</td>
                        <td class="text-end delivery-total">$0.00</td>
                    </tr>
                `;
                tbody.append(row);
            });

            // Attach event handlers
            $('.delivery-qty').on('input', function() {
                updateRowTotal($(this).closest('tr'));
            });
        })
        .fail(function() {
            alert('Failed to load gate pass items');
        });
}

function updateRowTotal(row) {
    const qty = parseFloat(row.find('.delivery-qty').val()) || 0;
    const priceText = row.find('td:nth-child(6)').text(); // Unit price column
    const price = parseFloat(priceText.replace('$', '')) || 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;

    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 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();
}
    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 => {
        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-file-invoice"></i>
                        Invoice ${invoiceData.invoice_number} - ${invoiceData.customer_name}
                    </h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive mb-3">
                        <table class="table table-sm table-striped">
                            <thead class="table-light">
                                <tr>
                                    <th>Item</th>
                                    <th>Picked Quantity</th>
                                    <th>Available Quantity</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${invoiceData.items.map(item => `
                                    <tr>
                                        <td><strong>${item.item_name}</strong></td>
                                        <td class="text-center">${item.picked_quantity}</td>
                                        <td class="text-center"><span class="badge bg-success">${item.max_deliverable_quantity}</span></td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>

                    <div class="delivery-items-section">
                        <h6 class="text-secondary mb-2">Delivery Items:</h6>
                        <button type="button" class="btn btn-success btn-sm mb-2"
                                onclick="addDeliveryRow('${invoiceData.customer_id}', '${invoiceData.factory_invoice_id}')">
                            <i class="fas fa-plus"></i> Add Delivery Item
                        </button>

                        <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>Deliver Qty</th>
                                        <th>Unit Price</th>
                                        <th>Total</th>
                                        <th>Notes</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="delivery-body-${invoiceData.factory_invoice_id}">
                                    <!-- Delivery items will be added here -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        `;
        container.append(invoiceSection);

        // Auto-populate delivery table with invoice items
        autoPopulateDeliveryItems(invoiceData);
    });
}


    deliveryRowCount++;
    const rowId = `delivery-row-${deliveryRowCount}`;

    const row = `
        <tr id="${rowId}" data-invoice-id="${invoiceId}" data-customer-id="${customerId}">
            <td>
                <input type="hidden" name="temp_gate_pass_item_id" value="${item.gate_pass_item_id}">
                <span class="fw-bold">${item.item_name}</span>
                <input type="hidden" name="temp_customer_account_id" value="${customerId}">
                <input type="hidden" name="temp_factory_invoice_id" value="${invoiceId}">
            </td>
            <td>
                <input type="number" class="form-control form-control-sm delivery-qty"
                       name="temp_delivered_quantity"
                       min="0" max="${item.max_deliverable_quantity}" step="0.01" value="${item.max_deliverable_quantity}" required>
            </td>
            <td>
                <input type="number" class="form-control form-control-sm delivery-price"
                       name="temp_delivered_unit_price"
                       min="0" step="0.01" value="0" required>
            </td>
            <td class="text-end delivery-total">$0.00</td>
            <td>
                <input type="text" class="form-control form-control-sm delivery-notes"
                       name="temp_notes" placeholder="Optional">
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-warning" onclick="removeDeliveryRow('${rowId}')">
                    <i class="fas fa-minus"></i>
                </button>
            </td>
        </tr>
    `;

    $(`#delivery-body-${invoiceId}`).append(row);

    // Update field names for auto-populated rows
    updateRowFieldNames(rowId, customerId);

    // Attach event handlers
    attachRowEventHandlers(rowId, customerId);

    // Set the price and calculate total
    const $rowElement = $(`#${rowId}`);
    $rowElement.find('.delivery-price').val('0.00'); // Default price, can be changed
    updateRowTotal($rowElement);
}

function addDeliveryRow(customerId, invoiceId) {
    deliveryRowCount++;
    const rowId = `delivery-row-${deliveryRowCount}`;

    // Create item options - only show items that are in this OGP
    let itemOptions = '<option value="">Select Item</option>';
    availableOgpItems.forEach(item => {
        const maxQty = item.max_deliverable_quantity;
        itemOptions += `<option value="${item.id}" data-available="${maxQty}" data-price="${item.unit_price}" data-item-id="${item.item_id}">${item.item_name} (Max: ${maxQty})</option>`;
    });

    const row = `
        <tr id="${rowId}" data-invoice-id="${invoiceId}" data-customer-id="${customerId}">
            <td>
                <select class="form-select form-select-sm delivery-item" name="temp_gate_pass_item_select" required>
                    ${itemOptions}
                </select>
                <input type="hidden" name="temp_gate_pass_item_id">
                <input type="hidden" name="temp_customer_account_id" value="${customerId}">
                <input type="hidden" name="temp_factory_invoice_id" value="${invoiceId}">
            </td>
            <td>
                <input type="number" class="form-control form-control-sm delivery-qty"
                       name="temp_delivered_quantity"
                       min="0" step="0.01" value="0" required>
            </td>
            <td>
                <input type="number" class="form-control form-control-sm delivery-price"
                       name="temp_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="temp_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>
    `;

    $(`#delivery-body-${invoiceId}`).append(row);

    // Attach event handlers
    attachRowEventHandlers(rowId, customerId);
}

function attachRowEventHandlers(rowId, invoiceId) {
    const row = $(`#${rowId}`);

    // For auto-populated rows, item is already selected
    if (!row.find('.delivery-item').prop('disabled')) {
        // Item selection change (only for manually added rows)
        row.find('.delivery-item').on('change', function() {
            const selectedOption = $(this).find('option:selected');
            const itemId = selectedOption.val();
            const maxQty = selectedOption.data('available') || 0; // This is max_deliverable_quantity
            const price = selectedOption.data('price') || 0;

            // Set the hidden gate_pass_item_id field
            row.find('[name="temp_gate_pass_item_id"]').val(itemId);

            row.find('.delivery-price').val(price.toFixed(2));
            row.find('.delivery-qty').attr('max', maxQty);

            updateRowTotal(row);
            updateRowFieldNames(rowId, row.closest('tr').data('customer-id'));
        });
    } else {
        // For auto-populated rows, update field names immediately
        const customerId = row.data('customer-id');
        updateRowFieldNames(rowId, customerId);
    }

    // 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();
}

// Removed updateCustomerForRow and updateFactoryInvoiceId as they're no longer needed

function updateRowFieldNames(rowId, customerId) {
    const row = $(`#${rowId}`);

    if (customerId) {
        // Update field names to match controller expectations
        const index = row.index();

        row.find('[name^="temp_"]').each(function() {
            const name = $(this).attr('name');
            let fieldName = name.replace('temp_', '');

            // Handle special case for select vs hidden field
            if (fieldName === 'gate_pass_item_select') {
                fieldName = 'gate_pass_item_id';
            }

            $(this).attr('name', `customer_items[${customerId}][${index}][${fieldName}]`);
        });
    }
}

function updateGrandTotal() {
    // Grand total is no longer needed as each invoice section handles its own totals
    // This function can be removed or kept for future use
}

function removeDeliveryRow(rowId) {
    $(`#${rowId}`).remove();
    // updateGrandTotal(); // Removed as we no longer have a global total
}


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 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 delivery row exists across all invoice sections
    let totalRows = 0;
    $('.delivery-table tbody tr').each(function() {
        totalRows++;
    });

    if (totalRows === 0) {
        alert('Please add at least one delivery item');
        return false;
    }

    // First, clear any previous error highlighting
    $('.delivery-qty, .delivery-item').removeClass('is-invalid');
    $('.invalid-feedback').remove();

    // Check if all delivery rows are properly filled
    let isValid = true;
    $('.delivery-table tbody tr').each(function() {
        const row = $(this);
        const item = row.find('.delivery-item').val();
        const qty = parseFloat(row.find('.delivery-qty').val()) || 0;

        if (!item) {
            row.find('.delivery-item').addClass('is-invalid');
            if (!row.find('.invalid-feedback').length) {
                row.find('.delivery-item').after('<div class="invalid-feedback">Please select an item.</div>');
            }
            if (isValid) row.find('.delivery-item').focus();
            isValid = false;
        }

        if (qty <= 0) {
            row.find('.delivery-qty').addClass('is-invalid');
            if (!row.find('.invalid-feedback').length) {
                row.find('.delivery-qty').after('<div class="invalid-feedback">Please enter a valid quantity.</div>');
            }
            if (isValid) row.find('.delivery-qty').focus();
            isValid = false;
        }
    });

    if (!isValid) return false;

    // Check total quantities per item across all rows
    const itemTotals = {};
    const itemMaxQuantities = {};

    $('.delivery-table tbody tr').each(function() {
        const row = $(this);
        const itemId = row.find('.delivery-item').val();
        const qty = parseFloat(row.find('.delivery-qty').val()) || 0;

        if (itemId && qty > 0) {
            if (!itemTotals[itemId]) {
                itemTotals[itemId] = 0;
                // Get max quantity from the selected option
                const selectedOption = row.find('.delivery-item option:selected');
                itemMaxQuantities[itemId] = selectedOption.data('available') || 0;
            }
            itemTotals[itemId] += qty;
        }
    });

    // Check if any item exceeds its maximum deliverable quantity
    for (const itemId in itemTotals) {
        const totalQty = itemTotals[itemId];
        const maxQty = itemMaxQuantities[itemId];

        if (totalQty > maxQty) {
            // Find all rows with this item and highlight them
            $('.delivery-table tbody tr').each(function() {
                const row = $(this);
                const rowItemId = row.find('.delivery-item').val();
                if (rowItemId === itemId) {
                    row.find('.delivery-qty').addClass('is-invalid');
                    if (!row.find('.invalid-feedback').length) {
                        row.find('.delivery-qty').after(`<div class="invalid-feedback">Total quantity (${totalQty}) exceeds maximum deliverable (${maxQty}).</div>`);
                    }
                }
            });
            if (isValid) {
                // Focus on the first problematic row
                $('.delivery-qty.is-invalid').first().focus();
            }
            isValid = false;
        }
    }

    return isValid;
}

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>
@endpush
