@extends('layouts.admin-simple')

@section('title', 'Create Site Transfer')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.site-transfers.index') }}">Site Transfers</a></li>
    <li class="breadcrumb-item active">Create</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">Create Site Transfer</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Transfer materials between project sites</p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            <a href="{{ route('warehouse.site-transfers.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="button" class="btn btn-sm btn-primary" id="submitTransferBtn">
                <i class="material-icons mr-1" style="font-size: 16px;">send</i>
                Complete Transfer
            </button>
        </div>
    </div>
@endsection

@section('content')
    <!-- 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

    <!-- Transfer 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>
                Transfer Information
            </h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="transfer_date">Transfer Date <span class="text-danger">*</span></label>
                        <input type="date" id="transfer_date" name="transfer_date"
                               class="form-control @error('transfer_date') is-invalid @enderror"
                               value="{{ old('transfer_date', date('Y-m-d')) }}" required>
                        @error('transfer_date')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="notes">Notes</label>
                        <textarea id="notes" name="notes" class="form-control @error('notes') is-invalid @enderror"
                                  rows="1" placeholder="Optional transfer notes...">{{ old('notes') }}</textarea>
                        @error('notes')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-md-4">
                    <div id="transfer-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="transfer-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 source project to view transferable items
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="from_project_id">From Project <span class="text-danger">*</span></label>
                        <select id="from_project_id" class="form-control @error('from_project_id') is-invalid @enderror" required>
                            <option value="">Select Source Project</option>
                            @foreach($projects as $project)
                                <option value="{{ $project->id }}" {{ old('from_project_id') == $project->id ? 'selected' : '' }}>
                                    {{ $project->project_number ? $project->project_number . ' - ' : '' }}{{ $project->project_name }}
                                </option>
                            @endforeach
                        </select>
                        @error('from_project_id')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                        <small class="form-text text-muted">Select the source project to load all transferable items (FIFO allocation)</small>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="to_project_id">To Project <span class="text-danger">*</span></label>
                        <select id="to_project_id" class="form-control @error('to_project_id') is-invalid @enderror" required>
                            <option value="">Select Destination Project</option>
                            @foreach($projects as $project)
                                <option value="{{ $project->id }}" {{ old('to_project_id') == $project->id ? 'selected' : '' }}>
                                    {{ $project->project_number ? $project->project_number . ' - ' : '' }}{{ $project->project_name }}
                                </option>
                            @endforeach
                        </select>
                        @error('to_project_id')
                            <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>
                    Transfer 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;">swap_horiz</i>
                <h5 class="text-muted">No Project Selected</h5>
                <p class="text-muted">Please select a source project above to load all transferable 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: 22%">Item Description</th>
                            <th style="width: 10%">Item Code</th>
                            <th style="width: 6%">Unit</th>
                            <th style="width: 10%">Total Available</th>
                            <th style="width: 8%">Sources</th>
                            <th style="width: 12%">Transfer Qty</th>
                            <th style="width: 6%">Allocation</th>
                            <th style="width: 10%">Notes</th>
                        </tr>
                    </thead>
                    <tbody id="items-tbody">
                    </tbody>
                </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Form Actions -->
    <div class="card">
        <div class="card-body text-center py-3">
            <button type="button" class="btn btn-success mr-3" id="submitTransferBtnBottom">
                <i class="material-icons mr-1" style="font-size: 16px;">send</i>
                Complete Transfer
            </button>
            <a href="{{ route('warehouse.site-transfers.index') }}" class="btn btn-outline-secondary">
                <i class="material-icons mr-1" style="font-size: 16px;">cancel</i>
                Cancel
            </a>
        </div>
    </div>
@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">
                            </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-transfer {
            background-color: #d4edda !important;
        }

        .item-row.has-transfer: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;
        }

        .transfer-qty-input {
            width: 90px;
        }

        .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 src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

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

        $(document).ready(function() {
            // Initialize Select2
            $('#from_project_id').select2({
                theme: 'bootstrap4',
                placeholder: 'Search and select source project...',
                allowClear: true,
                width: '100%',
                minimumResultsForSearch: 0
            });

            $('#to_project_id').select2({
                theme: 'bootstrap4',
                placeholder: 'Search and select destination project...',
                allowClear: true,
                width: '100%',
                minimumResultsForSearch: 0
            });

            // Handle from project selection - load all project items with FIFO sources
            $('#from_project_id').change(function() {
                const projectId = $(this).val();
                if (projectId) {
                    // Validate not same as destination
                    const toProjectId = $('#to_project_id').val();
                    if (toProjectId && projectId === toProjectId) {
                        Swal.fire('Invalid Selection', 'Source and destination projects cannot be the same.', 'error');
                        $(this).val('').trigger('change.select2');
                        return;
                    }
                    loadProjectItemsConsolidated(projectId);
                } else {
                    clearItemsTable();
                }
            });

            // Validate to project not same as from
            $('#to_project_id').change(function() {
                const toProjectId = $(this).val();
                const fromProjectId = $('#from_project_id').val();
                if (fromProjectId && toProjectId && fromProjectId === toProjectId) {
                    Swal.fire('Invalid Selection', 'Source and destination projects cannot be the same.', 'error');
                    $(this).val('').trigger('change.select2');
                }
            });

            // Submit buttons
            $('#submitTransferBtn, #submitTransferBtnBottom').click(function() {
                submitTransferForm();
            });

            // 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) {
            $('#no-items-message').hide();
            $('#items-table-container').hide();
            $('#loading-message').show();

            const ajaxUrl = "{{ route('warehouse.site-transfers.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) {
                    $('#loading-message').hide();

                    if (response.success && response.data && response.data.items.length > 0) {
                        projectItemsData = response.data.items;
                        $('#item_search_filter').val('');
                        populateItemsTable(response.data.items);
                        showProjectSummary(response.data);
                    } else {
                        showNoItemsMessage('No transferable 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 populateItemsTable(items) {
            let html = '';

            items.forEach(function(item, index) {
                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 sourceCount = item.sources ? item.sources.length : 0;
                const searchText = [
                    item.item_description || '',
                    item.item_code || '',
                    item.notes_search || ''
                ].join(' ').toLowerCase().replace(/"/g, '&quot;');

                html += `
                    <tr class="item-row" data-index="${index}" data-item-id="${item.item_id}" data-search="${searchText}">
                        <td>
                            <strong>${item.item_description}</strong>${focBadge}
                            <input type="hidden" 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-success">${parseFloat(item.total_available_qty).toFixed(2)}</strong>
                        </td>
                        <td class="text-center">
                            <span class="badge badge-info">${sourceCount}</span>
                        </td>
                        <td>
                            <input type="number"
                                   class="form-control form-control-sm transfer-qty-input"
                                   placeholder="0.00"
                                   step="0.01"
                                   min="0"
                                   max="${item.total_available_qty}"
                                   data-max="${item.total_available_qty}"
                                   data-index="${index}">
                        </td>
                        <td class="text-center">
                            <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" class="form-control form-control-sm item-notes" placeholder="Notes" style="width: 100px;">
                        </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="8" class="text-center text-muted py-4">No matching transferable items found.</td>
                        </tr>
                    `);
                }
            } else {
                $('#items-no-search-results').remove();
            }
        }

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

                // Validate doesn't exceed available
                if (transferQty > maxAvailable) {
                    Swal.fire('Exceeds Available', `Maximum available is ${maxAvailable.toFixed(2)} units.`, 'warning');
                    $(this).val(maxAvailable.toFixed(2));
                    autoAllocateFIFO(index, maxAvailable);
                    row.addClass('has-transfer');
                    return;
                }

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

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

        // 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.001; 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,
                        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));
        }

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

            const row = $(`.item-row[data-index="${itemIndex}"]`);
            const transferQty = parseFloat(row.find('.transfer-qty-input').val()) || 0;

            // 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) {
                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>';
                }

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

            if (transferQty > 0) {
                $('#allocation-warning').show();
                $('#allocation-warning-text').text(`You requested ${transferQty.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));

            if (currentEditingItemIndex !== null) {
                const row = $(`.item-row[data-index="${currentEditingItemIndex}"]`);
                const requestedTotal = parseFloat(row.find('.transfer-qty-input').val()) || 0;

                if (Math.abs(total - requestedTotal) > 0.01 && requestedTotal > 0) {
                    $('#allocation-warning').show().removeClass('alert-warning alert-success').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 alert-warning').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,
                        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 transfer qty to match total allocated
            row.find('.transfer-qty-input').val(totalAllocated > 0 ? totalAllocated.toFixed(2) : '');

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

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

        // Show project summary
        function showProjectSummary(data) {
            $('#transfer-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 transfer 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 source project above to load all transferable items.');
            $('#transfer-status-card').hide();
        }

        // Submit transfer form via AJAX
        function submitTransferForm() {
            const fromProjectId = $('#from_project_id').val();
            const toProjectId = $('#to_project_id').val();
            const transferDate = $('#transfer_date').val();
            const notes = $('#notes').val();

            // Validation
            if (!fromProjectId) {
                Swal.fire('Validation Error', 'Please select a source project.', 'warning');
                return;
            }
            if (!toProjectId) {
                Swal.fire('Validation Error', 'Please select a destination project.', 'warning');
                return;
            }
            if (fromProjectId === toProjectId) {
                Swal.fire('Validation Error', 'Source and destination projects cannot be the same.', 'error');
                return;
            }
            if (!transferDate) {
                Swal.fire('Validation Error', 'Please select a transfer date.', 'warning');
                return;
            }

            // Collect items with transfer quantities
            const items = [];
            let hasItems = false;

            $('.item-row').each(function() {
                const index = $(this).data('index');
                const transferQty = parseFloat($(this).find('.transfer-qty-input').val()) || 0;

                if (transferQty > 0) {
                    hasItems = true;

                    // Ensure FIFO allocation exists
                    let allocationsJson = $(this).find('.allocations-data').val();
                    if (!allocationsJson || allocationsJson === '[]') {
                        autoAllocateFIFO(index, transferQty);
                        allocationsJson = $(this).find('.allocations-data').val();
                    }

                    let allocations = [];
                    try {
                        allocations = JSON.parse(allocationsJson);
                    } catch(e) {
                        console.error('Error parsing allocations for item', index);
                    }

                    // Get project_inventory_id - we need to look it up
                    const itemData = projectItemsData[index];

                    // Convert allocations to the format the store method expects
                    const formattedAllocations = allocations.map(function(a) {
                        // For site_transfer sources with allocation_id, use STA prefix
                        if (a.source_type === 'site_transfer' && a.allocation_id) {
                            return {
                                inventory_id: 'STA-' + a.allocation_id,
                                quantity: a.allocated_qty
                            };
                        }

                        // Build the inventory_id prefix based on source_type
                        let prefix = '';
                        switch(a.source_type) {
                            case 'material_request': prefix = 'MR'; break;
                            case 'direct_delivery': prefix = 'DD'; break;
                            case 'supplier_delivery': prefix = 'SD'; break;
                            case 'site_transfer': prefix = 'ST'; break;
                            case 'foc_transfer': prefix = 'FOC'; break;
                        }
                        return {
                            inventory_id: prefix + '-' + a.source_item_id,
                            quantity: a.allocated_qty
                        };
                    });

                    items.push({
                        item_id: itemData.item_id,
                        quantity: transferQty,
                        allocations: formattedAllocations
                    });
                }
            });

            if (!hasItems) {
                Swal.fire('No Items', 'Please specify transfer quantities for at least one item.', 'warning');
                return;
            }

            // Get project names for confirmation
            const fromProjectName = $('#from_project_id option:selected').text().trim();
            const toProjectName = $('#to_project_id option:selected').text().trim();
            const totalQty = items.reduce((sum, item) => sum + item.quantity, 0);

            Swal.fire({
                title: 'Confirm Site Transfer',
                html: `
                    <div class="text-left">
                        <p><strong>From:</strong> ${fromProjectName}</p>
                        <p><strong>To:</strong> ${toProjectName}</p>
                        <p><strong>Items:</strong> ${items.length} item(s)</p>
                        <p><strong>Total Quantity:</strong> ${totalQty.toFixed(2)}</p>
                        <hr>
                        <p class="text-muted mb-0"><small>This will immediately move materials from the source to destination project.</small></p>
                    </div>
                `,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#6c757d',
                confirmButtonText: '<i class="material-icons" style="font-size: 16px; vertical-align: middle;">send</i> Yes, Complete Transfer',
                cancelButtonText: 'Cancel',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    // We need project_inventory_id for each item. Fetch from the API or use a lookup
                    // First, get project inventory mapping
                    $.ajax({
                        url: '{{ route("warehouse.site-transfers.project-inventory") }}',
                        method: 'GET',
                        data: { project_id: fromProjectId },
                        success: function(inventoryResponse) {
                            // Map item_id to project_inventory_id
                            const inventoryMap = {};
                            inventoryResponse.forEach(function(inv) {
                                inventoryMap[inv.item_id] = inv.id;
                            });

                            // Build final items with project_inventory_id
                            const finalItems = items.map(function(item) {
                                return {
                                    project_inventory_id: inventoryMap[item.item_id] || 0,
                                    quantity: item.quantity,
                                    allocations: item.allocations
                                };
                            });

                            // Check all items have inventory IDs
                            const missingInventory = finalItems.filter(i => !i.project_inventory_id);
                            if (missingInventory.length > 0) {
                                Swal.fire('Error', 'Some items could not be mapped to project inventory. Please try again.', 'error');
                                return;
                            }

                            // Submit the form
                            const formData = new FormData();
                            formData.append('_token', '{{ csrf_token() }}');
                            formData.append('from_project_id', fromProjectId);
                            formData.append('to_project_id', toProjectId);
                            formData.append('transfer_date', transferDate);
                            formData.append('notes', notes || '');
                            formData.append('items', JSON.stringify(finalItems));

                            const submitBtn = $('#submitTransferBtn, #submitTransferBtnBottom');
                            submitBtn.prop('disabled', true).html('<i class="material-icons mr-1">hourglass_empty</i>Submitting...');

                            $.ajax({
                                url: '{{ route("warehouse.site-transfers.store") }}',
                                method: 'POST',
                                data: formData,
                                processData: false,
                                contentType: false,
                                success: function(response) {
                                    Swal.fire({
                                        title: 'Transfer Completed!',
                                        text: 'Materials have been transferred successfully.',
                                        icon: 'success',
                                        confirmButtonColor: '#28a745',
                                        confirmButtonText: 'OK'
                                    }).then(() => {
                                        window.location.href = '{{ route("warehouse.site-transfers.index") }}';
                                    });
                                },
                                error: function(xhr) {
                                    let errorMessage = 'An error occurred while submitting the transfer.';

                                    if (xhr.status === 422) {
                                        try {
                                            const response = JSON.parse(xhr.responseText);
                                            if (response.errors) {
                                                errorMessage = '<ul class="text-left mb-0">';
                                                Object.keys(response.errors).forEach(field => {
                                                    errorMessage += `<li>${response.errors[field].join(', ')}</li>`;
                                                });
                                                errorMessage += '</ul>';
                                            }
                                        } catch (e) {
                                            errorMessage = 'Validation failed. Please check your inputs.';
                                        }
                                    } else if (xhr.status === 500) {
                                        errorMessage = 'A server error occurred. Please try again.';
                                    }

                                    Swal.fire({
                                        title: 'Transfer Failed',
                                        html: errorMessage,
                                        icon: 'error',
                                        confirmButtonColor: '#dc3545'
                                    });
                                },
                                complete: function() {
                                    submitBtn.prop('disabled', false);
                                    $('#submitTransferBtn').html('<i class="material-icons mr-1" style="font-size: 16px;">send</i> Complete Transfer');
                                    $('#submitTransferBtnBottom').html('<i class="material-icons mr-1" style="font-size: 16px;">send</i> Complete Transfer');
                                }
                            });
                        },
                        error: function() {
                            Swal.fire('Error', 'Failed to fetch project inventory mapping. Please try again.', 'error');
                        }
                    });
                }
            });
        }
    </script>
@endpush
