	<?php ($isEdit = isset($purchaseRequest)); ?>
<form action="<?php echo e($isEdit ? route('purchase-requests.update', $purchaseRequest) : route('purchase-requests.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-3">
			<label for="pr_number" class="form-label">PR Number</label>
			<input type="text" id="pr_number" name="pr_number" class="form-control <?php $__errorArgs = ['pr_number'];
$__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('pr_number', $isEdit ? $purchaseRequest->pr_number : ($autoPRNumber ?? ''))); ?>" readonly required>
			<?php if(!$isEdit): ?>
				<small class="form-text text-muted">
					<i class="fas fa-magic"></i> Auto-generated PR number
				</small>
			<?php endif; ?>
			<?php $__errorArgs = ['pr_number'];
$__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-9">
			<label for="remarks" class="form-label">Remarks</label>
			<textarea id="remarks" name="remarks" rows="1" class="form-control"><?php echo e(old('remarks', $isEdit ? $purchaseRequest->remarks : '')); ?></textarea>
			
			
		</div>
	</div>

	<div class="row g-3 mt-3">
		
		<div class="col-md-3">
			<label for="expected_date" class="form-label">Expected Date</label>
	
            <input
    type="date"
    id="expected_date"
    name="expected_date"
    class="form-control <?php $__errorArgs = ['expected_date'];
$__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('expected_date', $isEdit && $purchaseRequest->expected_date ? \Carbon\Carbon::parse($purchaseRequest->expected_date)->format('Y-m-d') : now()->format('Y-m-d'))); ?>"
    min="<?php echo e($isEdit ? $purchaseRequest->created_at->format('Y-m-d') : now()->format('Y-m-d')); ?>"
    required
    >
			<?php $__errorArgs = ['expected_date'];
$__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-3">
			<label for="priority" class="form-label">Priority</label>
			<select id="priority" name="priority" class="form-select <?php $__errorArgs = ['priority'];
$__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 Priority</option>
				<?php ($priorities = ['low' => 'Low', 'medium' => 'Medium', 'high' => 'High', 'urgent' => 'Urgent']); ?>
				<?php $__currentLoopData = $priorities; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
					<option value="<?php echo e($value); ?>" <?php echo e(old('priority', $isEdit ? $purchaseRequest->priority : 'medium') == $value ? 'selected' : ''); ?>><?php echo e($label); ?></option>
				<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
			</select>
			<?php $__errorArgs = ['priority'];
$__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>

	

	<hr class="my-4">
	<h4 class="m-3 text-center">Items</h4>
	<div id="pr-items">
        <div class="row">
            <div class="col-5">
                <label class="form-label">Item Description</label>
            </div>
            
            <div class="col-4">
                <label class="form-label">Quantity</label>
            </div>
            <div class="col-1">
                <label class="form-label">Unit</label>
            </div>

            
        </div>

		<?php ($oldItems = old('items', $isEdit ? $purchaseRequest->items->map(fn($i) => ['item_id' => $i->item_id, 'item_variation_id'=>$i->item_variation_id,'quantity' => $i->quantity, 'unit_code' => $i->unit_code, 'item_name' => $i->item->name ?? '', 'unit_name' => $i->item->uom->name ?? ($i->unit_code ?? '')])->toArray() : [['item_id' => '', 'item_variation_id'=>'', 'quantity' => '', 'unit_code' => '', 'item_name' => '', 'unit_name' => '']])); ?>

		<?php $__currentLoopData = $oldItems; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $row): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
		<div class="row g-2 align-items-end pr-item-row" data-index="<?php echo e($index); ?>">
			<div class="col-md-5">
				<select name="items[<?php echo e($index); ?>][item_id]" class="form-select item-select" required>
					<option value="">Search item...</option>
					<?php if(isset($row['item_id']) && $row['item_id']): ?>
						<option value="<?php echo e($row['item_id']); ?>" selected><?php echo e($row['item_name'] ?? 'Loading...'); ?></option>
					<?php endif; ?>
				</select>
			</div>
			
			<div class="col-md-4">
				<input type="number" step="0.000001" name="items[<?php echo e($index); ?>][quantity]" class="form-control <?php $__errorArgs = ['items.'.$index.'.quantity'];
$__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($row['quantity'] ?? ''); ?>" required>
				<?php $__errorArgs = ['items.'.$index.'.quantity'];
$__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-2">
                

                
                
                <div class="form-control unit-display" style="background-color: #f8f9fa; border-color: #dee2e6; color: #495057; cursor: not-allowed; display: flex; align-items: center; ">
                    <span class="unit-text">
                        <?php if(isset($row['item_id']) && $row['item_id']): ?>
                            <?php echo e($row['unit_name'] ?? 'No unit specified'); ?>

                        <?php else: ?>
                            Select item first
                        <?php endif; ?>
                    </span>
                </div>

			</div>
			
			<div class="col-md-1 m-0 mb-1">
				<button type="button" class="btn btn-outline-danger w-100 remove-row">Remove</button>
			</div>
		</div>
		<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
	</div>
	<div class="mt-2">
		<button type="button" id="add-row" class="btn btn-outline-secondary">Add Item</button>
	</div>

	<div class="d-flex gap-2 mt-4">
		<button type="submit" class="btn btn-primary"><?php echo e($isEdit ? 'Update' : 'Create'); ?></button>
		
	</div>
</form>

<?php $__env->startPush('plugin-styles'); ?>
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/select2/select2.min.css')); ?>">
<style>
/* Remove increment/decrement buttons from number inputs */
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
input[type="number"] {
    -moz-appearance: textfield;
}
/*  Change Select2 dropdown hover (highlight) color / Add for dark blue color appearance*/
.select2-container--bootstrap-5 .select2-results__option--highlighted,
.select2-container--default .select2-results__option--highlighted[aria-selected] {
    background-color: #cce5ff !important; /* Light blue */
    color: #000 !important; /* Dark text */
}

</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('plugin-scripts'); ?>
<script src="<?php echo e(asset('theme/vendors/select2/select2.min.js')); ?>"></script>


<?php echo $__env->make('common.item-select-script', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

<script>
	function initVariationSelect(el) {
		$(el).select2({
			theme: 'bootstrap-5',
			placeholder: 'Variation (optional)',
			ajax: {
				url: '<?php echo e(route('items.variations.search')); ?>',
				dataType: 'json', delay: 250,
				data: function(params){
					const row = el.closest('.pr-item-row');
					const item = row.querySelector('.item-select');
					return { q: params.term || '', item_id: item.value || 0 };
				},
				processResults: function (data) { return data; }, cache: true
			}
		});
	}

	// function loadSupplierInfo(itemId, row) {
	// 	if (!itemId) {
	// 		row.querySelector('.supplier-name').textContent = '';
	// 		row.querySelector('.supplier-price').textContent = '';
	// 		return;
	// 	}

	// 	fetch(`/items/${itemId}/supplier-info`)
	// 		.then(response => response.json())
	// 		.then(data => {
	// 			const supplierName = row.querySelector('.supplier-name');
	// 			const supplierPrice = row.querySelector('.supplier-price');

	// 			if (data.primary_supplier) {
	// 				supplierName.textContent = `Primary: ${data.primary_supplier.contact.name}`;
	// 				supplierPrice.textContent = data.primary_supplier.last_price ?
	// 					`Last Price: ${new Intl.NumberFormat('en-PK', { style: 'currency', currency: 'PKR' }).format(data.primary_supplier.last_price)}` :
	// 					'No price data';
	// 			} else {
	// 				supplierName.textContent = 'No primary supplier';
	// 				supplierPrice.textContent = '';
	// 			}
	// 		})
	// 		.catch(error => {
	// 			console.error('Error loading supplier info:', error);
	// 			row.querySelector('.supplier-name').textContent = 'Error loading supplier info';
	// 			row.querySelector('.supplier-price').textContent = '';
	// 		});
	// }

	// Comprehensive quantity validation function
	function validateQuantityInput(input) {
		const value = parseFloat(input.value);
		const max = parseFloat(input.max);
		const min = parseFloat(input.min);
		const row = input.closest('.pr-item-row') || input.closest('tr');
		const errorDiv = row.querySelector('.quantity-error') || createErrorDiv(row, input);

		// Clear previous errors
		input.classList.remove('is-invalid');
		errorDiv.style.display = 'none';
		errorDiv.textContent = '';

		// Check if value is a valid number
		if (isNaN(value)) {
			showQuantityError(input, errorDiv, 'Please enter a valid number');
			return false;
		}

		// Check for negative values
		if (value < 0) {
			showQuantityError(input, errorDiv, 'Quantity cannot be negative');
			return false;
		}

		// Check minimum value
		if (min && value < min) {
			showQuantityError(input, errorDiv, `Quantity must be at least ${min}`);
			return false;
		}

		// Check maximum value
		if (max && value > max) {
			showQuantityError(input, errorDiv, `Quantity cannot exceed ${max}`);
			return false;
		}

		// Check for zero or empty
		if (value === 0 || input.value.trim() === '') {
			showQuantityError(input, errorDiv, 'Quantity is required and must be greater than 0');
			return false;
		}

		return true;
	}

	function createErrorDiv(row, input) {
		const errorDiv = document.createElement('div');
		errorDiv.className = 'quantity-error invalid-feedback';
		errorDiv.style.display = 'none';
		input.parentNode.appendChild(errorDiv);
		return errorDiv;
	}

	function showQuantityError(input, errorDiv, message) {
		input.classList.add('is-invalid');
		errorDiv.textContent = message;
		errorDiv.style.display = 'block';
	}

	// Apply validation to all quantity inputs
	function setupQuantityValidation() {
		document.querySelectorAll('input[type="number"][name*="[quantity]"]').forEach(function(input) {
			input.addEventListener('input', function() {
				validateQuantityInput(this);
			});

			input.addEventListener('blur', function() {
				validateQuantityInput(this);
			});
		});
	}

	document.addEventListener('DOMContentLoaded', function () {
		const container = document.getElementById('pr-items');
		const addBtn = document.getElementById('add-row');
		let index = container.querySelectorAll('.pr-item-row').length;

		$('.item-select').each(function(){ initItemSelect(this); });
		$('.variation-select').each(function(){ if (this) { initVariationSelect(this); } });

		// Initialize item selects for existing items in edit mode
		$('.item-select').each(function() {
			const $this = $(this);
			const selectedOption = $this.find('option:selected');

			if (selectedOption.length && selectedOption.val()) {
				// Trigger the select2:select event to populate unit display
				$this.trigger('select2:select');
			}
		});

		// Initialize quantity validation
		setupQuantityValidation();

		addBtn.addEventListener('click', function () {
			const row = document.createElement('div');
			row.className = 'row g-2 align-items-end pr-item-row mt-1';
			row.dataset.index = index;
			row.innerHTML = `
				<div class="col-md-5">
					<select name="items[${index}][item_id]" class="form-select item-select" required>
						<option value="">Search item...</option>
					</select>
				</div>
				<div class="col-md-4">
					<input type="number" step="0.01" name="items[${index}][quantity]" class="form-control" required>
				</div>
				<div class="col-md-2">
					

					
					<div class="form-control unit-display" style="background-color: #f8f9fa; border-color: #dee2e6; color: #495057; cursor: not-allowed; display: flex; align-items: center;">
						<span class="unit-text">Select item first</span>
					</div>
				</div>
				<div class="col-md-1 m-0 mb-1">
					<button type="button" class="btn btn-outline-danger w-100 remove-row">Remove</button>
				</div>
			`;
			container.appendChild(row);
			initItemSelect(row.querySelector('.item-select'));
			const varSelect = row.querySelector('.variation-select');
			if (varSelect) { initVariationSelect(varSelect); }
			index++;
		});

		container.addEventListener('click', function (e) {
			if (e.target.classList.contains('remove-row')) {
				const row = e.target.closest('.pr-item-row');
				row.remove();
			}
		});

		// Form submission validation
		document.querySelector('form').addEventListener('submit', function(e) {
			// Validate all quantity inputs before form submission
			let hasErrors = false;
			document.querySelectorAll('input[type="number"][name*="[quantity]"]').forEach(function(input) {
				if (!validateQuantityInput(input)) {
					hasErrors = true;
				}
			});

			if (hasErrors) {
				e.preventDefault();
				alert('Please fix all quantity validation errors before submitting the form.');
				return false;
			}
		});
	});
</script>
<?php $__env->stopPush(); ?>
<?php /**PATH C:\laragon\www\habibcables-ERP\resources\views\purchase_requests\form.blade.php ENDPATH**/ ?>