@extends('layouts.app')

@section('title', 'Create GRN')
@push('plugin-styles')
<style>
    .received-qty:disabled,
    .received-qty[readonly] {
        background-color: #f8f9fa !important;
        color: #6c757d !important;
        cursor: not-allowed !important;
    }

    /* Style for readonly auto-generated number fields */
    input[readonly] {
        background-color: #f8f9fa !important;
        border-color: #dee2e6 !important;
        color: #495057 !important;
        cursor: not-allowed !important;
    }

    input[readonly]:focus {
        box-shadow: none !important;
        border-color: #dee2e6 !important;
    }

    .form-text.text-muted {
        font-size: 0.875em;
        color: #6c757d !important;
    }

    .form-text.text-muted i {
        margin-right: 0.25rem;
    }
</style>
@endpush
@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Create Goods Receipt Note (GRN)</h4>
                </div>
                <div class="card-body">
                    <!-- Display General Errors -->
                    @if ($errors->any())
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <strong>Please fix the following errors:</strong>
                            <ul class="mb-0">
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    @endif

                    <form action="{{ route('grns.store') }}" method="POST" id="grn-form">
                        @csrf

                        <!-- Basic Information -->
                        <div class="row g-3 mb-4">
                            <div class="col-md-3">
                                <label class="form-label">GRN Number</label>
                                <input type="text" name="grn_number" class="form-control @error('grn_number') is-invalid @enderror"
                                       value="{{ old('grn_number', $autoGRNNumber) }}" placeholder="Enter GRN number" readonly>
                                <small class="form-text text-muted">
                                    <i class="fas fa-magic"></i> Auto-generated GRN number
                                </small>
                                @error('grn_number')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Purchase Order *</label>
                                <select name="purchase_order_id" id="purchase_order_id" class="form-select @error('purchase_order_id') is-invalid @enderror" required>
                                    <option value="">Search Purchase Order...</option>
                                </select>
                                @error('purchase_order_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Inward Gate Pass *</label>
                                <select name="inward_gate_pass_id" id="inward_gate_pass_id" class="form-select @error('inward_gate_pass_id') is-invalid @enderror" required>
                                    <option value="">Select IGP (will load after PO selection)</option>
                                </select>
                                @error('inward_gate_pass_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Received Date</label>
                                <input type="date" name="received_date" class="form-control @error('received_date') is-invalid @enderror"
                                       value="{{ old('received_date', now()->format('Y-m-d')) }}" required>
                                @error('received_date')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        <!-- PO Information Display -->
                        <div id="po-info" class="card mb-4" style="display: none;">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Purchase Order Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-3">
                                        <strong>PO Number:</strong> <span id="po-number"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <strong>Supplier:</strong> <span id="po-supplier"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <strong>Order Date:</strong> <span id="po-date"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <strong>Status:</strong> <span id="po-status"></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- IGP Information Display -->
                        <div id="igp-info" class="card mb-4" style="display: none;">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Inward Gate Pass Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-3">
                                        <strong>IGP Number:</strong> <span id="igp-number"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <strong>Vehicle No:</strong> <span id="igp-vehicle"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <strong>Driver:</strong> <span id="igp-driver"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <strong>Gate Entry:</strong> <span id="igp-date"></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Items Section -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Receiving Items</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered" id="items-table">
                                        <thead>
                                            <tr>
                                                <th width="20%">Item</th>
                                                <th width="10%">PO Qty</th>
                                                <th width="10%">Received</th>
                                                <th width="10%">Pending</th>
                                                {{-- <th width="10%">IGP Qty</th> --}}
                                                <th width="10%">Actual Receive Qty *</th>
                                                <th width="10%">UOM</th>
                                                {{-- <th width="10%">Rate</th> --}}
                                                {{-- <th width="10%">Total</th> --}}
                                            </tr>
                                        </thead>
                                        <tbody id="items-tbody">
                                            <!-- Items will be loaded here dynamically -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <!-- Notes -->
                        <div class="row g-3 mb-4">
                            <div class="col-12">
                                <label class="form-label">Notes</label>
                                <textarea name="notes" class="form-control @error('notes') is-invalid @enderror"
                                          rows="3" placeholder="Enter any notes">{{ old('notes') }}</textarea>
                                @error('notes')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        <!-- Submit Buttons -->
                        <div class="row">
                            <div class="col-12">
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save me-1"></i>Create GRN
                                    </button>
                                    <a href="{{ route('grns.index') }}" class="btn btn-secondary">
                                        <i class="fas fa-times me-1"></i>Cancel
                                    </a>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('plugin-styles')
<link rel="stylesheet" href="{{ asset('theme/vendors/select2/select2.min.css') }}">


@endpush

@push('plugin-scripts')
<script src="{{ asset('theme/vendors/jquery/jquery.min.js') }}"></script>
<script src="{{ asset('theme/vendors/select2/select2.min.js') }}"></script>
<script src="{{ asset('theme/vendors/sweetalert2/sweetalert2.min.js') }}"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // const form = document.getElementById('grn-form');
    const poSelect = document.getElementById('purchase_order_id');
    const igpSelect = document.getElementById('inward_gate_pass_id');
    const itemsTbody = document.getElementById('items-tbody');

    let poDetails = null;
    let igpDetails = null;

    // Initialize Select2 for PO with AJAX
    $('#purchase_order_id').select2({
        theme: 'bootstrap-5',
        placeholder: 'Search Purchase Order...',
        allowClear: true,
        ajax: {
            url: '/grns/search-pos',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    search: params.term || ''
                };
            },
            processResults: function (data) {
                return {
                    results: data
                };
            },
            cache: true
        },
        minimumInputLength: 1
    });



    // Initialize Select2 for IGP with AJAX
    $('#inward_gate_pass_id').select2({
        theme: 'bootstrap-5',
        placeholder: 'Select IGP (will load after PO selection)',
        allowClear: true,
        ajax: {
            url: '/grns/search-igps',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    search: params.term || '',
                    supplier_id: window.selectedVendorId || null
                };
            },
            processResults: function (data) {
                return {
                    results: data.data || []
                };
            },
            cache: true
        },
        minimumInputLength: 0
    });

    // Handle PO selection using Select2 events
    $('#purchase_order_id').on('select2:select', function (e) {
        const poId = e.params.data.id;
        const vendorId = e.params.data.vendor_id;
        console.log('PO selection changed to:', poId, 'Vendor ID:', vendorId);
        if (poId) {
            loadPODetails(poId);
            // Load IGP options for this vendor
            loadIGPOptions(vendorId);
            // Clear IGP selection when PO changes
            $('#inward_gate_pass_id').val(null).trigger('change');
            hideIGPInfo();
            // Don't clear items immediately - let loadPODetails handle it
        }
    });

    // Handle PO clearing
    $('#purchase_order_id').on('select2:clear', function (e) {
        console.log('PO selection cleared');
        hidePOInfo();
        $('#inward_gate_pass_id').val(null).trigger('change');
        hideIGPInfo();
        clearItems(); // Clear items when PO is cleared
    });

    // Handle IGP selection
    $('#inward_gate_pass_id').on('select2:select', function (e) {
        const igpId = e.params.data.id;
        if (igpId && poDetails) {
            // Get IGP data from the selected option
            const selectedData = e.params.data;
            igpDetails = {
                id: selectedData.id,
                igp_number: selectedData.igp_number,
                vehicle_no: selectedData.vehicle_no,
                driver_name: selectedData.driver_name,
                gate_entry_datetime: selectedData.gate_entry_datetime,
                status: selectedData.status,
                items: selectedData.items
            };
            displayIGPInfo(igpDetails);
            // Don't reload items when IGP is selected since we removed IGP item logic
            // loadItems(); // Reload items to show IGP quantities
        }
    });

    // Handle IGP clearing
    $('#inward_gate_pass_id').on('select2:clear', function (e) {
        hideIGPInfo();
        clearItems();
    });

    // Load PO details
    function loadPODetails(poId) {
        console.log('Loading PO details for ID:', poId);
        const url = `/grns/po-details?po_id=${poId}`;
        console.log('Fetching from URL:', url);

        fetch(url)
            .then(response => {
                console.log('Response status:', response.status);
                return response.json();
            })
            .then(data => {
                console.log('PO details response:', data);
                if (data.success) {
                    poDetails = data.data;
                    console.log('PO Details set:', poDetails);
                    displayPOInfo(poDetails);
                    				loadIGPOptions(poDetails.po.contact_id);
                    loadItems(); // Load items immediately after PO details are loaded
                } else {
                    console.error('PO details error:', data.message);
                    Swal.fire('Error', data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Fetch error:', error);
                Swal.fire('Error', 'Failed to load PO details', 'error');
            });
    }

    // Display PO information
    function displayPOInfo(data) {
        document.getElementById('po-number').textContent = data.po.po_number;
        document.getElementById('po-supplier').textContent = data.po.vendor.name;
        document.getElementById('po-date').textContent = data.po.order_date;
        document.getElementById('po-status').textContent = data.po.status;
        document.getElementById('po-info').style.display = 'block';
    }

    // Hide PO information
    function hidePOInfo() {
        document.getElementById('po-info').style.display = 'none';
        poDetails = null;
    }

        // Load IGP options for supplier (for initial load)
    function loadIGPOptions(supplierId) {
        console.log('Loading IGPs for supplier ID:', supplierId);
        window.selectedVendorId = supplierId;

        // Clear and refresh the IGP select
        $('#inward_gate_pass_id').val(null).trigger('change');
    }

    // Display IGP information
    function displayIGPInfo(data) {
        document.getElementById('igp-number').textContent = data.igp_number;
        document.getElementById('igp-vehicle').textContent = data.vehicle_no;
        document.getElementById('igp-driver').textContent = data.driver_name || 'N/A';
        document.getElementById('igp-date').textContent = data.gate_entry_datetime;
        document.getElementById('igp-info').style.display = 'block';
    }

    // Hide IGP information
    function hideIGPInfo() {
        document.getElementById('igp-info').style.display = 'none';
        igpDetails = null;
    }

    // Load items table
    function loadItems() {
        console.log('Loading items...', { poDetails, igpDetails });
        if (!poDetails) {
            console.log('No PO details available');
            return;
        }

        // Store current user input values before clearing
        const currentValues = {};
        const existingRows = itemsTbody.querySelectorAll('tr');
        existingRows.forEach((row, index) => {
            const qtyInput = row.querySelector('.received-qty');
            if (qtyInput && qtyInput.value) {
                const itemId = row.querySelector('input[name*="[item_id]"]').value;
                currentValues[itemId] = qtyInput.value;
            }
        });

        itemsTbody.innerHTML = '';
        console.log('PO items:', poDetails.items);

        poDetails.items.forEach((poItem, index) => {
            console.log(`Creating row for item ${index}:`, poItem);
            console.log(`Item ${index} pending_qty:`, poItem.pending_qty);
            console.log(`Item ${index} item_id:`, poItem.item_id);

            const row = createItemRow(poItem, index, currentValues[poItem.item_id]);
            console.log(`Row ${index} created:`, row);
            console.log(`Row ${index} HTML:`, row.innerHTML);

            itemsTbody.appendChild(row);

            // Verify the input field was created
            const qtyInput = row.querySelector('input[name*="[received_quantity]"]');
            console.log(`Item ${index} quantity input:`, qtyInput);
            if (qtyInput) {
                console.log(`Item ${index} quantity input name:`, qtyInput.name);
                console.log(`Item ${index} quantity input value:`, qtyInput.value);
            } else {
                console.error(`Item ${index} missing quantity input!`);
            }
        });
    }

    // Create item row
    function createItemRow(poItem, index, preservedValue = null) {
        const row = document.createElement('tr');
        const maxQty = poItem.pending_qty;
        const inputValue = preservedValue || '';
        // <input type="hidden" name="items[${index}][igp_item_id]" value="">

        row.innerHTML = `
            <td>
                <input type="hidden" name="items[${index}][po_item_id]" value="${poItem.po_item_id}">
                <input type="hidden" name="items[${index}][item_id]" value="${poItem.item_id}">
                ${poItem.item_name}
            </td>
            <td>${poItem.ordered_qty}</td>
            <td>${poItem.received_qty}</td>
            <td>${poItem.pending_qty}</td>
            {{-- <td>${igpQty}</td> --}}
            <td>
                <input type="number" name="items[${index}][received_quantity]"
                       class="form-control received-qty"
                       step="0.01" min="0" max="${maxQty}"
                       value="${inputValue}"
                       placeholder="0.00">
                <div class="invalid-feedback"></div>
            </td>
            <td>${poItem.uom_name}</td>
            {{-- <td>${poItem.rate}</td> --}}
            {{-- <td>
                <span class="line-total">0.00</span>
                <input type="hidden" name="items[${index}][line_total]" value="0">
            </td> --}}
        `;

        // Add event listener for quantity calculation
        const qtyInput = row.querySelector('.received-qty');
        qtyInput.addEventListener('input', function() {
            // calculateLineTotal(row);
            validateQuantity(this, poItem);
        });

        // Check initial state - only disable on form load if already at max and no user input
        const initialValue = parseFloat(qtyInput.value) || 0;

        // If this item has no pending quantity (fully received), set it to readonly with 0
        if (maxQty <= 0) {
            qtyInput.value = '0';
            qtyInput.readOnly = true;
            qtyInput.classList.add('bg-light');
            qtyInput.title = 'Quantity read-only: Item fully received';

            // Add visual indicator
            let indicator = row.querySelector('.quantity-disabled-indicator');
            if (!indicator) {
                indicator = document.createElement('small');
                indicator.className = 'text-muted quantity-disabled-indicator';
                indicator.textContent = '✓ Fully received';
                qtyInput.parentNode.appendChild(indicator);
            }
        } else if (initialValue >= maxQty && !preservedValue) {
            qtyInput.readOnly = true;  // Use readOnly instead of disabled
            qtyInput.classList.add('bg-light');
            qtyInput.title = 'Quantity read-only: Received quantity equals or exceeds maximum allowed quantity';

            // Add visual indicator
            let indicator = row.querySelector('.quantity-disabled-indicator');
            if (!indicator) {
                indicator = document.createElement('small');
                indicator.className = 'text-muted quantity-disabled-indicator';
                indicator.textContent = '✓ Max quantity reached';
                qtyInput.parentNode.appendChild(indicator);
            }
        }

        return row;
    }

    // Calculate line total
    function calculateLineTotal(row) {
        const qtyInput = row.querySelector('.received-qty');
        const rate = parseFloat(row.querySelector('td:nth-child(8)').textContent);
        const qty = parseFloat(qtyInput.value) || 0;
        const total = qty * rate;

        row.querySelector('.line-total').textContent = total.toFixed(2);
        row.querySelector('input[name*="[line_total]"]').value = total.toFixed(2);
    }

    // Validate quantity
    function validateQuantity(input, poItem) {
        const qty = parseFloat(input.value) || 0;
        const maxQty = poItem.pending_qty;
        const feedback = input.parentNode.querySelector('.invalid-feedback');

        input.classList.remove('is-invalid');
        feedback.textContent = '';

        // Allow empty values (handled by backend)
        if (input.value === '' || input.value === null) {
            return; // No validation for empty values
        }

        if (qty > maxQty) {
            input.classList.add('is-invalid');
            feedback.textContent = `Cannot exceed ${maxQty} (PO pending qty)`;
        } else if (qty < 0) {
            input.classList.add('is-invalid');
            feedback.textContent = 'Quantity cannot be negative';
        } else if (qty >= maxQty) {
            // Set to readonly when max quantity is reached (but keep value for form submission)
            input.readOnly = true;
            input.classList.add('bg-light');
            input.title = 'Quantity read-only: Maximum quantity reached';

            // Add visual indicator
            let indicator = input.parentNode.querySelector('.quantity-disabled-indicator');
            if (!indicator) {
                indicator = document.createElement('small');
                indicator.className = 'text-muted quantity-disabled-indicator';
                indicator.textContent = '✓ Max quantity reached';
                input.parentNode.appendChild(indicator);
            }
        } else {
            // Re-enable input if quantity is below max
            input.readOnly = false;
            input.classList.remove('bg-light');
            input.title = '';

            // Remove visual indicator
            const indicator = input.parentNode.querySelector('.quantity-disabled-indicator');
            if (indicator) {
                indicator.remove();
            }
        }
    }

    // Clear items
    function clearItems() {
        itemsTbody.innerHTML = '';
    }

                // Form validation - TEMPORARILY DISABLED FOR TESTING
    form.addEventListener('submit', function(e) {
        console.log('Form submission started...');
        console.log('Form action:', form.action);
        console.log('Form method:', form.method);
        console.log('Form action URL:', form.action);
        console.log('Route name being used:', '{{ route("grns.store") }}');

        // Check CSRF token
        const csrfToken = document.querySelector('input[name="_token"]');
        console.log('CSRF Token found:', csrfToken ? 'Yes' : 'No');
        if (csrfToken) {
            console.log('CSRF Token value:', csrfToken.value);
        }

        // TEMPORARILY BYPASS HTML VALIDATION FOR TESTING
        console.log('Bypassing HTML validation for testing...');

        // Remove required attributes temporarily
        const requiredFields = form.querySelectorAll('[required]');
        requiredFields.forEach(field => {
            field.removeAttribute('required');
        });

        // TEMPORARILY ALLOW SUBMISSION FOR TESTING
        console.log('Allowing form submission for testing...');

        // Re-enable all readonly fields before submission to ensure they're included
        const readonlyFields = form.querySelectorAll('input[readonly]');
        readonlyFields.forEach(field => {
            field.readOnly = false;
            console.log('Re-enabled readonly field:', field.name, 'value:', field.value);
        });

        // Ensure all quantity fields have a value (set to 0 if empty)
        const quantityFields = form.querySelectorAll('input[name*="[received_quantity]"]');
        quantityFields.forEach(field => {
            if (field.value === '' || field.value === null) {
                field.value = '0';
                console.log('Set empty quantity field to 0:', field.name);
            }
        });

        // Double-check that all items have received_quantity values
        console.log('Final check - all quantity fields:');
        quantityFields.forEach(field => {
            console.log(field.name + ':', field.value, 'readonly:', field.readOnly);
        });

        // Add a small delay to see console logs
        setTimeout(() => {
            console.log('Form will submit now...');
        }, 100);

        // Log form data for debugging
        const formData = new FormData(form);
        console.log('Form data being submitted:');
        console.log('Total form entries:', formData.entries().length);

        for (let [key, value] of formData.entries()) {
            console.log(key + ':', value);
        }

        // Specifically check items array
        console.log('Checking items array specifically:');
        const itemsData = {};
        for (let [key, value] of formData.entries()) {
            if (key.startsWith('items[')) {
                itemsData[key] = value;
            }
        }
        console.log('Items data found:', itemsData);

        return true;

        // Original validation code (commented out for testing)
        /*
        // Check required fields
        const poSelect = document.getElementById('purchase_order_id');
        const igpSelect = document.getElementById('inward_gate_pass_id');
        const receivedDate = document.querySelector('input[name="received_date"]');

        console.log('PO Selected:', poSelect.value);
        console.log('IGP Selected:', igpSelect.value);
        console.log('Received Date:', receivedDate.value);

        let hasErrors = false;
        let errorMessages = [];

        // Check PO selection
        if (!poSelect.value) {
            hasErrors = true;
            errorMessages.push('Purchase Order is required');
            poSelect.classList.add('is-invalid');
        } else {
            poSelect.classList.remove('is-invalid');
        }

        // Check IGP selection
        if (!igpSelect.value) {
            hasErrors = true;
            errorMessages.push('Inward Gate Pass is required');
            igpSelect.classList.add('is-invalid');
        } else {
            igpSelect.classList.remove('is-invalid');
        }

        // Check received date
        if (!receivedDate.value) {
            hasErrors = true;
            errorMessages.push('Received Date is required');
            receivedDate.classList.add('is-invalid');
        } else {
            receivedDate.classList.remove('is-invalid');
        }

        // Check quantity inputs
        const qtyInputs = document.querySelectorAll('.received-qty');
        console.log('Found', qtyInputs.length, 'quantity inputs');

        qtyInputs.forEach((input, index) => {
            console.log(`Quantity input ${index}:`, input.value, 'Invalid:', input.classList.contains('is-invalid'));

            if (input.classList.contains('is-invalid') || !input.value || parseFloat(input.value) <= 0) {
                hasErrors = true;
                errorMessages.push(`Invalid quantity for item ${index + 1}`);
            }
        });

        if (hasErrors) {
            e.preventDefault();
            console.log('Form submission prevented due to errors:', errorMessages);
            Swal.fire('Validation Error', errorMessages.join('\n'), 'error');
        } else {
            console.log('Form validation passed, proceeding with submission...');
        }
        */
    });


});
</script>
@endpush
