<?php

    $isEdit = isset($item);
	// For editing, determine the main category and sub-category
	$mainCategoryId = null;
	$subCategoryId = null;

	if ($isEdit && $item) {
		// Use explicit fields: chart_of_account_id (main) and sub_chart_of_account_id (sub)
		$itemChartAccount = $item->chartOfAccount;
		$inventoryId = optional($inventoryAccount ?? null)->id;
		
		// If sub_chart_of_account_id exists, use it as sub category
		if ($item->sub_chart_of_account_id) {
			$subCategoryId = $item->sub_chart_of_account_id;
			// Main category should be the parent of sub category, or use chart_of_account_id
			if ($item->chart_of_account_id) {
				$mainCategoryId = $item->chart_of_account_id;
			}
		} elseif ($item->chart_of_account_id) {
			// No sub category, check if chart_of_account_id is main or sub
			$isMainCategory = $itemChartAccount && $itemChartAccount->parent_id == $inventoryId;
			$isSubCategory = $itemChartAccount && $itemChartAccount->parent_id != $inventoryId;

			if ($isMainCategory) {
				$mainCategoryId = $itemChartAccount->id;
				$subCategoryId = null;
			} elseif ($isSubCategory) {
				$mainCategoryId = $itemChartAccount->parent_id;
				$subCategoryId = $itemChartAccount->id;
			}
		}
	}
?>

<form action="<?php echo e($isEdit ? route('items.update', $item) : route('items.store')); ?>" method="POST">
	<?php echo csrf_field(); ?>
	<?php if($isEdit): ?>
		<?php echo method_field('PUT'); ?>
	<?php endif; ?>

	<div class="row g-3">
		<div class="col-md-6">
			<label for="name" class="form-label">Name</label>
			<input type="text" id="name" name="name" class="form-control <?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); ?>" value="<?php echo e(old('name', $isEdit && $item ? $item->name : '')); ?>" required>
			<?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>
		<div class="col-md-6">
			<label for="sku" class="form-label">SKU</label>
			<?php if($isEdit && $item): ?>
				<input type="text" id="sku" name="sku" class="form-control <?php $__errorArgs = ['sku'];
$__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); ?>"
					   value="<?php echo e(old('sku', $item->sku)); ?>" readonly>
			<?php else: ?>
				<input type="text" id="sku" name="sku" class="form-control <?php $__errorArgs = ['sku'];
$__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); ?>"
					   value="<?php echo e(old('sku', $itemNumber ?? '')); ?>"
					   data-sku="<?php echo e($itemNumber ?? ''); ?>" required>
			<?php endif; ?>
			<?php $__errorArgs = ['sku'];
$__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>

		<div class="col-md-6">
			<label for="category_id" class="form-label">Category</label>
				<select id="category_id" name="category_id" class="form-select <?php $__errorArgs = ['category_id'];
$__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); ?>" required>
				<option value="">Select Category</option>
				<?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $id => $name): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
					<?php
						$oldCategoryId = old('category_id');
						$isSelected = $oldCategoryId == $id || ($isEdit && $item && !$oldCategoryId && ($mainCategoryId ?? $item->chart_of_account_id) == $id);
						$isRawMaterial = $name === 'Raw Material';
						// Only default to Raw Material if no old value and not editing
						$shouldSelect = $isSelected || (!$isEdit && !$oldCategoryId && $isRawMaterial);
					?>
					<option value="<?php echo e($id); ?>" data-type="<?php echo e($name === 'Raw Material' ? 'RM' : 'FG'); ?>" <?php echo e($shouldSelect ? 'selected' : ''); ?>><?php echo e($name); ?></option>
				<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
			</select>
			<div class="form-text">Select from category</div>
			<?php $__errorArgs = ['category_id'];
$__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>
		<div class="col-md-6">
			<label for="item_category_id" class="form-label">Sub Category</label>
			<select id="item_category_id" name="item_category_id" class="form-select <?php $__errorArgs = ['item_category_id'];
$__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); ?>">
				<option value="">Select Sub Category</option>
				<?php
					$oldSubCategoryId = old('item_category_id');
					$subCategoryToShow = $oldSubCategoryId ?? ($isEdit && $subCategoryId ? $subCategoryId : null);
				?>
				<?php if($subCategoryToShow): ?>
					<?php
						$subCategory = \App\Models\ChartOfAccount::find($subCategoryToShow);
					?>
					<?php if($subCategory): ?>
						<option value="<?php echo e($subCategoryToShow); ?>" selected><?php echo e($subCategory->name); ?></option>
					<?php endif; ?>
				<?php endif; ?>
			</select>
			<div class="form-text">Sub-category based on selected category</div>
			<?php $__errorArgs = ['item_category_id'];
$__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>

		<!-- Type is now determined server-side based on chart_of_account_id -->

		<div class="col-md-6">
			<label for="uom_id" class="form-label">Unit of Measure</label>
			
            <?php echo $__env->make('common.unit-select', [
                'name' => 'uom_id',
                'class' => 'form-select',
                'selected' => old('uom_id', $isEdit ? ($item->uom_id ?? '') : ''),
                'required' => true,
                'placeholder' => 'Select UoM',
                'units' => $uoms
            ], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
            <?php $__errorArgs = ['uom_id'];
$__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>
		
		<div class="col-md-6">
			<label for="barcode" class="form-label">Barcode</label>
			<?php if($isEdit && $item): ?>
				<input type="text" id="barcode" name="barcode" class="form-control <?php $__errorArgs = ['barcode'];
$__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); ?>" value="<?php echo e(old('barcode', $item->barcode)); ?>" readonly>
				<small class="form-text text-muted">Barcode is auto-generated and cannot be changed.</small>
			<?php else: ?>
				<input type="text" id="barcode" name="barcode" class="form-control" value="Auto-generated" readonly disabled>
				<small class="form-text text-muted">Barcode will be auto-generated when item is created.</small>
			<?php endif; ?>
			<?php $__errorArgs = ['barcode'];
$__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>

		<div class="col-md-6" id="price_field" style="display: none;">
			<label for="price" class="form-label">Price (for Finished Goods)</label>
			<input type="number" step="0.01" min="0" id="price" name="price" class="form-control <?php $__errorArgs = ['price'];
$__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); ?>" value="<?php echo e(old('price', $isEdit && $item ? $item->price : '')); ?>">
			<?php $__errorArgs = ['price'];
$__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>

		
		<div class="col-md-6">
			<label for="status" class="form-label">Status</label>
			<select id="status" name="status" class="form-select <?php $__errorArgs = ['status'];
$__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); ?>" required>
				<?php
					$statuses = ['active' => 'Active', 'inactive' => 'Inactive'];
					$currentStatus = 'active';
					if ($isEdit && $item) {
						// Use status field if available, otherwise derive from is_active
						$currentStatus = $item->status ?? ($item->is_active ? 'active' : 'inactive');
					}
					$currentStatus = old('status', $currentStatus);
				?>
				<?php $__currentLoopData = $statuses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
					<option value="<?php echo e($value); ?>" <?php echo e($currentStatus === $value ? 'selected' : ''); ?>><?php echo e($label); ?></option>
				<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
			</select>
			<input type="hidden" name="is_active" value="1">
			<?php $__errorArgs = ['status'];
$__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>

        <div class="col-md-6">
            <label for="reorder_level" class="form-label">Reorder Level 
                <small class="text-muted">(Mark as Low Stock below this qty)</small>
            </label>
            <input type="number" 
                id="reorder_level" 
                name="reorder_level" 
                class="form-control <?php $__errorArgs = ['reorder_level'];
$__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); ?>"
                value="<?php echo e(old('reorder_level', $isEdit && $item ? $item->reorder_level : '')); ?>"
                min="0"
                step="0.01"
                placeholder="e.g. 50" required>
            <?php $__errorArgs = ['reorder_level'];
$__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>


		<!-- Active checkbox removed; status select controls state -->

		
	</div>

    

	<div class="d-flex gap-2 mt-3">
		<button type="submit" class="btn btn-primary"><?php echo e($isEdit && $item ? 'Update' : 'Create'); ?></button>
		<a href="<?php echo e(route('items.index')); ?>" class="btn btn-secondary">Cancel</a>
	</div>
</form>


<?php $__env->startPush('plugin-scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    console.log('Form script loading...');

    const $categoryId = $('#category_id');
    const $name = $('#name');
    const $sku = $('#sku');
    const $form = $('form');
    const $submitBtn = $form.find('button[type="submit"]');
    let skuTimer;
    const excludeId = <?php echo e($isEdit && $item ? (int) $item->id : 'null'); ?>;
    const $uom = $('#uom_id');
    const $subCat = $('#item_category_id');
    const $reorder_level = $('#reorder_level');
    const $status = $('#status');

    // Initialize price field visibility on page load
    <?php if($isEdit && $item): ?>
        <?php
            $chartOfAccount = $item->chartOfAccount;
            $parentAccount = $chartOfAccount ? $chartOfAccount->parent : null;
            $categoryName = $parentAccount ? $parentAccount->name : ($chartOfAccount ? $chartOfAccount->name : '');
            $isFinishedGood = $categoryName === 'Finished Goods';
        ?>
        <?php if($isFinishedGood): ?>
            $('#price_field').show();
        <?php endif; ?>
    <?php endif; ?>

    console.log('Elements found:', {
        categoryId: $categoryId.length,
        subCat: $subCat.length,
        name: $name.length,
        sku: $sku.length
    });


    // Function to handle category change logic
    function handleCategoryChange() {
        const categoryId = $categoryId.val();
        const selectedOption = $categoryId.find('option:selected');
        const type = selectedOption.data('type');

        console.log('Category changed:', categoryId, 'Type:', type);

        // Show/hide price field for Finished Goods
        const $priceField = $('#price_field');
        if (type === 'FG') {
            $priceField.show();
        } else {
            $priceField.hide();
        }

        // Clear sub-category selection and remove existing options
        $subCat.val(null).trigger('change');
        $subCat.find('option:not(:first)').remove(); // Keep only the first "Select Sub Category" option

        // Destroy and reinitialize Select2 to refresh the AJAX call
        if ($subCat.hasClass('select2-hidden-accessible')) {
            $subCat.select2('destroy');
        }

        // Reinitialize Select2 for sub-category with the new parent_id
        initSubCategorySelect2();

        // Regenerate SKU with new type and random number (only in create mode, not edit mode)
        <?php if(!($isEdit && $item)): ?>
            generateSku(true); // Pass true to force regeneration
        <?php endif; ?>
    }

    // When category changes manually
    $categoryId.on('change', function() {
        handleCategoryChange();
    });

    // Function to initialize sub-category Select2
    function initSubCategorySelect2() {
        const selectedCategoryId = $categoryId.val();
        console.log('Initializing sub-category Select2 with parent_id:', selectedCategoryId);

        if (!selectedCategoryId) {
            // If no category selected, just initialize empty Select2
            $subCat.select2({
                width: '100%',
                placeholder: 'Select Category first',
                allowClear: true,
                data: []
            });
            return;
        }

        $subCat.select2({
            width: '100%',
            placeholder: 'Select Sub Category',
            allowClear: true,
            ajax: {
                url: '<?php echo e(route("items.chart-account-children")); ?>',
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    console.log('AJAX call - parent_id:', selectedCategoryId, 'term:', params.term);

                    return {
                        q: params.term || '',
                        parent_id: selectedCategoryId
                    };
                },
                transport: function (params, success, failure) {
                    console.log('Making AJAX request with params:', params.data);
                    var $request = $.ajax(params);

                    $request.then(function(data) {
                        console.log('AJAX success:', data);
                        success(data);
                    });

                    $request.fail(function(jqXHR, textStatus, errorThrown) {
                        console.error('AJAX failed:', textStatus, errorThrown, jqXHR.responseText);
                        failure();
                    });

                    return $request;
                },
                processResults: function (data) {
                    console.log('AJAX response:', data);
                    return {
                        results: data.results || []
                    };
                },
                cache: false // Disable cache to ensure fresh data
            },
            // Trigger loading immediately when opened
            minimumInputLength: 0
        });

        // Trigger the dropdown open to load initial data
        setTimeout(function() {
            if (selectedCategoryId && $subCat.hasClass('select2-hidden-accessible')) {
                // This will trigger the AJAX call to load sub-categories
                $subCat.select2('open').select2('close');
            }
        }, 100);
    }

    // Initialize sub-category Select2 on page load
    initSubCategorySelect2();

    // Generate initial SKU if not editing
    if (!<?php echo e($isEdit && $item ? 'true' : 'false'); ?>) {
        generateSku();
    }

    // On page load, if category is already selected, trigger the logic
    if ($categoryId.val()) {
        console.log('Page load with pre-selected category:', $categoryId.val());

        // Generate SKU for pre-selected category (like Raw Material default)
        if (!<?php echo e($isEdit && $item ? 'true' : 'false'); ?>) {
            generateSku();
        }

        // Check if there's a pre-selected sub-category (for edit mode)
        const preSelectedSubCategory = $subCat.find('option:selected').val();
        console.log('Pre-selected sub-category:', preSelectedSubCategory);

        // Type is now determined server-side based on chart_of_account_id

        if (preSelectedSubCategory) {
            // For edit mode with existing sub-category, initialize Select2 with pre-loaded data
            console.log('Edit mode with existing sub-category, initializing Select2 with pre-loaded data');

            // Initialize Select2 with AJAX capability but also preserve existing option
            $subCat.select2({
                width: '100%',
                placeholder: 'Select Sub Category',
                allowClear: true,
                ajax: {
                    url: '<?php echo e(route("items.chart-account-children")); ?>',
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        return {
                            q: params.term || '',
                            parent_id: $categoryId.val()
                        };
                    },
                    processResults: function (data) {
                        return {
                            results: data.results || []
                        };
                    },
                    cache: false
                },
                minimumInputLength: 0
            });
        } else {
            // No pre-selected sub-category, trigger normal category change logic
            setTimeout(function() {
                handleCategoryChange();
            }, 200);
        }
    }

    function slugify(text){
        return text.toString().toUpperCase()
            .replace(/\s+/g,'-')
            .replace(/[^A-Z0-9\-]/g,'')
            .replace(/\-+/g,'-')
            .replace(/^\-+|\-+$/g,'');
    }

    function generateSku(force = false){
        // Don't generate SKU in edit mode
        <?php if($isEdit && $item): ?>
            return;
        <?php endif; ?>
        
        // Get the type from selected category
        const selectedOption = $categoryId.find('option:selected');
        const type = selectedOption.data('type') || 'RM'; // Default to RM if no type found

        // Generate new SKU if not touched by user OR if forced (category change)
        if (!$sku.data('touched') || force) {
            // If forced (category change), fetch new unique SKU from server
            if (force) {
                $.get('<?php echo e(route('items.generate-sku')); ?>', {
                    type: type,
                    _token: '<?php echo e(csrf_token()); ?>'
                }).done(function(resp){
                    if (resp && resp.sku) {
                        $sku.val(resp.sku);
                        $sku.data('sku', resp.sku); // Update data-sku attribute
                        $sku.data('touched', false); // Reset touched flag
                        // Trigger input event to check uniqueness
                        $sku.trigger('input');
                        console.log('Generated new unique SKU:', resp.sku);
                    }
                }).fail(function(){
                    console.error('Failed to generate SKU');
                    // Fallback to old method
                    const baseSku = $sku.data('sku');
                    if (baseSku) {
                        const numberPart = baseSku.substring(3);
                        $sku.val(type + '-' + numberPart);
                        $sku.trigger('input');
                    }
                });
            } else {
                // Initial load - use the base SKU from data-sku attribute
                const baseSku = $sku.data('sku');
                if (baseSku) {
                    // Extract the number part from the base SKU (e.g., "RM-0001" -> "0001")
                    const numberPart = baseSku.substring(3); // Remove "RM-" prefix
                    $sku.val(type + '-' + numberPart);
                    console.log('Generated SKU:', type + '-' + numberPart);
                }
            }
        }
    }

    // Mark SKU as edited and debounce uniqueness check
    $sku.on('input', function() {
        $(this).data('touched', true);
        clearTimeout(skuTimer);
        const val = $sku.val().trim();
        if (!val) { $submitBtn.prop('disabled', true); return; }
        skuTimer = setTimeout(function() {
            $.post('<?php echo e(route('items.check-sku')); ?>', {
                sku: val,
                exclude_id: excludeId,
                _token: '<?php echo e(csrf_token()); ?>'
            }).done(function(resp){
                if (resp && resp.unique) {
                    $sku.removeClass('is-invalid').addClass('is-valid');
                    $submitBtn.prop('disabled', false);
                } else {
                    // SKU is not unique, automatically generate a new available one
                    const selectedOption = $categoryId.find('option:selected');
                    const type = selectedOption.data('type') || 'RM';
                    
                    $.get('<?php echo e(route('items.generate-sku')); ?>', {
                        type: type,
                        _token: '<?php echo e(csrf_token()); ?>'
                    }).done(function(genResp){
                        if (genResp && genResp.sku) {
                            $sku.val(genResp.sku);
                            $sku.data('sku', genResp.sku); // Update data-sku attribute
                            $sku.removeClass('is-invalid').addClass('is-valid');
                            $submitBtn.prop('disabled', false);
                            console.log('Auto-updated to available SKU:', genResp.sku);
                        } else {
                            $sku.removeClass('is-valid').addClass('is-invalid');
                            $submitBtn.prop('disabled', true);
                        }
                    }).fail(function(){
                        $sku.removeClass('is-valid').addClass('is-invalid');
                        $submitBtn.prop('disabled', true);
                    });
                }
            }).fail(function(){
                $submitBtn.prop('disabled', true);
            });
        }, 300);
    });

    // SKU generation is now handled by category changes
    // Initial generation and check
    if (!$sku.val()) { generateSku(); }
    if ($sku.val()) { $sku.trigger('input'); }
});
</script>
<?php $__env->stopPush(); ?>
<?php /**PATH C:\laragon\www\habibcables-ERP\resources\views/items/form.blade.php ENDPATH**/ ?>