<?php

include 'load.php';


if (isset($_GET['prid'])) {

	$prid = mysqli_real_escape_string($conn, $_GET['prid']);
	$view_qury = mysqli_query($conn, "SELECT * FROM mobileproducts WHERE prid='$prid'");
	$view_result = mysqli_fetch_array($view_qury);

} else {
	echo "<script>window.location='productlist.php';</script>";
}


if (isset($_POST['update'])) {

	$prid = $_GET['prid'];
	$prcode = $_POST['prcode'];
	$itemcode = $_POST['itemcode'];
	$proname = $_POST['proname'];
	$category = $_POST['category'];
	$subcategory = $_POST['subcategory'];
	$supplier = $_POST['supplier'];
	$unit = $_POST['unit'];
	$expdate = "";
	$mqty = $_POST['mqty'];
	$qty = $_POST['qty'];
	$pdescription = "";
	$price = $_POST['price'];
	$profitmargin = $_POST['profitmargin'];
	$sellprice = $_POST['sellprice'];
	$status = $_POST['status'];
	$producttype = $_POST['producttype'];
	$brand_id = $_POST['brand_id'];
	$market_price = $_POST['marketprice'];
	$warranty = "None";

	$imgFile = $_FILES['user_image']['name'];
	$tmp_dir = $_FILES['user_image']['tmp_name'];
	$imgSize = $_FILES['user_image']['size'];

	if (isset($_POST['discount'])) {
		$discount = $_POST['discount'];
		//$discountpersentage = $_POST['discountpersentage'];
		$lastchar = substr($discount, -1); 
		if($lastchar=="%"){
			$discount = intval(substr($discount, 0, -1));
			
			$distype = 1;
			
		}else{
		
			$discount = $discount;
			$distype = 0;
		}
	} else {
		$discount = 0;
		//$discountpersentage = 0.0;
	}

	if (isset($_POST['tax']) && $_POST['tax'] != "") {
		$tax = $_POST['tax'];
		$lastchar = substr($tax, -1); 
		if($lastchar=="%"){
			$tax = intval(substr($tax, 0, -1));
			
			$taxtype = 1;
			
		}else{
		
			$tax = $tax;
			$taxtype = 0;
		}
		
	} else {
		$tax = 0;
		
	}


	if(empty($supplier)){
		$supplier = 0;
	}
	if(empty($category)){
		$category = 0;
	}
	if(empty($subcategory)){
		$subcategory = 0;
	}
	if(empty($brand)){
		$brand = 0;
	}
	if(empty($unit)){
		$unit = 0;
	}


	if ($imgFile) {

		$upload_dir = 'images/products/cover/'; // upload directory	

		$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension

		$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'docx', 'pdf', 'video', 'mp3'); // valid extensions

		$userpic = rand(1, 1000000) . "." . $imgExt;

		if (in_array($imgExt, $valid_extensions)) {

			if ($imgSize < 5000000) {

				unlink($upload_dir . $view_result['cover']);

				move_uploaded_file($tmp_dir, $upload_dir . $userpic);

			} else {

				$errMSG = "Sorry, your file is too large it investould be less then 5MB";

			}

		} else {

			$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";

		}

	} else {

		// if no image selected the old image remain as it is.

		$userpic = $view_result['cover']; // old image from database

	}

	if (!isset($errMSG)) {

		$stmt = $DB_con->prepare('UPDATE mobileproducts
			SET prcode=:prcode,
			itemcode=:itemcode,
			proname=:proname,
			category=:category,
			subcategory=:subcategory,
			supplier=:supplier,
			unit=:unit,
			expdate=:expdate,
			mqty=:mqty,
			qty=:qty,
			pdescription=:pdescription,
			discount1=:discount,
			price=:price,
			profitmargin=:profitmargin,
			sellprice=:sellprice,
			cover=:upic,
			status=:status,
			producttype=:producttype,
			brand_id=:brand_id,
			market_price=:market_price,
			warranty=:warranty,
			discount_type1=:discount_type,
			tax1=:tax,
			tax_type1=:tax_type
			WHERE prid=:prid');
		$stmt->bindParam(':prcode', $prcode);
		$stmt->bindParam(':itemcode', $itemcode);
		$stmt->bindParam(':proname', $proname);
		$stmt->bindParam(':category', $category);
		$stmt->bindParam(':subcategory', $subcategory);
		$stmt->bindParam(':supplier', $supplier);
		$stmt->bindParam(':unit', $unit);
		$stmt->bindParam(':expdate', $expdate);
		$stmt->bindParam(':mqty', $mqty);
		$stmt->bindParam(':qty', $qty);
		$stmt->bindParam(':pdescription', $pdescription);
		$stmt->bindParam(':discount', $discount);
		$stmt->bindParam(':price', $price);
		$stmt->bindParam(':profitmargin', $profitmargin);
		$stmt->bindParam(':sellprice', $sellprice);
		$stmt->bindParam(':upic', $userpic);
		$stmt->bindParam(':status', $status);
		$stmt->bindParam(':producttype', $producttype);
		$stmt->bindParam(':brand_id', $brand_id);
		$stmt->bindParam(':market_price', $market_price);
		$stmt->bindParam(':warranty', $warranty);
		$stmt->bindParam(':discount_type', $distype);
		$stmt->bindParam(':tax', $tax);
		$stmt->bindParam(':tax_type', $taxtype);
		$stmt->bindParam(':prid', $prid);

		if ($stmt->execute()) {

			$successMSG = "Products Successfully Updated ...";

			header("refresh:2;productlist.php"); // redirects image view page after 5 seconds.

		} else {

			$errMSG = "Sorry Data Could Not Updated !";

		}

	}

}

?>

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
	<meta name="description" content="POS - Eat More Resturant   | Pos & Invetory System | Dashboard
">
	<meta name="keywords" content="Eat More Resturant   | Pos & Invetory System | Dashboard
">
	<meta name="author" content="Eat More Resturant   | Pos & Invetory System | Dashboard
">
	<meta name="robots" content="noindex, nofollow">

	<title>Home | Eat More Resturant   | Pos & Invetory System | Dashboard
</title>


	<?php
	require_once 'headercss.php';
	
	?>
	<script src="assets/js/jquery-3.6.0.min.js"></script>
	<script src="assets/plugins/select2/js/select2.min.js"></script>
</head>

<body>

	<div id="global-loader">
		<div class="whirly-loader"> </div>
	</div>

	<div class="main-wrapper">
		<?php
		require_once 'header.php';
		?>

		<?php
		require_once 'navbar.php';
		?>

		<div class="page-wrapper">
			<div class="content">
				<div class="page-header">
					<div class="page-title">
						<h4>Product Edit</h4>
						<h6>Update your product</h6>
					</div>
				</div>

				<div class="card">
					<div class="card-body">
						<form method="POST" enctype="multipart/form-data">
							<?php

							if (isset($errMSG)) {

								?>

								<div class="alert alert-danger border-0 bg-danger alert-dismissible fade show py-2">
									<div class="d-flex align-items-center">
										<div class="font-35 text-white"><i class="bx bxs-message-square-x"></i>
										</div>
										<div class="ms-3">
											<h6 class="mb-0 text-white">Error Alerts</h6>
											<div class="text-white">
												<?php echo $errMSG; ?>!
											</div>
										</div>
									</div>
									<button type="button" class="btn-close" data-bs-dismiss="alert"
										aria-label="Close"></button>
								</div>

								<?php

							} else if (isset($successMSG)) {

								?>

									<div class="alert alert-success border-0 bg-success alert-dismissible fade show py-2">
										<div class="d-flex align-items-center">
											<div class="font-35 text-white"><i class="bx bxs-check-circle"></i>
											</div>
											<div class="ms-3">
												<h6 class="mb-0 text-white">Success Alerts</h6>
												<div class="text-white">
												<?php echo $successMSG; ?>!
												</div>
											</div>
										</div>
										<button type="button" class="btn-close" data-bs-dismiss="alert"
											aria-label="Close"></button>
									</div>

								<?php

							}

							?>
							<div class="row">
								<div class="col-lg-2 col-sm-2 col-12">
									<div class="form-group">
										<label>Product Code</label>
										<input type="text" name="prcode" class="form-control"
											placeholder="Enter Product Code"
											value="<?php echo $view_result['prcode']; ?>" readonly>
									</div>
								</div>
								<div class="col-lg-2 col-sm-2 col-12">
									<div class="form-group">
										<label>Type</label>
										<select class="form-control" name="producttype" required>
										<option value="None"<?php if($view_result['producttype'] == "None") { echo "selected";} ?>>None</option>
										<option value="Room"<?php if($view_result['producttype'] == "Room") { echo "selected";} ?>>Room</option>
										<option value="Service"<?php if($view_result['producttype'] == "Service") { echo "selected";} ?>>Service</option>
										<option value="Product"<?php if($view_result['producttype'] == "Product") { echo "selected";} ?>>Product</option>
										<option value="Customized"<?php if($view_result['producttype'] == "Customized") { echo "selected";} ?>>Customized</option>
										</select>
									</div>
								</div>
								<div class="col-lg-3 col-sm-3 col-12">
									<div class="form-group">
										<label>Barcode/Item/Room Code</label>
										<input type="text" name="itemcode" class="form-control" placeholder="Enter Barcode/Item/Room Code" value="<?php echo $view_result['itemcode']; ?>">
									</div>
								</div>
								<div class="col-lg-5 col-sm-5 col-12">
									<div class="form-group">
										<label>Product Name</label>
										<input type="text" name="proname" class="form-control" placeholder="Enter Product Name" value="<?php echo $view_result['proname']; ?>" required>
									</div>
								</div>
								<div class="col-lg-4 col-sm-4 col-12">
									<div class="form-group">
										<label>Category</label>
										<select name="category" class="form-control" id="inputcategory" required>
										<?php if ($view_result['category'] == "0") {?>
											<option value="0" selected>Select Category</option>
											<?php }else{ ?>
											<option value="<?php

											$id = $view_result['category'];

											$query = $DB_con->prepare('SELECT ctid FROM mobilecategory WHERE ctid=' . $id);

											$query->execute();

											$result = $query->fetch();

											echo $result['ctid'];

											?>"><?php

											$id = $view_result['category'];

											$query = $DB_con->prepare('SELECT catename FROM mobilecategory WHERE ctid=' . $id);

											$query->execute();

											$result = $query->fetch();

											echo $result['catename'];

											?></option>
											<?php } ?>
											<?php

											$stmt = $DB_con->prepare('SELECT * FROM mobilecategory ORDER BY ctid');

											$stmt->execute();

											if ($stmt->rowCount() > 0) {

												while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

													extract($row);

													?>
													<option value="<?php echo $row['ctid']; ?>"><?php echo $row['catename']; ?>
													</option>
													<?php
												}
											}
											?>
										</select>
									</div>
								</div>
								<div class="col-lg-4 col-sm-4 col-12">
									<div class="form-group">
										<label>Sub Category</label>
										<select name="subcategory" class="form-control select2" id="inputsubcategory">
										<?php if ($view_result['subcategory'] == "0") {?>
											<option value="0" selected>Select Sub Category</option>
											<?php }else{ ?>
											<option value="<?php

											$id = $view_result['subcategory'];

											$query = $DB_con->prepare('SELECT sbid FROM mobilesubcategory WHERE sbid=' . $id);

											$query->execute();

											$result = $query->fetch();

											echo $result['sbid'];

											?>"><?php

											$id = $view_result['subcategory'];

											$query = $DB_con->prepare('SELECT subname FROM mobilesubcategory WHERE sbid=' . $id);

											$query->execute();

											$result = $query->fetch();

											echo $result['subname'];

											?></option>
											<?php } ?>
											<?php

											$stmt = $DB_con->prepare('SELECT * FROM mobilesubcategory ORDER BY sbid');

											$stmt->execute();

											if ($stmt->rowCount() > 0) {

												while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

													extract($row);

													
													?>
													<!--<option value="<?php echo $row['sbid']; ?>"><?php echo $row['subname']; ?>
													</option>-->
													<?php
												}
											}
											?>
										</select>
									</div>
								</div>
								<div class="col-lg-4 col-sm-4 col-12">
									<div class="form-group">
										<label>Brand</label>
										<select name="brand_id" class="form-control select2" id="inputbrand">
											<option selected value="0">Select Brand</option>
											<?php

											$stmt = $DB_con->prepare('SELECT * FROM mobile_brand ORDER BY brand_id');

											$stmt->execute();

											if ($stmt->rowCount() > 0) {

												while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

													extract($row);
													if($view_result['brand_id']==$row['brand_id']){ ?>
														<option value="<?php echo $row['brand_id']; ?>" selected><?php echo $row['brand_name']; ?>
													</option>
													<?php }else{ ?>
														<option value="<?php echo $row['brand_id']; ?>"><?php echo $row['brand_name']; ?>
													</option>
													<?php }
													?>
													
													<?php
												}
											}
											?>
										</select>
									</div>
								</div>
								<div class="col-lg-4 col-sm-4 col-12">
									<div class="form-group">
										<label>Supplier</label>
										<select name="supplier" class="select select2" id="inputsupplier">
										<?php if ($view_result['supplier'] == "0") {?>
											<option value="0" selected>Select Supplier</option>
											<?php }else{ ?>
											<option value="<?php

											$id = $view_result['supplier'];

											$query = $DB_con->prepare('SELECT spid FROM mobilesuppliers WHERE spid=' . $id);

											$query->execute();

											$result = $query->fetch();

											echo $result['spid'];

											?>"><?php

											$id = $view_result['supplier'];

											$query = $DB_con->prepare('SELECT spname FROM mobilesuppliers WHERE spid=' . $id);

											$query->execute();

											$result = $query->fetch();

											echo $result['spname'];

											?></option>
											<?php } ?>
											<?php

											$stmt = $DB_con->prepare('SELECT * FROM mobilesuppliers ORDER BY spid');

											$stmt->execute();

											if ($stmt->rowCount() > 0) {

												while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

													extract($row);

													?>
													<option value="<?php echo $row['spid']; ?>"><?php echo $row['spname']; ?>
													</option>
													<?php
												}
											}
											?>
										</select>
									</div>
								</div>
								<div class="col-lg-3 col-sm-3 col-12">
									<div class="form-group">
										<label>Unit</label>
										<select class="select select2" name="unit" required>
										<?php if ($view_result['unit'] == "0") {?>
											<option value="0" selected>Select Unit</option>
											<?php }else{ ?>
											<option value="<?php

											$id = $view_result['unit'];

											$query = $DB_con->prepare('SELECT unit_id FROM unit WHERE unit_id=' . $id);

											$query->execute();

											$result = $query->fetch();

											echo $result['unit_id'];

											?>"><?php

											$id = $view_result['unit'];

											$query = $DB_con->prepare('SELECT unit_name FROM unit WHERE unit_id=' . $id);

											$query->execute();

											$result = $query->fetch();

											echo $result['unit_name'];

											?></option>
											<?php } ?>
											<?php

											$stmt = $DB_con->prepare('SELECT * FROM unit ORDER BY unit_id');

											$stmt->execute();

											if ($stmt->rowCount() > 0) {

												while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

													extract($row);

													?>
													<option value="<?php echo $row['unit_id']; ?>"><?php echo $row['unit_name']; ?>
													</option>
													<?php
												}
											}
											?>
											
										</select>
									</div>
								</div>
								<div class="col-lg-2 col-sm-2 col-12">
									<div class="form-group">
										<label>Minimum Qty</label>
										<input type="text" name="mqty" class="form-control"
											placeholder="Enter Minimum Qty" value="<?php echo number_format((int)$view_result['mqty']); ?>">
									</div>
								</div>
								<div class="col-lg-3 col-sm-3 col-12">
									<div class="form-group">
										<label>Quantity/Capacity</label>
										<input type="text" name="qty" class="form-control" placeholder="Enter Qty/Capacity" value="<?php echo number_format((int)$view_result['qty']); ?>">
									</div>
								</div>
								<div class="col-lg-3 col-sm-3 col-12">
									<div class="form-group">
										<label>Cost Price</label>
										<input type="text" required name="price" onchange="calculateSellingPrice(); calculateProfitPrice();"
											id="price" class="form-control" value="<?php echo $view_result['price']; ?>"
											placeholder="Enter Cost Price">
									</div>
								</div>
								<div class="col-lg-3 col-sm-3 col-12">
									<div class="form-group">
										<label>Profit Margin</label>
										<input type="text" required onchange="calculateSellingPrice()"
											name="profitmargin" id="profitmargin" class="form-control"
											value="<?php echo $view_result['profitmargin']; ?>"
											placeholder="Enter Profit Margin">
									</div>
								</div>
								<div class="col-lg-3 col-sm-3 col-12">
									<div class="form-group">
										<label>Sell Price</label>
										<input type="text" name="sellprice" id="sellprice" onchange="calculateProfitPrice()"
											class="form-control" value="<?php echo $view_result['sellprice']; ?>"
											placeholder="Your Sell Price">
									</div>
								</div>
								<div class="col-lg-3 col-sm-3 col-12">
									<div class="form-group">
										<label>Market Price</label>
										<input type="text" name="marketprice" id="marketprice""
											class="form-control" placeholder="Market Price" value="<?php echo $view_result['market_price']; ?>">
									</div>
								</div>	
								<!--<div class="col-lg-12 col-sm-6 col-12">
									<div class="form-group">
										<div class="form-check">
											<input class="form-check-input" onchange="disableDiscount()" type="checkbox"
												value="" id="checkboxDiscount">
											<label class="form-check-label" for="flexCheckDefault">
												are you not using Discount?
											</label>
										</div>
									</div>
								</div>-->
								<div class="col-lg-3 col-sm-3 col-12">
									<div class="form-group">
										<label>Discount</label>
										<?php if($view_result['discount_type1']==1){
											$dis = $view_result['discount1']."%";
										}else{
											$dis = $view_result['discount1'];
										} ?>
										<input type="text" required name="discount"
											id="discount" class="form-control"
											value="<?php echo $dis; ?>"
											placeholder="Enter Discount">
									</div>
								</div>
								<div class="col-lg-3 col-sm-3 col-12">
									<div class="form-group">
										<label>Tax</label>
										<?php if($view_result['tax_type1']==1){
											$taxx = $view_result['tax1']."%";
										}else{
											$taxx = $view_result['tax1'];
										} ?>
										<input type="text" required name="tax"
											id="tax" class="form-control"
											value="<?php echo $taxx; ?>"
											placeholder="Enter Discount">
									</div>
								</div>
								<!--<div class="col-lg-4 col-sm-6 col-12">
									<div class="form-group">
										<label>Discount Percentage</label>
										<input type="text" readonly
											value="<?php echo $view_result['discountpersentage']; ?>"
											name="discountpersentage" id="discountpersentage" class="form-control"
											placeholder="Discount Percentage">
									</div>
								</div>-->
								<div class="col-lg-3 col-sm-3 col-12">
									<div class="form-group">
										<label>Status</label>
										<select class="form-control" name="status" required>
											<option value="1" <?php if ($view_result['status'] == "1") {
												echo "selected";
											} ?>>Active</option>
											<option value="0" <?php if ($view_result['status'] == "0") {
												echo "selected";
											} ?>>Deactive</option>
										</select>
									</div>
								</div>
								<div class="col-lg-12 col-sm-12 col-12">
									<div class="form-group">
										<label> Product Image</label>
										<label for="user_image"><img src="assets/img/empty.png" id="yourImgTag"
												class="pro_pick" style="width:200px;height:200px;"></label>
										<input type="file" name="user_image" id="user_image" hidden="yes"
											onChange="dis_name();">
										<script>
											window.addEventListener("load", function () {
												var discountValue = parseFloat(document.getElementById("discount").value);
												var checkbox = document.getElementById("checkboxDiscount");

												if (discountValue === 0) {
													checkbox.checked = true;
													document.getElementById("discount").disabled = true;
													document.getElementById("discountpercentage").disabled = true;
												}else{
													checkbox.checked = false;
													document.getElementById("discount").disabled = false;
													document.getElementById("discountpercentage").disabled = false;
												}
											});

											function dis_name() {
												var input = document.getElementById("user_image");
												var fReader = new FileReader();
												fReader.readAsDataURL(input.files[0]);
												fReader.onloadend = function (event) {
													var img = document.getElementById("yourImgTag");
													img.src = event.target.result;
												}
											}

											function calculateSellingPrice() {
												var costPrice = parseFloat(document.getElementById("price").value);
												var profitmargin = parseFloat(document.getElementById("profitmargin").value);

												if (costPrice != "" && profitmargin != "") {
													var sellingPrice = costPrice + profitmargin;
													document.getElementById("sellprice").value = sellingPrice.toFixed(2);
												}
											}

											function calculateProfitPrice(){
												var costPrice = parseFloat(document.getElementById("price").value);
												var sellprice = parseFloat(document.getElementById("sellprice").value);  
												
												if (costPrice != "" && sellprice != "") {
													var profitmargin = sellprice - costPrice;
												}else{
													var profitmargin = 0;

												}
												document.getElementById("profitmargin").value = profitmargin.toFixed(2);
											}

											function disableDiscount() {
												var checkbox = document.getElementById("checkboxDiscount");
												var isChecked = checkbox.checked;

												document.getElementById("discount").disabled = isChecked;
												document.getElementById("discountpercentage").disabled = isChecked;
											}

											function convertToPercentage() {
												var percentageValue = parseFloat(document.getElementById("discount").value);

												if (numericValue != "") {
													var numericValue = percentageValue / 100;
													document.getElementById("discountpersentage").value = numericValue.toFixed(2);
												}
											}
										</script>
									</div>
								</div>
								<div class="col-lg-12">
									<a href="productlist.php" class="btn btn-cancel">Cancel</a>
									<button type="submit" name="update" class="btn btn-submit me-2">Update</button>
								</div>
							</div>
						</form>
					</div>
				</div>

			</div>
		</div>
	</div>


	<!--<script src="assets/js/jquery-3.6.0.min.js"></script>-->

	<script src="assets/js/feather.min.js"></script>

	<script src="assets/js/jquery.slimscroll.min.js"></script>

	<script src="assets/js/jquery.dataTables.min.js"></script>
	<script src="assets/js/dataTables.bootstrap4.min.js"></script>

	<script src="assets/js/bootstrap.bundle.min.js"></script>

	

	<script src="assets/plugins/sweetalert/sweetalert2.all.min.js"></script>
	<script src="assets/plugins/sweetalert/sweetalerts.min.js"></script>

	<script src="assets/js/script.js"></script>
	<script>
		$(document).ready(function(){
    $('.select2').select2({
       
    });
});
</script>
<script>
	$(document).ready(function(){
			$('#inputcategory').change(function(){
				var inputcategory = $(this).val();
					$.ajax({
						type: "POST",
						data: {inputcategory:inputcategory},
						url: "category-change.php",
						success: function(data){
							$("#inputsubcategory").html(data);
						}
					});
			});
		});



</script>
</body>

</html>