<?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")){


			$cond = isset($_GET['pid'])? ' AND P.product_id_fk='.$_GET['pid']:'';
			$cond1 = '';

			if(isset($_GET['branch_id']) && $_GET['branch_id'] !=0){ 
				$cond1 = ' AND S.branch_id_fk ='.$_GET['branch_id'];
			}

			$table  =  '(
				SELECT
					stock_id,
					stock_name,
					S.location,
					sku,
					stock_note,
					stock_type_id_fk,
					branch_id_fk,
					branch_name,
					
					(

					(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
					        	WHERE  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.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.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.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.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.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.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.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.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.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Expired" ),0)
					) 


					) AS  product_cnt
					
					
					 FROM
					 	 stock S 

					 	 LEFT JOIN branch B ON (B.branch_id = S.branch_id_fk)
					 	 
					WHERE 
					(S.is_deleted = 0  '.$cond1.' ) 			
				) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'stock_id';
			$columns =  array(
				  			  	array( 'db' => 'stock_id', 'dt' => 0 ),
			    				array( 'db' => 'stock_name','dt' => 1 ),
			    				array( 'db' => 'location','dt' => 2 ),
			    				array( 'db' => 'branch_name','dt' => 3 ),
			    				array( 'db' => 'stock_note','dt' => 4 ),
			    				array( 'db' => 'product_cnt','dt' => 5 ),
			    				array( 'db' => 'branch_id_fk','dt' => 6 ),

								
			);
			// 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'];

			$cond = (isset($_POST['branch_id']) && $_POST['branch_id'] > 0)? ' AND S.branch_id_fk='.$_POST['branch_id']:'';


			$res = $db->query("SELECT * FROM stock S WHERE S.is_deleted = 0 $cond");
			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['location'];
						$result[3] = $row['branch_id_fk'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


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

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

			$res = $db->query("SELECT product_id,erbil_code,turkish_code FROM product P  WHERE P.is_deleted = 0 ");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['product_id'];
						$result[1]  = $row['erbil_code'];
						$result[2]  = $row['turkish_code'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

		

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

			$id 			= $_POST['obj_id'];
			$stock_name		=addslashes($_POST["stock_name"]);
			$location		=addslashes($_POST["location"]);
			$branch_id_fk	=addslashes($_POST["branch_id_fk"]);
			$stock_note		=addslashes($_POST["stock_note"]);

			$op  = array('is_success'=>false, 'data' => '');
			$lastaction = "Update stock type";

			$res = $db->query("SELECT * FROM stock WHERE is_deleted=0 AND stock_name = '$stock_name' AND stock_id != '$id'");

			if (mysqli_num_rows($res)>0) {
				$op['is_success'] = false;
				$op['data'] 	  = "خطأ الاسم مكرر";
				echo json_encode($op);
				exit;
			}


			$lastaction = "Update Stock information";
			$update_qry = "UPDATE stock SET  	stock_name = '$stock_name',
												location = '$location',
												branch_id_fk = '$branch_id_fk', 
												stock_note='$stock_note',
												last_action='$lastaction',
												last_action_by='".$_SESSION['user_id']."'
								WHERE stock_id = $id";


			$res = $db->query($update_qry);
			if ($res) {
					// update roles

					$lastaction = "Update Stock roles";
					$role_name = 'Access_Stock_'.$stock_name;
					
					$update_qry1 = "UPDATE role SET  role = '$role_name',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE id_fk = $id AND table_name = 'stock' AND action ='view'";
					$res1 = $db->query($update_qry1);					

					$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']=="delete") {

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


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

			$res = $db->query("SELECT * FROM purchase WHERE is_deleted=0  AND stock_id_fk = '$id'");
			if (mysqli_num_rows($res)>0) {
			
				$op['is_success'] = false;
				$op['data'] 	  = "لا يمكنك حذف هذا المخزن فهنالك قوائم مشتريات تابعة له";
				echo json_encode($op);
				exit;
			}

			$res1 = $db->query("SELECT * FROM product_stock WHERE is_deleted=0  AND stock_id_fk = '$id'");
			if (mysqli_num_rows($res1)>0) {
			
				$op['is_success'] = false;
				$op['data'] 	  = "لا يمكنك حذف المخزن هناك مواد داخله في هذا المخزن";
				echo json_encode($op);
				exit;
			}


      		$res = $db->query("UPDATE stock SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE stock_id=$id");
	     	if ($res){
	     			// we should delete stock roles
	     			$lastaction = "Delete Stock roles";
						
					$update_qry1 = "UPDATE role SET  	is_deleted = 1 ,
														deleted_at = '$reg_date',
														last_action='$lastaction',
														last_action_by='".$_SESSION['user_id']."' 
									WHERE id_fk = $id AND table_name = 'stock' AND action ='view'";
					$res1 = $db->query($update_qry1);

						
	     			$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") {

			$stock_name			=addslashes($_POST["stock_name"]);
			$location			=addslashes($_POST["location"]);
			$branch_id_fk		=addslashes($_POST["branch_id_fk"]);
			$stock_note			=addslashes($_POST["stock_note"]);

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


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

			$sql ="INSERT INTO stock(	stock_name,
										location,
										branch_id_fk,
										stock_note,
										created_by,
										last_action,
										last_action_by)
								VALUES( '$stock_name',
										'$location',
										'$branch_id_fk',
										'$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 ".$stock_name;
				$role_name = 'Access_Stock_'.$stock_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);

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

