<?php
if(!isset($_SESSION)) 
{ 
session_start(); 
} 
if(!isset($_SESSION['is_login']) ){
header("location: login.php");
?>
<script>
window.location="login.php";
</script>
<?php
}

// $permission  = explode(',',$_SESSION['permission_id']);
// if(!in_array(19,$permission) && !in_array(1,$permission)  ){

// $op['is_success'] = false;
// $op['data'] 	  = "عذرا انت غير مخول للوصل الى هذه الصفحة";
// echo json_encode($op);
// exit;

// }

date_default_timezone_set($_SESSION['SYSTimezone']);

if (isset($_POST['type']) || isset($_GET['type'])){
		require_once "db_connect.php";

		if( isset($_GET['type']) && ($_GET['type'] == "load")){


			$cond1 = isset($_GET['id'])? ' AND PS.product_id_fk='.$_GET['id']:'';
			$cond2 = isset($_GET['pid'])? ' AND P.product_type="'.$_GET['pid'].'"':'';

			$cond3 = '';
			if(isset($_GET['branch_id']) && $_GET['branch_id'] !=0){ 
				$cond3 = ' AND PS.branch_id_fk ='.$_GET['branch_id'];
			}
			
			$cond = $cond1 . $cond2 . $cond3 ;
			
			$table  =  '(

				SELECT
					
					

					stock_id,
					stock_name,
					product_id,
					product_name,
					product_code,
					product_type,
					product_stock_id,
					recieved_quantity,
					resons,
					stock_transaction,
					transaction_date,
					PS.updated_at,
					PS.created_by,
					PS.last_action_by,
					ST.full_name AS created_staff,
					ST1.full_name AS updated_staff

					
				FROM
					product_stock PS
					LEFT JOIN stock S ON (PS.stock_id_fk = S.stock_id AND S.is_deleted=0 '.$cond3.')
					LEFT JOIN product  P ON (PS.product_id_fk = P.product_id AND P.is_deleted=0)
					LEFT JOIN staff  ST ON (PS.created_by = ST.staff_id AND ST.is_deleted=0)
					LEFT JOIN staff  ST1 ON (PS.last_action_by = ST1.staff_id AND ST1.is_deleted=0)
					
				WHERE
					( PS.is_deleted = 0 '.$cond.') 
		
				) AS ALLTBL';
			
			
			// Table's primary key
			// echo $table;
			$primaryKey = 'product_stock_id';
			$columns =  array(
				  			  	array( 'db' => 'product_stock_id', 'dt' => 0 ),
			    				array( 'db' => 'product_name','dt' => 1 ),
			    				array( 'db' => 'product_code','dt' => 2 ),
			    				array( 'db' => 'product_type','dt' => 3 ),
			    				array( 'db' => 'stock_name','dt' => 4 ),
			    				array( 'db' => 'recieved_quantity','dt' => 5 ),
			    				array( 'db' => 'stock_transaction','dt' => 6 ),
			    				array( 'db' => 'transaction_date','dt' => 7 ),
			    				array( 'db' => 'created_staff','dt' => 8 ),
			    				array( 'db' => 'updated_at','dt' => 9 ),
			    				array( 'db' => 'updated_staff','dt' => 10 ),
			    				// array( 'db' => 'resons','dt' => 11 ),
			    				array( 'db' => 'product_id','dt' => 11 ),
			    				array( 'db' => 'stock_id','dt' => 12 ),
			    				
			    				
								
			);
			// SQL server connection information
			$sql_details = array(
			    'user' => $mysql_user,
			    'pass' => $mysql_password,
			    'db'   => $mysql_db,
			    'host' => $mysql_server
			);
			require( 'ssp.php' );
			echo json_encode(
			    SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns ,null, '' )
			);
			exit;


		}

		if ($_POST['type']=="get") {

			//$user_id = $_POST['cusid'];

			$res = $db->query("SELECT * FROM stock WHERE is_deleted = 0");
			if ($res) {
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['stock_id'];
						$result[1] = $row['stock_name'];
						$result[2] = $row['stock_type'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}



		if ($_POST['type']=="get_on_hand") {

			$id 	= $_POST['stock_id'];
			$pid 	= $_POST['product_id'];

			$res = $db->query('
								SELECT
			
					(

					(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
					        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Purchase" ),0)
					) 
					+
					(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
					        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Initial" ),0)
					) 

					+
					(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
					        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Return" ),0)
					) 
					+
					(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
					        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Moved In" ),0)
					) 
					-
					(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
					        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Invoice" ),0)
					) 
					-
					(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
					        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Damage" ),0)
					) 

					
					-
					(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
					        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Moved Out" ),0)
					) 
					-
					(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
					        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Used" ),0)
					) 
					-
					(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
					        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Offer" ),0)
					) 
					-
					(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
					        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Expired" ),0)
					) 


					) AS on_hand_quantity,

					stock_id,
					stock_name,
					product_id,
					product_name,
					product_code

					
					
				FROM
					product  P
					LEFT JOIN stock S ON (S.is_deleted=0)
					
				WHERE
					( P.is_deleted = 0 AND P.product_id ='.$pid.' AND S.stock_id='.$id.' )
								');
			if ($res) {
				$op  = array('is_success'=>false, 'data' =>array());
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result['stock_id'] = $row['stock_id'];
						$result['stock_name'] = $row['stock_name'];
						$result['on_hand_quantity'] = $row['on_hand_quantity'];
						$result['product_id'] = $row['product_id'];
						$result['product_name'] = $row['product_name'];
						$result['product_code'] = $row['product_code'];
						array_push($op['data'],$result);
				}
				$op['is_success'] = true;
				echo json_encode($op);
				exit;
			}else{
				$op['is_success'] = false;
				$op['data'] = "لا تتوفر معلومات";
				echo json_encode($op);
				
				exit;
			}
		}

		


		if ($_POST['type']=="delete") {

			$id=addslashes($_POST["obj_id"]);
			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Delete Transaction";


			$op  = array('is_success'=>false, 'data' => '');

			
			

			


      		$res = $db->query("UPDATE product_stock SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE product_stock_id=$id");
 			if ($res){
 
 				$op['is_success'] = true;
				$op['data'] 	  = "لقد تم الحذف بنجاح";
				echo json_encode($op);
			
 				exit;
 			}
				else{
  				$op['is_success'] = false;
				$op['data'] 	  = "حصل خطأ : الرجاء اعد تحميل الصفحة من جديد";
				echo json_encode($op);
				exit;
 			}
		}


		if ($_POST['type'] == "update") {

            			$stock_id 			=addslashes($_POST["stock_id"]);
            			$product_id_fk		=addslashes($_POST["product_id_fk"]);
            			$recieved_quantity 	=addslashes($_POST["recieved_quantity"]);
            			$resons 			='';
            			// $resons 			=addslashes($_POST["resons"]);
            			$id 				=addslashes($_POST["obj_id"]);

						

							
						$delete 	= 0;
						$reg_date 	= date("Y-m-d h:i:s", time());
						$lastaction = "Update information";
						
						$db->autocommit(FALSE); // to rollback insertion if update fail

						$sql ="UPDATE product_stock SET recieved_quantity 	= '$recieved_quantity',
														  
														  product_id_fk 	= '$product_id_fk',
														  stock_id_fk   	= '$stock_id',
														  resons   			= '$resons',
														  
														  last_action 		= '$lastaction',
														  last_action_by 	= '".$_SESSION['user_id']."',
														  updated_at 		= '$reg_date'
										WHERE product_stock_id = '$id' ";

						$res = $db->query($sql);

		     			if ($res){

								$db->commit();
			     				$op['is_success'] = true;
								$op['data'] 	  = "تمت عملية التحديث بنجاح";
								echo json_encode($op);
	     						exit;
	     					
		     			}else{
		     				$db->rollback();
		     				$op['is_success'] = false;
							$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
							echo json_encode($op);
							exit;
		     			}
							
						

		}

		

		

		if ($_POST['type'] == "add_damage") {

            			
			$id 				=addslashes($_POST["obj_id"]);
			$damage_qty 		=addslashes($_POST["damage_qty"]);
			$stock_id_damage 	=addslashes($_POST["stock_id_damage"]);
			$damage_resons 		=addslashes($_POST["damage_resons"]);

			$reg_date 	= date("Y-m-d h:i:s", time());
			$lastaction = "Add Damage Length";

			$tansaction = "Damage";
 			
 			$sql1 ="INSERT INTO product_stock (recieved_quantity,
 											  resons,
											  stock_transaction,
											  stock_transaction_type,
											  transaction_date,
											  product_id_fk,
											  stock_id_fk,
											  created_by,
											  last_action,
											  last_action_by)
									   VALUES('$damage_qty',
									   		  '$damage_resons',
									   		  '$tansaction',
									   		  '2',
									   		  '$reg_date',
									   		  '$id',
									   		  '$stock_id_damage',
									   		  '".$_SESSION['user_id']."',
									   		  '$lastaction',
									   		  '".$_SESSION['user_id']."')";

			$res1 = $db->query($sql1);

			if ($res1){
				
 				$op['is_success'] = true;
				$op['data'] 	  = "تمت العملية  بنجاح";
				echo json_encode($op);
					exit;
				}else{
					
 				$op['is_success'] = false;
				$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
				echo json_encode($op);
				exit;
 			}


		}


		if ($_POST['type'] == "add_expire") {

            			
			$id 				=addslashes($_POST["obj_id"]);
			$expire_qty 		=addslashes($_POST["expire_qty"]);
			$stock_id_expire 	=addslashes($_POST["stock_id_expire"]);
			$expire_resons 		=addslashes($_POST["expire_resons"]);

			$reg_date 	= date("Y-m-d h:i:s", time());
			$lastaction = "Add Expire Length";

			$tansaction = "Expired";
 			
 			$sql1 ="INSERT INTO product_stock (recieved_quantity,
 											  resons,
											  stock_transaction,
											  stock_transaction_type,
											  transaction_date,
											  product_id_fk,
											  stock_id_fk,
											  created_by,
											  last_action,
											  last_action_by)
									   VALUES('$expire_qty',
									   		  '$expire_resons',
									   		  '$tansaction',
									   		  '2',
									   		  '$reg_date',
									   		  '$id',
									   		  '$stock_id_expire',
									   		  '".$_SESSION['user_id']."',
									   		  '$lastaction',
									   		  '".$_SESSION['user_id']."')";

			$res1 = $db->query($sql1);

			if ($res1){
				
 				$op['is_success'] = true;
				$op['data'] 	  = "تمت العملية  بنجاح";
				echo json_encode($op);
					exit;
				}else{
					
 				$op['is_success'] = false;
				$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
				echo json_encode($op);
				exit;
 			}


		}


		if ($_POST['type'] == "used_product") {

            			
            			$id 				=addslashes($_POST["obj_id"]);
            			$qty 				=addslashes($_POST["qty"]);
            			$stock_id_used 		=addslashes($_POST["stock_id_used"]);
            			$used_resons 		=addslashes($_POST["used_resons"]);

						$reg_date 	= date("Y-m-d h:i:s", time());
						$lastaction = "Add Used Quantity";

						$tansaction = "Used";
		     			
		     			$sql1 ="INSERT INTO product_stock (recieved_quantity,
		     											  resons,
														  stock_transaction,
														  transaction_date,
														  product_id_fk,
														  stock_id_fk,
														  created_by,
														  last_action,
														  last_action_by)
												   VALUES('$qty',
												   		  '$used_resons',
												   		  '$tansaction',
												   		  '$reg_date',
												   		  '$id',
												   		  '$stock_id_used',
												   		  '".$_SESSION['user_id']."',
												   		  '$lastaction',
												   		  '".$_SESSION['user_id']."')";

							$res1 = $db->query($sql1);

							if ($res1){
								
			     				$op['is_success'] = true;
								$op['data'] 	  = "تمت العملية  بنجاح";
								echo json_encode($op);
	     						exit;
	     					}else{
	     						
			     				$op['is_success'] = false;
								$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
								echo json_encode($op);
								exit;
			     			}

					
		}




		if ($_POST['type'] == "create") {

            			$name=addslashes($_POST["name"]);
						$res = $db->query("SELECT * FROM stock WHERE stock_name = '$name'");
						if (mysqli_num_rows($res)>0) {
							$op['is_success'] = false;
							$op['data'] 	  = "خطأ الاسم مكرر";
							echo json_encode($op);
							exit;
						}else{
							$stock_type=addslashes($_POST["stock_type"]);
							$stock_note=addslashes($_POST["stock_note"]);

							$delete = 0;
							$reg_date = date("Y-m-d h:i:s", time());
							$lastaction = "Create New Stock";

						$sql ="INSERT INTO stock(stock_name,stock_type,stock_note,created_by,last_action,last_action_by)
						VALUES('$name','$stock_type','$stock_note','".$_SESSION['user_id']."','$lastaction','".$_SESSION['user_id']."')";

						$res = $db->query($sql);
							if ($res) {
								$last_inserted_id = $db->insert_id;
								// create Role for this stock
								$lastaction = "Create New Role for stock ".$name;
								$role_name = 'Access_مخزن_'.$name;
								$sql1 ="INSERT INTO role (role,id_fk,table_name,action,created_by,last_action,last_action_by)
								VALUES('$role_name','$last_inserted_id','stock','view','".$_SESSION['user_id']."','$lastaction','".$_SESSION['user_id']."')";
								$res1 = $db->query($sql1);

								$role_name = 'يمكنه_النقل_من_مخزن_'.$name;
								$sql2 ="INSERT INTO role (role,id_fk,table_name,action,created_by,last_action,last_action_by)
								VALUES('$role_name','$last_inserted_id','stock','transfer','".$_SESSION['user_id']."','$lastaction','".$_SESSION['user_id']."')";
								$res2 = $db->query($sql2);

								

								$op['is_success'] = true;
								$op['data'] 	  = "تم اضافة المخزن بنجاح ";
								echo json_encode($op);
								exit;
							}
							else{
								$op['is_success'] = false;
								$op['data'] 	  = "هناك خطأ : لم يتم اضافة المخزن الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
								echo json_encode($op);
								exit;
							}
						}

		}
	}
	else{
		header("Location:../");
		exit;
	}
?>

