<div class="col-lg-12">
	<form action="<?= site_url('admin/savequote') ?>" name="filter" id="filter" class="row g-3" method="post">
		<!-- filters -->
		<div class="card" id="print-area">
			<div class="card-body">
				<!-- <div class="card-title">Quotation</div> -->
				
				
				<div class="form-group row justify-content-between">
					<div class="col-sm-3">
						<label for="quotationdate" class="form-label">Quotation Date:</label>
						<input type="date" name="quotationdate" id="quotationdate" class="form-control p-1" value="<?php echo date("Y-m-d",time());?>">
						<label for="quotationvalid" class="form-label mt-3">Validity Date :</label>
						<input type="date" name="quotationvalid" id="quotationvalid" class="form-control p-1" value="<?php echo date("Y-m-d",strtotime('+15 Days'));?>">
					</div>
					<div class="col-sm-3">
						<label for="purchaseorder" class="form-label">P.O Number :</label>
						<input type="text" name="purchaseorder" id="purchaseorder" class="form-control p-1">
						<label for="purchaseorderdate" class="form-label mt-3">P.O Date :</label>
						<input type="date" name="purchaseorderdate" id="purchaseorderdate" class="form-control p-1" value="<?php echo date("Y-m-d",time());?>">
					</div>
					
				</div>
				<div class="form-group row mb-0">
					<label for="customername" class="col-sm-2 col-form-label">Customer</label>
					<div class="col">
						
						<select name="customername" id="customername" class="form-select">
							 <?php foreach($customers as $customer): ?>

            <option value="<?= $customer['cid'] ?>">

                <?= esc($customer['c_cname']) ?>

            </option>

        <?php endforeach; ?>
						</select>
					</div>
				</div>
			</div>
		<!-- </div> -->
		<!-- product / service  -->
		<!-- <div class="card mt-2"> -->
			<div class="card-body">
				<div class="form-group row justify-content-between align-items-md-center">
					<div class="col-sm-4">
						<label for="product" class="form-label">Product / Services</label>
						<input type="text" class="form-control p-2" id="product" name="product" value="Select Product">
						<!-- <select name="product" id="product" class="form-select p-1" >
							<option value="10345" data="White Chinees Helmet">White Helmet China</option>
							<option value="10346">Red Helmet China</option>
							<option value="10347">Green Helmet China</option>
							<option value="10348">Yellow Helmet China</option>
						</select> -->
					</div>    
					<div class="col-sm-4">
						<label for="description" class="form-label">Discription</label>
						<input type="text" name="description" id="description" class="form-control p-2" value="Discription" >
					</div>
					<div class="col">
						<label for="units" class="form-label">Unit</label>
						<select name="units" id="units" class="form-select p-1" >
							<option value="Pcs" selected>Pcs</option>
							<option value="Box">Box</option>
							<option value="m">Meter</option>
							<option value="M2">m<sup>2</sup></option>
							<option value="M3">m<sup>3</sup></option>
							<option value="kg">Kg</option>
							<option value="mg">mg</option>
							<option value="L">Liters</option>
							<option value="Ton">Tons</option>
							
						</select>
					</div>
					<div class="col">
						<label for="qty" class="form-label">Qty</label>
						<input type="text" name="qty" id="qty" class="form-control p-2" value="100">
					</div>
				</div>
				
				<div class="align-items-end form-group row ">
					<div class="col-sm-4">
						<label for="unitprice" class="form-label">Unit Price</label>
						<input type="text" name="unitprice" id="unitprice" class="form-control p-2" value="10">
					</div>
					<div class="col">
						<label for="vat" class="form-label">VAT</label>
						<select name="vat" id="vat" class="form-select p-1" readonly>
							<option value="15" selected>15%</option>
						</select>
					</div>
					<div class="col-sm-4">
						<label for="amount" class="form-label">Amount</label>
						<input class="form-control p-2"type="text" id="amount" name="amount" readonly>
					</div>
					<div class="col">
						<input type="button" value="Add" name="addproduct" id="addproduct" class="btn btn-success">
					</div>
				</div>
			</div>
		<!-- </div> -->
		<!-- list of items -->
		<table class="table table-striped" id="productTable">
			<thead>
				<tr>
					<th>S.No</th>
					<th>Product / Services</th>
					<th>Description </th>
					<th>Units</th>
					<th>Qty</th>
					<th>Unit Price</th>
					<th>Amount</th>
					<th>Tax </th>
					<th>Action</th>
				</tr>
			</thead>
			<tbody class="border-secondary">
				
				
			</tbody>
			
		</table>
		<!-- <div class="card"> -->
			<div class="card-body p-2">
				<div class="form-goup row justify-content-end align-items-sm-baseline">
					<label for="subtotal" class="col-sm-3 col-form-label text-end p-2">Sub-total</label>
					<div class="col-sm-3">
						<input type="text" name="subtotal" id="subtotal" class="form-control p-1 text-end" readonly >
					</div>
				</div>
				<div class="form-goup row justify-content-end align-items-sm-baseline">
					<label for="discount" class="col-sm-3 col-form-label text-end p-2">Discount</label>
					<div class="col-sm-3">
						<input type="text" name="discount" id="discount" class="form-control p-1 text-end">
					</div>
				</div>
				<div class="form-goup row justify-content-end align-items-sm-baseline">
					<label for="afterdiscount" class="col-sm-3 col-form-label text-end p-2">Amount After Discount</label>
					<div class="col-sm-3">
						<input type="text" name="afterdiscount" id="afterdiscount" class="form-control p-1 text-end" readonly>
					</div>
				</div>
				<div class="form-goup row justify-content-end align-items-sm-baseline">
					<label for="displayvat" class="col-sm-3 col-form-label text-end p-2">VAT</label>
					<div class="col-sm-3">
						<input type="text" name="displayvat" id="displayvat" class="form-control p-1 text-end" readonly >
					</div>
				</div>
				<div class="form-goup row justify-content-end align-items-sm-baseline">
					<label for="netamount" class="col-sm-3 col-form-label text-end p-2">Net Amount</label>
					<div class="col-sm-3">
						<input type="text" name="netamount" id="netamount" class="form-control p-1 text-end" readonly>
					</div>
				</div>
			</div>
		<!-- </div> -->
		<div class="card mt-2">
			<div class="card-body">
				<h5>Terms & Condition </h5>
				<div class="form-goup row">
					<div class="form-check form-check-flat form-check-primary col-sm-2">
						
						<label for="cbpayment" class="form-check-label">
							<input type="checkbox" name="cbpayment" id="cbpayment" class="form-check-input" checked>
							Payment Terms:
						</label>
					</div>
					<div class="col-sm-10">
						<input type="text" class="col-sm-6 form-control" name="paymentterms" id="paymentterms" value="30% advance payment shall be deposit along purchase order. Progressive invoice biweekly" >
					</div>
				</div>
				<div class="form-goup row">
					<div class="form-check form-check-flat form-check-primary col-sm-2">
						
						<label for="cbdeliveryterms" class="form-check-label">
							<input type="checkbox" name="cbdeliveryterms" id="cbdeliveryterms" class="form-check-input" checked>
							Delivery Terms:
						</label>
					</div>
					<div class="col-sm-10">
						<input type="text" name="contendeliveryterms" id="contendeliveryterms" value="Delivery time is 3-5 working days" class="form-control">
					</div>
				</div>
				
				<div class="form-group mt-3 text-end">
					<button type="submit" class="btn btn-primary"><i class="mdi mdi-18px mdi-plus"></i>Save & Print</button>
					<button type="button" class="btn btn-info" onclick="window.print();"><i class="mdi mdi-18px mdi-printer"></i>Print</button>
					<button type="button" class="btn btn-success" id="saveButton"><i class="mdi mdi-18px mdi-database"></i>Save</button>
					<input type="reset" value="Reset" class="btn btn-light">
				</div>
				
			</div>
		</div>
		<input type="hidden" id="quotation_items"name="quotation_items">
	</form>
	
	
	
</div>


<!-- <input type="text" name="customername" id="customername" class="form-control"> -->
<script>
	document.addEventListener('DOMContentLoaded', () => {
		// declaration 
		const tableBody = document.querySelector('#productTable tbody');

			//Calculate Total 
				// 1. Add functionality to Qty + unit Price Update
				const qtyInput = document.getElementById('qty');
				const unitPriceInput = document.getElementById('unitprice');
				qtyInput.addEventListener('input',updateTotalAmount);
				unitPriceInput.addEventListener('input',updateTotalAmount);

			// Add Item 
				// Add functionality to Add Product Button 
				const addProduct = document.getElementById('addproduct');
				addProduct.addEventListener('click',addListItems);
			//Update Subtotal 
			
			//Update Discount
			const discount = document.getElementById('discount');
			discount.addEventListener('change',updateDiscount);

			// functions 
			function updateTotalAmount(){
				let qty = parseFloat(qtyInput.value).toFixed(2)||0;
				let unitPrice = parseFloat(unitPriceInput.value).toFixed(2)||0;
				let amountInput = qty*unitPrice;
				document.getElementById('amount').value=parseFloat(amountInput).toFixed(2)||0;
			}

			function addListItems(){
				const tableBody = document.querySelector('#productTable tbody');
				const nextSerialNumber = tableBody.rows.length + 1;

				// Input Values 
				const product=document.getElementById('product').value.trim();
				const description = document.getElementById('description').value.trim();
				const qty = qtyInput.value||0;
				const unitPrice = unitPriceInput.value||0;
				const unit = document.getElementById('units').value;
				const vat = document.getElementById('vat').value;
				const amount = document.getElementById('amount').value;
				
				// Validation Check 
				if (!product || !qty || !unitPrice || !amount) {
				alert('Please fill out Product, Quantity, and Unit Price fields.');
				return;
				}
				const vatAmount = parseFloat(unitPrice*qty*(vat/100)).toFixed(2)
				// Create New Element
				const row = document.createElement('tr');
			
				// Populate cells with data attributes for easy retrieval later
				row.innerHTML = `
				<td class="cell-serial">${nextSerialNumber}</td>
				<td class="cell-product">${product}</td>
				<td class="cell-description">${description}</td>
				<td class="cell-unit">${unit}</td>
				<td class="cell-qty">${qty}</td>
				<td class="cell-unitPrice">${parseFloat(unitPrice).toFixed(2)}</td>
				<td class="cell-amount">${parseFloat(amount).toFixed(2)}</td>
				<td class="cell-vatamount">${vatAmount}</td>
				<td class="cell-action"><i class="mdi text-danger mdi-trash-can mdi-18px"></i></td>
			`;
				// Attach deletion event directly to the new button inside this row
				row.querySelector('.mdi-trash-can').addEventListener('click', () => {
				row.remove();                // Remove the row from the DOM
				recalculateSerialNumbers();  // Fix serial numbers sequentially
			});
				// Append row to the table body
				tableBody.appendChild(row);
				/* update Total amount including discoust trigering  */
				updateNetAmount();
				// Clear Input
				// clearInput();
				

			}

			function clearInput(){
				// Clear inputs for the next entry
			document.getElementById('product').value = '';
			document.getElementById('description').value = '';
			document.getElementById('qty').value = '1';
			document.getElementById('unitprice').value = '';
			}
			
			function updateNetAmount(){
				
				// Collect Amount from list 
				const rows=tableBody.querySelectorAll('tr');
				let subtotalVal = 0;
				let vat=0;
				//Loop through table
				
				rows.forEach(row=>{
					
					// const qty = parseFloat(row.querySelector('.cell-qty').textContent) || 0;
					// const unitPrice = parseFloat(row.querySelector('.cell-unitPrice').textContent) || 0
					// const lineAmount = parseFloat(qty*unitPrice).toFixed(2);
					let listamount = row.querySelector('.cell-amount').textContent;
					// amount = +amount;
					subtotalVal+= +listamount; //+used to convert into number
				});
				console.log(subtotalVal);

				document.getElementById('subtotal').value=parseFloat(subtotalVal).toFixed(2);
				updateDiscount();

			}

			function updateDiscount(){
				let subtotal = document.getElementById('subtotal').value||0;
				let discountVal = discount.value;
				let amountAfterDiscount = subtotal-discountVal;
				let newVat = amountAfterDiscount*0.15;
				//display
				document.getElementById('afterdiscount').value=amountAfterDiscount;
				document.getElementById('displayvat').value=parseFloat(newVat).toFixed(2);
				let netamount = amountAfterDiscount+newVat;
				document.getElementById('netamount').value=parseFloat(netamount).toFixed(2);

			}

			function recalculateSerialNumbers() {
				const rows = tableBody.querySelectorAll('tr');
					rows.forEach((row, index) => {
						row.querySelector('.cell-serial').textContent = index + 1;
					});
					updateNetAmount();
			}

		// Terms&Condition 
		const cbPay = document.getElementById('cbpayment');
		const cbPayTerms = document.getElementById('paymentterms');
		cbPay.addEventListener('change', function(event) {
		cbPayTerms.disabled = !this.checked;
		});

		const cbDel = document.getElementById('cbdeliveryterms');
		const cbDelTerms = document.getElementById('contendeliveryterms');
		cbDel.addEventListener('change', function(event) {
		cbDelTerms.disabled = !this.checked;
		})

		// form submit
		const myForm = document.getElementById("filter");
			if(myForm) {
				myForm.addEventListener("submit", function(event) {
				// event.preventDefault();
				var items=[];
				const rows=document.querySelectorAll('#productTable tbody tr');
				rows.forEach(function(row){
					items.push({
						product_name: row.querySelector('.cell-product').textContent.trim(),
						description: row.querySelector('.cell-description').textContent.trim(),
						unit: row.querySelector('.cell-unit').textContent.trim(),
						qty: row.querySelector('.cell-qty').textContent.trim(),
						unitPrice: row.querySelector('.cell-unitPrice').textContent.trim(),
						amount: row.querySelector('.cell-amount').textContent.trim(),
						vat: row.querySelector('.cell-vatamount').textContent.trim(),
					});
					
				});
				 document.getElementById('quotation_items').value = JSON.stringify(items);
				 return true;
				});
			}
		// End Form Submit
			
	});
	
</script>