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

$last = substr($discount, -1);
/* */ 
if(isset($_SESSION['order_id']) && $_SESSION['order_id'] !=0){
	/* */ 
	$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');
				
				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 = 0;
				
				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 {
				
						$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";
						}
				
				
						
						$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)
						VALUES ('$orid','$pay_type', '$totalbillvalue', '$discount' ,'$cashamount','$due_amount', '$cardno','$cheque','$duedate', '$customer', '$deliveryCost','$country','$city','$user_id', '$today' ,'$type' ,'$branchid','1')";
						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
												}
				
											}
										}
										////////////////////////////////
				
									} 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');

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 = 0;

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 {

		$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";
		}


		
		$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)
		VALUES ('$orid','$pay_type', '$totalbillvalue', '$discount' ,'$cashamount','$due_amount', '$cardno','$cheque','$duedate', '$customer', '$deliveryCost','$country','$city','$user_id', '$today' ,'$type' ,'$branchid','0')";
		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
								}

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

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


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



	}

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

}

if($last_id !=0){
echo $last_id;
}

?>