@extends('layouts.admin-simple')

@section('title', 'New Site Return')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.site-return.index') }}">Site Return</a></li>
    <li class="breadcrumb-item active">New Return</li>
@endsection

@section('page-title')
    <div class="d-flex justify-content-between align-items-center w-100">
        <div class="page-title-left">
            <h3 class="mb-1">New Site Return</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Create a new site return operation</p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            <a href="{{ route('warehouse.site-return.index') }}" class="btn btn-sm btn-outline-secondary mr-2">
                <i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i>
                Back to List
            </a>
            <button type="submit" form="returnForm" class="btn btn-sm btn-primary">
                <i class="material-icons mr-1" style="font-size: 16px;">save</i>
                Save Return
            </button>
        </div>
    </div>
@endsection

@section('content')
    <form id="returnForm" action="{{ route('warehouse.incoming-operations.store') }}" method="POST" enctype="multipart/form-data">
        @csrf
        <input type="hidden" name="operation_type" value="site_return">
        <input type="hidden" name="currency" value="AED">
        <input type="hidden" name="exchange_rate" value="1.0000">
        <input type="hidden" name="reference_type" id="reference_type" value="consolidated">

        <!-- Validation Errors -->
        @if ($errors->any())
            <div class="alert alert-danger">
                <h6><i class="material-icons align-middle mr-1">error</i> Please fix the following errors:</h6>
                <ul class="mb-0">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <!-- Basic Information Card -->
        <div class="card mb-3">
            <div class="card-header">
                <h6 class="card-title mb-0 d-flex align-items-center">
                    <i class="material-icons mr-2">info</i>
                    Basic Information
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="operation_number">Return Number</label>
                            <input type="text" name="operation_number" id="operation_number"
                                   class="form-control @error('operation_number') is-invalid @enderror"
                                   placeholder="Auto-generated if empty" value="{{ old('operation_number') }}">
                            @error('operation_number')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="operation_date">Return Date <span class="text-danger">*</span></label>
                            <input type="date" name="operation_date" id="operation_date"
                                   class="form-control @error('operation_date') is-invalid @enderror"
                                   value="{{ old('operation_date', date('Y-m-d')) }}" required>
                            @error('operation_date')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div id="return-status-card" class="alert alert-info" style="display: none;">
                            <strong><i class="material-icons align-middle mr-1">assessment</i> Project Summary</strong>
                            <div id="return-status-content" class="mt-2">
                                <span id="status-badge" class="badge badge-info">Select Project</span>
                                <div id="status-details" class="mt-2 text-muted small">
                                    Select a project to view returnable items
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-12">
                        <div class="form-group">
                            <label for="project_id_select">Project <span class="text-danger">*</span></label>
                            <select name="project_id" id="project_id_select" class="form-control @error('project_id') is-invalid @enderror" required>
                                <option value="">Select Project</option>
                                @foreach($projects ?? [] as $project)
                                    <option value="{{ $project->id }}" {{ old('project_id') == $project->id ? 'selected' : '' }}>
                                        {{ $project->project_number }} - {{ $project->project_name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('project_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                            <small class="form-text text-muted">Select the project to load all returnable items (FIFO allocation)</small>
                        </div>
                    </div>
                </div>

                <!-- File Upload -->
                <div class="row mt-3">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="delivery_file">Return Document</label>
                            <input type="file"
                                   name="delivery_file"
                                   id="delivery_file"
                                   class="form-control @error('delivery_file') is-invalid @enderror"
                                   accept=".pdf,.doc,.docx,.jpg,.jpeg,.png">
                            <small class="form-text text-muted">Upload supporting document (PDF, DOC, DOCX, JPG, PNG - Max: 10MB)</small>
                            @error('delivery_file')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Materials & Items Card -->
        <div class="card mb-3">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="card-title mb-0 d-flex align-items-center">
                        <i class="material-icons mr-2">inventory</i>
                        Return Materials & Items
                    </h6>
                    <small class="text-muted">All project items with auto FIFO allocation</small>
                </div>
            </div>
            <div class="card-body p-0">
                <div id="no-items-message" class="text-center py-5">
                    <i class="material-icons text-muted mb-2" style="font-size: 48px;">assignment</i>
                    <h5 class="text-muted">No Project Selected</h5>
                    <p class="text-muted">Please select a project above to load all returnable items.</p>
                </div>

                <div id="loading-message" class="text-center py-5" style="display: none;">
                    <div class="spinner-border text-primary" role="status">
                        <span class="sr-only">Loading...</span>
                    </div>
                    <p class="text-muted mt-2">Loading project items...</p>
                </div>

                <div id="items-table-container" style="display: none;">
                    <div class="p-3 border-bottom bg-light">
                        <div class="row align-items-center">
                            <div class="col-md-6">
                                <label for="item_search_filter" class="mb-1 font-weight-bold">Search Items</label>
                                <input type="text" id="item_search_filter" class="form-control form-control-sm"
                                       placeholder="Search by item code, description, or saved note">
                            </div>
                        </div>
                    </div>
                    <div class="table-responsive">
                    <table class="table table-sm mb-0" id="items-table">
                        <thead class="bg-light">
                            <tr>
                                <th style="width: 20%">Item Description</th>
                                <th style="width: 8%">Item Code</th>
                                <th style="width: 5%">Unit</th>
                                <th style="width: 8%">Total Issued</th>
                                <th style="width: 8%">Prev. Returned</th>
                                <th style="width: 8%">Transferred</th>
                                <th style="width: 8%">Available</th>
                                <th style="width: 8%">Return Qty</th>
                                <th style="width: 8%">Damaged Qty</th>
                                <th style="width: 9%">Return Reason</th>
                                <th style="width: 5%">Allocation</th>
                                <th style="width: 5%">Notes</th>
                            </tr>
                        </thead>
                        <tbody id="items-tbody">
                            <!-- Item rows will be populated dynamically -->
                        </tbody>
                    </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Received By & Additional Information Card -->
        <div class="card mb-3">
            <div class="card-header">
                <h6 class="card-title mb-0 d-flex align-items-center">
                    <i class="material-icons mr-2">person</i>
                    Received By & Additional Information
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="received_by">Received By</label>
                            <select name="received_by" id="received_by" class="form-control @error('received_by') is-invalid @enderror">
                                <option value="">Select User</option>
                                @foreach($users ?? [] as $user)
                                    <option value="{{ $user->id }}" {{ old('received_by') == $user->id ? 'selected' : '' }}>
                                        {{ $user->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('received_by')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="received_by_name">Received By Name</label>
                            <input type="text" name="received_by_name" id="received_by_name"
                                   class="form-control @error('received_by_name') is-invalid @enderror"
                                   placeholder="Enter full name" value="{{ old('received_by_name', auth()->user()->name ?? '') }}">
                            @error('received_by_name')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="notes">Return Notes</label>
                    <textarea name="notes" id="notes" class="form-control @error('notes') is-invalid @enderror"
                              rows="3" placeholder="Enter return notes, reasons, or additional comments">{{ old('notes') }}</textarea>
                    @error('notes')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-check">
                            <input type="checkbox" name="force_close_return" id="force_close_return"
                                   class="form-check-input" value="1" {{ old('force_close_return') ? 'checked' : '' }}>
                            <label class="form-check-label" for="force_close_return">
                                <i class="material-icons text-warning mr-1" style="font-size: 18px;">warning</i>
                                Force Close Return
                            </label>
                            <small class="form-text text-muted">
                                Check this to forcefully close the return operation without normal approval workflow
                            </small>
                        </div>
                    </div>
                    <div class="col-md-6" id="force_close_reason_container" style="display: none;">
                        <div class="form-group">
                            <label for="force_close_reason">Reason for Force Close <span class="text-danger">*</span></label>
                            <textarea name="force_close_reason" id="force_close_reason" class="form-control @error('force_close_reason') is-invalid @enderror"
                                      rows="3" placeholder="Please provide a reason for force closing this return...">{{ old('force_close_reason') }}</textarea>
                            @error('force_close_reason')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Form Actions -->
        <div class="card">
            <div class="card-body text-center py-3">
                <button type="submit" class="btn btn-success mr-3">
                    <i class="material-icons mr-1" style="font-size: 16px;">assignment_return</i>
                    Return Items to Inventory
                </button>
                <a href="{{ route('warehouse.site-return.index') }}" class="btn btn-outline-secondary">
                    <i class="material-icons mr-1" style="font-size: 16px;">cancel</i>
                    Cancel
                </a>
            </div>
        </div>
    </form>
@endsection

@section('modals')
    <!-- Allocation Modal -->
    <div class="modal fade" id="allocationModal" tabindex="-1" role="dialog" aria-labelledby="allocationModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="allocationModalLabel">
                        <i class="material-icons align-middle mr-2">account_tree</i>
                        FIFO Allocation Details
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <h6 id="modal-item-name" class="font-weight-bold"></h6>
                        <small class="text-muted" id="modal-item-code"></small>
                    </div>
                    <div class="alert alert-info">
                        <i class="material-icons align-middle mr-1" style="font-size: 16px;">info</i>
                        <strong>FIFO Allocation:</strong> Quantities are automatically allocated from oldest sources first. You can manually adjust if needed.
                    </div>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered" id="allocation-table">
                            <thead class="thead-light">
                                <tr>
                                    <th>Reference</th>
                                    <th>Date</th>
                                    <th>Type</th>
                                    <th class="text-right">Available</th>
                                    <th class="text-right" style="width: 100px;">Allocate Qty</th>
                                </tr>
                            </thead>
                            <tbody id="allocation-tbody">
                                <!-- Allocation rows will be populated dynamically -->
                            </tbody>
                            <tfoot>
                                <tr class="table-warning">
                                    <th colspan="4" class="text-right">Total Allocated:</th>
                                    <th class="text-right" id="total-allocated">0.00</th>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    <div id="allocation-warning" class="alert alert-warning mt-2" style="display: none;">
                        <i class="material-icons align-middle mr-1" style="font-size: 16px;">warning</i>
                        <span id="allocation-warning-text"></span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveAllocation">
                        <i class="material-icons align-middle mr-1" style="font-size: 16px;">save</i>
                        Apply Allocation
                    </button>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('styles')
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@1.5.2/dist/select2-bootstrap4.min.css">
    <style>
        .form-group label {
            font-weight: 600;
            color: #495057;
            font-size: 14px;
        }

        .card-title {
            font-size: 16px;
            font-weight: 600;
            color: #495057;
        }

        .table th {
            border-top: none;
            font-weight: 600;
            color: #495057;
            background-color: #f8f9fa;
            font-size: 12px;
        }

        .table td {
            vertical-align: middle;
            font-size: 12px;
        }

        .btn-sm {
            padding: 4px 8px;
            font-size: 11px;
            line-height: 1.5;
        }

        .btn-sm .material-icons {
            font-size: 14px !important;
        }

        .form-control-sm {
            height: calc(1.5em + 0.5rem + 2px);
            padding: 0.25rem 0.5rem;
            font-size: 0.8rem;
        }

        .item-row {
            border-bottom: 1px solid #dee2e6;
        }

        .item-row:hover {
            background-color: #f8f9fa;
        }

        .item-row.has-return {
            background-color: #d4edda !important;
        }

        .item-row.has-return:hover {
            background-color: #c3e6cb !important;
        }

        /* Select2 Bootstrap 4 Theme Overrides */
        .select2-container--bootstrap4 .select2-selection {
            min-height: 38px;
            border: 1px solid #ced4da;
        }
        .select2-container--bootstrap4 .select2-selection--single .select2-selection__rendered {
            line-height: 36px;
            padding-left: 12px;
        }
        .select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow {
            height: 36px;
        }
        .select2-container {
            width: 100% !important;
        }
        .select2-container--open {
            z-index: 9999 !important;
        }
        .select2-dropdown {
            z-index: 9999 !important;
        }

        .badge-source-type {
            font-size: 10px;
            padding: 2px 6px;
        }

        .allocation-btn {
            padding: 2px 6px;
            font-size: 11px;
        }

        .allocation-btn .material-icons {
            font-size: 14px;
        }

        #allocation-table .form-control {
            font-size: 12px;
            padding: 4px 8px;
            height: auto;
        }

        .return-qty-input {
            width: 80px;
        }

        .text-danger {
            color: #dc3545 !important;
        }

        .invalid-feedback {
            display: block;
        }

        .badge-outline-primary {
            color: #007bff;
            background-color: transparent;
            border: 1px solid #007bff;
        }
    </style>
@endpush

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <script>
        // Global data storage for items and their allocations
        let projectItemsData = [];
        let currentEditingItemIndex = null;

        $(document).ready(function() {
            // Initialize Select2 with Bootstrap 4 theme for project dropdown (searchable)
            $('#project_id_select').select2({
                theme: 'bootstrap4',
                placeholder: 'Search and select a project...',
                allowClear: true,
                width: '100%',
                minimumResultsForSearch: 0
            });

            // Initialize Select2 for other dropdowns
            $('#received_by').select2({
                theme: 'bootstrap4',
                placeholder: 'Please select...',
                allowClear: true,
                width: '100%'
            });

            // Handle force close checkbox toggle
            $('#force_close_return').change(function() {
                if ($(this).is(':checked')) {
                    $('#force_close_reason_container').show();
                    $('#force_close_reason').prop('required', true);
                } else {
                    $('#force_close_reason_container').hide();
                    $('#force_close_reason').prop('required', false);
                    $('#force_close_reason').val('');
                }
            });

            // Handle project selection - load all project items with FIFO sources
            $('#project_id_select').change(function() {
                const projectId = $(this).val();
                if (projectId) {
                    loadProjectItemsConsolidated(projectId);
                } else {
                    clearItemsTable();
                }
            });

            // Auto-fill received by name when user is selected
            $('#received_by').change(function() {
                const selectedOption = $(this).find('option:selected');
                if (selectedOption.val()) {
                    $('#received_by_name').val(selectedOption.text());
                }
            });

            // Handle form submission
            $('#returnForm').on('submit', function(e) {
                return validateAndPrepareForm(e);
            });

            // Save allocation button handler
            $('#saveAllocation').click(function() {
                saveAllocationChanges();
            });

            $('#item_search_filter').on('input', function() {
                filterProjectItemsTable($(this).val());
            });
        });

        // Load all project items consolidated with FIFO sources
        function loadProjectItemsConsolidated(projectId) {
            console.log('Loading consolidated items for project ID:', projectId);

            // Show loading state
            $('#no-items-message').hide();
            $('#items-table-container').hide();
            $('#loading-message').show();

            const ajaxUrl = "{{ route('warehouse.site-return.get-project-items-consolidated', ':id') }}".replace(':id', projectId);

            $.ajax({
                url: ajaxUrl,
                method: 'GET',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    'Accept': 'application/json'
                },
                success: function(response) {
                    console.log('Consolidated items response:', response);
                    $('#loading-message').hide();

                    if (response.success && response.data && response.data.items.length > 0) {
                        projectItemsData = response.data.items;
                        $('#item_search_filter').val('');
                        populateConsolidatedItemsTable(response.data.items);
                        showProjectSummary(response.data);
                    } else {
                        showNoItemsMessage('No returnable items found for this project.');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', xhr.responseText);
                    $('#loading-message').hide();
                    showNoItemsMessage('Error loading project items. Please try again.');
                }
            });
        }

        // Populate the items table with consolidated data
        function populateConsolidatedItemsTable(items) {
            let html = '';

            items.forEach(function(item, index) {
                const isFullyReturned = item.total_available_qty <= 0;
                const rowClass = isFullyReturned ? 'table-secondary' : '';
                // Check if any source is FOC
                const hasFocSource = item.sources && item.sources.some(s => s.is_foc === true);
                const focBadge = hasFocSource ? '<span class="badge badge-warning ml-1">FOC</span>' : '';
                const searchText = [
                    item.item_description || '',
                    item.item_code || '',
                    item.notes_search || ''
                ].join(' ').toLowerCase().replace(/"/g, '&quot;');

                html += `
                    <tr class="item-row ${rowClass}" data-index="${index}" data-item-id="${item.item_id}" data-search="${searchText}">
                        <td>
                            <strong>${item.item_description}</strong>${focBadge}
                            <input type="hidden" name="items[${index}][item_id]" value="${item.item_id}">
                            <input type="hidden" name="items[${index}][allocations]" class="allocations-data" value="">
                        </td>
                        <td><code>${item.item_code}</code></td>
                        <td><span class="badge badge-secondary">${item.unit}</span></td>
                        <td class="text-right"><strong class="text-info">${parseFloat(item.total_issued).toFixed(2)}</strong></td>
                        <td class="text-right"><span class="text-warning">${parseFloat(item.total_previously_returned).toFixed(2)}</span></td>
                        <td class="text-right"><span class="text-primary">${parseFloat(item.total_transferred).toFixed(2)}</span></td>
                        <td class="text-right">
                            ${isFullyReturned ?
                                '<span class="badge badge-secondary">Fully Returned</span>' :
                                `<strong class="text-success">${parseFloat(item.total_available_qty).toFixed(2)}</strong>`
                            }
                        </td>
                        <td>
                            ${isFullyReturned ?
                                '<span class="text-muted">N/A</span>' :
                                `<input type="number"
                                       name="items[${index}][returnable_qty]"
                                       class="form-control form-control-sm return-qty-input returnable-qty"
                                       placeholder="0.00"
                                       step="0.01"
                                       min="0"
                                       max="${item.total_available_qty}"
                                       data-max="${item.total_available_qty}"
                                       data-index="${index}">`
                            }
                        </td>
                        <td>
                            ${isFullyReturned ?
                                '<span class="text-muted">N/A</span>' :
                                `<input type="number"
                                       name="items[${index}][damaged_qty]"
                                       class="form-control form-control-sm return-qty-input damaged-qty"
                                       placeholder="0.00"
                                       step="0.01"
                                       min="0"
                                       max="${item.total_available_qty}"
                                       data-max="${item.total_available_qty}"
                                       data-index="${index}">`
                            }
                        </td>
                        <td>
                            <select name="items[${index}][return_reason]" class="form-control form-control-sm">
                                <option value="excess_materials">Excess</option>
                                <option value="project_completion">Completed</option>
                                <option value="damaged_items">Damaged</option>
                                <option value="wrong_specification">Wrong Spec</option>
                                <option value="quality_issues">Quality</option>
                                <option value="other">Other</option>
                            </select>
                        </td>
                        <td class="text-center">
                            ${isFullyReturned ?
                                '<span class="text-muted">-</span>' :
                                `<button type="button" class="btn btn-sm btn-outline-info allocation-btn"
                                         onclick="openAllocationModal(${index})" title="View/Edit FIFO Allocation">
                                    <i class="material-icons">account_tree</i>
                                </button>`
                            }
                        </td>
                        <td>
                            <input type="text" name="items[${index}][notes]" class="form-control form-control-sm" placeholder="Notes" style="width: 80px;">
                        </td>
                    </tr>
                `;
            });

            $('#items-tbody').html(html);
            $('#items-table-container').show();

            // Bind quantity input handlers
            bindQuantityInputHandlers();
        }

        function filterProjectItemsTable(searchTerm) {
            const term = (searchTerm || '').toLowerCase().trim();
            let visibleRows = 0;

            $('#items-tbody .item-row').each(function() {
                const rowSearch = ($(this).data('search') || '').toString().toLowerCase();
                const isMatch = !term || rowSearch.indexOf(term) !== -1;
                $(this).toggle(isMatch);
                if (isMatch) {
                    visibleRows++;
                }
            });

            if (term && visibleRows === 0) {
                if ($('#items-no-search-results').length === 0) {
                    $('#items-tbody').append(`
                        <tr id="items-no-search-results">
                            <td colspan="12" class="text-center text-muted py-4">No matching returnable items found.</td>
                        </tr>
                    `);
                }
            } else {
                $('#items-no-search-results').remove();
            }
        }

        // Bind event handlers to quantity inputs
        function bindQuantityInputHandlers() {
            $('.returnable-qty, .damaged-qty').off('input').on('input', function() {
                const index = $(this).data('index');
                const row = $(this).closest('tr');
                const maxAvailable = parseFloat($(this).data('max'));

                const returnableQty = parseFloat(row.find('.returnable-qty').val()) || 0;
                const damagedQty = parseFloat(row.find('.damaged-qty').val()) || 0;
                const totalQty = returnableQty + damagedQty;

                // Validate total doesn't exceed available
                if (totalQty > maxAvailable) {
                    alert(`Total quantity cannot exceed ${maxAvailable.toFixed(2)} units for this item.`);
                    $(this).val(0);
                    return;
                }

                // Auto-allocate using FIFO
                autoAllocateFIFO(index, totalQty);

                // Visual feedback
                if (totalQty > 0) {
                    row.addClass('has-return');
                } else {
                    row.removeClass('has-return');
                }
            });
        }

        // Auto-allocate quantity using FIFO method
        function autoAllocateFIFO(itemIndex, totalQty) {
            const item = projectItemsData[itemIndex];
            if (!item || !item.sources) return;

            let remainingQty = totalQty;
            const allocations = [];

            // Sources are already sorted by date (FIFO - oldest first)
            for (let i = 0; i < item.sources.length && remainingQty > 0; i++) {
                const source = item.sources[i];
                const availableFromSource = parseFloat(source.available_qty);
                const allocatedQty = Math.min(remainingQty, availableFromSource);

                if (allocatedQty > 0) {
                    allocations.push({
                        source_type: source.source_type,
                        source_id: source.source_id,
                        source_item_id: source.source_item_id,
                        reference_number: source.reference_number,
                        allocated_qty: allocatedQty,
                        unit_price: source.unit_price,
                        division_id: source.division_id || null,
                        is_foc: source.is_foc || false,
                        allocation_id: source.allocation_id || null
                    });
                    remainingQty -= allocatedQty;
                }
            }

            // Store allocations in hidden field
            const row = $(`.item-row[data-index="${itemIndex}"]`);
            row.find('.allocations-data').val(JSON.stringify(allocations));

            console.log(`FIFO Allocation for item ${itemIndex}:`, allocations);
        }

        // Open allocation modal
        function openAllocationModal(itemIndex) {
            currentEditingItemIndex = itemIndex;
            const item = projectItemsData[itemIndex];
            if (!item) return;

            const row = $(`.item-row[data-index="${itemIndex}"]`);
            const returnableQty = parseFloat(row.find('.returnable-qty').val()) || 0;
            const damagedQty = parseFloat(row.find('.damaged-qty').val()) || 0;
            const totalRequestedQty = returnableQty + damagedQty;

            // Get current allocations
            let currentAllocations = [];
            try {
                const allocationsJson = row.find('.allocations-data').val();
                if (allocationsJson) {
                    currentAllocations = JSON.parse(allocationsJson);
                }
            } catch (e) {
                console.error('Error parsing allocations:', e);
            }

            // Populate modal
            $('#modal-item-name').text(item.item_description);
            $('#modal-item-code').text('Code: ' + item.item_code);

            let tableHtml = '';
            item.sources.forEach(function(source, sourceIndex) {
                // Get source type badge
                let typeBadge = '';
                switch (source.source_type) {
                    case 'material_request':
                        typeBadge = '<span class="badge badge-primary badge-source-type">MR</span>';
                        break;
                    case 'direct_delivery':
                        typeBadge = '<span class="badge badge-info badge-source-type">DD</span>';
                        break;
                    case 'supplier_delivery':
                        typeBadge = '<span class="badge badge-warning badge-source-type">SD</span>';
                        break;
                    case 'site_transfer':
                        typeBadge = '<span class="badge badge-success badge-source-type">ST</span>';
                        break;
                    case 'foc_transfer':
                        typeBadge = '<span class="badge badge-danger badge-source-type">FOC</span>';
                        break;
                    default:
                        typeBadge = '<span class="badge badge-secondary badge-source-type">?</span>';
                }

                // Add FOC indicator if it's a FOC source
                const focIndicator = source.is_foc ? ' <span class="badge badge-outline-warning" style="font-size: 9px;">FOC</span>' : '';

                // Find current allocation for this source
                const existingAllocation = currentAllocations.find(a =>
                    a.source_type === source.source_type &&
                    a.source_item_id === source.source_item_id
                );
                const allocatedQty = existingAllocation ? existingAllocation.allocated_qty : 0;

                tableHtml += `
                    <tr data-source-index="${sourceIndex}" data-is-foc="${source.is_foc ? 'true' : 'false'}">
                        <td><strong>${source.reference_number}</strong>${focIndicator}${source.division_name ? '<br><small class="text-muted">' + source.division_name + '</small>' : ''}</td>
                        <td>${source.reference_date_display}</td>
                        <td>${typeBadge}</td>
                        <td class="text-right">${parseFloat(source.available_qty).toFixed(2)}</td>
                        <td>
                            <input type="number" class="form-control form-control-sm allocation-qty-input"
                                   value="${allocatedQty.toFixed(2)}"
                                   min="0" max="${source.available_qty}" step="0.01"
                                   data-source-index="${sourceIndex}"
                                   data-max="${source.available_qty}"
                                   data-is-foc="${source.is_foc ? 'true' : 'false'}">
                        </td>
                    </tr>
                `;
            });

            $('#allocation-tbody').html(tableHtml);
            updateAllocationTotal();

            // Show warning if total requested doesn't match
            if (totalRequestedQty > 0) {
                $('#allocation-warning').show();
                $('#allocation-warning-text').text(`You requested ${totalRequestedQty.toFixed(2)} units. Please ensure allocations match.`);
            } else {
                $('#allocation-warning').hide();
            }

            // Bind allocation input handlers
            $('.allocation-qty-input').on('input', function() {
                const max = parseFloat($(this).data('max'));
                const val = parseFloat($(this).val()) || 0;
                if (val > max) {
                    $(this).val(max.toFixed(2));
                }
                updateAllocationTotal();
            });

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

        // Update the total allocated display
        function updateAllocationTotal() {
            let total = 0;
            $('.allocation-qty-input').each(function() {
                total += parseFloat($(this).val()) || 0;
            });
            $('#total-allocated').text(total.toFixed(2));

            // Update warning based on current return qty
            if (currentEditingItemIndex !== null) {
                const row = $(`.item-row[data-index="${currentEditingItemIndex}"]`);
                const returnableQty = parseFloat(row.find('.returnable-qty').val()) || 0;
                const damagedQty = parseFloat(row.find('.damaged-qty').val()) || 0;
                const requestedTotal = returnableQty + damagedQty;

                if (Math.abs(total - requestedTotal) > 0.01 && requestedTotal > 0) {
                    $('#allocation-warning').show().removeClass('alert-warning').addClass('alert-danger');
                    $('#allocation-warning-text').text(`Mismatch: Allocated ${total.toFixed(2)} vs Requested ${requestedTotal.toFixed(2)}`);
                } else if (total > 0) {
                    $('#allocation-warning').show().removeClass('alert-danger').addClass('alert-success');
                    $('#allocation-warning-text').text(`Allocation matches the requested quantity.`);
                } else {
                    $('#allocation-warning').hide();
                }
            }
        }

        // Save allocation changes
        function saveAllocationChanges() {
            if (currentEditingItemIndex === null) return;

            const item = projectItemsData[currentEditingItemIndex];
            const allocations = [];
            let totalAllocated = 0;

            $('.allocation-qty-input').each(function() {
                const sourceIndex = $(this).data('source-index');
                const qty = parseFloat($(this).val()) || 0;
                if (qty > 0) {
                    const source = item.sources[sourceIndex];
                    allocations.push({
                        source_type: source.source_type,
                        source_id: source.source_id,
                        source_item_id: source.source_item_id,
                        reference_number: source.reference_number,
                        allocated_qty: qty,
                        unit_price: source.unit_price,
                        division_id: source.division_id || null,
                        is_foc: source.is_foc || false,
                        allocation_id: source.allocation_id || null
                    });
                    totalAllocated += qty;
                }
            });

            // Update the hidden field with new allocations
            const row = $(`.item-row[data-index="${currentEditingItemIndex}"]`);
            row.find('.allocations-data').val(JSON.stringify(allocations));

            // Update the return qty fields to match total allocated
            const returnableQty = parseFloat(row.find('.returnable-qty').val()) || 0;
            const damagedQty = parseFloat(row.find('.damaged-qty').val()) || 0;
            const currentTotal = returnableQty + damagedQty;

            // If allocation changed, update the return qty (distribute proportionally to good/damaged)
            if (Math.abs(totalAllocated - currentTotal) > 0.01) {
                if (damagedQty > 0 && returnableQty > 0) {
                    const ratio = returnableQty / currentTotal;
                    row.find('.returnable-qty').val((totalAllocated * ratio).toFixed(2));
                    row.find('.damaged-qty').val((totalAllocated * (1 - ratio)).toFixed(2));
                } else if (damagedQty > 0) {
                    row.find('.damaged-qty').val(totalAllocated.toFixed(2));
                } else {
                    row.find('.returnable-qty').val(totalAllocated.toFixed(2));
                }
            }

            // Update visual feedback
            if (totalAllocated > 0) {
                row.addClass('has-return');
            } else {
                row.removeClass('has-return');
            }

            $('#allocationModal').modal('hide');
            console.log('Saved allocations for item ' + currentEditingItemIndex + ':', allocations);
        }

        // Show project summary
        function showProjectSummary(data) {
            $('#return-status-card').show();
            $('#status-badge').text(`${data.summary.total_unique_items} Items`);
            $('#status-details').html(`
                <div>${data.summary.total_sources} source references available</div>
                <small class="text-muted">Enter return quantities - FIFO allocation will be applied automatically</small>
            `);
        }

        // Show no items message
        function showNoItemsMessage(message) {
            $('#items-table-container').hide();
            $('#no-items-message').show();
            $('#no-items-message h5').text('No Items Found');
            $('#no-items-message p').text(message);
        }

        // Clear items table
        function clearItemsTable() {
            projectItemsData = [];
            $('#items-tbody').html('');
            $('#items-table-container').hide();
            $('#no-items-message').show();
            $('#no-items-message h5').text('No Project Selected');
            $('#no-items-message p').text('Please select a project above to load all returnable items.');
            $('#return-status-card').hide();
        }

        // Validate and prepare form for submission
        function validateAndPrepareForm(e) {
            const projectId = $('#project_id_select').val();

            if (!projectId) {
                e.preventDefault();
                showValidationError('Please select a project first.');
                return false;
            }

            // Check if at least one item has a return quantity > 0
            let hasReturnQuantity = false;
            let hasValidAllocations = true;

            $('.item-row').each(function() {
                const returnableQty = parseFloat($(this).find('.returnable-qty').val()) || 0;
                const damagedQty = parseFloat($(this).find('.damaged-qty').val()) || 0;
                const totalQty = returnableQty + damagedQty;

                if (totalQty > 0) {
                    hasReturnQuantity = true;

                    // Verify allocations exist
                    const allocationsJson = $(this).find('.allocations-data').val();
                    if (!allocationsJson || allocationsJson === '[]') {
                        // Auto-allocate if not already done
                        const index = $(this).data('index');
                        autoAllocateFIFO(index, totalQty);
                    }
                }
            });

            if (!hasReturnQuantity) {
                e.preventDefault();
                showValidationError('Please specify return quantities for at least one item.');
                return false;
            }

            // Remove items with no return quantities
            $('.item-row').each(function() {
                const returnableQty = parseFloat($(this).find('.returnable-qty').val()) || 0;
                const damagedQty = parseFloat($(this).find('.damaged-qty').val()) || 0;
                const totalQty = returnableQty + damagedQty;

                if (totalQty <= 0) {
                    $(this).find('input[name], select[name]').each(function() {
                        $(this).removeAttr('name');
                    });
                }
            });

            return true;
        }

        // Show validation error
        function showValidationError(message) {
            $('.alert-validation-error').remove();
            const errorAlert = `
                <div class="alert alert-danger alert-validation-error">
                    <h6><i class="material-icons align-middle mr-1">error</i> Validation Error:</h6>
                    <p class="mb-0">${message}</p>
                </div>
            `;
            $('#returnForm').prepend(errorAlert);
            $('html, body').animate({
                scrollTop: $('#returnForm').offset().top - 20
            }, 500);
            setTimeout(function() {
                $('.alert-validation-error').fadeOut(500, function() {
                    $(this).remove();
                });
            }, 10000);
        }
    </script>
@endpush
