{{--
    Common Item Select2 Initialization Script

    This script should be included after the Select2 library is loaded.
    It automatically initializes all elements with the 'item-select' class.
--}}

<script>
/**
 * Initialize Item Select2 for a specific element
 */
function initItemSelect(el) {
    if (!el || !$ || !$.fn.select2) {
        console.error('Item Select: jQuery Select2 not available');
        return;
    }

    // Prevent duplicate initialization
    if (el.hasAttribute('data-select2-initialized')) {
        return;
    }

    const $el = $(el);
    const $parent = $(document.body);

    // Get selected item IDs to avoid duplicates
    function getSelectedItemIds() {
        return Array.from(document.querySelectorAll('.item-select'))
            .map(function(sel) { return sel.value; })
            .filter(Boolean);
    }

    // Initialize Select2
    $el.select2({
        theme: 'bootstrap-5',
        placeholder: $el.data('placeholder') || 'Search item…',
        width: '100%',
        dropdownAutoWidth: false,
        closeOnSelect: true,
        allowClear: true,
        dropdownParent: $parent,
        ajax: {
            url: '{{ route('items.search') }}',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term || '',
                    type: 'RM', // Only Raw Material items (accounts, not chart of accounts)
                    page: params.page || 1
                };
            },
            processResults: function (data) {
                const selected = getSelectedItemIds();
                // Filter out already selected items to prevent duplicates
                const filtered = (data.results || []).filter(function(opt) {
                    return selected.indexOf(String(opt.id)) === -1;
                });

                return {
                    results: filtered,
                    pagination: data.pagination || { more: false }
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) {
            return markup;
        },
        templateResult: function (item) {
            if (item.loading) {
                return item.text;
            }

            // Enhanced template showing SKU, name, and UoM
            var $container = $(
                '<div class="item-result">' +
                    '<div class="item-main">' + (item.text || item.name || 'Unknown Item') + '</div>' +
                    '<div class="item-details text-muted small">' +
                        '<span class="item-sku">SKU: ' + (item.sku || 'N/A') + '</span>' +
                        (item.unit_of_measure ? ' | UoM: ' + item.unit_of_measure : '') +
                        (item.barcode ? ' | Barcode: ' + item.barcode : '') +
                    '</div>' +
                '</div>'
            );

            return $container;
        },
        templateSelection: function (item) {
            return item.text || item.name || 'Select an item';
        }
    }).on('select2:open', function() {
        // Force dropdown to open below to avoid positioning issues
        $('.select2-dropdown').removeClass('select2-dropdown--above').addClass('select2-dropdown--below');
    }).on('select2:select', function (e) {
        // Handle item selection - can be extended for specific forms
        const row = this.closest('.pr-item-row, .po-item-row, .item-row');
        if (row) {
            const varSel = row.querySelector('.variation-select');
            if (varSel) {
                $(varSel).val(null).trigger('change');
            }

            // Auto-populate unit display if item has UOM
            const unitDisplay = row.querySelector('.unit-display');
            const unitText = row.querySelector('.unit-text');
            const unitValueInput = row.querySelector('.unit-value-input');

            console.log('Unit display found:', unitDisplay); // Debug log
            if (unitDisplay && unitText && e.params && e.params.data) {
                const itemData = e.params.data;

                console.log('Item selected:', itemData); // Debug log

                let unitDisplayText = '';

                if (itemData.uom_id && itemData.uom_name) {
                    // Use UOM relationship data
                    console.log('Setting UOM:', itemData.uom_name); // Debug log
                    unitDisplayText = itemData.uom_name;
                } else if (itemData.unit_of_measure) {
                    // Fallback to old unit_of_measure field
                    console.log('Setting unit_of_measure:', itemData.unit_of_measure); // Debug log
                    unitDisplayText = itemData.unit_of_measure;
                } else {
                    // No unit information available
                    unitDisplayText = 'No unit specified';
                }

                // Update the hidden input value (if it exists)
                if (unitValueInput) {
                    unitValueInput.value = unitDisplayText;
                }

                // Update the display text
                unitText.textContent = unitDisplayText;

                console.log('Unit display updated:', unitDisplayText); // Debug log
            }
        }
    });

    // Load initial data if provided
    const initialId = el.dataset.initialId;
    const initialText = el.dataset.initialText;

    if (initialId && initialText && !getSelectedItemIds().includes(String(initialId))) {
        const option = new Option(initialText, initialId, true, true);
        $el.append(option).trigger('change');
    }

    // Mark as initialized to prevent duplicate initialization
    el.setAttribute('data-select2-initialized', 'true');
}

/**
 * Initialize all item selects on the page
 */
function initAllItemSelects() {
    document.querySelectorAll('.item-select:not([data-select2-id])').forEach(function(el) {
        initItemSelect(el);
    });
}

// Auto-initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    if (typeof $ !== 'undefined' && $.fn.select2) {
        initAllItemSelects();
        console.log('Item Select2 components initialized');
    } else {
        console.warn('Item Select2: jQuery or Select2 not available');
    }
});

// Make functions globally available for dynamic forms
window.initItemSelect = initItemSelect;
window.initAllItemSelects = initAllItemSelects;

{{--
OLD: Unit select version - commented out (preserved for future use)

// Auto-populate unit select if item has UOM
const unitSelect = row.querySelector('.unit-select') || row.querySelector('select[name*="unit_code"]');
if (unitSelect && e.params && e.params.data) {
    const itemData = e.params.data;

    // Enable the select temporarily to set the value
    unitSelect.disabled = false;

    if (itemData.uom_id && itemData.uom_name) {
        // Check if option exists, if not create it
        let option = unitSelect.querySelector(`option[value="${itemData.uom_name}"]`);
        if (!option) {
            option = document.createElement('option');
            option.value = itemData.uom_name;
            option.textContent = itemData.uom_name;
            unitSelect.appendChild(option);
        }
        unitSelect.value = itemData.uom_name;
    } else if (itemData.unit_of_measure) {
        // Check if option exists, if not create it
        let option = unitSelect.querySelector(`option[value="${itemData.unit_of_measure}"]`);
        if (!option) {
            option = document.createElement('option');
            option.value = itemData.unit_of_measure;
            option.textContent = itemData.unit_of_measure;
            unitSelect.appendChild(option);
        }
        unitSelect.value = itemData.unit_of_measure;
    }

    // Disable the select after setting the value
    unitSelect.disabled = true;
    $(unitSelect).trigger('change');
}
--}}
</script>

<style>
/* Enhanced styling for item select results */
.item-result {
    padding: 4px 0;
}

.item-result .item-main {
    font-weight: 500;
    color: #333;
    margin-bottom: 2px;
}

.item-result .item-details {
    font-size: 0.85em;
    color: #666;
    line-height: 1.2;
}

.item-result .item-sku {
    font-weight: 500;
    color: #007bff;
}

/* Ensure consistent Select2 styling */
.item-select + .select2-container .select2-selection {
    min-height: 38px;
    border-color: #ced4da;
}

.item-select + .select2-container .select2-selection__rendered {
    line-height: 26px;
    padding-left: 12px;
}

.item-select + .select2-container .select2-selection__arrow {
    height: 36px;
    right: 10px;
}

.item-select + .select2-container .select2-selection__placeholder {
    color: #6c757d;
}

/* Error state styling */
.item-select.is-invalid + .select2-container .select2-selection {
    border-color: #dc3545;
}
</style>
