<?php include 'db_connect.php';

if(isset($_GET['id'])){
	$qry = $conn->query("SELECT * FROM receiving_list where id=".$_GET['id'])->fetch_array();
	foreach($qry as $k => $val){
		$$k = $val;
	}
	$inv = $conn->query("SELECT i.*, b.batch_number FROM inventory i
		LEFT JOIN batch_list b ON b.id = i.batch_id
		WHERE i.type=1 AND i.form_id=".$_GET['id']);
}

// Get products
$product = $conn->query("SELECT * FROM product_list ORDER BY name ASC");
$prod = [];
while($row = $product->fetch_assoc()){
	$prod[$row['id']] = $row;
}
?>

<div class="container-fluid">
	<div class="col-lg-12">
		<div class="modern-card">
			<div class="card-header">
				<h3 class="card-title">
					<i class="fas fa-truck-loading mr-2"></i>
					<?php echo isset($_GET['id']) ? 'Edit' : 'New'; ?> Receiving
				</h3>
				<a href="index.php?page=receiving" class="btn btn-secondary btn-sm">
					<i class="fas fa-arrow-left mr-1"></i> Back
				</a>
			</div>
			<div class="card-body">
				<form action="" id="manage-receiving">
					<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 : mt_rand(10000000, 99999999) ?>">

					<!-- Supplier Selection -->
					<div class="row mb-4">
						<div class="col-md-6">
							<label class="form-label">Supplier <span class="text-danger">*</span></label>
							<select name="supplier_id" id="supplier_id" class="form-control select2" required>
								<option value="">Select Supplier</option>
							<?php
							$supplier = $conn->query("SELECT * FROM supplier_list ORDER BY supplier_name ASC");
							while($row = $supplier->fetch_assoc()):
							?>
								<option value="<?php echo $row['id'] ?>" <?php echo (isset($supplier_id) && $supplier_id == $row['id']) ? 'selected' : ''; ?>><?php echo $row['supplier_name'] ?></option>
							<?php endwhile; ?>
							</select>
						</div>
					</div>

					<hr class="my-4">

					<!-- Add Product Section -->
					<div class="modern-card mb-4" style="background: var(--gray-50);">
						<div class="card-body">
							<h5 class="mb-3"><i class="fas fa-plus-circle text-primary mr-2"></i>Add Product to Receiving</h5>
							<div class="row">
								<div class="col-md-3 mb-3">
									<label class="form-label">Product <span class="text-danger">*</span></label>
									<select id="product" class="form-control select2">
										<option value="">Select Product</option>
									<?php
									$product = $conn->query("SELECT * FROM product_list ORDER BY name ASC");
									while($row = $product->fetch_assoc()):
									?>
										<option value="<?php echo $row['id'] ?>" data-name="<?php echo htmlspecialchars($row['name']) ?>" data-description="<?php echo htmlspecialchars($row['description']) ?>" data-buying-price="<?php echo $row['buying_price'] ?>" data-selling-price="<?php echo $row['selling_price'] ?>"><?php echo $row['name'] . ' | ' . $row['sku'] ?></option>
									<?php endwhile; ?>
									</select>
								</div>
								<div class="col-md-2 mb-3">
									<label class="form-label">Expiry Date <span class="text-danger">*</span></label>
									<input type="date" class="form-control" id="expiry_date" min="<?php echo date('Y-m-d'); ?>">
								</div>
								<div class="col-md-2 mb-3">
									<label class="form-label">Qty <span class="text-danger">*</span></label>
									<input type="number" class="form-control text-center" id="qty" min="1">
								</div>
								<div class="col-md-2 mb-3">
									<label class="form-label">Buying Price <span class="text-danger">*</span></label>
									<input type="number" class="form-control text-right" step="0.01" id="buying_price" min="0" placeholder="0.00">
								</div>
								<div class="col-md-2 mb-3">
									<label class="form-label">Selling Price</label>
									<input type="number" class="form-control text-right" step="0.01" id="selling_price" min="0" readonly style="background-color: #f8f9fa;">
								</div>
								<div class="col-md-2 mb-3">
									<label class="form-label">&nbsp;</label>
									<button class="btn btn-primary btn-block" type="button" id="add_list">
										<i class="fa fa-plus mr-1"></i> Add
									</button>
								</div>
							</div>
						</div>
					</div>

					<!-- Items Table -->
					<div class="table-responsive">
						<table class="table table-bordered" id="list">
							<thead style="background: var(--gray-100);">
								<tr>
									<th class="text-center" width="12%">Batch No.</th>
									<th class="text-center" width="10%">Expiry Date</th>
									<th class="text-center" width="18%">Product</th>
									<th class="text-center" width="10%">Qty</th>
									<th class="text-center" width="12%">Buying Price</th>
									<th class="text-center" width="12%">Selling Price <small>(Fixed)</small></th>
									<th class="text-center" width="12%">Amount</th>
									<th class="text-center" width="6%">Action</th>
								</tr>
							</thead>
							<tbody>
								<?php
								if(isset($id)):
								while($row = $inv->fetch_assoc()):
									$details = json_decode($row['other_details'], true);
									$buying_price = isset($details['buying_price']) ? $details['buying_price'] : 0;
									// Selling price always comes from product (fixed)
									$selling_price = $prod[$row['product_id']]['selling_price'];
									$batch_num = $row['batch_number'] ?? ($details['batch_number'] ?? 'N/A');
								?>
									<tr class="item-row" data-id="<?php echo $row['product_id']; ?>">
										<td>
											<input type="hidden" name="batch_number[]" value="<?php echo htmlspecialchars($batch_num); ?>">
											<code class="text-primary"><?php echo htmlspecialchars($batch_num); ?></code>
										</td>
										<td>
											<input type="date" name="expiry_date[]" class="form-control" value="<?php echo date("Y-m-d", strtotime($row['expiry_date'])); ?>" required>
										</td>
										<td>
											<input type="hidden" name="inv_id[]" value="<?php echo $row['id'] ?>">
											<input type="hidden" name="product_id[]" value="<?php echo $row['product_id'] ?>">
											<strong><?php echo htmlspecialchars($prod[$row['product_id']]['name']); ?></strong>
											<br><small class="text-muted"><?php echo htmlspecialchars($prod[$row['product_id']]['description']); ?></small>
										</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="number" min="0" step="0.01" name="buying_price[]" value="<?php echo $buying_price; ?>" class="form-control text-right buying-price-input">
										</td>
										<td>
											<input type="number" min="0" step="0.01" name="selling_price[]" value="<?php echo $selling_price; ?>" class="form-control text-right" readonly style="background-color: #f8f9fa;">
										</td>
										<td>
											<p class="amount text-right font-weight-bold mb-0"></p>
										</td>
										<td class="text-center">
											<button type="button" class="btn btn-sm btn-danger" onclick="rem_list($(this))">
												<i class="fa fa-trash"></i>
											</button>
										</td>
									</tr>
								<?php endwhile; ?>
								<?php endif; ?>
							</tbody>
							<tfoot>
								<tr style="background: var(--gray-100);">
									<th class="text-right" colspan="6">Total Amount:</th>
									<th class="text-right tamount" style="font-size: 1.1rem;"></th>
									<th><input type="hidden" name="tamount" value="0"></th>
								</tr>
							</tfoot>
						</table>
					</div>

					<!-- Submit Button -->
					<div class="row mt-4">
						<div class="col-12 text-right">
							<a href="index.php?page=receiving" class="btn btn-secondary mr-2">
								<i class="fas fa-times mr-1"></i> Cancel
							</a>
							<button type="submit" class="btn btn-primary">
								<i class="fas fa-save mr-1"></i> Save Receiving
							</button>
						</div>
					</div>
				</form>
			</div>
		</div>
	</div>
</div>

<!-- Row Template -->
<template id="tr_template">
	<tr class="item-row">
		<td>
			<input type="hidden" name="batch_number[]" value="">
			<code class="batch-display text-primary"></code>
		</td>
		<td>
			<input type="date" name="expiry_date[]" class="form-control" required>
		</td>
		<td>
			<input type="hidden" name="inv_id[]" value="">
			<input type="hidden" name="product_id[]" value="">
			<strong class="pname"></strong>
			<br><small class="text-muted pdesc"></small>
		</td>
		<td>
			<input type="number" min="1" name="qty[]" class="form-control text-center qty-input">
		</td>
		<td>
			<input type="number" min="0" step="0.01" name="buying_price[]" class="form-control text-right buying-price-input">
		</td>
		<td>
			<input type="number" min="0" step="0.01" name="selling_price[]" class="form-control text-right" readonly style="background-color: #f8f9fa;">
		</td>
		<td>
			<p class="amount text-right font-weight-bold mb-0"></p>
		</td>
		<td class="text-center">
			<button type="button" class="btn btn-sm btn-danger" onclick="rem_list($(this))">
				<i class="fa fa-trash"></i>
			</button>
		</td>
	</tr>
</template>

<style>
	#list td {
		vertical-align: middle !important;
	}
	#list td input {
		border: 1px solid var(--gray-300);
		border-radius: 6px;
		padding: 0.5rem;
	}
	#list td input:focus {
		border-color: var(--primary);
		outline: none;
		box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
	}
</style>

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

	$(document).ready(function(){
		calculate_total();
		bindInputEvents();
	});

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

	function bindInputEvents(){
		$('.qty-input, .buying-price-input, .selling-price-input').off('input').on('input', function(){
			calculate_total();
		});
	}

	// Function to generate batch number
	function generateBatchNumber(){
		var now = new Date();
		var year = now.getFullYear();
		var month = String(now.getMonth() + 1).padStart(2, '0');
		var day = String(now.getDate()).padStart(2, '0');
		var hours = String(now.getHours()).padStart(2, '0');
		var mins = String(now.getMinutes()).padStart(2, '0');
		var secs = String(now.getSeconds()).padStart(2, '0');
		var ms = String(now.getMilliseconds()).padStart(3, '0');
		return 'BTH-' + year + month + day + '-' + hours + mins + secs + ms;
	}

	// Auto-load prices when product is selected
	$('#product').on('change', function(){
		var selected = $(this).find('option:selected');
		var buyingPrice = selected.attr('data-buying-price') || '';
		var sellingPrice = selected.attr('data-selling-price') || '';
		$('#buying_price').val(buyingPrice);
		$('#selling_price').val(sellingPrice);
	});

	$('#add_list').click(function(){
		var product = $('#product').val(),
			productName = $('#product option:selected').attr('data-name'),
			productDesc = $('#product option:selected').attr('data-description'),
			batchNumber = generateBatchNumber(), // Auto-generate batch number
			expiryDate = $('#expiry_date').val(),
			qty = $('#qty').val(),
			buyingPrice = $('#buying_price').val(),
			sellingPrice = $('#selling_price').val();

		// Validation
		if(product == ''){
			alert_toast("Please select a product", 'danger');
			return false;
		}
		if(expiryDate == ''){
			alert_toast("Please select expiry date", 'danger');
			return false;
		}
		if(qty == '' || qty < 1){
			alert_toast("Please enter valid quantity", 'danger');
			return false;
		}
		if(buyingPrice == '' || buyingPrice < 0){
			alert_toast("Please enter valid buying price", 'danger');
			return false;
		}
		if(sellingPrice == '' || sellingPrice < 0){
			alert_toast("Please enter valid selling price", 'danger');
			return false;
		}

		// Clone template and populate
		var template = document.getElementById('tr_template');
		var tr = $(template.content.cloneNode(true)).find('tr');

		tr.attr('data-id', product);
		tr.find('[name="product_id[]"]').val(product);
		tr.find('[name="batch_number[]"]').val(batchNumber);
		tr.find('.batch-display').text(batchNumber);
		tr.find('[name="expiry_date[]"]').val(expiryDate);
		tr.find('[name="qty[]"]').val(qty);
		tr.find('[name="buying_price[]"]').val(buyingPrice);
		tr.find('[name="selling_price[]"]').val(sellingPrice);
		tr.find('.pname').text(productName);
		tr.find('.pdesc').text(productDesc || 'No description');

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

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

		// Reset form
		$('#product').val('').trigger('change');
		$('#expiry_date').val('');
		$('#qty').val('');
		$('#buying_price').val('');
		$('#selling_price').val('');
	});

	function calculate_total(){
		var total = 0;
		$('#list tbody .item-row').each(function(){
			var qty = parseFloat($(this).find('[name="qty[]"]').val()) || 0;
			var buyingPrice = parseFloat($(this).find('[name="buying_price[]"]').val()) || 0;
			var amount = qty * buyingPrice;
			$(this).find('.amount').text(amount.toLocaleString('en-US', {style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2}));
			total += amount;
		});
		$('#list [name="tamount"]').val(total);
		$('#list .tamount').text(total.toLocaleString('en-US', {style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2}));
	}

	$('#manage-receiving').submit(function(e){
		e.preventDefault();

		if($('#supplier_id').val() == ''){
			alert_toast("Please select a supplier", 'danger');
			return false;
		}

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

		start_load();
		$.ajax({
			url: 'ajax.php?action=save_receiving',
			method: 'POST',
			data: $(this).serialize(),
			success: function(resp){
				if(resp == 1){
					alert_toast("Receiving saved successfully", 'success');
					setTimeout(function(){
						location.href = "index.php?page=receiving";
					}, 1500);
				} else {
					alert_toast("Error saving receiving", 'danger');
					end_load();
				}
			},
			error: function(){
				alert_toast("Connection error", 'danger');
				end_load();
			}
		});
	});
</script>
