<?php

include 'load.php';

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

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'])) {


	$productid = $_POST['productid'];
	$pqty = $_POST['pqty'];
	$status = $_POST['status'];
	$tobranch_id = $_POST['branch_id'];

	if (empty($productid)) {
		$errMSG = "Please Select Product Name.";
	} else if (empty($pqty)) {
		$errMSG = "Please Enter Product Qty.";
	} else if (empty($status)) {
		$errMSG = "Please Select Active Or Deactive.";

	} else if (empty($tobranch_id)) {
		$errMSG = "Please Select Branch.";
	}

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

	if (!isset($errMSG)) {

		if($tobranch_id == $user_branch){	

			$CheckDB = $conn->query("SELECT COUNT(*) FROM tbl_stock WHERE prid = '$productid' AND branch_id='$user_branch'");
			if ($rs = $CheckDB->fetch_array()) {

				$AlreadyDBCount = $rs[0];
				// $successMSG = $AlreadyDBCount;

				if ($AlreadyDBCount == '0') {
					$AddNewStock = "INSERT INTO `tbl_stock`(`prid`, `branch_id`, `qty`, `add_date`) VALUES ('$productid','$user_branch','$pqty','$currentDate')";
					if ($conn->query($AddNewStock) === TRUE) {
						$successMSG = "Successfully! Add Your Stock....";
						header("refresh:2;stocklist.php"); // redirects image view page after 5 seconds.
					} else {
						$errMSG = "error while inserting....";
					}
				} else {

					$sql3 = "UPDATE tbl_stock SET qty=qty+$pqty WHERE prid='$productid' ";
					if ($conn->query($sql3)) {
						echo "Stock updated";
						$successMSG = "Successfully! Add Your Stock....";
						header("refresh:2;stocklist.php"); // redirects image view page after 5 seconds.
					} else {
						$errMSG = "error while updating....";
					}
				}
			}
		}else{
			$CheckDB = $conn->query("SELECT COUNT(*) FROM tbl_stock WHERE prid = '$productid' AND branch_id='$tobranch_id'");

			if ($rs = $CheckDB->fetch_array()) {

				$AlreadyDBCount = $rs[0];
				// $successMSG = $AlreadyDBCount;

				if ($AlreadyDBCount == '0') {
					$AddNewStock = "INSERT INTO `tbl_stock`(`prid`, `branch_id`, `qty`, `add_date`) VALUES ('$productid','$tobranch_id','$pqty','$currentDate')";
					if ($conn->query($AddNewStock) === TRUE) {

						$sql4 = "UPDATE tbl_stock SET qty=qty-$pqty WHERE prid='$productid' AND branch_id = '$user_branch' ";
						if ($conn->query($sql4)) {
							$successMSG = "Successfully! Add Your Stock....";
							header("refresh:2;stocklist.php"); // redirects image view page after 5 seconds.
						}else{
							$errMSG = "error while inserting....";
						}
					} else {
						$errMSG = "error while inserting....";
					}
				} else {

					$sql4 = "UPDATE tbl_stock SET qty=qty-$pqty WHERE prid='$productid' AND branch_id = '$user_branch' ";

					if ($conn->query($sql4)) {
						$sql5 = "UPDATE tbl_stock SET qty=qty+$pqty WHERE prid='$productid' AND branch_id = '$tobranch_id' ";

						if ($conn->query($sql5)) {
							echo "Stock updated";
							$successMSG = "Successfully! Add Your Stock....";
							header("refresh:2;stocklist.php"); // redirects image view page after 5 seconds.
						} else {
							$errMSG = "error while updating....";
						}

					} else {
						$errMSG = "error while updating....";
					}
				}
				
			}
		}
	}

}

?>

<!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 - Pos & Invetory Systems">
	<meta name="keywords" content="Pos & Invetory Systems">
	<meta name="author" content="Pos & Invetory Systems">
	<meta name="robots" content="noindex, nofollow">

	<title>Add Stock | Eat More Resturant   | Pos & Invetory System | Dashboard

</title>


	<?php
	require_once 'headercss.php';
	?>
</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 Add Stock</h4>
						<h6>Create new product Stock</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-8 col-sm-8 col-12">
									<div class="form-group">
										<label>Product</label>
										<select name="productid" class="form-control select2" id="inputproductid">
											<option selected>Select/Search Product</option>
											<?php

											$stmt = $DB_con->prepare('SELECT * FROM mobileproducts ORDER BY prid');
											$stmt->execute();
											
											if ($stmt->rowCount() > 0) {
												while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
													extract($row);
													$productid2 = $row['prid'];

													$stmt2 = $DB_con->prepare("SELECT * FROM tbl_stock WHERE prid= '$productid2' AND branch_id = '$user_branch'");
													$stmt2->execute();
													
													if($row2 = $stmt2->fetch(PDO::FETCH_ASSOC)){
													extract($row2);
														?>
														<option value="<?php echo $row['prid']; ?>">
															<?php echo $row['proname']; ?> - <?php echo $row['itemcode']; ?> | Stock Balance: <?php echo $row2['qty']; ?>
														</option>
														<?php
													}else{?>
														<option value="<?php echo $row['prid']; ?>">
															<?php echo $row['proname']; ?> - <?php echo $row['itemcode']; ?>  | Stock Balance: 0
														</option>
														<?php
													}
												}
											}
											?>
										</select>
									</div>

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

									<script>
										// Initialize Select2 plugin with typing search functionality
										$('.select2').select2();
									</script>

								</div>
								<div class="col-lg-4 col-sm-4 col-12">
									<div class="form-group">
										<label for="fullName">Qty</label>
										<input type="text" name="pqty" class="form-control" placeholder="Enter Qty">
									</div>
								</div>

								<div class="col-lg-8 col-sm-8 col-12">
									<div class="form-group">
										<label> Branch</label>
										<select class="select" name="branch_id" required>
											<option value="">Please Select Warehouse</option>
											<?php
											$BranchListQuery = $conn->query("SELECT * FROM branch");
											while ($row = $BranchListQuery->fetch_array()) {
												?>
												<option <?php if($user_branch == $row['branch_id']) : echo 'selected'; endif; ?> value="<?php echo $row[0]; ?>"><?php echo $row[1]; ?> <?php if($user_branch == $row['branch_id']) : echo '| Your Branch'; endif; ?></option>
											<?php } ?>
										</select>
									</div>
								</div>

								<div class="col-lg-4 col-sm-4 col-12">
									<div class="form-group">
										<label>Status</label>
										<select class="form-control" name="status" required>
											<option value="1">Active</option>
											<option value="0">Deactive</option>
										</select>
									</div>
								</div>
								<div class="col-lg-12">
									<a href="stocklist.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 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/select2/js/select2.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>
</body>

</html>