<?php include 'db_connect.php';

if(isset($_GET['id'])){
	$qry = $conn->query("SELECT * FROM sales_list where id=".$_GET['id'])->fetch_array();
	foreach($qry as $k => $val){
		$$k = $val;
	}
	$inv = $conn->query("SELECT * FROM inventory where type=2 and form_id=".$_GET['id']);
}

// Get products with stock info
$cat = $conn->query("SELECT * FROM category_list order by name asc");
while($row=$cat->fetch_assoc()):
	$cat_arr[$row['id']] = $row['name'];
endwhile;

$product = $conn->query("SELECT * FROM product_list order by name asc");
while($row=$product->fetch_assoc()):
	$prod[$row['id']] = $row;
endwhile;
?>

<div class="container-fluid">
	<div class="row">
		<!-- Left Panel: Product Selection -->
		<div class="col-lg-7">
			<div class="modern-card mb-4">
				<div class="card-header">
					<h3 class="card-title">
						<i class="fas fa-shopping-cart mr-2"></i>
						<?php echo isset($_GET['id']) ? 'Edit Sale' : 'New Sale'; ?>
					</h3>
					<a href="index.php?page=sales" class="btn btn-secondary btn-sm">
						<i class="fas fa-arrow-left mr-1"></i> Back to Sales
					</a>
				</div>
				<div class="card-body">
					<form action="" id="manage-sales">
						<input type="hidden" name="id" value="<?php echo isset($_GET['id']) ? $_GET['id'] : '' ?>">
						<input type="hidden" name="ref_no" value="<?php echo isset($ref_no) ? $ref_no : '' ?>">

						<!-- Customer Selection -->
						<div class="row mb-4">
							<div class="col-md-8">
								<label class="form-label">
									<i class="fas fa-user mr-1"></i> Customer <span class="text-danger">*</span>
								</label>
								<div class="input-group">
									<select name="customer_id" id="customer_id" class="form-control select2" required>
										<option value="0" selected>Walk-in Customer</option>
									<?php
									$customer = $conn->query("SELECT * FROM customer_list order by name asc");
									while($row=$customer->fetch_assoc()):
									?>
										<option value="<?php echo $row['id'] ?>" <?php echo (isset($customer_id) && $customer_id == $row['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($row['name']) ?></option>
									<?php endwhile; ?>
									</select>
									<div class="input-group-append">
										<button type="button" class="btn btn-success" id="add_new_customer" title="Add New Customer">
											<i class="fas fa-user-plus"></i>
										</button>
									</div>
								</div>
								<small class="text-muted">Select a registered customer for credit sales or <a href="javascript:void(0)" id="add_customer_link">add new</a></small>
							</div>
						</div>

						<!-- Product Search -->
						<div class="product-search-box mb-4">
							<h5 class="mb-3"><i class="fas fa-pills mr-2 text-primary"></i>Add Products</h5>
							<div class="row">
								<div class="col-md-6 mb-3">
									<label class="form-label">Select Product</label>
									<select name="" id="product" class="form-control select2">
										<option value="">Search or select product...</option>
									<?php
									$product = $conn->query("SELECT p.*,
										(SELECT COALESCE(SUM(CASE WHEN type=1 THEN qty ELSE -qty END), 0) FROM inventory WHERE product_id = p.id) as stock
										FROM product_list p ORDER BY name ASC");
									while($row=$product->fetch_assoc()):
									?>
										<option value="<?php echo $row['id'] ?>"
											data-name="<?php echo htmlspecialchars($row['name']) ?>"
											data-measurement="<?php echo htmlspecialchars($row['measurement']) ?>"
											data-description="<?php echo htmlspecialchars($row['description']) ?>"
											data-stock="<?php echo $row['stock'] ?>"
											data-price="<?php echo $row['selling_price'] ?>">
											<?php echo htmlspecialchars($row['name']) ?> | <?php echo $row['sku'] ?> (Stock: <?php echo $row['stock'] ?>)
										</option>
									<?php endwhile; ?>
									</select>
								</div>
								<div class="col-md-3 mb-3">
									<label class="form-label">Quantity</label>
									<input type="number" class="form-control text-center" id="qty" min="1" value="1" style="font-size: 1.1rem; font-weight: 600;">
								</div>
								<div class="col-md-3 mb-3">
									<label class="form-label">&nbsp;</label>
									<button class="btn btn-primary btn-block" type="button" id="add_list" style="height: 46px;">
										<i class="fas fa-plus mr-1"></i> Add
									</button>
								</div>
							</div>
							<div class="text-right">
								<a href="javascript:void(0)" id="search_prod" class="text-primary">
									<i class="fas fa-search mr-1"></i> Advanced product search
								</a>
							</div>
						</div>

						<!-- Items Table -->
						<div class="items-container">
							<h5 class="mb-3"><i class="fas fa-list mr-2 text-primary"></i>Cart Items</h5>
							<div class="table-responsive">
								<table class="table" id="list">
									<thead>
										<tr>
											<th style="width: 40%;">Product</th>
											<th class="text-center" style="width: 15%;">Qty</th>
											<th class="text-right" style="width: 18%;">Price</th>
											<th class="text-right" style="width: 18%;">Amount</th>
											<th class="text-center" style="width: 9%;"></th>
										</tr>
									</thead>
									<tbody>
										<?php
										if(isset($id)):
										while($row = $inv->fetch_assoc()):
											foreach(json_decode($row['other_details']) as $k=>$v){
												$row[$k] = $v;
											}
										?>
											<tr class="item-row" data-id="<?php echo $row['product_id'] ?>">
												<td>
													<input type="hidden" name="inv_id[]" value="<?php echo $row['id'] ?>">
													<input type="hidden" name="product_id[]" value="<?php echo $row['product_id'] ?>">
													<div class="product-info">
														<strong><?php echo htmlspecialchars($prod[$row['product_id']]['name']) ?></strong>
														<small class="text-muted d-block"><?php echo htmlspecialchars($prod[$row['product_id']]['description']) ?></small>
													</div>
												</td>
												<td>
													<input type="number" min="1" name="qty[]" value="<?php echo $row['qty'] ?>" class="form-control text-center qty-input">
												</td>
												<td>
													<input type="hidden" name="price[]" value="<?php echo $row['price'] ?>">
													<p class="text-right mb-0 price-display"><?php echo number_format($row['price'], 2) ?></p>
												</td>
												<td>
													<p class="amount text-right mb-0 font-weight-bold"></p>
												</td>
												<td class="text-center">
													<button type="button" class="btn btn-sm btn-light text-danger" onclick="rem_list($(this))">
														<i class="fas fa-times"></i>
													</button>
												</td>
											</tr>
										<?php endwhile; ?>
										<?php endif; ?>
									</tbody>
								</table>

								<!-- Empty State -->
								<div id="empty-cart" class="text-center py-5" style="<?php echo (isset($id) && $inv->num_rows > 0) ? 'display:none;' : ''; ?>">
									<div class="empty-cart-icon mb-3">
										<i class="fas fa-shopping-basket" style="font-size: 4rem; color: var(--gray-300);"></i>
									</div>
									<h5 class="text-muted">Cart is empty</h5>
									<p class="text-muted">Add products to start the sale</p>
								</div>
							</div>
						</div>
					</form>
				</div>
			</div>
		</div>

		<!-- Right Panel: Payment Summary -->
		<div class="col-lg-5">
			<div class="modern-card payment-panel" style="position: sticky; top: 20px;">
				<div class="card-header" style="background: linear-gradient(135deg, var(--primary), #4f46e5); color: white; border-radius: 16px 16px 0 0;">
					<h3 class="card-title" style="color: white;">
						<i class="fas fa-calculator mr-2"></i>
						Payment Summary
					</h3>
				</div>
				<div class="card-body">
					<!-- Customer Display -->
					<div class="customer-display mb-4 p-3 text-center" style="background: var(--gray-50); border-radius: 12px; border: 2px dashed var(--gray-300);">
						<div class="customer-avatar mx-auto mb-2" style="width: 50px; height: 50px; border-radius: 50%; background: linear-gradient(135deg, var(--primary), #4f46e5); display: flex; align-items: center; justify-content: center; color: white; font-weight: 700; font-size: 1.2rem;">
							<i class="fas fa-user" id="customer-icon"></i>
						</div>
						<div id="customer-name" style="font-weight: 600; font-size: 1.1rem;">Walk-in Customer</div>
						<small class="text-muted" id="customer-type">Cash Sale Only</small>
					</div>

					<!-- Summary -->
					<div class="summary-section mb-4">
						<div class="summary-row d-flex justify-content-between mb-2">
							<span class="text-muted">Items:</span>
							<span id="item-count">0</span>
						</div>
						<div class="summary-row d-flex justify-content-between mb-2">
							<span class="text-muted">Subtotal:</span>
							<span id="subtotal">0.00</span>
						</div>
						<hr>
						<div class="summary-row d-flex justify-content-between">
							<span style="font-size: 1.2rem; font-weight: 600;">Total:</span>
							<span id="total-display" style="font-size: 1.8rem; font-weight: 700; color: var(--primary);">0.00</span>
						</div>
						<input type="hidden" name="tamount" id="tamount" value="0">
					</div>

					<!-- Payment Section -->
					<div class="payment-section">
						<div class="form-group mb-3">
							<label class="form-label">Amount Tendered</label>
							<div class="input-group input-group-lg">
								<div class="input-group-prepend">
									<span class="input-group-text" style="background: var(--gray-100); border: none;">TZS</span>
								</div>
								<input type="text" name="amount_tendered" id="amount_tendered" class="form-control text-right" value="0" style="font-size: 1.5rem; font-weight: 600;">
							</div>
						</div>

						<!-- Change / Debt Display -->
						<div class="form-group mb-3">
							<label class="form-label">Change / Balance</label>
							<div class="change-display text-center py-3" style="background: var(--gray-100); border-radius: 12px;">
								<span id="change-display" style="font-size: 2rem; font-weight: 700; color: var(--success);">0.00</span>
								<div id="debt-label" class="text-danger mt-1" style="display: none; font-weight: 600;">
									<i class="fas fa-exclamation-circle mr-1"></i> DENI (Credit Balance)
								</div>
							</div>
						</div>

						<!-- Quick Amount Buttons -->
						<div class="quick-amounts mb-4">
							<label class="form-label">Quick Amount</label>
							<div class="d-flex flex-wrap gap-2">
								<button type="button" class="btn btn-outline-secondary quick-amt" data-amount="500">500</button>
								<button type="button" class="btn btn-outline-secondary quick-amt" data-amount="1000">1,000</button>
								<button type="button" class="btn btn-outline-secondary quick-amt" data-amount="2000">2,000</button>
								<button type="button" class="btn btn-outline-secondary quick-amt" data-amount="5000">5,000</button>
								<button type="button" class="btn btn-outline-secondary quick-amt" data-amount="10000">10,000</button>
								<button type="button" class="btn btn-outline-primary exact-amt">Exact</button>
							</div>
						</div>

						<!-- Payment Type Selection -->
						<div class="form-group mb-4" id="payment-type-group">
							<label class="form-label">Payment Type</label>
							<div class="btn-group btn-group-toggle w-100" data-toggle="buttons">
								<label class="btn btn-outline-success active flex-fill" id="cash-label">
									<input type="radio" name="payment_type" value="cash" checked>
									<i class="fas fa-money-bill-wave mr-1"></i> Cash (Full)
								</label>
								<label class="btn btn-outline-warning flex-fill" id="credit-label">
									<input type="radio" name="payment_type" value="credit">
									<i class="fas fa-credit-card mr-1"></i> Credit (Deni)
								</label>
							</div>
						</div>

						<!-- Credit Warning -->
						<div id="credit-warning" class="alert alert-warning py-2 mb-3" style="display: none;">
							<i class="fas fa-info-circle mr-1"></i>
							<strong>Credit Sale:</strong> Customer must be registered. Walk-in customers cannot have credit.
						</div>

						<!-- Pay Buttons -->
						<div class="row">
							<div class="col-12">
								<button type="button" class="btn btn-success btn-lg btn-block" id="pay" style="padding: 16px; border-radius: 12px; font-size: 1.2rem;">
									<i class="fas fa-check-circle mr-2"></i> Complete Sale
								</button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<!-- Clone Template (hidden) -->
<div id="tr_clone" style="display: none;">
	<table>
		<tr class="item-row">
			<td>
				<input type="hidden" name="inv_id[]" value="">
				<input type="hidden" name="product_id[]" value="">
				<div class="product-info">
					<strong class="pname">Product Name</strong>
					<small class="text-muted d-block pdesc">Description</small>
				</div>
			</td>
			<td>
				<input type="number" min="1" name="qty[]" value="1" class="form-control text-center qty-input">
			</td>
			<td>
				<input type="hidden" name="price[]" value="0">
				<p class="text-right mb-0 price-display">0.00</p>
			</td>
			<td>
				<p class="amount text-right mb-0 font-weight-bold"></p>
			</td>
			<td class="text-center">
				<button type="button" class="btn btn-sm btn-light text-danger" onclick="rem_list($(this))">
					<i class="fas fa-times"></i>
				</button>
			</td>
		</tr>
	</table>
</div>

<!-- Add Customer Modal -->
<div class="modal fade" id="addCustomerModal" tabindex="-1" role="dialog">
	<div class="modal-dialog" role="document">
		<div class="modal-content" style="border-radius: 16px; border: none;">
			<div class="modal-header" style="background: linear-gradient(135deg, var(--success), #16a34a); color: white; border-radius: 16px 16px 0 0;">
				<h5 class="modal-title"><i class="fas fa-user-plus mr-2"></i>Add New Customer</h5>
				<button type="button" class="close text-white" data-dismiss="modal">
					<span>&times;</span>
				</button>
			</div>
			<form id="quick-add-customer">
				<div class="modal-body">
					<div class="form-group">
						<label class="form-label">Customer Name <span class="text-danger">*</span></label>
						<input type="text" name="name" id="new_customer_name" class="form-control" required placeholder="Enter customer name">
					</div>
					<div class="form-group">
						<label class="form-label">Phone Number</label>
						<input type="text" name="contact" id="new_customer_contact" class="form-control" placeholder="Enter phone number">
					</div>
					<div class="form-group">
						<label class="form-label">Address</label>
						<textarea name="address" id="new_customer_address" class="form-control" rows="2" placeholder="Enter address (optional)"></textarea>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
					<button type="submit" class="btn btn-success">
						<i class="fas fa-save mr-1"></i> Save Customer
					</button>
				</div>
			</form>
		</div>
	</div>
</div>

<style>
	.product-search-box {
		background: var(--gray-50);
		padding: 20px;
		border-radius: 12px;
		border: 1px dashed var(--gray-300);
	}

	#list thead th {
		background: var(--gray-50);
		font-weight: 600;
		font-size: 0.75rem;
		text-transform: uppercase;
		letter-spacing: 0.05em;
		color: var(--gray-600);
		padding: 12px;
		border-bottom: 2px solid var(--gray-200);
	}

	#list tbody td {
		padding: 12px;
		vertical-align: middle;
		border-bottom: 1px solid var(--gray-100);
	}

	#list .qty-input {
		width: 70px;
		margin: 0 auto;
		font-weight: 600;
	}

	.payment-panel {
		box-shadow: 0 10px 40px rgba(0,0,0,0.1);
	}

	.quick-amounts .btn {
		flex: 1;
		min-width: 70px;
		margin: 4px;
		border-radius: 8px;
	}

	.gap-2 {
		gap: 0.5rem;
	}

	.btn-group-toggle .btn {
		border-radius: 8px !important;
		margin: 0 4px;
	}

	.btn-group-toggle .btn.active {
		box-shadow: 0 4px 12px rgba(0,0,0,0.15);
	}

	@media (max-width: 991px) {
		.payment-panel {
			position: relative !important;
			top: 0 !important;
			margin-top: 1rem;
		}
	}
</style>

<script>
	$('.select2').select2({
		placeholder: "Select an option",
		width: "100%",
		dropdownParent: $('body')
	});

	$(document).ready(function(){
		if('<?php echo isset($id) ?>' == 1){
			$('[name="customer_id"]').val('<?php echo isset($customer_id) ? $customer_id : 0 ?>').trigger('change');
			calculate_total();
		}
		updateEmptyState();
		updateCustomerDisplay();
	});

	// Add new customer modal
	$('#add_new_customer, #add_customer_link').click(function(){
		$('#addCustomerModal').modal('show');
		$('#quick-add-customer')[0].reset();
	});

	// Save new customer
	$('#quick-add-customer').submit(function(e){
		e.preventDefault();

		var name = $('#new_customer_name').val().trim();
		if(name == ''){
			alert_toast("Please enter customer name", 'danger');
			return false;
		}

		start_load();
		$.ajax({
			url: 'ajax.php?action=save_customer',
			method: 'POST',
			data: $(this).serialize(),
			success: function(resp){
				if(resp > 0){
					// Destroy Select2 first
					$('#customer_id').select2('destroy');

					// Add new option to the select element
					$('#customer_id').append('<option value="' + resp + '">' + name + '</option>');

					// Set the new value
					$('#customer_id').val(resp);

					// Re-initialize Select2
					$('#customer_id').select2({
						placeholder: "Select an option",
						width: "100%",
						dropdownParent: $('body')
					});

					$('#addCustomerModal').modal('hide');
					alert_toast("Customer added successfully!", 'success');
					updateCustomerDisplay();
				} else {
					alert_toast("Error saving customer", 'danger');
				}
				end_load();
			},
			error: function(){
				alert_toast("Connection error", 'danger');
				end_load();
			}
		});
	});

	$('#search_prod').click(function(){
		uni_modal("Find Available Product.", "find_product.php", "large");
	});

	function select_prod($id){
		start_load();
		$('#product').val($id).trigger('change');
		end_load();
		$('.modal').modal('hide');
	}

	function rem_list(_this){
		_this.closest('tr').remove();
		calculate_total();
		updateEmptyState();
	}

	function updateEmptyState(){
		if($('#list tbody .item-row').length > 0){
			$('#empty-cart').hide();
		} else {
			$('#empty-cart').show();
		}
	}

	$('#add_list').click(function(){
		var tr = $('#tr_clone tr.item-row').clone();
		var product = $('#product').val(),
			qty = $('#qty').val() || 1,
			selectedOption = $('#product option:selected');

		if($('#list').find('tr[data-id="'+product+'"]').length > 0){
			alert_toast("Product already in cart", 'warning');
			return false;
		}

		if(product == ''){
			alert_toast("Please select a product", 'danger');
			return false;
		}

		var stock = parseInt(selectedOption.attr('data-stock')) || 0;
		if(stock < qty){
			alert_toast("Insufficient stock! Available: " + stock, 'danger');
			return false;
		}

		$.ajax({
			url: 'ajax.php?action=chk_prod_availability',
			method: 'POST',
			data: {id: product},
			success: function(resp){
				resp = JSON.parse(resp);
				if(resp.available >= qty){
					tr.attr('data-id', product);
					tr.find('.pname').html(selectedOption.attr('data-name') + "<sup>" + selectedOption.attr('data-measurement') + "</sup>");
					tr.find('.pdesc').text(selectedOption.attr('data-description') || 'No description');
					tr.find('.price-display').text(parseFloat(resp.price).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
					tr.find('[name="product_id[]"]').val(product);
					tr.find('[name="qty[]"]').val(qty);
					tr.find('[name="price[]"]').val(resp.price);

					var amount = parseFloat(resp.price) * parseFloat(qty);
					tr.find('.amount').text(parseFloat(amount).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));

					$('#list tbody').append(tr);
					calculate_total();
					updateEmptyState();

					// Bind events to new row
					tr.find('.qty-input').on('input', function(){
						calculate_total();
					});

					// Reset form
					$('#product').val('').trigger('change');
					$('#qty').val(1);
				} else {
					alert_toast("Insufficient stock! Available: " + resp.available, 'danger');
				}
			}
		});
	});

	// Bind qty input events to existing rows
	$('.qty-input').on('input', function(){
		calculate_total();
	});

	function calculate_total(){
		var total = 0;
		var itemCount = 0;

		$('#list tbody').find('.item-row').each(function(){
			var _this = $(this);
			var qty = parseFloat(_this.find('[name="qty[]"]').val()) || 0;
			var price = parseFloat(_this.find('[name="price[]"]').val()) || 0;
			var amount = qty * price;

			_this.find('.amount').text(parseFloat(amount).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
			total += amount;
			itemCount++;
		});

		$('#tamount').val(total);
		$('#subtotal').text(parseFloat(total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
		$('#total-display').text(parseFloat(total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
		$('#item-count').text(itemCount + ' item' + (itemCount != 1 ? 's' : ''));

		// Recalculate change
		calculateChange();
	}

	function calculateChange(){
		var tenderedStr = $('#amount_tendered').val().replace(/[^0-9]/g, '');
		var tendered = parseFloat(tenderedStr) || 0;
		var total = parseFloat($('#tamount').val()) || 0;
		var change = tendered - total;

		if(change >= 0){
			// Has change or exact amount
			$('#change-display').text(parseFloat(change).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
			$('#change-display').css('color', 'var(--success)');
			$('#debt-label').hide();

			// Show cash option
			$('#cash-label').removeClass('disabled');
			$('input[name="payment_type"][value="cash"]').prop('disabled', false);
		} else {
			// Has debt
			var debt = Math.abs(change);
			$('#change-display').text(parseFloat(debt).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
			$('#change-display').css('color', 'var(--danger)');
			$('#debt-label').show();
		}
	}

	function updatePaymentType(){
		var tenderedStr = $('#amount_tendered').val().replace(/[^0-9]/g, '');
		var tendered = parseFloat(tenderedStr) || 0;
		var total = parseFloat($('#tamount').val()) || 0;
		var customerId = $('#customer_id').val();
		var paymentType = $('input[name="payment_type"]:checked').val();

		// Show/hide credit warning
		if(paymentType == 'credit' || tendered < total){
			if(customerId == '0' || customerId == ''){
				$('#credit-warning').show();
			} else {
				$('#credit-warning').hide();
			}
		} else {
			$('#credit-warning').hide();
		}
	}

	// Handle amount tendered input - simple approach
	$('#amount_tendered').on('blur', function(){
		// Format and calculate on blur only
		var val = $(this).val().replace(/[^0-9]/g, '');
		var num = parseInt(val) || 0;
		$(this).val(num.toLocaleString('en-US'));
		calculateChange();
		updatePaymentType();
	});

	$('#customer_id').on('change', function(){
		updatePaymentType();
		updateCustomerDisplay();
	});

	function updateCustomerDisplay(){
		var customerId = $('#customer_id').val();
		var customerName = $('#customer_id option:selected').text();

		if(customerId == '0' || customerId == ''){
			$('#customer-name').text('Walk-in Customer');
			$('#customer-type').text('Cash Sale Only').removeClass('text-success').addClass('text-muted');
			$('#customer-icon').removeClass().addClass('fas fa-user');
			$('.customer-avatar').css('background', 'linear-gradient(135deg, var(--gray-400), var(--gray-500))');
		} else {
			$('#customer-name').text(customerName);
			$('#customer-type').text('Credit Eligible').removeClass('text-muted').addClass('text-success');
			$('#customer-icon').removeClass().addClass('fas fa-user-check');
			$('.customer-avatar').css('background', 'linear-gradient(135deg, var(--primary), #4f46e5)');
		}
	}

	$('input[name="payment_type"]').on('change', function(){
		updatePaymentType();
	});

	// Quick amount buttons
	$('.quick-amt').click(function(){
		var currentStr = $('#amount_tendered').val().replace(/[^0-9]/g, '');
		var current = parseFloat(currentStr) || 0;
		var add = parseFloat($(this).attr('data-amount'));
		var newVal = current + add;
		$('#amount_tendered').val(newVal.toLocaleString('en-US'));
		calculateChange();
	});

	$('.exact-amt').click(function(){
		var total = parseFloat($('#tamount').val()) || 0;
		$('#amount_tendered').val(total.toLocaleString('en-US'));
		calculateChange();
	});

	$('#pay').click(function(){
		if($("#list .item-row").length <= 0){
			alert_toast("Please add at least 1 item", 'danger');
			return false;
		}

		var total = parseFloat($('#tamount').val()) || 0;
		var tenderedStr = $('#amount_tendered').val().replace(/[^0-9]/g, '');
		var tendered = parseFloat(tenderedStr) || 0;
		var customerId = $('#customer_id').val();
		var paymentType = $('input[name="payment_type"]:checked').val();
		var debt = 0;

		// Check if there's a debt
		if(tendered < total){
			debt = total - tendered;

			// Must have registered customer for credit
			if(customerId == '0' || customerId == ''){
				alert_toast("Credit sales require a registered customer. Walk-in customers cannot have credit.", 'danger');
				return false;
			}

			// Confirm credit sale
			if(!confirm('This sale has a debt of TZS ' + debt.toLocaleString('en-US', {minimumFractionDigits: 2}) + '. \n\nTotal: TZS ' + total.toLocaleString('en-US', {minimumFractionDigits: 2}) + '\nPaid: TZS ' + tendered.toLocaleString('en-US', {minimumFractionDigits: 2}) + '\nDebt: TZS ' + debt.toLocaleString('en-US', {minimumFractionDigits: 2}) + '\n\nProceed with credit sale?')){
				return false;
			}
		} else {
			// Show confirmation for cash sale
			if(!confirm('Complete this sale for TZS ' + total.toLocaleString('en-US', {minimumFractionDigits: 2}) + '?')){
				return false;
			}
		}

		submitSale(debt);
	});

	function submitSale(debt){
		start_load();

		// Clean the amount_tendered value before submitting (remove commas)
		var cleanTendered = $('#amount_tendered').val().replace(/[^0-9]/g, '');
		var totalAmount = $('#tamount').val();

		var formData = $('#manage-sales').serialize();
		// Add fields that are outside the form (in payment panel)
		formData += '&tamount=' + totalAmount;
		formData += '&amount_tendered=' + cleanTendered;
		formData += '&debt_amount=' + debt;
		formData += '&payment_type=' + $('input[name="payment_type"]:checked').val();

		$.ajax({
			url: 'ajax.php?action=save_sales',
			method: 'POST',
			data: formData,
			success: function(resp){
				if(resp > 0){
					end_load();
					alert_toast("Sale completed successfully!", 'success');
					var nw = window.open("print_sales.php?id=" + resp, "_blank", "height=700,width=900");
					nw.print();
					setTimeout(function(){
						nw.close();
						location.href = "index.php?page=sales";
					}, 1000);
				} else {
					end_load();
					alert_toast("Error saving sale", 'danger');
				}
			},
			error: function(){
				end_load();
				alert_toast("Connection error", 'danger');
			}
		});
	}
</script>
