

<?php
    // Set default values
    $fieldId = $id ?? $name ?? 'item_select_' . uniqid();
    $fieldLabel = $label ?? 'Select Item';
    $fieldPlaceholder = $placeholder ?? 'Search for items...';
    $fieldRequired = $required ?? false;
    $fieldClass = $class ?? '';
    $fieldMultiple = $multiple ?? false;
    $fieldAllowClear = $allowClear ?? true;
    $fieldDisabled = $disabled ?? false;
    $fieldShowLabel = $showLabel ?? true;

    // Handle pre-selected item for edit mode
    $preSelectedId = $initialId ?? null;
    $preSelectedText = $initialText ?? null;

    // If selectedItem object is provided, use that instead
    if (isset($selectedItem) && $selectedItem) {
        $preSelectedId = $selectedItem->id;
        $preSelectedText = $selectedItem->sku . ' - ' . $selectedItem->name;
    }
?>

<div class="form-group">
    <?php if($fieldShowLabel && $fieldLabel): ?>
        <label for="<?php echo e($fieldId); ?>" class="form-label">
            <?php echo e($fieldLabel); ?>

            <?php if($fieldRequired): ?><span class="text-danger">*</span><?php endif; ?>
        </label>
    <?php endif; ?>

    <select
        name="<?php echo e($name); ?><?php echo e($fieldMultiple ? '[]' : ''); ?>"
        id="<?php echo e($fieldId); ?>"
        class="form-select item-select2 <?php echo e($fieldClass); ?> <?php $__errorArgs = [$name];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
        <?php if($fieldRequired): ?> required <?php endif; ?>
        <?php if($fieldDisabled): ?> disabled <?php endif; ?>
        <?php if($fieldMultiple): ?> multiple <?php endif; ?>
        data-placeholder="<?php echo e($fieldPlaceholder); ?>"
        data-allow-clear="<?php echo e($fieldAllowClear ? 'true' : 'false'); ?>"
    >
        <option value=""><?php echo e($fieldPlaceholder); ?></option>
        <?php if($preSelectedId): ?>
            <option value="<?php echo e($preSelectedId); ?>" selected><?php echo e($preSelectedText); ?></option>
        <?php endif; ?>
    </select>

    <?php $__errorArgs = [$name];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
        <div class="invalid-feedback"><?php echo e($message); ?></div>
    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>

    <div class="form-text text-muted">
        <small><i class="fas fa-info-circle"></i> Only Raw Material items are shown</small>
    </div>
</div>

<?php $__env->startPush('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize the item Select2 for this specific field
    const itemSelect = document.getElementById('<?php echo e($fieldId); ?>');
    if (itemSelect && typeof $ !== 'undefined' && $.fn.select2) {
        $('#<?php echo e($fieldId); ?>').select2({
            theme: 'bootstrap-5',
            width: '100%',
            placeholder: '<?php echo e($fieldPlaceholder); ?>',
            allowClear: <?php echo e($fieldAllowClear ? 'true' : 'false'); ?>,
            ajax: {
                url: '<?php echo e(route("items.search")); ?>',
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        q: params.term || '',
                        type: 'RM', // Only Raw Material items
                        page: params.page || 1
                    };
                },
                processResults: function (data) {
                    console.log('Item Select2 Response:', data);
                    return {
                        results: data.results || [],
                        pagination: {
                            more: data.pagination && data.pagination.more
                        }
                    };
                },
                cache: true
            },
            minimumInputLength: 0,
            escapeMarkup: function (markup) {
                return markup;
            },
            templateResult: function (item) {
                if (item.loading) {
                    return item.text;
                }

                // Custom template for item display
                var $container = $(
                    '<div class="item-select-result">' +
                        '<div class="item-name">' + (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 : '') +
                        '</div>' +
                    '</div>'
                );

                return $container;
            },
            templateSelection: function (item) {
                // Simple display for selected item
                return item.text || item.name || 'Select an item';
            }
        });

        // Handle pre-selected item in edit mode
        <?php if($preSelectedId): ?>
            console.log('Pre-selecting item:', '<?php echo e($preSelectedId); ?>', '<?php echo e($preSelectedText); ?>');
        <?php endif; ?>

        console.log('Item Select2 initialized for field: <?php echo e($fieldId); ?>');
    } else {
        console.error('Select2 not available or element not found for field: <?php echo e($fieldId); ?>');
    }
});
</script>
<?php $__env->stopPush(); ?>

<style>
.item-select-result {
    padding: 2px 0;
}

.item-select-result .item-name {
    font-weight: 500;
    color: #333;
}

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

.item-select2 + .select2-container .select2-selection {
    min-height: 38px;
    padding: 6px 12px;
    border-color: #ced4da;
}

.item-select2 + .select2-container .select2-selection__rendered {
    line-height: 26px;
}

.item-select2 + .select2-container .select2-selection__arrow {
    height: 36px;
}
</style>
<?php /**PATH C:\laragon\www\habibcables-ERP\resources\views\common\item-select.blade.php ENDPATH**/ ?>