@extends('layouts.app')
@section('title', 'Create Purchase Order from PR')

@push('plugin-styles')
<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;
}

/* Make UOM column wider for select dropdown */
.table th:nth-child(4),
.table td:nth-child(4) {
    min-width: 150px;
    width: 150px;
}

/* Ensure select dropdown fits properly */
.table select.form-select-sm {
    min-width: 140px;
}
</style>
@endpush

@section('content')
<div class="card">
	<div class="card-header">
		<div class="d-flex justify-content-between align-items-center">
			<h5 class="card-title mb-0">Create Purchase Order from PR</h5>
			<div class="d-flex gap-2">
				<a href="{{ route('purchase-requests.show', $purchaseRequest) }}" class="btn btn-secondary">
					<i class="fas fa-arrow-left me-2"></i>Back to PR
				</a>
			</div>
		</div>
	</div>
	<div class="card-body">
		<!-- PR Information -->
		<div class="alert alert-info">
			<h6 class="alert-heading">Purchase Request Information</h6>
			<div class="row">
				<div class="col-md-3">
					<strong>PR Number:</strong> {{ $purchaseRequest->pr_number }}
				</div>
				<div class="col-md-3">
					<strong>Status:</strong> {!! $purchaseRequest->status_badge !!}
				</div>
				<div class="col-md-3">
					<strong>Requested By:</strong> {{ optional($purchaseRequest->user)->name ?? 'N/A' }}
				</div>
				<div class="col-md-3">
					<strong>Created:</strong> {{ $purchaseRequest->created_at->format('M d, Y') }}
				</div>
			</div>
		</div>

		@if(session('success'))
			<div class="alert alert-success">{{ session('success') }}</div>
		@endif
		@if($errors->any())
			<div class="alert alert-danger">{{ $errors->first() }}</div>
		@endif

		<form action="{{ route('purchase-orders.store') }}" method="POST" id="poForm">
			@csrf
			<input type="hidden" name="purchase_request_id" value="{{ $purchaseRequest->id }}">

			<!-- Basic Information -->
			<div class="row g-3 mb-4">
				<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', $autoPONumber) }}" required>
					@error('po_number')
						<div class="invalid-feedback">{{ $message }}</div>
					@enderror
				</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 select2 @error('vendor_id') is-invalid @enderror" required>
						<option value="">Select Vendor</option>
						@foreach($vendors as $vendor)
							<option value="{{ $vendor->id }}" {{ old('vendor_id') == $vendor->id ? 'selected' : '' }}>{{ $vendor->name }}</option>
						@endforeach
					</select>
					@error('vendor_id')
						<div class="invalid-feedback">{{ $message }}</div>
					@enderror
				</div>
				<div class="col-md-3">
					<label for="order_date" class="form-label">Order Date</label>
					<input type="date" id="order_date" name="order_date" class="form-control @error('order_date') is-invalid @enderror" value="{{ old('order_date', date('Y-m-d')) }}" required>
					@error('order_date')
						<div class="invalid-feedback">{{ $message }}</div>
					@enderror
				</div>
				<div class="col-md-3">
					<label for="expected_delivery_date" class="form-label">Expected Delivery Date</label>
					<input type="date" id="expected_delivery_date" name="expected_delivery_date" class="form-control @error('expected_delivery_date') is-invalid @enderror" value="{{ old('expected_delivery_date') }}">
					@error('expected_delivery_date')
						<div class="invalid-feedback">{{ $message }}</div>
					@enderror
				</div>
			</div>

			<hr class="my-4">

			<!-- Items Section -->
			<h6 class="mb-3">Order Items</h6>
			<div class="table-responsive">
				<table class="table table-bordered">
					<thead class="table-light">
						<tr>
							<th>Item</th>
							{{-- <th>PR Qty</th> --}}
							<th>Order Qty</th>
							<th>UOM</th>
							<th>Unit Price</th>
							<th>Tax %</th>
							<th>Discount</th>
							<th>Total</th>
							<th>Action</th>
						</tr>
					</thead>
					<tbody>
						@foreach($prItems as $index => $item)
						<tr>
							<td>
								{{ $item['item_name'] }}
								<input type="hidden" name="items[{{ $index }}][item_id]" value="{{ $item['item_id'] }}">
								<input type="hidden" name="items[{{ $index }}][purchase_request_item_id]" value="{{ $item['pr_item_id'] }}">
							</td>
							{{-- <td>{{ $item['item_variation_name'] }}</td> --}}
							{{-- <td class="text-muted">{{ number_format($item['requested_qty'], 6) }}</td> --}}
							<td>
                                <span class="text-danger d-block text-center">{{ number_format($item['requested_qty'], 2) }}</span>
								<input type="number"
									name="items[{{ $index }}][quantity]"
									class="form-control form-control-sm quantity-input"
									step="0.01"
									min="1"
									max="{{  number_format($item['requested_qty'], 2) }}"
									value="{{ old('items.'.$index.'.quantity', number_format($item['requested_qty'], 2)) }}"
									data-max-qty="{{ $item['max_qty'] }}"
									required>

							</td>
														<td>
								<select name="items[{{ $index }}][uom_id]" class="form-select form-select-sm" required>
									<option value="">Select UOM</option>
									@foreach($uoms as $uom)
										<option value="{{ $uom->id }}"
											{{ old('items.'.$index.'.uom_id', $item['uom_id']) == $uom->id ? 'selected' : '' }}
											data-code="{{ $uom->code }}">
											{{ $uom->name }}
										</option>
									@endforeach
								</select>
								<input type="hidden" name="items[{{ $index }}][unit_code]" value="{{ $item['unit_code'] }}">
							</td>
							<td>
								<input type="number"
									name="items[{{ $index }}][unit_price]"
									class="form-control form-control-sm unit-price-input"
									step="0.01"
									min="0"
									value="{{ old('items.'.$index.'.unit_price', '0.00') }}"
									required>
							</td>
							<td>
								<input type="number"
									name="items[{{ $index }}][tax_rate]"
									class="form-control form-control-sm tax-rate-input"
									step="0.01"
									min="0"
									max="100"
									value="{{ old('items.'.$index.'.tax_rate', '0.00') }}">
							</td>
							<td>
								<input type="number"
									name="items[{{ $index }}][discount]"
									class="form-control form-control-sm discount-input"
									step="0.01"
									min="0"
									value="{{ old('items.'.$index.'.discount', '0.00') }}">
							</td>
							<td>
								<span class="line-total">0.00</span>
							</td>
							<td>
								<button type="button" class="btn btn-sm btn-outline-danger delete-row" title="Delete Row">
									<i class="fas fa-trash"></i>
								</button>
							</td>
						</tr>
						@endforeach
					</tbody>
					<tfoot>
						<tr class="table-light">
							<td colspan="6" class="text-end"><strong>Grand Total:</strong></td>
							<td colspan="2" ><strong><span id="grand-total">0.00</span></strong></td>
							{{-- <td></td> --}}
						</tr>
					</tfoot>
				</table>
			</div>

			<!-- Hidden input for grand total -->
			<input type="hidden" name="total_amount" id="total_amount_input" value="0.00">

			<div class="d-flex gap-2 mt-4">
				<button type="submit" class="btn btn-primary">
					<i class="fas fa-save me-2"></i>Create Purchase Order
				</button>
				<a href="{{ route('purchase-requests.show', $purchaseRequest) }}" class="btn btn-secondary">Cancel</a>
			</div>
		</form>
	</div>
</div>
@endsection

@push('plugin-scripts')
<script src="{{ asset('theme/vendors/select2/select2.min.js') }}"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
	// Initialize Select2 for vendor selection
	$('#vendor_id').select2({
		theme: 'bootstrap-5',
		placeholder: 'Select Vendor',
		allowClear: true,
		width: '100%'
	});

	// Calculate line totals and grand total
	function calculateTotals() {
		let grandTotal = 0;

		document.querySelectorAll('tbody tr').forEach(function(row) {
			const quantityInput = row.querySelector('.quantity-input');
			const unitPriceInput = row.querySelector('.unit-price-input');
			const taxRateInput = row.querySelector('.tax-rate-input');
			const discountInput = row.querySelector('.discount-input');
			const lineTotalSpan = row.querySelector('.line-total');

			if (quantityInput && unitPriceInput && lineTotalSpan) {
				const quantity = parseFloat(quantityInput.value) || 0;
				const unitPrice = parseFloat(unitPriceInput.value) || 0;
				const taxRate = parseFloat(taxRateInput ? taxRateInput.value : 0) || 0;
				const discount = parseFloat(discountInput ? discountInput.value : 0) || 0;

				// Calculate line total: (quantity * unit_price) * (1 + tax_rate/100) - discount
				const subtotal = quantity * unitPrice;
				const taxAmount = subtotal * (taxRate / 100);
				const lineTotal = subtotal + taxAmount - discount;

				lineTotalSpan.textContent = lineTotal.toFixed(2);
				grandTotal += lineTotal;
			}
		});

		// Update grand total display and hidden input
		const grandTotalSpan = document.getElementById('grand-total');
		const totalAmountInput = document.getElementById('total_amount_input');

		if (grandTotalSpan) {
			grandTotalSpan.textContent = grandTotal.toFixed(2);
		}

		if (totalAmountInput) {
			totalAmountInput.value = grandTotal.toFixed(2);
		}

		console.log('Grand Total calculated:', grandTotal.toFixed(2)); // Debug log
	}

	// Add event listeners for calculation
	document.querySelectorAll('.quantity-input, .unit-price-input, .tax-rate-input, .discount-input').forEach(function(input) {
		input.addEventListener('input', calculateTotals);
	});

	// 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('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);
			});
		});
	}

	// Initialize quantity validation
	setupQuantityValidation();

	// Handle UOM selection to update unit_code
	document.querySelectorAll('select[name*="[uom_id]"]').forEach(function(select) {
		select.addEventListener('change', function() {
			const selectedOption = this.options[this.selectedIndex];
			const unitCode = selectedOption.dataset.code;
			const row = this.closest('tr');
			const unitCodeInput = row.querySelector('input[name*="[unit_code]"]');
			if (unitCodeInput && unitCode) {
				unitCodeInput.value = unitCode;
			}
		});
	});

	// Handle delete row buttons
	document.addEventListener('click', function(e) {
		if (e.target.closest('.delete-row')) {
			e.preventDefault();
			const button = e.target.closest('.delete-row');
			const row = button.closest('tr');
			const tbody = row.closest('tbody');
			const rows = tbody.querySelectorAll('tr');

			// Prevent deletion if only one row remains
			if (rows.length <= 1) {
				alert('Cannot delete the last item. At least one item is required.');
				return;
			}

			// Show confirmation dialog
			if (confirm('Are you sure you want to delete this item?')) {
				row.remove();
				calculateTotals(); // Recalculate totals after deletion
			}
		}
	});

	// Form submission validation
	document.getElementById('poForm').addEventListener('submit', function(e) {
		const tbody = document.querySelector('tbody');
		const rows = tbody.querySelectorAll('tr');

		if (rows.length === 0) {
			e.preventDefault();
			alert('At least one item is required to create a purchase order.');
			return false;
		}

		// 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;
		}
	});

	// Initial calculation
	calculateTotals();

	// Also recalculate after a short delay to ensure all elements are loaded
	setTimeout(calculateTotals, 100);
});
</script>
@endpush
