<?php
session_start();
include_once('includes/config.php');
if (strlen($_SESSION['aid']) == 0) {
	header('location:logout.php');
} else {
	$pid = intval($_GET['id']); // product id

	// Permission Check
	$can_manage_shipping = has_permission('manage_shipping_overrides');

	if (isset($_POST['submit'])) {
		$category = $_POST['category'];
		$subcat = $_POST['subcategory'];
		$productname = $_POST['productName'];
		$productcompany = $_POST['productCompany'];
		$productprice = $_POST['productprice'];
		$productpricebd = $_POST['productpricebd'];
		$productdescription = $_POST['productDescription'];
		$productscharge = $_POST['productShippingcharge'];
		$productavailability = $_POST['productAvailability'];



		// Shipping Overrides (Only for Admin/Staff)
		if ($can_manage_shipping) {
			$shipping_pickup_fee = ($_POST['shipping_pickup_fee'] !== '') ? "'" . mysqli_real_escape_string($con, $_POST['shipping_pickup_fee']) . "'" : 'NULL';
			$shipping_door_fee = ($_POST['shipping_door_fee'] !== '') ? "'" . mysqli_real_escape_string($con, $_POST['shipping_door_fee']) . "'" : 'NULL';
			$shipping_days_min = ($_POST['shipping_days_min'] !== '') ? "'" . mysqli_real_escape_string($con, $_POST['shipping_days_min']) . "'" : 'NULL';
			$shipping_days_max = ($_POST['shipping_days_max'] !== '') ? "'" . mysqli_real_escape_string($con, $_POST['shipping_days_max']) . "'" : 'NULL';

			$sql = mysqli_query($con, "update products set category='$category',subCategory='$subcat',productName='$productname',productCompany='$productcompany',productPrice='$productprice',productDescription='$productdescription',shippingCharge='$productscharge',productAvailability='$productavailability',productPriceBeforeDiscount='$productpricebd', shipping_pickup_fee=$shipping_pickup_fee, shipping_door_fee=$shipping_door_fee, shipping_days_min=$shipping_days_min, shipping_days_max=$shipping_days_max where id='$pid' ");
		} else {
			// Update without changing shipping overrides
			$sql = mysqli_query($con, "update products set category='$category',subCategory='$subcat',productName='$productname',productCompany='$productcompany',productPrice='$productprice',productDescription='$productdescription',shippingCharge='$productscharge',productAvailability='$productavailability',productPriceBeforeDiscount='$productpricebd' where id='$pid' ");
		}

		if ($sql) {
			$_SESSION['msg'] = "Product Updated Successfully !!";
		} else {
			$_SESSION['msg'] = "Error updating product: " . mysqli_error($con);
		}
	}
	?>
	<!DOCTYPE html>
	<html lang="en">

	<head>
		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
		<meta name="description" content="Update Product | Awesome Mall Admin" />
		<title>Update Product | Admin</title>
		<link href="css/styles.css" rel="stylesheet" />
		<link href="css/admin-professional.css" rel="stylesheet" />
		<script src="js/all.min.js" crossorigin="anonymous"></script>
		<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
		<script>
			function getSubcat(val) {
				$.ajax({
					type: "POST",
					url: "get_subcat.php",
					data: 'cat_id=' + val,
					success: function (data) {
						$("#subcategory").html(data);
					}
				});
			}
		</script>
	</head>

	<body class="sb-nav-fixed">
		<?php include_once('includes/header.php'); ?>
		<div id="layoutSidenav">
			<?php include_once('includes/sidebar.php'); ?>
			<div id="layoutSidenav_content">
				<main>
					<div class="container-fluid px-4">
						<div class="page-header mt-4">
							<div class="d-flex justify-content-between align-items-center">
								<h1><i class="fas fa-edit me-2"></i> Update Product</h1>
								<a href="manage-products.php" class="btn btn-secondary"><i
										class="fas fa-arrow-left me-2"></i> Back to Products</a>
							</div>
						</div>

						<?php if (isset($_POST['submit'])) { ?>
							<div class="alert alert-success alert-dismissible fade show" role="alert">
								<i class="fas fa-check-circle me-2"></i>
								<strong>Success!</strong>
								<?php echo htmlentities($_SESSION['msg']); ?> 		<?php echo htmlentities($_SESSION['msg'] = ""); ?>
								<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
							</div>
						<?php } ?>

						<div class="card mb-4 table-card">
							<div class="card-header">
								<h5 class="mb-0"><i class="fas fa-box-open me-2"></i>Product Details</h5>
							</div>
							<div class="card-body">
								<form class="form-horizontal" name="insertproduct" method="post"
									enctype="multipart/form-data">
									<?php
									$query = mysqli_query($con, "select products.*,category.categoryName as catname,category.id as cid,subcategory.subcategory as subcatname,subcategory.id as subcatid from products join category on category.id=products.category join subcategory on subcategory.id=products.subCategory where products.id='$pid'");
									$cnt = 1;
									while ($row = mysqli_fetch_array($query)) {
										?>

										<div class="row">
											<div class="col-md-6 mb-3">
												<label class="form-label fw-bold">Category</label>
												<select name="category" class="form-select" onChange="getSubcat(this.value);"
													required>
													<option value="<?php echo htmlentities($row['cid']); ?>">
														<?php echo htmlentities($row['catname']); ?>
													</option>
													<?php $query_cat = mysqli_query($con, "select * from category");
													while ($rw = mysqli_fetch_array($query_cat)) {
														if ($row['catname'] == $rw['categoryName']) {
															continue;
														} else {
															?>
															<option value="<?php echo $rw['id']; ?>"><?php echo $rw['categoryName']; ?>
															</option>
														<?php }
													} ?>
												</select>
											</div>

											<div class="col-md-6 mb-3">
												<label class="form-label fw-bold">Sub Category</label>
												<select name="subcategory" id="subcategory" class="form-select" required>
													<option value="<?php echo htmlentities($row['subcatid']); ?>">
														<?php echo htmlentities($row['subcatname']); ?>
													</option>
												</select>
											</div>
										</div>

										<div class="row">
											<div class="col-md-6 mb-3">
												<label class="form-label fw-bold">Product Name</label>
												<input type="text" name="productName"
													value="<?php echo htmlentities($row['productName']); ?>"
													class="form-control" placeholder="Enter Product Name" required>
											</div>
											<div class="col-md-6 mb-3">
												<label class="form-label fw-bold">Product Company</label>
												<input type="text" name="productCompany"
													value="<?php echo htmlentities($row['productCompany']); ?>"
													class="form-control" placeholder="Enter Product Company" required>
											</div>
										</div>

										<!-- Pricing with Auto-Calculation -->
										<div class="row">
											<div class="col-md-3 mb-3">
												<label class="form-label fw-bold">Price Before Discount (Original)</label>
												<div class="input-group">
													<span class="input-group-text">$</span>
													<input type="number" name="productpricebd" id="productpricebd"
														placeholder="Original Price"
														value="<?php echo htmlentities($row['productPriceBeforeDiscount']); ?>"
														class="form-control" required oninput="calculateFinalPrice()">
												</div>
											</div>

											<div class="col-md-3 mb-3">
												<label class="form-label fw-bold">Discount (%)</label>
												<?php
												$discount_val = 0;
												if ($row['productPriceBeforeDiscount'] > 0) {
													$discount_val = round((($row['productPriceBeforeDiscount'] - $row['productPrice']) / $row['productPriceBeforeDiscount']) * 100);
												}
												?>
												<div class="input-group">
													<input type="number" name="productDiscount" id="productDiscount"
														placeholder="0" value="<?php echo $discount_val; ?>"
														class="form-control" oninput="calculateFinalPrice()">
													<span class="input-group-text">%</span>
												</div>
											</div>

											<div class="col-md-3 mb-3">
												<label class="form-label fw-bold text-success">Selling Price (Final)</label>
												<div class="input-group">
													<span class="input-group-text">$</span>
													<input type="text" name="productprice" id="productprice"
														placeholder="Selling Price"
														value="<?php echo htmlentities($row['productPrice']); ?>"
														class="form-control bg-light" readonly required>
												</div>
											</div>

											<div class="col-md-3 mb-3">
												<label class="form-label fw-bold">Shipping Charge</label>
												<div class="input-group">
													<span class="input-group-text">$</span>
													<input type="text" name="productShippingcharge"
														value="<?php echo htmlentities($row['shippingCharge']); ?>"
														class="form-control" required>
												</div>
											</div>
										</div>

										<div class="mb-3">
											<label class="form-label fw-bold">Product Description</label>
											<textarea name="productDescription" class="form-control" rows="6"
												placeholder="Enter Product Description"><?php echo htmlentities($row['productDescription']); ?></textarea>
										</div>

										<div class="mb-3">
											<label class="form-label fw-bold">Product Availability</label>
											<select name="productAvailability" class="form-select" required>
												<option value="<?php echo htmlentities($row['productAvailability']); ?>">
													<?php echo htmlentities($row['productAvailability']); ?>
												</option>
												<option value="In Stock">In Stock</option>
												<option value="Out of Stock">Out of Stock</option>
											</select>
										</div>

										<?php if ($can_manage_shipping) { ?>
											<div class="card mb-4">
												<div class="card-header fw-bold bg-light">
													<i class="fas fa-truck me-2"></i>Shipping Configuration Overrides (Optional)
												</div>
												<div class="card-body">
													<p class="text-muted small mb-3">Leave blank to use global store settings.</p>
													<div class="row">
														<div class="col-md-3 mb-3">
															<label class="form-label small fw-bold">Pickup Fee Override</label>
															<input type="number" name="shipping_pickup_fee" class="form-control"
																value="<?php echo htmlentities($row['shipping_pickup_fee']); ?>"
																step="0.01" min="0" placeholder="Global">
														</div>
														<div class="col-md-3 mb-3">
															<label class="form-label small fw-bold">Door Delivery Fee
																Override</label>
															<input type="number" name="shipping_door_fee" class="form-control"
																value="<?php echo htmlentities($row['shipping_door_fee']); ?>"
																step="0.01" min="0" placeholder="Global">
														</div>
														<div class="col-md-3 mb-3">
															<label class="form-label small fw-bold">Min Delivery Days</label>
															<input type="number" name="shipping_days_min" class="form-control"
																value="<?php echo htmlentities($row['shipping_days_min']); ?>"
																min="0" placeholder="Global">
														</div>
														<div class="col-md-3 mb-3">
															<label class="form-label small fw-bold">Max Delivery Days</label>
															<input type="number" name="shipping_days_max" class="form-control"
																value="<?php echo htmlentities($row['shipping_days_max']); ?>"
																min="0" placeholder="Global">
														</div>
													</div>
												</div>
											</div>
										<?php } ?>
										<div class="row">
											<div class="col-md-4 mb-3">
												<div class="card h-100">
													<div class="card-header text-center fw-bold">Image 1</div>
													<div class="card-body text-center">
														<img src="productimages/<?php echo htmlentities($pid); ?>/<?php echo htmlentities($row['productImage1']); ?>"
															class="img-fluid mb-2" style="max-height: 150px;">
														<br>
														<a href="update-image1.php?id=<?php echo $row['id']; ?>"
															class="btn btn-sm btn-outline-secondary mt-2">Change Image 1</a>
													</div>
												</div>
											</div>
											<div class="col-md-4 mb-3">
												<div class="card h-100">
													<div class="card-header text-center fw-bold">Image 2</div>
													<div class="card-body text-center">
														<img src="productimages/<?php echo htmlentities($pid); ?>/<?php echo htmlentities($row['productImage2']); ?>"
															class="img-fluid mb-2" style="max-height: 150px;">
														<br>
														<a href="update-image2.php?id=<?php echo $row['id']; ?>"
															class="btn btn-sm btn-outline-secondary mt-2">Change Image 2</a>
													</div>
												</div>
											</div>
											<div class="col-md-4 mb-3">
												<div class="card h-100">
													<div class="card-header text-center fw-bold">Image 3</div>
													<div class="card-body text-center">
														<img src="productimages/<?php echo htmlentities($pid); ?>/<?php echo htmlentities($row['productImage3']); ?>"
															class="img-fluid mb-2" style="max-height: 150px;">
														<br>
														<a href="update-image3.php?id=<?php echo $row['id']; ?>"
															class="btn btn-sm btn-outline-secondary mt-2">Change Image 3</a>
													</div>
												</div>
											</div>
										</div>

									<?php } ?>

									<div class="d-grid gap-2 mt-4">
										<button type="submit" name="submit" class="btn btn-primary btn-lg"><i
												class="fas fa-save me-2"></i> Update Product Details</button>
									</div>

								</form>
							</div>
						</div>
					</div>
				</main>
				<?php include_once('includes/footer.php'); ?>
			</div>
		</div>
		<script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
		<script src="js/scripts.js"></script>
		<script>
			function calculateFinalPrice() {
				var originalPrice = parseFloat(document.getElementById('productpricebd').value) || 0;
				var discountPercent = parseFloat(document.getElementById('productDiscount').value) || 0;

				if (originalPrice > 0) {
					var discountAmount = (originalPrice * discountPercent) / 100;
					var finalPrice = originalPrice - discountAmount;
					document.getElementById('productprice').value = Math.round(finalPrice);
				}
			}
		</script>
	</body>

	</html>
<?php } ?>
