<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
	session_start();
}

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors on page
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Access Check
if (!has_permission('manage_products')) {
	echo "<script>alert('Access Denied. Redirecting to Dashboard...'); window.location.href = 'dashboard.php';</script>";
	exit();
}

if (isset($_POST['submit'])) {
	$category = db_prepare($con, $_POST['category']);
	$subcat = db_prepare($con, $_POST['subcategory']);
	$productname = db_prepare($con, $_POST['productName']);
	$productcompany = db_prepare($con, $_POST['productCompany']);
	$productprice = db_prepare($con, $_POST['productprice']);
	$productpricebd = db_prepare($con, $_POST['productpricebd']);
	$productdescription = db_prepare($con, $_POST['productDescription']);
	$productscharge = db_prepare($con, $_POST['productShippingcharge']);
	$productdeliverycharge = !empty($_POST['productDeliveryCharge']) ? db_prepare($con, $_POST['productDeliveryCharge']) : "NULL";
	$productavailability = db_prepare($con, $_POST['productAvailability']);
	$productlocation = db_prepare($con, $_POST['productLocation']);
	$stockQuantity = intval($_POST['stock_quantity']);
	$sku = db_prepare($con, $_POST['sku']);
	$productimage1 = $_FILES["productimage1"]["name"];
	$productimage2 = $_FILES["productimage2"]["name"];
	$productimage3 = $_FILES["productimage3"]["name"];

	//for getting product id
	$query = mysqli_query($con, "select max(id) as pid from products");
	$result = mysqli_fetch_array($query);
	$productid = $result['pid'] + 1;
	$dir = "productimages/$productid";

	if (!is_dir($dir)) {
		mkdir("productimages/" . $productid);
	}

	move_uploaded_file($_FILES["productimage1"]["tmp_name"], "productimages/$productid/" .
		$_FILES["productimage1"]["name"]);
	move_uploaded_file($_FILES["productimage2"]["tmp_name"], "productimages/$productid/" .
		$_FILES["productimage2"]["name"]);
	move_uploaded_file($_FILES["productimage3"]["tmp_name"], "productimages/$productid/" .
		$_FILES["productimage3"]["name"]);

	$addedby = $_SESSION['aid'];

	$sql = mysqli_query($con, "insert into
products(category,subCategory,productName,productCompany,productPrice,productDescription,shippingCharge,productDeliveryCharge,productAvailability,productImage1,productImage2,productImage3,productPriceBeforeDiscount,product_location,stock_quantity,sku,addedBy)
values('$category','$subcat','$productname','$productcompany','$productprice','$productdescription','$productscharge',$productdeliverycharge,'$productavailability','$productimage1','$productimage2','$productimage3','$productpricebd','$productlocation','$stockQuantity','$sku','$addedby')");
	if ($sql) {
		log_activity("Added Product", "Product Name: $productname, SKU: $sku");
		$_SESSION['msg'] = "Product Inserted Successfully!";
	} else {
		$_SESSION['errmsg'] = "Error: " . 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="Insert Product - Awesome Mall Admin" />
	<meta name="author" content="" />
	<title>Awesome Mall | Insert Product</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">
					<!-- Page Header -->
					<div class="page-header mt-4">
						<div>
							<h1><i class="fas fa-plus-square me-2"></i> Insert Product</h1>
							<p>Add a new product to your store inventory</p>
						</div>
					</div>

					<!-- Success Message -->
					<?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 } ?>

					<!-- Product Form -->
					<div class="table-card">
						<div class="card-header">
							<h5 class="mb-0"><i class="fas fa-box me-2"></i>Product Information</h5>
						</div>
						<div class="card-body">
							<form method="post" enctype="multipart/form-data">
								<!-- Category Selection -->
								<div class="row">
									<div class="col-md-6 mb-3">
										<label for="category" class="form-label fw-semibold">Category <span
												class="text-danger">*</span></label>
										<select name="category" id="category" class="form-select"
											onChange="getSubcat(this.value);" required>
											<option value="">Select Category</option>
											<?php
											$query = mysqli_query($con, "select * from category");
											while ($row = mysqli_fetch_array($query)) {
												?>
												<option value="<?php echo $row['id']; ?>">
													<?php echo $row['categoryName']; ?>
												</option>
											<?php } ?>
										</select>
									</div>
									<div class="col-md-6 mb-3">
										<label for="subcategory" class="form-label fw-semibold">Sub Category <span
												class="text-danger">*</span></label>
										<select name="subcategory" id="subcategory" class="form-select" required>
											<option value="">Select Subcategory</option>
										</select>
									</div>
								</div>

								<!-- Row 2: Product Name & SKU -->
								<div class="row">
									<div class="col-md-6 mb-3">
										<label for="productName" class="form-label fw-semibold">Product Name <span
												class="text-danger">*</span></label>
										<input type="text" name="productName" id="productName"
											placeholder="Enter Product Name" class="form-control" required>
									</div>
									<div class="col-md-6 mb-3">
										<label for="sku" class="form-label fw-semibold">SKU (Stock Keeping Unit)</label>
										<input type="text" name="sku" id="sku" placeholder="e.g., PROD-12345"
											class="form-control">
									</div>
								</div>

								<!-- Row 3: Brand & Stock -->
								<div class="row">
									<div class="col-md-6 mb-3">
										<label for="productCompany" class="form-label fw-semibold">Brand/Company</label>
										<input type="text" name="productCompany" id="productCompany"
											placeholder="Enter Brand or Company Name" class="form-control">
									</div>
									<div class="col-md-6 mb-3">
										<label for="stock_quantity" class="form-label fw-semibold">Stock Quantity <span
												class="text-danger">*</span></label>
										<input type="number" name="stock_quantity" id="stock_quantity" placeholder="0"
											class="form-control" min="0" required>
									</div>
								</div>

								<!-- Row 4: Pricing & Location -->
								<div class="row">
									<div class="col-md-3 mb-3">
										<label for="productpricebd" class="form-label fw-semibold">Original Price (₵)
											<span class="text-danger">*</span></label>
										<input type="number" name="productpricebd" id="productpricebd" placeholder="0"
											class="form-control" required oninput="calculateFinalPrice()">
									</div>
									<div class="col-md-3 mb-3">
										<label for="productDiscount" class="form-label fw-semibold">Discount (%)</label>
										<input type="number" name="productDiscount" id="productDiscount" value="0"
											class="form-control" oninput="calculateFinalPrice()">
									</div>
									<div class="col-md-3 mb-3">
										<label for="productprice" class="form-label fw-semibold">Selling Price (₵) <span
												class="text-danger">*</span></label>
										<input type="text" name="productprice" id="productprice"
											class="form-control bg-light" readonly required>
									</div>
									<div class="col-md-3 mb-3">
										<label for="productLocation" class="form-label fw-semibold">Location <span
												class="text-danger">*</span></label>
										<select name="productLocation" id="productLocation" class="form-select"
											required>
											<option value="">Select Location</option>
											<?php
											$query_loc = mysqli_query($con, "SELECT city_name FROM cities ORDER BY city_name ASC");
											while ($row_loc = mysqli_fetch_array($query_loc)) {
												echo "<option value='" . htmlentities($row_loc['city_name']) . "'>" . htmlentities($row_loc['city_name']) . "</option>";
											}
											?>
										</select>
									</div>
								</div>

								<!-- Row 5: Availability & Description -->
								<div class="row">
									<div class="col-md-4 mb-3">
										<label for="productAvailability" class="form-label fw-semibold">Availability
											<span class="text-danger">*</span></label>
										<select name="productAvailability" id="productAvailability" class="form-select"
											required>
											<option value="In Stock">In Stock</option>
											<option value="Out of Stock">Out of Stock</option>
										</select>
									</div>
									<div class="col-md-4 mb-3">
										<label for="productShippingcharge" class="form-label fw-semibold">Shipping
											Charge <span class="text-danger">*</span></label>
										<input type="number" name="productShippingcharge" id="productShippingcharge"
											placeholder="Enter Charge" class="form-control" required>
									</div>
									<div class="col-md-4 mb-3">
										<label for="productDeliveryCharge" class="form-label fw-semibold">Delivery
											Charge (Optional)</label>
										<input type="number" name="productDeliveryCharge" id="productDeliveryCharge"
											placeholder="Default from Settings" class="form-control">
									</div>
								</div>

								<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>

								<div class="row">
									<div class="col-md-12 mb-3">
										<label for="productDescription" class="form-label fw-semibold">Product
											Description</label>
										<textarea name="productDescription" id="productDescription"
											placeholder="Enter Product Description" rows="4"
											class="form-control"></textarea>
									</div>
								</div>

								<!-- Product Images -->
								<div class="row">
									<div class="col-md-4 mb-3">
										<label for="productimage1" class="form-label fw-semibold">Product Image 1 <span
												class="text-danger">*</span></label>
										<input type="file" name="productimage1" id="productimage1" class="form-control"
											accept="image/*" required>
										<small class="text-muted">Primary product image</small>
									</div>
									<div class="col-md-4 mb-3">
										<label for="productimage2" class="form-label fw-semibold">Product Image 2 <span
												class="text-danger">*</span></label>
										<input type="file" name="productimage2" id="productimage2" class="form-control"
											accept="image/*" required>
										<small class="text-muted">Secondary product image</small>
									</div>
									<div class="col-md-4 mb-3">
										<label for="productimage3" class="form-label fw-semibold">Product Image
											3</label>
										<input type="file" name="productimage3" id="productimage3" class="form-control"
											accept="image/*">
										<small class="text-muted">Optional third image</small>
									</div>
								</div>

								<!-- Submit Buttons -->
								<div class="d-flex gap-2">
									<button type="submit" name="submit" class="btn btn-primary">
										<i class="fas fa-check me-2"></i>Insert Product
									</button>
									<a href="manage-products.php" class="btn btn-outline-secondary">
										<i class="fas fa-arrow-left me-2"></i>Back to Products
									</a>
								</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>
</body>

</html>
<?php ?>