<?php include 'load.php';

if (isset($_SESSION['user_id'])) {

	$user_qury_02 = mysqli_query($conn, "SELECT * FROM tbl_user_branch WHERE user_id='" . $_SESSION['user_id'] . "'");

	$user_res = mysqli_fetch_array($user_qury_02);

	$user_branch = $user_res['branch_id'];

}

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

	$prcode = $_POST['prcode'];

	$itemcode = $_POST['itemcode'];

	$proname = $_POST['proname'];

	$category = $_POST['category'];

	$subcategory = $_POST['subcategory'];

	$brand = $_POST['brand'];

	$supplier = $_POST['supplier'];

	$unit = $_POST['unit'];

	$expdate = $_POST['expdate'];

	$mqty = $_POST['mqty'];

	$qty = $_POST['qty'];

	$pdescription = $_POST['pdescription'];

	$price = $_POST['price'];

	$profitmargin = $_POST['profitmargin'];

	$sellprice = $_POST['sellprice'];

	$status = $_POST['status'];

	$producttype = $_POST['producttype'];

	$market_price = $_POST['marketprice'];

	$warranty = $_POST['warranty'];

	$imgFile = $_FILES['user_image']['name'];

	$tmp_dir = $_FILES['user_image']['tmp_name'];

	$imgSize = $_FILES['user_image']['size'];

	$prsize = $_POST['prsize'];

	$whole_sale_price = $_POST['whole_sale_price'];
	$loose_price = $_POST['loose_price'];


	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 (isset($_POST['discount']) && $_POST['discount'] != "") {

		$discount = $_POST['discount'];

		$lastchar = substr($discount, -1); 

		if($lastchar=="%"){

			$discount = intval(substr($discount, 0, -1));

			

			$distype = 1;

			

		}else{

		

			$discount = $discount;

			$distype = 0;

		}

		//$discountpersentage = $_POST['discountpersentage'];

	} else {

		$discount = 0;

		//$discountpersentage = "";

	}



	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($status)) {

		$errMSG = "Please Select Active Or Deactive.";

	} {

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

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

		// valid image extensions

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

		// rename uploading image

		if ($imgSize > 0) {

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

		} else {

			$userpic = "";

		}

		// allow valid image file formats

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

			// investck file size '100MB'

			if ($imgSize < 100000000) {

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

			} else {

				$errMSG = "Sorry, your file is too large.";

			}

		}

	}

	// if no error occured, continue ....



	if (!isset($errMSG)) {

		$stmt = $DB_con->prepare('INSERT INTO mobileproducts(prcode,itemcode,proname,category,subcategory,supplier,unit,expdate,mqty,qty,pdescription,discount1,price,profitmargin,sellprice,cover,status,producttype,brand_id,market_price,warranty,discount_type1,tax1,tax_type1,prsize,whole_sale_price,loose_price) VALUES(:prcode,:itemcode,:proname,:category,:subcategory,:supplier,:unit,:expdate,:mqty,:qty,:pdescription,:discount,:price,:profitmargin,:sellprice,:upic,:status,:producttype,:brand_id,:market_price,:warranty,:discount_type,:tax,:tax_type,:prsize,:whole_sale_price,:loose_price)');

		$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(':discountpersentage', $discountpersentage);

		$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);

		$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(':prsize', $prsize);

		$stmt->bindParam(':whole_sale_price', $whole_sale_price);
		$stmt->bindParam(':loose_price', $loose_price);

		if ($stmt->execute()) {

			$productid = $DB_con->lastInsertId(); // Retrieve the last inserted product ID



			date_default_timezone_set('Asia/Colombo');

			$currentDate = date('Y-m-d H:i:s');



			$AddNewStock = "INSERT INTO `tbl_stock`(`prid`, `branch_id`, `qty`, `add_date`) VALUES ('$productid','$user_branch','$qty','$currentDate')";

			if ($conn->query($AddNewStock) === TRUE) {

				$successMSG = "Successfully! Add Your Products....";

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

			} else {

				$errMSG = "Error while inserting stock data....";

			}

		} else {

			$errMSG = "Error while inserting product data....";

		}

	}

}; ?>

<!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 - Payroll | Pos & Invetory System | Dashboard">

	<meta name="keywords" content="Payroll | Pos & Invetory System | Dashboard">

	<meta name="author" content="Payroll | Pos & Invetory System | Dashboard">

	<meta name="robots" content="noindex, nofollow">

	<title>Home | Payroll | Pos & Invetory System | Dashboard</title>

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

	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

	<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/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_update">

					<div class="page-title">

						<h2>Product Add</h2>

						<p>Create new product</p>

					</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-3 col-12">

									<div class="form-group">

										<label>Product Code</label>

										<?php

										$productid = '';

										$productnumber = '';

										$stmt = $DB_con->prepare('SELECT IFNULL(MAX(prid)+1,1) AS prid FROM `mobileproducts`');

										$stmt->execute();



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

											extract($row);

											$productid = $row['prid'];

											$productnumber = "0000$productid";

										}

										?>

										<input type="text" name="prcode" class="form-control" placeholder="Enter Product Code" value="<?php echo $productnumber; ?>" readonly>

									</div>

								</div>

								<div class="col-lg-3 col-sm-4 col-12">

									<div class="form-group">

										<label>Product Type</label>

										<!-- <select class="select select2"  name="producttype" required> -->

										<select class="form-control" name="producttype" required>

											<option disabled selected value>Select Product Type</option>

											<option value="None">None</option>

											<option value="Customized">Customized</option>

											<option value="Service">Service</option>

										</select>

									</div>

								</div>

								<div class="col-lg-3 col-sm-5 col-12">

									<div class="form-group">

										<label>Barcode/Item Code</label>

										<input type="text" name="itemcode" class="form-control" placeholder="Enter Barcode/Item Code" required>

									</div>

								</div>

								<div class="col-lg-4 col-sm-12 col-12">

									<div class="form-group">

										<label>Product Name</label>

										<input type="text" name="proname" class="form-control" placeholder="Enter Product Name" required>

									</div>

								</div>

								<div class="col-lg-3 col-sm-4 col-12">

									<div class="form-group">

										<label>Category</label>

										<select name="category" class="form-control select2" id="inputcategory" required>

											<option selected value="0">Select Category</option>

											<?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-3 col-sm-4 col-12">

									<div class="form-group">

										<label>Sub Category</label>

										<select name="subcategory" class="form-control select2" id="inputsubcategory">

											<option selected value="0">Select Sub Category</option>



										</select>

									</div>

								</div>

								<div class="col-lg-3 col-sm-4 col-12">

									<div class="form-group">

										<label>Brand</label>

										<select name="brand" 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);



											?>

													<option value="<?php echo $row['brand_id']; ?>"><?php echo $row['brand_name']; ?>

													</option>

											<?php

												}

											}

											?>

										</select>

									</div>

								</div>

								<div class="col-lg-3 col-sm-4 col-12">

									<div class="form-group">

										<label>Size</label>

										<select name="prsize" class="form-control select2" id="inputbrand">

											<option selected value="0">Select Size</option>

											<?php



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



											$stmt->execute();



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



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



											extract($row);



											?>

											<option value="<?php echo $row['szid']; ?>"><?php echo $row['sizename']; ?></option>

											<?php

											}

											}

											?>

										</select>

									</div>

								</div>

								<div class="col-lg-3 col-sm-6 col-12">

									<div class="form-group">

										<label>Supplier</label>

										<select name="supplier" class="form-control select2" id="inputsupplier">

											<option disabled selected value="0">Select Supplier</option>

											<?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="form-control select2" name="unit" required>

											<option disabled selected value="0">Select Unit</option>

											<?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-3 col-sm-3 col-12">

									<div class="form-group">

										<label>Expire Date</label>

										<input type="date" name="expdate" class="form-control" placeholder="Enter Expire Date">

									</div>

								</div>

								<div class="col-lg-3 col-sm-3 col-12">

									<div class="form-group">

										<label>Minimum Qty</label>

										<input type="text" name="mqty" class="form-control" placeholder="Enter Minimum Qty" value="0" required>

									</div>

								</div>

								<div class="col-lg-3 col-sm-3 col-12">

									<div class="form-group">

										<label>Quantity</label>

										<input type="text" name="qty" class="form-control" placeholder="Enter Quantity" value="0" required>

									</div>

								</div>

								<div class="col-lg-3 col-sm-6 col-12">

									<div class="form-group">

										<label>Cost Price</label>

										<input type="text" name="price" onchange="calculateSellingPrice(); calculateProfitPrice();" id="price" class="form-control" placeholder="Enter Cost Price">

									</div>

								</div>

								<div class="col-lg-3 col-sm-6 col-12">

									<div class="form-group">

										<label>Profit Margin</label>

										<input type="text" onchange="calculateSellingPrice()" name="profitmargin" id="profitmargin" class="form-control" placeholder="Enter Profit Margin">

									</div>

								</div>

								<div class="col-lg-3 col-sm-6 col-12">

									<div class="form-group">

										<label>Sell Price</label>

										<input type="text" name="sellprice" id="sellprice" onchange="calculateProfitPrice()" class="form-control" placeholder="Your Sell Price">

									</div>

								</div>

								<div class="col-lg-3 col-sm-6 col-12">

									<div class="form-group">

										<label>Whole Sell Price</label>

										<input type="text" name="whole_sale_price" id="whole_sale_price" class="form-control" placeholder="Your Whole Sell Price">

									</div>

								</div>

								<div class="col-lg-3 col-sm-6 col-12">

									<div class="form-group">

										<label>Market Price</label>

										<input type="text" name="marketprice" id="marketprice" class=" form-control" placeholder="Market Price">

									</div>

								</div>
								<div class="col-lg-3 col-sm-6 col-12">

									<div class="form-group">

										<label>Loose Price</label>

										<input type="text" name="loose_price" id="loose_price" class=" form-control" placeholder="Loose Price">

									</div>

								</div>			
								<div class="col-lg-12">

									<div class="form-group">

										<label>Description</label>

										<textarea class="form-control" name="pdescription" placeholder="Enter Description"></textarea>

									</div>

								</div>

								<br>

								<!--<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-4 col-sm-6 col-12">

									<div class="form-group">

										<label>Discount</label>

										<input type="number" required onchange="convertToPercentage()" name="discount" id="discount" class="form-control" 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 name="discountpersentage" id="discountpersentage" class="form-control" placeholder="Discount Percentage">

									</div>

								</div> -->

								<div class="col-lg-4 col-sm-6 col-12">

									<div class="form-group">

										<label>Discount</label>

										<input type="text" name="discount" id="discount" class="form-control" value="0" placeholder="Enter Discount">

									</div>

								</div>

								<div class="col-lg-4 col-sm-6 col-12">

									<div class="form-group">

										<label>Tax</label>

										<input type="text" name="tax" id="tax" class="form-control" value="0" placeholder="Enter Tax">

									</div>

								</div>

								<div class="col-lg-4 col-sm-6 col-12">

									<div class="form-group">

										<label>Warranty</label>

										<select class="form-control select2" required name="warranty" required>

											<option value="0" selected>Select Warranty</option>

											<option value="No Warranty">No Warranty</option>

											<option value="1 Month Warranty">1 Month Warranty</option>

											<option value="3 Month Warranty">3 Month Warranty</option>

											<option value="6 Month Warranty">6 Month Warranty</option>

											<option value="1 Year Warranty">1 Year Warranty</option>

											<option value="2 Year Warranty">2 Year Warranty</option>

											<option value="3 Year Warranty">3 Year Warranty</option>

											<option value="4 Year Warranty">4 Year Warranty</option>

											<option value="5 Year Warranty">5 Year Warranty</option>

											<option value="10 Year Warranty">10 Year Warranty</option>

										</select>

									</div>

								</div>

								<div class="col-lg-4 col-sm-6 col-12">

									<div class="form-group">

										<label>Status</label>

										<select class="form-control select2" required name="status" required>

											<option value="1">Active</option>

											<option value="0">Deactive</option>

										</select>

									</div>

								</div>

								<div class="col-lg-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>

											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;

												}

											}

										</script>

									</div>

								</div>

								<div class="col-lg-12">

									<a href="productlist.php" class="btn btn-cancel">Cancel</a>

									<button type="submit" name="save" class="btn btn-submit me-2">Save</button>

								</div>

							</div>

						</form>

					</div>

				</div>



			</div>

		</div>

	</div>

	<script>

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

			}

		}







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

	<?php

	require_once 'footerjs.php';

	?>

</body>



</html>