<?php
include '../db/db.php';
session_start();

if(isset($_SESSION['userID'])) {
	$log = htmlspecialchars(strip_tags(trim($_SESSION['userID'])), ENT_QUOTES, 'UTF-8');
} else {
	$log = '';
}

if (empty($log)) {     
	$redirectUrl = "../";
	echo "<script type=\"text/javascript\">";
	echo "window.location.href = '$redirectUrl'";
	echo "</script>";
	 
} else {
	$sqlu = "SELECT id FROM user_acc_tbl WHERE userID='$log' and access=1 and val=1";
	$stmtu = mysqli_query($conn, $sqlu);
	$countu = mysqli_num_rows($stmtu);
	
	if($countu == 1) {
		$rowu = mysqli_fetch_assoc($stmtu);
		$uid = $rowu['id'];
		
		date_default_timezone_set('Asia/Colombo');
		$date = date('Y-m-d');
		$time = date('H:i:s');
		
		/*************************** Add Supplier Return ***************************/
		
		if(isset($_POST['sup_id'])) {
			$sup_id = htmlspecialchars(strip_tags(trim($_POST['sup_id'])), ENT_QUOTES, 'UTF-8');
			$order_no = htmlspecialchars(strip_tags(trim($_POST['inv_no'])), ENT_QUOTES, 'UTF-8');
			$date = htmlspecialchars(strip_tags(trim($_POST['date'])), ENT_QUOTES, 'UTF-8');
		
			$stmt1 = mysqli_query($conn, "SELECT order_no FROM srn_tkn_order WHERE order_no='$order_no' AND sup_id!='$sup_id'");
			$row_count1 = mysqli_num_rows($stmt1);
			
			$stmt3 = mysqli_query($conn, "SELECT p_order FROM stock_orders WHERE p_order='$order_no'");
			$row_count3 = mysqli_num_rows($stmt3);
			
			$stmt2 = mysqli_query($conn, "SELECT inv_no FROM srn_tkn_order WHERE sup_id='$sup_id'");
			$row_count2 = mysqli_num_rows($stmt2);
		
			if($row_count1 == 0 && $row_count3 == 0) {
				if($row_count2 == 0) {
					$sql_inv = mysqli_fetch_assoc(mysqli_query($conn, "SELECT purchase FROM invoice_no"));
					$inv_no = $sql_inv['purchase'];
					mysqli_query($conn, "UPDATE invoice_no SET purchase=purchase+1");
					
					$stmt4 = mysqli_query($conn, "SELECT inv_no FROM srn_tkn_order WHERE inv_no='$inv_no'");
					$stmt5 = mysqli_query($conn, "SELECT invoice FROM stock_orders WHERE invoice='$inv_no'");
					
					if(mysqli_num_rows($stmt4) == 0 && mysqli_num_rows($stmt5) == 0) {
						$sql = "INSERT INTO srn_tkn_order SET order_no='$order_no', sup_id='$sup_id', date='$date', time='$time', inv_no='$inv_no'";
						$stmt_log = mysqli_query($conn, $sql);
						
						if($stmt_log === false) {
							echo json_encode(array("msgType" => 2, "msg" => "error"));
						
						} else {
							echo json_encode(array("msgType" => 1, "msg" => "success", 'inv_no' => $inv_no, 'sup_id' => $sup_id));
						}
					
					} else {
						//mysqli_query($conn, "UPDATE invoice_no SET purchase=purchase+1");
					}
				
				} else {
					$sql_supp = mysqli_fetch_assoc($stmt2); 
					$inv_no = $sql_supp['inv_no'];
					
					$sql = "UPDATE srn_tkn_order SET date='$date', time='$time', order_no='$order_no' WHERE sup_id='$sup_id'";
					$stmt_log = mysqli_query($conn, $sql);
					
					if($stmt_log === false) {
						echo json_encode(array("msgType" => 2, "msg" => "error"));
					
					} else {
						echo json_encode(array("msgType" => 1, "msg" => "success", 'inv_no' => $inv_no, 'sup_id' => $sup_id));
					}
				}
			
			} else {
				echo json_encode(array("msgType" => 3, "msg" => "data exist")); // order no exist
			}
		}
		
		/************************ Supplier Return Items ************************/
	    
		if(isset($_POST['gsup_id'])) {
			$sup_id = htmlspecialchars(strip_tags(trim($_POST['gsup_id'])), ENT_QUOTES, 'UTF-8');
			$inv_no = htmlspecialchars(strip_tags(trim($_POST['ginv_no'])), ENT_QUOTES, 'UTF-8');
			$item_id = htmlspecialchars(strip_tags(trim($_POST['item_id'])), ENT_QUOTES, 'UTF-8');
			$qty = htmlspecialchars(strip_tags(trim($_POST['qty'])), ENT_QUOTES, 'UTF-8');

			if(empty($sup_id) || empty($inv_no) ||  empty($item_id) || empty($qty)) {
				echo json_encode(array("msgType" => 4, "msg" => "empty"));
				
			} else {
				$stmt1 = mysqli_query($conn, "SELECT id FROM srn_tkn_order WHERE inv_no='$inv_no' AND sup_id='$sup_id'");
				$row_count1 = mysqli_num_rows($stmt1);
				
				$stmt2 = mysqli_query($conn, "SELECT id FROM srn_tkn_stock WHERE inv_no='$inv_no' AND sup_id='$sup_id' AND item='$item_id'");
				$row_count2 = mysqli_num_rows($stmt2);
				
				if($row_count1 == 0) {
					echo json_encode(array("msgType" => 4, "msg" => "empty"));
				
				} else {
					if($row_count2 == 0) {
						$row_bal = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(`dr_qty`) - SUM(`cr_qty`) AS bal FROM `stock` WHERE stock_card='$item_id' AND supp_id='$sup_id'"));
						$bal = $row_bal['bal'];
						if($bal == null) {$bal = 0;}
						
						if($bal >= $qty) {
							$sql = "INSERT INTO srn_tkn_stock SET inv_no='$inv_no', sup_id='$sup_id', item='$item_id', qty='$qty', date=now()";
							$stmt_log = mysqli_query($conn, $sql);
							
							if($stmt_log === false) {
								echo json_encode(array("msgType" => 2, "msg" => "error"));
							
							} else {
								echo json_encode(array("msgType" => 1, "msg" => "success"));
							}
						
						} else {
							echo json_encode(array("msgType" => 5, "msg" => "empty bal", "bal" => $bal));
						}
					
					} else {
						echo json_encode(array("msgType" => 3, "msg" => "data exist")); // item exist
					}
				}
			}
	    }
		
		/************************ Remove Item *************************/
		
	    if (array_key_exists('remove_data', $_POST)) {
			$id = htmlspecialchars(strip_tags(trim($_POST['id'])), ENT_QUOTES, 'UTF-8');
			
			if(empty($id)) {
				echo json_encode(array("msgType" => 3, "msg" => "empty"));
			
			} else {
				$sql = "DELETE FROM srn_tkn_stock WHERE id=$id";
				$stmt_log = mysqli_query($conn, $sql);
				
				if( $stmt_log === false ) {
					echo json_encode(array("msgType" => 2, "msg" => "Sorry ! not deleted"));
				
				} else {
					echo json_encode(array("msgType" => 1, "msg" => "Successfully Removed"));
				}
			}
	    }
		
		/************************ SRN Finalize ************************/
	    
		if (array_key_exists('finalize_srn', $_POST)) {
			$sup_id = htmlspecialchars(strip_tags(trim($_POST['fsup_id'])), ENT_QUOTES, 'UTF-8');
			$inv_no = htmlspecialchars(strip_tags(trim($_POST['finv_no'])), ENT_QUOTES, 'UTF-8');

			if(empty($sup_id) || empty($inv_no)) {
				echo json_encode(array("msgType" => 4, "msg" => "empty"));
				
			} else {
				$sql_srn = mysqli_query($conn, "SELECT * FROM srn_tkn_order WHERE inv_no='$inv_no' AND sup_id='$sup_id'");
				if(mysqli_num_rows($sql_srn) == 0) {
					echo json_encode(array("msgType" => 5, "msg" => "empty"));
				
				} else {
					$sql_gr = mysqli_fetch_assoc($sql_srn);
					$order_no = $sql_gr['order_no'];
					$gdate = $sql_gr['date'];
					$gtime = $sql_gr['time'];
					
					$sqlsup = mysqli_fetch_assoc(mysqli_query($conn, "SELECT acc_no FROM supplier WHERE id='$sup_id'"));
					$sup_acc = $sqlsup['acc_no'];
					
					$sql_inv = mysqli_fetch_assoc(mysqli_query($conn, "SELECT stock FROM invoice_no"));
					$ref = $sql_inv['stock'];
					mysqli_query($conn, "UPDATE invoice_no SET stock=stock+1");
					
					$sql_ordn = mysqli_query($conn, "SELECT ref FROM stock_orders WHERE ref='$ref'");
					$sql_stkn = mysqli_query($conn, "SELECT ref FROM stock WHERE ref='$ref'");
					
					if(mysqli_num_rows($sql_ordn) == 0 && mysqli_num_rows($sql_stkn) == 0) {
						$sql_stk = "INSERT INTO stock_orders SET supp_id='$sup_id', sup_acc='$sup_acc', type='Supplier Return', invoice='$inv_no', ref='$ref', p_order='$order_no', stock_date='$gdate', stock_time='$gtime', date='$date', time=CURTIME(), userID='$uid'";
						$stmt_log = mysqli_query($conn, $sql_stk);
						
						if($stmt_log === false) {
							echo json_encode(array("msgType" => 2, "msg" => "error"));
							
						} else {
							$sql_ordr = mysqli_query($conn, "SELECT * FROM stock_orders WHERE invoice='$inv_no' AND supp_id='$sup_id'");
							if(mysqli_num_rows($sql_ordr) == 0) {
								echo json_encode(array("msgType" => 4, "msg" => "empty"));
							
							} else {
								$sqls = mysqli_query($conn, "SELECT * FROM srn_tkn_stock WHERE inv_no='$inv_no' and sup_id='$sup_id'");
								while($rows = mysqli_fetch_array($sqls)) {
									$item = $rows['item'];
									$qty = $rows['qty'];
									$sdate = $rows['date'];
									$id_gr = $rows['id'];
									
									$row_bal = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(`dr_qty`) - SUM(`cr_qty`) AS bal FROM `stock` WHERE stock_card='$item' AND supp_id='$sup_id'"));
									$bal = $row_bal['bal'];
									
									if($bal >= $qty) {
										$sql_ref = "INSERT INTO stock SET stock_card='$item', ref='$ref', cr_qty='$qty', stock_date='$sdate', date=now(), supp_id='$sup_id'";
										$stmt_log1 = mysqli_query($conn, $sql_ref);
										
										if($stmt_log1 === false) {
											echo json_encode(array("msgType" => 2, "msg" => "error"));
											
										} else {
											mysqli_query($conn, "DELETE FROM srn_tkn_stock WHERE id='$id_gr'");
										}
									
									} else {
										mysqli_query($conn, "DELETE FROM srn_tkn_stock WHERE id='$id_gr'");
									}
									
									/*------- Update Item Qty ---------*/
									$stk_bal = mysqli_fetch_array(mysqli_query($conn, "SELECT bal_qty AS bal FROM `stock_qty` WHERE stock_card='$item'"));

									$itm_qty = $stk_bal['bal'];
									if($itm_qty == null) {$itm_qty=0;}
									
									if($itm_qty <= 0) {
										mysqli_query($conn, "UPDATE bookdetails SET qty='0', stock_out=1 WHERE id='$item'");
									
									} else {
										mysqli_query($conn, "UPDATE bookdetails SET qty='$itm_qty', stock_out=0 WHERE id='$item'");
									}
									/*-------------- // ------------*/
								}
								
								$sql_del = mysqli_query($conn, "DELETE FROM srn_tkn_order WHERE inv_no='$inv_no' AND sup_id='$sup_id'");
								if($sql_del === false) {
									echo json_encode(array("msgType" => 2, "msg" => "error"));
								
								} else {
									echo json_encode(array("msgType" => 1, "msg" => "Success"));
								}
							}
						}
					
					} else {
						//mysqli_query($conn, "UPDATE invoice_no SET stock=stock+1");
					}
				}
			}
	    }
		
		/************************ Get Return Items ****************************/
		
		if (array_key_exists('get_srn_items', $_POST)) {
			$ref_id = htmlspecialchars(strip_tags(trim($_POST['ref_id'])), ENT_QUOTES, 'UTF-8');
			$supp = htmlspecialchars(strip_tags(trim($_POST['supp'])), ENT_QUOTES, 'UTF-8');
			$arr_data = array();
			
			if(empty($ref_id) || empty($supp)) {
			
			} else {
				$sql_sup = mysqli_fetch_assoc(mysqli_query($conn, "SELECT
supplier.name,
stock_orders.p_order,
stock_orders.invoice,
stock_orders.stock_date
FROM
stock_orders
Inner Join supplier ON stock_orders.supp_id = supplier.id
WHERE stock_orders.ref='$ref_id' AND stock_orders.supp_id='$supp'"));
				$supp_arr = array('sup_name' => $sql_sup['name'], 'p_order' => $sql_sup['p_order'], 'invoice' => $sql_sup['invoice'], 'stock_date' => $sql_sup['stock_date']);
				array_push($arr_data, $supp_arr);
				
				$sql = "SELECT
	bookdetails.name,
	stock.cr_qty
	FROM
	stock
	Inner Join bookdetails ON stock.stock_card = bookdetails.id
	WHERE
	stock.ref = '$ref_id' AND
	stock.supp_id = '$supp'";
				$result = mysqli_query($conn, $sql);
				if(mysqli_num_rows($result) > 0) {
					while($row = mysqli_fetch_assoc($result)) {
						$data[] = $row;	
					}
					array_push($arr_data, $data);
				}
				
				echo json_encode($arr_data);
			}
		}
		
		/************************************************************/
		
	} else {
		$redirectUrl = "../";
		echo "<script type=\"text/javascript\">";
		echo "window.location.href = '$redirectUrl'";
		echo "</script>";
	}
}
?>