@push('plugin-styles')
<link rel="stylesheet" href="{{ asset('theme/vendors/select2/select2.min.css') }}">
<style>
	/* Keep Select2 width consistent with field */
	.select2-container {
        width: 100% !important;
        height: 47px;
    }
    .select2-selection{
        padding-top: 7px;
    }
	/* .select2-dropdown { min-width: 100% !important; max-width: 100% !important; } */

	/* Validation styling */
	.invalid-feedback {
		display: block;
		font-size: 0.875em;
		margin-top: 0.25rem;
	}

	.is-invalid {
		border-color: #dc3545;
		box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
	}

	.is-valid {
		border-color: #198754;
		box-shadow: 0 0 0 0.2rem rgba(25, 135, 84, 0.25);
	}
</style>
@endpush
@php($isEdit = isset($purchaseOrder))
<form action="{{ $isEdit ? route('purchase-orders.update', $purchaseOrder) : route('purchase-orders.store') }}" method="POST" id="po-form">
	@csrf
	@if($isEdit)
		@method('PUT')
	@endif

	<div class="row g-3">
		<div class="col-md-3">
			<label for="po_number" class="form-label">PO Number *</label>
			<input type="text" id="po_number" name="po_number" class="form-control @error('po_number') is-invalid @enderror" value="{{ old('po_number', $isEdit ? $purchaseOrder->po_number : ($autoPONumber ?? '')) }}" {{ $isEdit ? '' : 'readonly' }} required readonly>
			@if(!$isEdit)
				<small class="form-text text-muted"><i class="fas fa-magic"></i> Auto-generated PO number</small>
			@endif
			@error('po_number')<div class="invalid-feedback">{{ $message }}</div>@enderror
			<div class="invalid-feedback" id="po_number_error"></div>
		</div>

		<div class="col-md-4">
			<label class="form-label">Purchase Request *</label>
			<select name="purchase_request_id" id="purchase_request_id" class="form-select @error('purchase_request_id') is-invalid @enderror" data-initial-id="{{ old('purchase_request_id', $isEdit ? ($purchaseOrder->purchase_request_id ?? '') : '') }}" data-initial-text="{{ $isEdit && $purchaseOrder->purchase_request_id ? ($purchaseOrder->purchaseRequest->pr_number ?? '') : '' }}" required>
				<option value="">Search PR...</option>
			</select>
			@error('purchase_request_id')<div class="invalid-feedback">{{ $message }}</div>@enderror
			<div class="invalid-feedback" id="purchase_request_id_error"></div>
		</div>

		{{-- <div class="col-md-2">
			<label class="form-label">Order Date *</label>
			<input type="date" name="order_date" class="form-control @error('order_date') is-invalid @enderror" value="{{ old('order_date', $isEdit ? optional($purchaseOrder->order_date)->format('Y-m-d') : now()->format('Y-m-d')) }}" required>
			@error('order_date')<div class="invalid-feedback">{{ $message }}</div>@enderror
			<div class="invalid-feedback" id="order_date_error"></div>
		</div> --}}
		{{-- <div class="col-md-2">
			<label class="form-label">Expected Delivery</label>
			<input type="date" name="expected_delivery_date" class="form-control @error('expected_delivery_date') is-invalid @enderror" value="{{ old('expected_delivery_date', $isEdit ? optional($purchaseOrder->expected_delivery_date)->format('Y-m-d') : '') }}">
			@error('expected_delivery_date')<div class="invalid-feedback">{{ $message }}</div>@enderror
			<div class="invalid-feedback" id="expected_delivery_date_error"></div>
		</div> --}}

        <div class="col-md-2">
			<label for="expected_date" class="form-label">Expected Date</label>
	{{-- {{ dd($purchaseOrder->expected_date) }} --}}
            <input
    type="date"
    id="expected_date"
    name="expected_date"
    class="form-control @error('expected_date') is-invalid @enderror"
    value="{{ old('expected_date', $isEdit && $purchaseOrder->expected_date ? \Carbon\Carbon::parse($purchaseOrder->expected_date)->format('Y-m-d') : now()->format('Y-m-d')) }}"
    min="{{ $isEdit ? $purchaseOrder->created_at->format('Y-m-d') : now()->format('Y-m-d') }}"
    required
    >
        </div>
        <div class="col-md-3">
					<label for="vendor_id" class="form-label">Vendor <span class="text-danger">*</span></label>
					<select id="vendor_id" name="vendor_id" class="form-select @error('vendor_id') is-invalid @enderror" required>
						<option value="">Search Vendor...</option>
					</select>
					@error('vendor_id')
						<div class="invalid-feedback">{{ $message }}</div>
					@enderror
				</div>
	</div>

	<div class="row g-3 mt-2">
		<div class="col-12">
			<label class="form-label">Remarks (optional)</label>
			<textarea name="remarks" rows="2" class="form-control">{{ old('remarks', $isEdit ? ($purchaseOrder->remarks ?? '') : '') }}</textarea>
		</div>
	</div>

	<hr class="my-4">
	<h6>Items from Purchase Request</h6>
	<div class="table-responsive">
		<table class="table table-bordered align-middle" id="po-items-table">
			<thead class="table-light">
				<tr>
					<th style="width:30%">Item</th>
					<th style="width:12%" class="text-end">Ordered Qty</th>
					<th style="width:12%" class="text-end">Requested Qty</th>
					<th style="width:12%">Unit</th>
					<th style="width:12%" class="text-end">Order Qty *</th>
					<th style="width:12%" class="text-end">Unit Price *</th>
					<th style="width:17%" class="text-end">Total Amount</th>
				</tr>
			</thead>
			<tbody id="po-items-body">
				<tr class="no-items"><td colspan="6" class="text-center text-muted">Select a Purchase Request to load items</td></tr>
			</tbody>
			<tfoot id="po-items-footer" style="display: none;">
				<tr class="table-info">
					<td colspan="5" class="text-end fw-bold">Total Amount:</td>
					<td class="text-end fw-bold">
						<span id="total-amount">0.00</span>
						<input type="hidden" name="total_amount" id="total-amount-input" value="0">
					</td>
				</tr>
			</tfoot>
		</table>
	</div>

	<div class="d-flex gap-2 mt-4">
		<button type="submit" class="btn btn-primary" id="submit-btn">{{ $isEdit ? 'Update' : 'Create' }}</button>
		{{-- <a href="{{ route('purchase-orders.index') }}" class="btn btn-secondary">Cancel</a>
		<button type="button" class="btn btn-info" onclick="debugValidation()">Debug Validation</button> --}}
	</div>

	<!-- Hidden fields for totals -->
	<input type="hidden" name="total_amount" id="form-total-amount" value="0">
</form>



@push('plugin-scripts')
<script src="{{ asset('theme/vendors/select2/select2.min.js') }}"></script>
<script>
	function renderItems(items){
		const tbody = document.getElementById('po-items-body');
		const footer = document.getElementById('po-items-footer');
		tbody.innerHTML = '';

		if(!items || !items.length){
			const tr = document.createElement('tr');
			tr.className = 'no-items';
			tr.innerHTML = '<td colspan="6" class="text-center text-muted">No items found for this PR</td>';
			tbody.appendChild(tr);
			footer.style.display = 'none';
			return;
		}

		items.forEach(function(row, idx){
			console.log(`Rendering item ${idx}:`, row); // Debug log
			const tr = document.createElement('tr');
			tr.innerHTML = `
				<td>
					<input type="hidden" name="items[${idx}][purchase_request_item_id]" value="${row.pr_item_id||''}">
					<input type="hidden" name="items[${idx}][item_id]" value="${row.item_id}">
					<input type="hidden" name="items[${idx}][uom_id]" value="${row.uom_id||''}">
					<input type="hidden" name="items[${idx}][unit_code]" value="${row.unit_code||''}">
					${row.item_name||''}
				</td>
				<td class="text-end">${(row.already_ordered_qty ?? 0)}</td>
				<td class="text-end">${(row.requested_qty ?? 0)}</td>
				<td>${(row.unit_code ?? row.uom_name ?? '')}</td>
				<td>
					<input type="number" step="0.000001" min="0" max="${(row.max_qty ?? '')}" name="items[${idx}][quantity]" class="form-control text-end js-order-qty" data-max="${(row.max_qty ?? 0)}" data-row="${idx}" placeholder="<= ${(row.max_qty ?? '')}">
					<div class="invalid-feedback" id="qty_error_${idx}"></div>
				</td>
				<td>
					<input type="number" step="0.0001" min="0" name="items[${idx}][unit_price]" class="form-control text-end js-unit-price" data-row="${idx}" placeholder="0.00">
					<div class="invalid-feedback" id="price_error_${idx}"></div>
				</td>
				<td class="text-end">
					<input type="number" step="0.0001" min="0" name="items[${idx}][total_price]" class="form-control text-end js-total-amount" data-row="${idx}" placeholder="0.00" readonly>
					<div class="invalid-feedback" id="total_amount_error_${idx}"></div>
				</td>
			`;
			tbody.appendChild(tr);
		});

		// Show footer when items are loaded
		footer.style.display = 'table-row-group';

		// Bind validation events after rendering
		bindValidationEvents();

		// Initialize totals after a short delay to ensure DOM is ready
		// setTimeout(() => {
		// 	updateAllTotals();
		// 	validateForm(); // Validate the form after items are loaded
		// }, 100);
	}

	function bindValidationEvents() {
		// Order Qty validation
		document.querySelectorAll('.js-order-qty').forEach(function(input) {
			input.addEventListener('input', validateOrderQty);
			input.addEventListener('blur', validateOrderQty);
		});

		// Unit Price validation
		document.querySelectorAll('.js-unit-price').forEach(function(input) {
			input.addEventListener('input', validateUnitPrice);
			input.addEventListener('blur', validateUnitPrice);
		});

		// Required field validation
		document.querySelectorAll('input[required], select[required]').forEach(function(input) {
			input.addEventListener('blur', validateRequired);
			input.addEventListener('input', validateRequired);
			input.addEventListener('change', validateRequired);
		});
	}

	function calculateRowTotal(rowIndex) {
		const row = document.querySelectorAll('#po-items-body tr:not(.no-items)')[rowIndex];
		if (!row) return 0;

		const qtyInput = row.querySelector('input[name$="[quantity]"]');
		const priceInput = row.querySelector('input[name$="[unit_price]"]');
		const totalInput = row.querySelector('input[name$="[total_price]"]');

		if (qtyInput && priceInput && totalInput) {
			const qty = parseFloat(qtyInput.value) || 0;
			const price = parseFloat(priceInput.value) || 0;
			const total = qty * price;

			totalInput.value = total.toFixed(4);
			console.log(`Row ${rowIndex}: Qty=${qty}, Price=${price}, Total=${total}`);
			return total;
		}
		return 0;
	}

	function updateAllTotals() {
		let grandTotal = 0;
		const rows = document.querySelectorAll('#po-items-body tr:not(.no-items)');

		rows.forEach((row, index) => {
			const total = calculateRowTotal(index);
			grandTotal += total;
		});

		// Update grand total display and hidden input
		document.getElementById('total-amount').textContent = grandTotal.toFixed(2);
		document.getElementById('total-amount-input').value = grandTotal.toFixed(2);
		document.getElementById('form-total-amount').value = grandTotal.toFixed(2); // Update hidden input
		console.log(`Grand Total: ${grandTotal}`);
	}

	function validateOrderQty(event) {
		const input = event.target;
		const maxQty = parseFloat(input.dataset.max) || 0;
		const raw = input.value;
		const value = parseFloat(raw);
		const errorDiv = document.getElementById(`qty_error_${input.dataset.row}`);

		// Clear previous validation
		input.classList.remove('is-invalid', 'is-valid');
		errorDiv.textContent = '';

		// If empty, do not flag invalid (row may be intentionally left blank)
		if (raw === '' || isNaN(value)) {
			// leave neutral state
		} else if (value > maxQty) {
			input.classList.add('is-invalid');
			errorDiv.textContent = `Order quantity cannot exceed requested quantity (${maxQty})`;
		} else {
			input.classList.add('is-valid');
		}

		// Update row total when quantity changes
		calculateRowTotal(parseInt(input.dataset.row));
		updateAllTotals();

		// Update submit button state
		updateSubmitButton();
	}

	function validateUnitPrice(event) {
		const input = event.target;
		const raw = input.value;
		const value = parseFloat(raw);
		const errorDiv = document.getElementById(`price_error_${input.dataset.row}`);

		// Clear previous validation
		input.classList.remove('is-invalid', 'is-valid');
		errorDiv.textContent = '';

		// If empty, do not flag invalid
		if (raw === '' || isNaN(value)) {
			// leave neutral state
		} else if (value < 0) {
			input.classList.add('is-invalid');
			errorDiv.textContent = 'Unit price cannot be negative';
		} else {
			input.classList.add('is-valid');
		}

		// Update row total when price changes
		calculateRowTotal(parseInt(input.dataset.row));
		updateAllTotals();

		// Update submit button state
		updateSubmitButton();
	}

	function validateRequired(event) {
		const input = event.target;
		const value = input.value.trim();

		// Clear previous validation
		input.classList.remove('is-invalid', 'is-valid');

		// Validation rules
		if (value === '') {
			input.classList.add('is-invalid');
		} else {
			input.classList.add('is-valid');
		}

		// Update submit button state
		updateSubmitButton();
	}

	function updateSubmitButton() {
		const submitBtn = document.getElementById('submit-btn');

		// Check if all required fields have values
		const requiredFields = document.querySelectorAll('input[required], select[required]');
		const requiredFieldsValid = Array.from(requiredFields).every(field => {
			const value = field.value.trim();
			return value !== '';
		});

		// At least one complete row rule (qty > 0 and <= max, and price > 0)
		let hasCompleteRow = false;
		document.querySelectorAll('#po-items-body tr:not(.no-items)').forEach((row) => {
			const qtyInput = row.querySelector('.js-order-qty');
			const priceInput = row.querySelector('.js-unit-price');
			if (!qtyInput || !priceInput) return;
			const qty = parseFloat(qtyInput.value) || 0;
			const max = parseFloat(qtyInput.dataset.max) || 0;
			const price = parseFloat(priceInput.value) || 0;
			if (qty > 0 && qty <= max && price > 0) { hasCompleteRow = true; }
		});

		// Check if there are any items loaded
		const hasItems = document.querySelectorAll('#po-items-body tr:not(.no-items)').length > 0;

		// Enable submit button if all conditions are met
		const canSubmit = requiredFieldsValid && hasItems && hasCompleteRow;

		submitBtn.disabled = !canSubmit;

		// Debug logging
		console.log('Validation State:', {
			requiredFieldsValid,
			hasCompleteRow,
			hasItems,
			canSubmit
		});
	}

	function validateForm() {
		// Validate all required fields
		document.querySelectorAll('input[required], select[required]').forEach(field => {
			const event = { target: field };
			validateRequired(event);
		});

		// Validate all order qty fields
		document.querySelectorAll('.js-order-qty').forEach(field => {
			const event = { target: field };
			validateOrderQty(event);
		});

		// Validate all unit price fields
		document.querySelectorAll('.js-unit-price').forEach(field => {
			const event = { target: field };
			validateUnitPrice(event);
		});

		// Update submit button state
		updateSubmitButton();
	}

	function debugValidation() {
		console.log('=== VALIDATION DEBUG ===');

		// Check required fields
		const requiredFields = document.querySelectorAll('input[required], select[required]');
		console.log('Required Fields:', requiredFields.length);
		requiredFields.forEach((field, index) => {
			console.log(`Field ${index}:`, {
				name: field.name,
				value: field.value,
				valid: field.value.trim() !== ''
			});
		});

		// Check order qty fields
		const orderQtyFields = document.querySelectorAll('.js-order-qty');
		console.log('Order Qty Fields:', orderQtyFields.length);
		orderQtyFields.forEach((field, index) => {
			const value = parseFloat(field.value) || 0;
			const max = parseFloat(field.dataset.max) || 0;
			console.log(`Order Qty ${index}:`, {
				value: value,
				max: max,
				valid: value > 0 && value <= max
			});
		});

		// Check unit price fields
		const unitPriceFields = document.querySelectorAll('.js-unit-price');
		console.log('Unit Price Fields:', unitPriceFields.length);
		unitPriceFields.forEach((field, index) => {
			const value = parseFloat(field.value) || 0;
			console.log(`Unit Price ${index}:`, {
				value: value,
				valid: value > 0
			});
		});

		// Check items
		const hasItems = document.querySelectorAll('#po-items-body tr:not(.no-items)').length > 0;
		console.log('Has Items:', hasItems);

		// Check submit button
		const submitBtn = document.getElementById('submit-btn');
		console.log('Submit Button Disabled:', submitBtn.disabled);

		// Run validation
		validateForm();
		updateSubmitButton();
	}

	async function loadPrItems(prId){
		try{
			const resp = await fetch(`{{ route('api.pr-items') }}?pr_id=${encodeURIComponent(prId)}`);
			const data = await resp.json();

			// Render items
			renderItems(data.items || []);

			// Update expected date from PR
			if (data.pr_details && data.pr_details.expected_date) {
				document.getElementById('expected_date').value = data.pr_details.expected_date;
			}
		}catch(e){ console.error(e); }
	}

	document.addEventListener('DOMContentLoaded', function(){
		// Initialize vendor select2
		const vendorSelect = $('#vendor_id');
		vendorSelect.select2({
			theme: 'bootstrap-5',
			placeholder: 'Search Vendor...',
			allowClear: true,
			width: '100%',
			ajax: {
				url: '{{ route('api.contacts.search') }}',
				dataType: 'json',
				delay: 250,
				data: function(params) {
					return {
						q: params.term || '',
						type: 'supplier'
					};
				},
				processResults: function(data) {
					return {
						results: data.results || []
					};
				},
				cache: true
			},
			templateResult: function(data) {
				if (data.loading) return data.text;
				if (!data.id) return data.text;
				return $('<div>' + data.text + '</div>');
			},
			templateSelection: function(data) {
				return data.text || 'Search Vendor...';
			}
		});
		// ✅ Prefill vendor when editing a Purchase Order
setTimeout(function () {
	const vendorId = "{{ old('vendor_id', $isEdit ? ($purchaseOrder->vendor_id ?? '') : '') }}";
	const vendorName = "{{ $isEdit && $purchaseOrder->vendor ? $purchaseOrder->vendor->name : '' }}";

	if (vendorId && vendorName) {
		console.log('Prefilling vendor:', vendorId, vendorName);
		const option = new Option(vendorName, vendorId, true, true);
		vendorSelect.append(option).trigger('change');
	}
}, 300);



		const prSel = document.getElementById('purchase_request_id');
		$(prSel).select2({
			theme: 'bootstrap-5', placeholder: 'Search PR...', allowClear: true, width: '100%',
			ajax: { url: '{{ url('purchase-requests/search') }}', dataType: 'json', delay: 250,
				data: function(params){ return { q: params.term || '' }; },
				processResults: function(data){ return { results: data.results || data }; },
				cache: true
			}
		});


		// Preselect if exists
		const initId = prSel.dataset.initialId; const initText = prSel.dataset.initialText;
		if(initId && initText){ const opt = new Option(initText, initId, true, true); $(prSel).append(opt).trigger('change'); loadPrItems(initId); }


		$(prSel).on('select2:select', function(e){ const id = e.params.data.id; loadPrItems(id); });
		$(prSel).on('select2:clear select2:unselect', function(){ renderItems([]); });


		// Form submission validation
		document.getElementById('po-form').addEventListener('submit', function(ev){
			// Calculate all totals before submission
			updateAllTotals();

			// Validate the entire form
			validateForm();

			// Check if form can be submitted
			const hasInvalidFields = document.querySelectorAll('.is-invalid').length > 0;
			if(hasInvalidFields) {
				ev.preventDefault();
				alert('Please fix all validation errors before submitting.');
				return false;
			}

			// Check if at least one order qty > 0
			let hasQty = false;
			this.querySelectorAll('input[name$="[quantity]"]').forEach(function(inp){
				if(parseFloat(inp.value||'0')>0){ hasQty=true; }
			});
			if(!hasQty){
				ev.preventDefault();
				alert('Please enter at least one Order Quantity greater than 0.');
				return false;
			}

			// Ensure total amount is set
			const totalAmount = document.getElementById('form-total-amount').value;
			if (!totalAmount || parseFloat(totalAmount) <= 0) {
				ev.preventDefault();
				alert('Please ensure all item totals are calculated correctly.');
				return false;
			}
		});

		// Initial validation state
		updateSubmitButton();
	});
</script>
@endpush




{{-- Uncomment for handling : Edit Purchase Order error and shows the selected QTY at edit page --}}


{{-- @push('plugin-scripts')
<script src="{{ asset('theme/vendors/select2/select2.min.js') }}"></script>
<script>

// existing PO items for prefill on edit
const existingPoItems = @json($isEdit ? $purchaseOrder->items->keyBy('purchase_request_item_id') : []);

function renderItems(items) {
    const tbody  = document.getElementById('po-items-body');
    const footer = document.getElementById('po-items-footer');
    tbody.innerHTML = '';

    if (!items || !items.length) {
        tbody.innerHTML = '<tr class="no-items"><td colspan="7" class="text-center text-muted">No items found for this PR</td></tr>';
        footer.style.display = 'none';
        return;
    }

    items.forEach(function (row, idx) {
        // prefill from existing PO item if editing
        const existing   = existingPoItems[row.pr_item_id] || null;
        const prefillQty   = existing ? existing.quantity   : '';
        const prefillPrice = existing ? existing.unit_price : '';
        const prefillTotal = existing ? existing.total_price : '';

        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>
                <input type="hidden" name="items[${idx}][purchase_request_item_id]" value="${row.pr_item_id || ''}">
                <input type="hidden" name="items[${idx}][item_id]"   value="${row.item_id}">
                <input type="hidden" name="items[${idx}][uom_id]"    value="${row.uom_id || ''}">
                <input type="hidden" name="items[${idx}][unit_code]" value="${row.unit_code || ''}">
                ${row.item_name || ''}
            </td>
            <td class="text-end">${row.already_ordered_qty ?? 0}</td>
            <td class="text-end">${row.requested_qty ?? 0}</td>
            <td>${row.unit_code ?? row.uom_name ?? ''}</td>
            <td>
                <input type="number" step="0.000001" min="0"
                    max="${row.max_qty ?? ''}"
                    name="items[${idx}][quantity]"
                    class="form-control text-end js-order-qty"
                    data-max="${row.max_qty ?? 0}"
                    data-row="${idx}"
                    value="${prefillQty}"
                    placeholder="<= ${row.max_qty ?? ''}">
                <div class="invalid-feedback" id="qty_error_${idx}"></div>
            </td>
            <td>
                <input type="number" step="0.0001" min="0"
                    name="items[${idx}][unit_price]"
                    class="form-control text-end js-unit-price"
                    data-row="${idx}"
                    value="${prefillPrice}"
                    placeholder="0.00">
                <div class="invalid-feedback" id="price_error_${idx}"></div>
            </td>
            <td class="text-end">
                <input type="number" step="0.0001" min="0"
                    name="items[${idx}][total_price]"
                    class="form-control text-end js-total-amount"
                    data-row="${idx}"
                    value="${prefillTotal}"
                    placeholder="0.00" readonly>
            </td>
        `;
        tbody.appendChild(tr);
    });

    footer.style.display = 'table-row-group';
    bindValidationEvents();
    updateAllTotals(); // recalculate totals after prefill
}

function bindValidationEvents() {
    document.querySelectorAll('.js-order-qty').forEach(function (input) {
        input.addEventListener('input', calculateAndUpdate);
    });
    document.querySelectorAll('.js-unit-price').forEach(function (input) {
        input.addEventListener('input', calculateAndUpdate);
    });
}

function calculateAndUpdate(e) {
    const row   = e.target.closest('tr');
    const qty   = parseFloat(row.querySelector('.js-order-qty').value)   || 0;
    const price = parseFloat(row.querySelector('.js-unit-price').value)  || 0;
    const total = row.querySelector('.js-total-amount');
    if (total) total.value = (qty * price).toFixed(4);
    updateAllTotals();
}

function calculateRowTotal(rowIndex) {
    const row = document.querySelectorAll('#po-items-body tr:not(.no-items)')[rowIndex];
    if (!row) return 0;
    const qty   = parseFloat(row.querySelector('.js-order-qty')?.value)  || 0;
    const price = parseFloat(row.querySelector('.js-unit-price')?.value) || 0;
    const total = qty * price;
    const totalInput = row.querySelector('.js-total-amount');
    if (totalInput) totalInput.value = total.toFixed(4);
    return total;
}

function updateAllTotals() {
    let grandTotal = 0;
    document.querySelectorAll('#po-items-body tr:not(.no-items)').forEach((row, index) => {
        grandTotal += calculateRowTotal(index);
    });
    document.getElementById('total-amount').textContent       = grandTotal.toFixed(2);
    document.getElementById('total-amount-input').value       = grandTotal.toFixed(2);
    document.getElementById('form-total-amount').value        = grandTotal.toFixed(2);
}

async function loadPrItems(prId) {
    try {
        const resp = await fetch(`{{ route('api.pr-items') }}?pr_id=${encodeURIComponent(prId)}`);
        const data = await resp.json();
        renderItems(data.items || []);
        if (data.pr_details && data.pr_details.expected_date) {
            document.getElementById('expected_date').value = data.pr_details.expected_date;
        }
    } catch (e) {
        console.error(e);
    }
}

document.addEventListener('DOMContentLoaded', function () {

    // == VENDOR SELECT2 ==
    const vendorSelect = $('#vendor_id');
    vendorSelect.select2({
        theme: 'bootstrap-5',
        placeholder: 'Search Vendor...',
        allowClear: true,
        width: '100%',
        ajax: {
            url: '{{ route('api.contacts.search') }}',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return { q: params.term || '', type: 'supplier' };
            },
            processResults: function (data) {
                return { results: data.results || [] };
            },
            cache: true
        }
    });

    // prefill vendor on edit — use contact_id not vendor_id
    @if($isEdit)
    setTimeout(function () {
        const vendorId   = "{{ old('vendor_id', $purchaseOrder->contact_id ?? '') }}";
        const vendorName = "{{ $purchaseOrder->contact->name ?? '' }}";
        if (vendorId && vendorName) {
            vendorSelect.append(new Option(vendorName, vendorId, true, true)).trigger('change');
        }
    }, 300);
    @endif

    // == PR SELECT2 ==
    const prSel = document.getElementById('purchase_request_id');
    $(prSel).select2({
        theme: 'bootstrap-5', placeholder: 'Search PR...', allowClear: true, width: '100%',
        ajax: {
            url: '{{ url('purchase-requests/search') }}', dataType: 'json', delay: 250,
            data: function (params) { return { q: params.term || '' }; },
            processResults: function (data) { return { results: data.results || data }; },
            cache: true
        }
    });

    // preselect PR and load items
    const initId   = prSel.dataset.initialId;
    const initText = prSel.dataset.initialText;
    if (initId && initText) {
        $(prSel).append(new Option(initText, initId, true, true)).trigger('change');
        loadPrItems(initId); // loads items and prefills qty/price from existingPoItems
    }

    $(prSel).on('select2:select',  function (e) { loadPrItems(e.params.data.id); });
    $(prSel).on('select2:clear select2:unselect', function () { renderItems([]); });

    // == FORM SUBMIT ==
    document.getElementById('po-form').addEventListener('submit', function (ev) {
        updateAllTotals();

        let hasQty = false;
        this.querySelectorAll('input[name$="[quantity]"]').forEach(function (inp) {
            if (parseFloat(inp.value || '0') > 0) hasQty = true;
        });

        if (!hasQty) {
            ev.preventDefault();
            alert('Please enter at least one Order Quantity greater than 0.');
            return false;
        }
    });
});
</script>
@endpush --}}
