<?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 PID.stock_id_fk='.$_GET['id']:'';
			$cond2 = isset($_GET['pid'])? ' AND PID.product_id_fk='.$_GET['pid']:'';
			$cond3 = isset($_GET['sid'])? ' AND PID.item_status='.$_GET['sid']:'';

			$cond = $cond1 . $cond2 . $cond3;
			
			$table  =  '(
				SELECT
					purchase_item_detail_id,
					item_length,
					item_status,
					product_id_fk,
					stock_type,
					stock_id_fk,
					stock_name,
					erbil_code,
					turkish_code,
					damage_length,
					used_length,
					previous_status,
					is_part,
					purchase_item_detail_id_fk,

					(SELECT item_length FROM purchase_item_detail PID1 WHERE PID1.purchase_item_detail_id = PID.purchase_item_detail_id_fk AND PID1.is_deleted=0 ) AS original_roll_length,

					(select sum(sell_item_detail_height) FROM sell_item_detail SID WHERE SID.purchase_item_detail_id_fk = PID.purchase_item_detail_id AND SID.part_status=0 AND SID.is_deleted=0) as sold_length,

					(	COALESCE(damage_length,0) + 
						COALESCE((select sum(damage_length) FROM sell_item_detail SID WHERE SID.purchase_item_detail_id_fk = PID.purchase_item_detail_id AND SID.part_status=0 AND SID.is_deleted=0),0)
					) as damge_length,

					(	COALESCE(item_length,0) - 
						(COALESCE(damage_length,0) + 
						COALESCE(used_length,0) + 	
						COALESCE((select sum(sell_item_detail_height) FROM sell_item_detail SID WHERE SID.purchase_item_detail_id_fk = PID.purchase_item_detail_id AND SID.part_status=0 AND SID.is_deleted=0),0) + 
						COALESCE((select sum(damage_length) FROM sell_item_detail SID WHERE SID.purchase_item_detail_id_fk = PID.purchase_item_detail_id AND SID.part_status=0 AND SID.is_deleted=0),0))

					) as remained_length
					
					
					 FROM
					 	 purchase_item_detail PID
					 	 LEFT JOIN stock S ON (PID.stock_id_fk = S.stock_id)
					 	 LEFT JOIN product P ON (PID.product_id_fk = P.product_id)
					 	 
					WHERE 
					(PID.is_deleted = 0 AND PID.item_status =7 '.$cond.' ) 			
				) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'purchase_item_detail_id';
			$columns =  array(
				  			  	array( 'db' => 'purchase_item_detail_id', 'dt' => 0 ),
			    				array( 'db' => 'stock_name','dt' => 1 ),
			    				array( 'db' => 'stock_type','dt' => 2 ),
			    				array( 'db' => 'erbil_code','dt' => 3 ),
			    				array( 'db' => 'turkish_code','dt' => 4 ),
			    				array( 'db' => 'item_length','dt' => 5 ),
			    				array( 'db' => 'purchase_item_detail_id_fk','dt' => 6 ),
			    				
			    				array( 'db' => 'item_status','dt' => 7 ),
			    				array( 'db' => 'stock_id_fk','dt' => 8 ),
			    				array( 'db' => 'product_id_fk','dt' => 9 ),
			    				array( 'db' => 'previous_status','dt' => 10 ),
			    				array( 'db' => 'is_part','dt' => 11 ),
			    				array( 'db' => 'original_roll_length','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'] == "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'] 	  = "حصل خطأ في عملية التحديث : " . $db->error;
										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'] 	  = "حصل خطأ في عملية التحديث : " . $db->error;
								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'] 	  	= "Something went Wrong";
				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'] == "transfer_stock") {

            			$stock_id 	=addslashes($_POST["stock_id"]);
            			$id 		=addslashes($_POST["obj_id"]);

						$res = $db->query("SELECT * FROM purchase_item_detail WHERE purchase_item_detail_id = '$id'");

						$row 				= $res->fetch_assoc();
						$item_status 		= $row['item_status'];
						$previous_status 	= $row['previous_status'];
						$stock_id_fk 		= $row['stock_id_fk'];
						$damage_length  	= $row['damage_length'];

						

						$res = $db->query("SELECT * FROM stock WHERE stock_id = '$stock_id'");

						$row = $res->fetch_assoc();
						$stock_type = $row['stock_type'];

							
						switch ($previous_status) {
							case '2':
								if($stock_type == 1){
									$item_status='2'; // production store
								}else{
									$item_status='0'; // store stock
								}
								
								break;

							case '8':
								if($stock_type == 1){
									$item_status='11'; // production store with damage
								}else{
									$item_status='8'; // store stock with damage
								}
								break;
							case '5':
								$item_status='5'; // Partially Sold
								break;							
							
							
							default:
								$item_status= '5'; // That mean its Part 
								break;
						}
						

							
						$delete 	= 0;
						$reg_date 	= date("Y-m-d h:i:s", time());
						$lastaction = "Transfer Item to another Store";

						$res = $db->query("UPDATE purchase_item_detail SET stock_id_fk = '$stock_id', item_status='$item_status' ,last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE purchase_item_detail_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'] == "return_to_original") {

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

						$reg_date 	= date("Y-m-d h:i:s", time());
						$lastaction = "Return part to its original roll";

						$res = $db->query("SELECT * FROM purchase_item_detail WHERE purchase_item_detail_id = '$id' AND is_deleted=0");

						$row = $res->fetch_assoc();
						$previous_status 				= $row['previous_status'];
						$purchase_item_detail_id_fk 	= $row['purchase_item_detail_id_fk'];
						

						// We will just remove the part from purchase and thats all

						

						$res = $db->query("UPDATE purchase_item_detail SET  is_deleted='1',item_status = '$previous_status',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE purchase_item_detail_id=$id");

		     			if ($res){

		     				// we should update the parent roll status
		     				$res1 = $db->query("UPDATE purchase_item_detail SET  item_status = '$previous_status',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE purchase_item_detail_id=$purchase_item_detail_id_fk");
		     				
		     				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;
		     				}

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

		}

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

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

						$reg_date 	= date("Y-m-d h:i:s", time());
						$lastaction = "Set is as Completlly Damages";

						$res = $db->query("SELECT * FROM purchase_item_detail WHERE purchase_item_detail_id = '$id' AND is_deleted=0");

						$row = $res->fetch_assoc();
						$item_status 	= $row['item_status'];
						$used_length 	= $row['used_length'];
						$damage_length 	= $row['damage_length'];
						$item_length 	= $row['item_length'];

						// prevent make fully damage to these status
						if ($item_status==1 || $item_status==3 || $item_status==4 || $item_status==5 || $item_status==6 || $item_status==9 || $item_status==10) {
							$op['is_success'] = false;
							$op['data'] 	  = "لا يمكن اعتبار هذه المادة تالفة بالكامل";
							echo json_encode($op);
							exit;
						}

						$res = $db->query("UPDATE purchase_item_detail SET  item_status='6',damage_length ='$item_length' ,last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE purchase_item_detail_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'] == "add_damage") {

            			
            			$id 		=addslashes($_POST["obj_id"]);
            			$length_m 	=addslashes($_POST["length_m"]);

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

						$res = $db->query("SELECT * FROM purchase_item_detail WHERE purchase_item_detail_id = '$id' AND is_deleted=0");

						$row = $res->fetch_assoc();
						$item_status 	= $row['item_status'];
						$used_length 	= $row['used_length'];
						$damage_length 	= $row['damage_length'];
						$item_length 	= $row['item_length'];

						// prevent adding damges length to these status
						if ($item_status==1 || $item_status==4 || $item_status==6 || $item_status==7 || $item_status==10) {
							$op['is_success'] = false;
							$op['data'] 	  = "لا يمكن اضافة تالف الى هذه المادة (انظر الى الحالة)";
							echo json_encode($op);
							exit;
						}

						

						

						// we should compute the remained item length to check if he can add damage length according to the remaining length and not the original length

						$res1 = $db->query("SELECT sum(sell_item_detail_height) as sold_length, 
												   sum(damage_length) as sell_damage_length  
											FROM sell_item_detail 
											WHERE purchase_item_detail_id_fk = '$id' AND part_status =0 AND is_deleted=0");

						$row1 = $res1->fetch_assoc();
						$sold_length 			= $row1['sold_length'];
						$sell_damage_length 	= $row1['sell_damage_length'];
						


						$new_damage_length = $damage_length + $length_m;

						$remained_length = $item_length - ($used_length + $damage_length + $sold_length + $sell_damage_length);
						

						// prevent adding damges length greater than original roll length
						if ($length_m > $remained_length) {
							$op['is_success'] = false;
							$op['data'] 	  = " خطأ اصبح الطول الكلي التالف اكبر من طول العنصر المتبقي.. الرجاء التأكد من القيمة ";
							echo json_encode($op);
							exit;
						}

						// now we should compute remained length again may be item remained length will be 0 so we should change item status to finished because we havnt any thing to use or sell

						$new_remained_length = $item_length - ($used_length + $damage_length + $sold_length + $sell_damage_length + $length_m);

						// change item status for not used rolls only
						$new_item_status ='';

						if ($new_remained_length <=0 ) {

							if ($item_status==0 || $item_status==2 || $item_status==8 || $item_status==11) {
								$new_item_status = 6; // that mean all roll became damage
							}

							if ( $item_status==3) {
								$new_item_status = 4; // that mean it were used in production and now finished
							}
							if ( $item_status==5) {
								$new_item_status = 1; // that mean it were partially sold and now finished
							}
							if ( $item_status==9) {
								$new_item_status = 10; // that mean it were partially sold and used in production and now finished
							}
						}else{
							if ($item_status==0 ) {
								$new_item_status = 8;
							}

							if ( $item_status==2) {
								$new_item_status = 11;
							}
						}

						

						if ( $new_item_status !='') {
							$res = $db->query("UPDATE purchase_item_detail SET  item_status='$new_item_status',damage_length='$new_damage_length' ,last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE purchase_item_detail_id=$id");
						}else{
							$res = $db->query("UPDATE purchase_item_detail SET  damage_length='$new_damage_length' ,last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE purchase_item_detail_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'] == "used_product") {

            			
            			$id 		=addslashes($_POST["obj_id"]);
            			$length_m 	=addslashes($_POST["length_m"]);

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

						$res = $db->query("SELECT * FROM purchase_item_detail WHERE purchase_item_detail_id = '$id' AND is_deleted=0");

						$row = $res->fetch_assoc();
						$item_status 	= $row['item_status'];
						$used_length 	= $row['used_length'];
						$damage_length 	= $row['damage_length'];
						$item_length 	= $row['item_length'];

						// prevent adding used length to these status
						if ($item_status==0 || $item_status==1 || $item_status==4 || $item_status==6 || $item_status==7 || $item_status==8 || $item_status==10) {
							$op['is_success'] = false;
							$op['data'] 	  = "لا يمكن اضافة طول لاستخدامه في الانتاج من هذه المادة (انظر الى حالة المادة)";
							echo json_encode($op);
							exit;
						}


						// we should compute the remained item length to check if he can add used length according to the remaining length and not the original length

						$res1 = $db->query("SELECT sum(sell_item_detail_height) as sold_length, 
												   sum(damage_length) as sell_damage_length  
											FROM sell_item_detail 
											WHERE purchase_item_detail_id_fk = '$id' AND part_status =0 AND is_deleted=0");

						$row1 = $res1->fetch_assoc();
						$sold_length 			= $row1['sold_length'];
						$sell_damage_length 	= $row1['sell_damage_length'];
						


						$new_length = $used_length + $length_m;

						$remained_length = $item_length - ($used_length + $damage_length + $sold_length + $sell_damage_length);

						// prevent adding damges length greater than original roll length
						if ($length_m > $remained_length) {
							$op['is_success'] = false;
							$op['data'] 	  = " خطأ اصبح الطول الكلي المستخدم اكبر من طول العنصر المتبقي.. الرجاء التأكد من القيمة ";
							echo json_encode($op);
							exit;
						}

						
						// now we should compute remained length again may be item remained length will be 0 so we should change item status to finished because we havnt any thing to use or sell

						$new_remained_length = $item_length - ($used_length + $damage_length + $sold_length + $sell_damage_length + $length_m);

						// change item status according to remaining 
						$new_item_status ='';

						if ($new_remained_length <=0 ) {

							if ($item_status==2 || $item_status==3  || $item_status==11) {
								$new_item_status = 4; // that mean all roll became used
							}

							
							if ( $item_status==5 || $item_status==9) {
								$new_item_status = 10; // that mean it were partially sold and used in production and now finished
							}
						}else{
							
							// change item status for not used rolls only
							if ($item_status==2 || $item_status==11) {
								$new_item_status = 3; // it mean item were used 
							}

							if ($item_status==5 ) {
								$new_item_status = 9; // it mean item were partially sold and now used in production 
							}

						}

						
						

						if ( $new_item_status !='') {
							$res = $db->query("UPDATE purchase_item_detail SET  item_status='$new_item_status',used_length='$new_length' ,last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE purchase_item_detail_id=$id");
						}else{
							$res = $db->query("UPDATE purchase_item_detail SET  used_length='$new_length' ,last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE purchase_item_detail_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'] == "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;
	}
?>

