<?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']:'';
			$table  =  '(
				SELECT
					stock_id,
					stock_name,
					stock_type,
					stock_note,
					
					(SELECT COUNT(*) FROM purchase_item_detail P WHERE S.stock_id = P.stock_id_fk AND P.is_deleted=0 '.$cond.' ) AS product_cnt
					
					
					 FROM
					 	 stock S
					 	 
					WHERE 
					(S.is_deleted = 0   ) 			
				) 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' => 'stock_type','dt' => 2 ),
			    				array( 'db' => 'stock_note','dt' => 3 ),
			    				array( 'db' => 'product_cnt','dt' => 4 ),
								
			);
			// 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_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'];
			$name=addslashes($_POST["name"]);
			$stock_type=addslashes($_POST["stock_type"]);
			$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 = '$name' AND stock_id != '$id'");

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

			// checking for changing stock type
			$res1 = $db->query("SELECT * FROM stock WHERE is_deleted=0  AND stock_id = '$id'");

			$row = $res1->fetch_assoc();

			// check if changing stock type from production to store
			if($row['stock_type'] != $stock_type AND $row['stock_type'] ==1){

				// checking if this stock has rolls inside it and not finished yet
				$res2 = $db->query("SELECT * FROM purchase_item_detail WHERE is_deleted=0 AND item_status >2 AND stock_id_fk = '$id'");

					if (mysqli_num_rows($res2)>0) {
						$op['is_success'] = false;
						$op['data'] 	  = "لا يمكنك تحويل نوع المخزن من مخزن انتاج الى مخزن خزن لان المخزن الحالي يحوي على طوب قماش مستخدم وبردات تم تصنيعها , الرجاء قم بنقل الطوب المستخدمة والتي تم تصنيع منها ستائر الى مخزن انتاج اخر لكي تستطيع اتمام عملية التحديث بنجاح";
						echo json_encode($op);
						exit;
					}


						$db->autocommit(FALSE); // to rollback insertion if update fail

						$update_qry = "UPDATE stock SET  stock_name = '$name', stock_type='$stock_type',stock_note='$stock_note',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE stock_id = $id";

						$res3 = $db->query($update_qry);

						if ($res3) {

								$lastaction = "Change roll fabric item_status in purchase_item_detail to be 0 because we change stock to store type";

								$sql = "UPDATE purchase_item_detail SET  item_status = 0,  last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE item_status = 2 AND stock_id_fk = $id";

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

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

										$lastaction = "Update Stock roles";
										$role_name = 'Access_مخزن_'.$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);

										$role_name = 'يمكنه_النقل_من_مخزن_'.$name;
										$update_qry2 = "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 ='transfer'";
										$res2 = $db->query($update_qry2);

										$db->commit();
										$op['is_success'] = true;
										$op['data'] 	  = "تمت عملية التحديث بنجاح";
										echo json_encode($op);
										exit;
								}

						}

			// check if changing stock type from stre to production		
			}elseif($row['stock_type'] != $stock_type AND $row['stock_type'] ==0){

				// check if this store has sold roll
				$res2 = $db->query("SELECT * FROM purchase_item_detail WHERE is_deleted=0 AND item_status =1 AND stock_id_fk = '$id'");

				if (mysqli_num_rows($res2)>0) {
					$op['is_success'] = false;
					$op['data'] 	  = "لا يمكنك تحويل نوع المخزن من مخزن خزن الى مخزن انتاج لان المخزن الحالي يحوي على طوب قماش تم بيعهم , الرجاء قم بنقل الطوب االتي تم بيعهم الى مخزن خزن اخر لكي تستطيع اتمام عملية التحديث بنجاح";
					echo json_encode($op);
					exit;
				}


				$db->autocommit(FALSE); // to rollback insertion if update fail

				$update_qry = "UPDATE stock SET  stock_name = '$name', stock_type='$stock_type',stock_note='$stock_note',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE stock_id = $id";

				$res3 = $db->query($update_qry);

				if ($res3) {

						$lastaction = "Change roll fabric item_status in purchase_item_detail to be 2 because we change stock to production type";

						$sql = "UPDATE purchase_item_detail SET  item_status = 2,  last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE item_status = 0 AND stock_id_fk = $id";

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

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

								$lastaction = "Update Stock roles";
								$role_name = 'Access_مخزن_'.$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);

								$role_name = 'يمكنه_النقل_من_مخزن_'.$name;
								$update_qry2 = "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 ='transfer'";
								$res2 = $db->query($update_qry2);


								$db->commit();
								$op['is_success'] = true;
								$op['data'] 	  = "تمت عملية التحديث بنجاح";
								echo json_encode($op);
								exit;
						} // if res4

				} // if res3
			}

			




			$lastaction = "Update Stock information";
			$update_qry = "UPDATE stock SET  stock_name = '$name', 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_مخزن_'.$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);

					$role_name = 'يمكنه_النقل_من_مخزن_'.$name;
					$update_qry2 = "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 ='transfer'";
					$res2 = $db->query($update_qry2);


					$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 purchase_item_detail 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);

					$update_qry2 = "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 ='transfer'";
					$res2 = $db->query($update_qry2);

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

