<?php
session_start();
require_once 'dbconfig.php';
require_once 'db_connection.php';
$totalbillvalue = $_POST['totalbillvalue'];
$cashamounthidden = $_POST['cashamounthidden'];
$customer = $_POST['customer'];
$cashamount = $_POST['cashamount'];
$cardno = $_POST['cardno'];
$cheque = $_POST['cheque'];
$duedate = $_POST['duedate'];
$cheque_number = $_POST['cheque_number'];
$pay_type = $_POST['pay_type'];
$totalAmountvalue = $_POST['totalAmountvalue'];
$discount = $_POST['discount'];
$branchid = $_SESSION['branch_id'];
$oid = $_POST['oid'];

$last = substr($discount, -1);
/* */ 
if($_SESSION['order_id'] !=0 && isset($_SESSION['order_id'])){

		/* */ 
		$orderid = $_SESSION['order_id'];

		$sql5 = "DELETE FROM invoice_other_details WHERE order_id ='$orderid'";
		if ($conn->query($sql5) === TRUE) {
			$sql6 = "DELETE FROM mobileorders WHERE order_id ='$orderid'";
				if ($conn->query($sql6) === TRUE) {
					$sql7 = "UPDATE mobiletemporarycart SET orderid='0' WHERE orderid='$orderid'";
					if ($conn->query($sql7) === TRUE) {}





if($last=="%"){
	$type = 1;
}else{
	$type = 0;
}

$user_id = $_SESSION['user_id'];

$branch_id = $_POST['branch_id'];

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

$admincommision = 0;
$customercommision = 0;
$admininfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileusers WHERE user_id='$user_id'"));
$adminrate = $admininfo['ucomission'];

$customerinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobilecustomers WHERE coid ='$customer'"));
$customerrate = $customerinfo['comission'];

if ($discount > 0 && $discount < 101) {
	$discounted_amount = (int)$totalbillvalue / 100 * (int)$discount;
	$totalbillvalue = (int)$totalbillvalue - (int)$discounted_amount;
}

$country = $_POST['country'];
$city = $_POST['city'];
$deliveryCost = $_POST['deliveryCost'];

if ($pay_type == 'credit') {
	$due_amount = $totalAmountvalue - $cashamount;
	$paid_amount = $cashamount;

	if ($due_amount >= 0) {
		$sql3 = "UPDATE mobilecustomers SET ccredit = ? WHERE coid = ?";
		$stmt = $conn->prepare($sql3);
		$stmt->bind_param("is", $due_amount, $customer);
		if ($stmt->execute()) {
			// Stock updated successfully
		} else {
			// Error occurred while updating stock
		}
		$stmt->close();
	} else {
		$sql3 = "UPDATE mobilecustomers SET ccredit = 0 WHERE coid = ?";
		$stmt = $conn->prepare($sql3);
		$stmt->bind_param("s", $customer);
		if ($stmt->execute()) {
			// Stock updated successfully
		} else {
			// Error occurred while updating stock
		}
		$stmt->close();
	}


} else {
	$due_amount = 0;
	$paid_amount = $totalbillvalue;
}

if ($totalbillvalue > 0 || $oid != 0) {

	//if ($pay_type == 'card' && strlen($cardno) < 3) {
	//	echo "Enter valid debit card number..";
	//} 
	//if ($pay_type == 'cash' && $cashamount == 0 || $pay_type == 'cash' && $totalbillvalue > $cashamount) {
	
		





	if ($pay_type == 'cash' && $cashamount == 0) {
		echo "Enter cash amount..";
	} elseif ($pay_type == 'credit' && !$customer > 0) {
		echo "Select credit customer..";
	}elseif ($customer == 'dc' && !$country > 0) {
		echo "Select Delivery Country..";
	} elseif ($customer == 'dc' && !$city > 0) {
		echo "Select Delivery City..";
	} else {


		if ($pay_type == 'credit'){
			$creditval = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobilecustomers WHERE coid='$customer'"));

			$credit_limit = $creditval['credit_limit'];
			if($credit_limit > $totalAmountvalue){

			}else{
				echo "Customer credit limit is ".$credit_limit;
			}

			

		}





		$comid = '';
		$orid = '';
		$stmt = $DB_con->prepare('SELECT IFNULL(MAX(order_id)+1,1) AS order_id FROM `mobileorders`');
		$stmt->execute();
		while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
			extract($row);
			$comid = $row['order_id'];
			$orid = "100$comid";
		}
		if($adminrate==0 || empty($adminrate)){
			$admincommision = 0;
		}else{
			$admincommision = (float)$totalbillvalue / 100 * $adminrate;
		}
		if($customerrate==0 || empty($customerrate)){
			$customercommision = 0;
		}else{
			$customercommision = (float)$totalbillvalue / 100 * $customerrate;
		}

		if($oid != 0){
			$return_qty = mysqli_query($conn, "SELECT * FROM temp_return_qty WHERE order_id='$oid' AND return_type='1' AND add_to_return='1'");
			$datetime = date("Y-m-d H:i:s");
			$amountdetails = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(return_amount) as returnamount,order_id,add_to_return FROM temp_return_qty WHERE order_id='$oid' AND add_to_return='1'"));
            $amount = $amountdetails['returnamount'];
			$sql5 = "INSERT INTO tbl_return (order_id, return_datetime, return_amount)VALUES ('$oid', '$datetime', '$amount')";
			if ($conn->query($sql5) === TRUE) {
				$last_id = $conn->insert_id;
				$returnitemlist = mysqli_query($conn, "SELECT * FROM temp_return_qty WHERE order_id='$oid' AND return_type='1' AND add_to_return='1'");
				if ($returnitemlist->num_rows > 0) {
					 while($rw1 = $returnitemlist->fetch_assoc()) {
						 $pid = $rw1['product_id'];
						 $return_qty = $rw1['return_qty'];
						 $orderr_id = $rw1['order_id'];
						 $return_reson = $rw1['return_reson'];
						 $sql6 = "INSERT INTO tbl_return_items (return_id, prid, qty,order_id,return_type,return_reson)VALUES ('$last_id', '$pid', '$return_qty', '$orderr_id','1','$return_reson')";
						 if ($conn->query($sql6) === TRUE) {
							 $stockresult = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM tbl_stock WHERE prid='$pid'"));

						   
							 $stock = $stockresult['qty'];
							 $stock =+ $return_qty;
							 $sql3 = "UPDATE tbl_stock SET qty='$stock' WHERE prid='$pid'";

							 $sql7 = "DELETE FROM temp_return_qty";
							 $conn->query($sql7);

							 $sql8 = "UPDATE mobiletemporarycart SET orderid='$oid',return_to_new='1' WHERE orderid=0 AND hold=0 ";
							if ($conn->query($sql8) === TRUE) {
								$sql2 = "SELECT * FROM mobiletemporarycart WHERE orderid='$oid' ORDER BY tempid DESC";
								$result2 = $conn->query($sql2);
								if ($result2->num_rows > 0) {
									while ($row = $result2->fetch_assoc()) {
										$proid = $row["proid"];
										$pro_qty = $row["pro_qty"];
		
										$sql9 = "UPDATE tbl_stock SET qty= qty-$pro_qty WHERE prid='$proid' AND branch_id='$branch_id' ";
										if ($conn->query($sql9) === TRUE) {
											//echo "Stock updated"; $branch_id
		
											if ($pay_type == 'credit'){
												$creditval = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobilecustomers WHERE coid='$customer'"));
												if($credit_limit > $totalAmountvalue){
													$sql10 = "UPDATE mobilecustomers SET ccredit= '$totalAmountvalue' WHERE coid='$customer'";
													if ($conn->query($sql10) === TRUE) {
		
													}
												}
		
											}
										}
		
									}
								}

							}


							 unset($_SESSION['order_id']);
							

							 header("refresh:2;return-list.php"); 

						 }


					 }
				}
			}
		}else{


		






		$sql = "INSERT INTO mobileorders (orid,pay_option, amount, discount ,paid_amount,due_amount, payment_option_number,cheque_no,cheque_due_date, customer, delivery_cost, country, city,  user_id, create_at, dis_type,branch_id,status,admin_id,admin_commiision,customer_commision,cheque_number)
		VALUES ('$orid','$pay_type', '1000', '$discount' ,'$cashamount','$due_amount', '$cardno','$cheque','$duedate', '$customer', '$deliveryCost','$country','$city','$user_id', '$today' ,'$type' ,'$branchid','1','$user_id','$admincommision','$customercommision','$cheque_number')";
		if ($conn->query($sql) === TRUE) {
			$last_id = $conn->insert_id;
			if ($last_id > 0) {
				$sql = "UPDATE mobiletemporarycart SET orderid='$last_id' WHERE orderid=0 AND user_id='$user_id' AND hold=0 ";
				if ($conn->query($sql) === TRUE) {
					echo $last_id;

					$sql = "INSERT INTO `invoice_other_details`(`invoice_other_id`, `order_id`, `branch_id`) VALUES (null,'$last_id', '$branch_id')";
					if ($conn->query($sql) === TRUE) {
						//echo "New record created successfully";

						//update quantity///////////////
						$sql2 = "SELECT * FROM mobiletemporarycart WHERE orderid='$last_id' ORDER BY tempid DESC";
						$result2 = $conn->query($sql2);
						if ($result2->num_rows > 0) {
							while ($row = $result2->fetch_assoc()) {
								$proid = $row["proid"];
								$pro_qty = $row["pro_qty"];

								$sql3 = "UPDATE tbl_stock SET qty= qty-$pro_qty WHERE prid='$proid' AND branch_id='$branch_id' ";
								if ($conn->query($sql3) === TRUE) {
									//echo "Stock updated"; $branch_id

									if ($pay_type == 'credit'){
										$creditval = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobilecustomers WHERE coid='$customer'"));
										if($credit_limit > $totalAmountvalue){
											$sql4 = "UPDATE mobilecustomers SET ccredit= '$totalAmountvalue' WHERE coid='$customer'";
											if ($conn->query($sql4) === TRUE) {

											}
										}

									}
								}

							}
						}
						////////////////////////////////

					} else {
						echo "Error: " . $sql . "<br>" . $conn->error;
					}


				}
			}
		} else {
			echo "Error: " . $sql . "<br>" . $conn->error;
		}


	}








	}

} else {
	echo "Please refresh pos panel....";
}

}


}



	/* */ 
}else{
/* */ 





if($last=="%"){
	$type = 1;
}else{
	$type = 0;
}

$user_id = $_SESSION['user_id'];

$branch_id = $_POST['branch_id'];

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

$admincommision = 0;
$customercommision = 0;
$admininfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileusers WHERE user_id='$user_id'"));
$adminrate = $admininfo['ucomission'];

$customerinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobilecustomers WHERE coid ='$customer'"));
$customerrate = $customerinfo['comission'];

if ($discount > 0 && $discount < 101) {
	$discounted_amount = (int)$totalbillvalue / 100 * (int)$discount;
	$totalbillvalue = (int)$totalbillvalue - (int)$discounted_amount;
}

$country = $_POST['country'];
$city = $_POST['city'];
$deliveryCost = $_POST['deliveryCost'];

if ($pay_type == 'credit') {
	$due_amount = $totalAmountvalue - $cashamount;
	$paid_amount = $cashamount;

	if ($due_amount >= 0) {
		$sql3 = "UPDATE mobilecustomers SET ccredit = ? WHERE coid = ?";
		$stmt = $conn->prepare($sql3);
		$stmt->bind_param("is", $due_amount, $customer);
		if ($stmt->execute()) {
			// Stock updated successfully
		} else {
			// Error occurred while updating stock
		}
		$stmt->close();
	} else {
		$sql3 = "UPDATE mobilecustomers SET ccredit = 0 WHERE coid = ?";
		$stmt = $conn->prepare($sql3);
		$stmt->bind_param("s", $customer);
		if ($stmt->execute()) {
			// Stock updated successfully
		} else {
			// Error occurred while updating stock
		}
		$stmt->close();
	}


} else {
	$due_amount = 0;
	$paid_amount = $totalbillvalue;
}

if ($totalbillvalue > 0) {
	
	//if ($pay_type == 'card' && strlen($cardno) < 3) {
	//	echo "Enter valid debit card number..";
	//} 
	//if ($pay_type == 'cash' && $cashamount == 0 || $pay_type == 'cash' && $totalbillvalue > $cashamount) {
	if ($pay_type == 'cash' && $cashamount == 0) {
		echo "Enter cash amount..";
	} elseif ($pay_type == 'credit' && !$customer > 0) {
		echo "Select credit customer..";
	}elseif ($customer == 'dc' && !$country > 0) {
		echo "Select Delivery Country..";
	} elseif ($customer == 'dc' && !$city > 0) {
		echo "Select Delivery City..";
	} else {


		if ($pay_type == 'credit'){
			$creditval = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobilecustomers WHERE coid='$customer'"));

			$credit_limit = $creditval['credit_limit'];
			if($credit_limit > $totalAmountvalue){

			}else{
				echo "Customer credit limit is ".$credit_limit;
			}

			

		}
		
		$comid = '';
		$orid = '';
		$stmt = $DB_con->prepare('SELECT IFNULL(MAX(order_id)+1,1) AS order_id FROM `mobileorders`');
		$stmt->execute();
		while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
			extract($row);
			$comid = $row['order_id'];
			$orid = "100$comid";
		}

		if($adminrate==0 || empty($adminrate)){
			$admincommision = 0;
		}else{
			$admincommision = (float)$totalbillvalue / 100 * $adminrate;
		}
		if($customerrate==0 || empty($customerrate)){
			$customercommision = 0;
		}else{
			$customercommision = (float)$totalbillvalue / 100 * $customerrate;
		}
		
		//$admincommision = (float)$admincommision;
		//$customercommision = (float)$customercommision;





		if($oid != 0){
			
			$return_qty = mysqli_query($conn, "SELECT * FROM temp_return_qty WHERE order_id='$oid' AND return_type='1' AND add_to_return='1'");
			$datetime = date("Y-m-d H:i:s");
			$amountdetails = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(return_amount) as returnamount,order_id,add_to_return FROM temp_return_qty WHERE order_id='$oid' AND add_to_return='1'"));
            $amount = $amountdetails['returnamount'];
			$sql5 = "INSERT INTO tbl_return (order_id, return_datetime, return_amount)VALUES ('$oid', '$datetime', '$amount')";
			if ($conn->query($sql5) === TRUE) {
				
				$last_id = $conn->insert_id;
				$returnitemlist = mysqli_query($conn, "SELECT * FROM temp_return_qty WHERE order_id='$oid' AND return_type='1' AND add_to_return='1'");
				if ($returnitemlist->num_rows > 0) {
					 while($rw1 = $returnitemlist->fetch_assoc()) {
						 $pid = $rw1['product_id'];
						 $return_qty = $rw1['return_qty'];
						 $orderr_id = $rw1['order_id'];
						 $return_reson = $rw1['return_reson'];
						 $sql6 = "INSERT INTO tbl_return_items (return_id, prid, qty,order_id,return_type,return_reson)VALUES ('$last_id', '$pid', '$return_qty', '$orderr_id','1','$return_reson')";
						 if ($conn->query($sql6) === TRUE) {
							 $stockresult = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM tbl_stock WHERE prid='$pid'"));

						   
							 $stock = $stockresult['qty'];
							 $stock =+ $return_qty;
							 $sql12 = "UPDATE tbl_stock SET qty='$stock' WHERE prid='$pid'";
							 $conn->query($sql12);
							
							 $sql7 = "DELETE FROM temp_return_qty";
							 $conn->query($sql7);

							 $sql8 = "UPDATE mobiletemporarycart SET orderid='$oid',return_to_new='1' WHERE orderid=0  AND hold=0 ";
							if ($conn->query($sql8) === TRUE) {
								
								$sql2 = "SELECT * FROM mobiletemporarycart WHERE orderid='$oid'";
								$result2 = $conn->query($sql2);
								if ($result2->num_rows > 0) {
									
									while ($row = $result2->fetch_assoc()) {
										$proid = $row["proid"];
										$pro_qty = $row["pro_qty"];
										$qry13 = mysqli_query($conn, "SELECT * FROM tbl_stock WHERE prid='$proid'");
    									$rw = mysqli_fetch_array($qry13);
										$qt = $rw['qty']-$pro_qty;
										$sql9 = "UPDATE tbl_stock SET qty='$qt' WHERE prid='$proid'";
										if ($conn->query($sql9) === TRUE) {
											
											
											
											if ($pay_type == 'credit'){
												$creditval = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobilecustomers WHERE coid='$customer'"));
												if($credit_limit > $totalAmountvalue){
													$sql10 = "UPDATE mobilecustomers SET ccredit= '$totalAmountvalue' WHERE coid='$customer'";
													if ($conn->query($sql10) === TRUE) {
													
													}
												}
		
											}

											//var_dump("test");
											//unset($_SESSION['order_id']);
							
											
											//header("refresh:2;return-list.php"); 
											//exit();
										}
		
									}
								}

							}


							

						 }


					 }
				}
			}
		}else{


		









		$sql = "INSERT INTO mobileorders (orid,pay_option, amount, discount ,paid_amount,due_amount, payment_option_number,cheque_no,cheque_due_date, customer, delivery_cost, country, city,  user_id, create_at, dis_type,branch_id,status,admin_id,admin_commiision,customer_commision,cheque_number)
		VALUES ('$orid','$pay_type', '1000', '$discount' ,'$cashamount','$due_amount', '$cardno','$cheque','$duedate', '$customer', '$deliveryCost','$country','$city','$user_id', '$today' ,'$type' ,'$branchid','1','$user_id','$admincommision','$customercommision','$cheque_number')";
		if ($conn->query($sql) === TRUE) {
			$last_id = $conn->insert_id;
			if ($last_id > 0) {
				$sql = "UPDATE mobiletemporarycart SET orderid='$last_id' WHERE orderid=0 AND user_id='$user_id' AND hold=0 ";
				if ($conn->query($sql) === TRUE) {
					echo $last_id;

					$sql = "INSERT INTO `invoice_other_details`(`invoice_other_id`, `order_id`, `branch_id`) VALUES (null,'$last_id', '$branch_id')";
					if ($conn->query($sql) === TRUE) {
						//echo "New record created successfully";

						//update quantity///////////////
						$sql2 = "SELECT * FROM mobiletemporarycart WHERE orderid='$last_id' ORDER BY tempid DESC";
						$result2 = $conn->query($sql2);
						if ($result2->num_rows > 0) {
							while ($row = $result2->fetch_assoc()) {
								$proid = $row["proid"];
								$pro_qty = $row["pro_qty"];

								$sql3 = "UPDATE tbl_stock SET qty= qty-$pro_qty WHERE prid='$proid' AND branch_id='$branch_id' ";
								if ($conn->query($sql3) === TRUE) {
									//echo "Stock updated"; $branch_id

									if ($pay_type == 'credit'){
										$creditval = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobilecustomers WHERE coid='$customer'"));
										if($credit_limit > $totalAmountvalue){
											$sql4 = "UPDATE mobilecustomers SET ccredit= ' $totalAmountvalue' WHERE coid='$customer'";
											if ($conn->query($sql4) === TRUE) {
												unset($_SESSION['order_id']);
							

												header("refresh:2;return-list.php"); 
											}
										}

									}
									//unset($_SESSION['order_id']);
							

									//header("refresh:2;return-list.php"); 
								}

							}
						}
						////////////////////////////////

					} else {
						echo "Error: " . $sql . "<br>" . $conn->error;
					}


				}
			}
		} else {
			echo "Error: " . $sql . "<br>" . $conn->error;
		}


	}
















	}

} else {
	echo "Please refresh pos panel....";
}




}
?>