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

require_once 'vendor/autoload.php';

// for barcode


include('barcode/src/BarcodeGenerator.php');
include('barcode/src/BarcodeGeneratorPNG.php');
include('barcode/src/BarcodeGeneratorSVG.php');
include('barcode/src/BarcodeGeneratorJPG.php');
include('barcode/src/BarcodeGeneratorHTML.php');


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

		if( isset($_GET['type']) && ($_GET['type'] == "load")){
			// DB table to use
			// show All products for specific category
			$cond = isset($_GET['id'])? ' AND Inv.customer_id_fk='.$_GET['id']:'';
			$cond1 = isset($_GET['ip'])? ' AND Inv.invoice_status='.$_GET['ip']:'';
			
			
			
			$table  =  '(
				(
					SELECT
						invoice_id,
						invoice_number,
						invoice_date,
						invoice_status,
						
						invoice_note,
						delivery_status,
						delivery_time,
						
						author,
						
						invoice_transaction,
						original_invoice_id_fk,

											
						customer_full_name 
						
					 FROM
					 invoice Inv
					 LEFT JOIN customer Cus ON (Inv.customer_id_fk=Cus.customer_id) 
					
				WHERE
					( Inv.delivery_status = 2   AND Inv.is_deleted = 0  '.$cond.' '.$cond1.') 
				)
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'invoice_id';
			$columns = array(
		    	array( 'db' => 'invoice_id', 'dt' => 0 ),
		    	array( 'db' => 'invoice_number', 'dt' => 1 ),
		    	array( 'db' => 'invoice_date', 'dt' => 2, 'formatter'=> function($d){
							return date('Y-m-d',strtotime($d));
					} ),
		    	array( 'db' => 'delivery_time', 'dt' => 3, 'formatter'=> function($d){
							return date('Y-m-d',strtotime($d));
					} ),
		    	array( 'db' => 'customer_full_name', 'dt' => 4 ),
		    	
				array( 'db' => 'author', 'dt' => 5 ),
				array( 'db' => 'delivery_status', 'dt' => 6 ),
				

			  	array( 'db' => 'invoice_note', 'dt' => 7 ),
				array( 'db' => 'invoice_transaction', 'dt' => 8 ),
				array( 'db' => 'original_invoice_id_fk', 'dt' => 9 ),
			);
			// 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_orders") {

			// $stage 	= $_POST['stage'];

			switch ($_POST['stage']) {
				case 'cnc':
					$stage 	= 2;
					
					break;
				
				default:
					$stage 	= $_POST['stage'];
					break;
			}


			$res = $db->query("SELECT 
									invoice_id, 
									invoice_number, 
									invoice_date, 
									invoice_status, 
									
									invoice_note,
									author,
									
									delivery_status, 
									delivery_time,
									
									
									customer_full_name
								  

								FROM invoice I
										
			 	 				LEFT JOIN customer C ON (C.customer_id = I.customer_id_fk)

								WHERE I.delivery_status='$stage'  AND I.is_deleted = 0");
			if ($res) {

				$op  = array('invoice'=>array(),'details'=>array());
				while ($row = $res->fetch_assoc()) {

					$generatorPNG = new Picqer\Barcode\BarcodeGeneratorPNG();
							
				   	$result['invoice_barcode1']  = '<img src="data:image/png;base64,'.base64_encode($generatorPNG->getBarcode($row['invoice_number'], $generatorPNG::TYPE_CODE_128,2)) . '">';

				   

					$result['invoice_id']  					= $row['invoice_id'];
					$result['invoice_number']  				= $row['invoice_number'];
					$result['invoice_date']  				= date('Y-m-d',strtotime($row['invoice_date'])) ;
					$result['invoice_status']  				= $row['invoice_status'];
					$result['invoice_note']  				= $row['invoice_note'];
					$result['author']  						= $row['author'];
					$result['customer_full_name']  			= $row['customer_full_name'];
					
					$result['delivery_time']  				= $row['delivery_time'];
					
					$result['delivery_status']  			= $row['delivery_status'];
					
					array_push($op['invoice'],$result);
			
				}		
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


		function secondsToTime($seconds) {
		    $dtF = new \DateTime('@0');
		    $dtT = new \DateTime("@$seconds");
		    return $dtF->diff($dtT)->format(' %h h, %i m and %s sec');
		}

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

			$id 			= $_POST['id'];
			$curent_stage 	= $_POST['curent_stage'];


			$res = $db->query("SELECT 
										invoice_id, 
										invoice_number, 
										invoice_date, 
										invoice_status, 
										invoice_usd_rate, 
										invoice_currency,
										invoice_total_price_actual, 
										invoice_total_net_balance, 
										discount,
										discount_type, 
										I.actual_discount, 
										invoice_note,
										author,
										invoice_sequence_no,
										delivery_status, 
										delivery_time,
										destination, 
										offer_number, 
										date_of_offer, 
										term_and_conditions, 
										invoice_barcode,
										customer_id_fk, 
										pay_terms,
										request_for_quta_number,
										sell_item_id,
										sell_item_quantity,
										cnc_quantity,
										sell_item_height,
										sell_item_width, 
										sell_item_height_production, 
										sell_item_width_production, 
										item_buy_price_per_unit, 
										item_sell_price_per_unit, 
										tax_per_unit, 
										sell_item_barcode,
										sell_item_notes,
										sell_item_comment,
										cell_color,
										item_production_stage,
										sell_item_delivery_name, 
										SI.model_id_fk,
										color_product_id_fk, 
										customer_full_name,
										customer_email,
										customer_phone,
										customer_address,									  
									  	customer_company,

									  	M.model_name,
									  	M.model_code,
									  	M.model_type,

									  	Pr1.product_name AS product_name_color,
									  	Pr1.product_code AS product_code_color,
									  	Pr1.product_type AS product_type_color,

									  	

									  	COALESCE((SELECT SUM( TIMESTAMPDIFF(SECOND, st_stage_".$curent_stage.", et_stage_".$curent_stage.") ) FROM sell_item_status SIS1  
											WHERE  SIS1.sell_item_id_fk =SI.sell_item_id AND  SIS1.item_production_stage >'$curent_stage' AND SIS1.is_deleted=0),0
										) AS elapsed_time,

									  	COALESCE((SELECT COUNT(*) FROM sell_item_status SIS1  
											WHERE  SIS1.sell_item_id_fk =SI.sell_item_id AND  SIS1.item_production_stage >'$curent_stage' AND SIS1.is_deleted=0),0
										) AS completed_qty
									  		
									  													
									  	

									

								  

										FROM invoice I
										LEFT JOIN sell_item SI ON (SI.invoice_id_fk = I.invoice_id AND SI.is_deleted=0)
										LEFT JOIN model M ON (SI.model_id_fk = M.model_id )
										LEFT JOIN product Pr1 ON (SI.color_product_id_fk = Pr1.product_id )
					 	 				LEFT JOIN customer C ON (C.customer_id = I.customer_id_fk)

										WHERE I.invoice_id='$id'  AND I.is_deleted = 0");
			if ($res) {
				//$row = $res->fetch_all();
				//echo json_encode($row);

				$op  = array('invoice'=>array(),'details'=>array());
				while ($row = $res->fetch_assoc()) {

					if($row['delivery_status'] ==4){
						$deliver = 'Delivered In Factory';
					}elseif($row['delivery_status'] ==3){
						$deliver = 'Delivered In Shop';

					}elseif($row['delivery_status'] ==2){
						$deliver = 'Finished Production';

					}elseif($row['delivery_status'] ==1){
						$deliver = 'In Production Progress';

					}else{
						$deliver = 'Not Start Yet';

					}

					$generatorPNG = new Picqer\Barcode\BarcodeGeneratorPNG();

							

				   	$result['invoice_barcode1']  = '<img src="data:image/png;base64,'.base64_encode($generatorPNG->getBarcode($row['invoice_number'], $generatorPNG::TYPE_CODE_128,2)) . '">';

				   	$result['item_barcode']  = '<img src="data:image/png;base64,'.base64_encode($generatorPNG->getBarcode($row['sell_item_barcode'], $generatorPNG::TYPE_CODE_128,1)) . '">';



					$result['invoice_id']  					= $row['invoice_id'];
					$result['invoice_number']  				= $row['invoice_number'];
					$result['invoice_date']  				= date('Y-m-d',strtotime($row['invoice_date'])) ;
					$result['invoice_status']  				= $row['invoice_status'];
					$result['invoice_usd_rate']  			= $row['invoice_usd_rate'];
					$result['invoice_currency']  			= $row['invoice_currency'];
					$result['invoice_total_price_actual'] 	= $row['invoice_total_price_actual'];
					$result['invoice_total_net_balance']  	= $row['invoice_total_net_balance'];
					$result['discount']  					= $row['discount'];
					$result['discount_type']  				= $row['discount_type'];
					$result['actual_discount']  			= $row['actual_discount'];
					$result['invoice_note']  				= $row['invoice_note'];
					$result['invoice_sequence_no']  		= $row['invoice_sequence_no'];
					$result['author']  						= $row['author'];
					$result['destination']  				= $row['destination'];
					$result['sell_item_width']  			= $row['sell_item_width'];
					$result['sell_item_height']  			= $row['sell_item_height'];
					$result['sell_item_height_production']  = $row['sell_item_height_production'];
					$result['sell_item_width_production']  	= $row['sell_item_width_production'];
					$result['term_and_conditions']  		= $row['term_and_conditions'];
					$result['invoice_barcode']  			= $row['invoice_barcode'];
					$result['customer_id_fk']  				= $row['customer_id_fk'];
					$result['sell_item_id']  				= $row['sell_item_id'];
					$result['sell_item_quantity']  			= $row['sell_item_quantity'];
					$result['cnc_quantity']  			= $row['cnc_quantity'];
					$result['item_buy_price_per_unit']  	= $row['item_buy_price_per_unit'];
					$result['item_sell_price_per_unit']  	= $row['item_sell_price_per_unit'];
					$result['tax_per_unit']  				= $row['tax_per_unit'];
					$result['cell_color']  					= $row['cell_color'];
					$result['sell_item_barcode']  			= $row['sell_item_barcode'];
					$result['sell_item_notes']  			= $row['sell_item_notes'];
					$result['sell_item_comment']  			= $row['sell_item_comment'];
					$result['item_production_stage']  		= $row['item_production_stage'];

					$result['model_id_fk']  				= $row['model_id_fk'];
					$result['color_product_id_fk']  		= $row['color_product_id_fk'];
					$result['customer_full_name']  			= $row['customer_full_name'];
					$result['customer_phone']  				= $row['customer_phone'];
					$result['customer_address']  			= $row['customer_address'];
					$result['customer_email']  				= $row['customer_email'];
					$result['customer_company']  			= $row['customer_company'];
					
					$result['model_name']  					= $row['model_name'];
					$result['model_code']  					= $row['model_code'];
					$result['model_type']  					= $row['model_type'];
					$result['product_name_color']  			= $row['product_name_color'];
					$result['product_code_color']  			= $row['product_code_color'];
					$result['product_type_color']  			= $row['product_type_color'];
					
					$result['delivery_time']  				= $row['delivery_time'];
					$result['completed_qty']  				= $row['completed_qty'];
					
					$result['delivery_status']  			= $deliver;

					if($row['elapsed_time'] =='' || $row['elapsed_time'] == NULL || $row['elapsed_time'] < 1){
						$tim = 1;
					}else{
						$tim= $row['elapsed_time'];
					}
					
					$result['elapsed_time'] 	  		= secondsToTime($tim);

					array_push($op['invoice'],$result);



				
				
				
				
				
			
				}		
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}



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

			$id = $_POST['id'];


			$res = $db->query("SELECT 
										invoice_id, 
										invoice_number, 
										invoice_date, 
										invoice_status, 
										
										invoice_note,
										author,
										
										delivery_status, 
										delivery_time,
										
										invoice_barcode,
										customer_id_fk, 
										
										sell_item_id,
										sell_item_quantity,
										sell_item_height,
										sell_item_width, 
										sell_item_height_production, 
										sell_item_width_production, 
										
										sell_item_notes,
										sell_item_comment,
										
										SI.model_id_fk,
										color_product_id_fk, 
										customer_full_name,
										customer_email,
										customer_phone,
										customer_address,									  
									  	customer_company,

									  	M.model_name,
									  	M.model_code,
									  	M.model_type,

									  	Pr1.product_name AS product_name_color,
									  	Pr1.product_code AS product_code_color,
									  	Pr1.product_type AS product_type_color,

									  	SIS.sell_item_barcode,
									  	sell_item_id_fk,
									  	sell_item_status_id
									  		
									  													
									  	

									

								  

										FROM invoice I
										LEFT JOIN sell_item SI ON (SI.invoice_id_fk = I.invoice_id AND SI.is_deleted=0)
										LEFT JOIN sell_item_status SIS ON (SIS.invoice_id_fk = I.invoice_id AND SIS.sell_item_id_fk = SI.sell_item_id AND SIS.is_deleted=0)
										LEFT JOIN model M ON (SI.model_id_fk = M.model_id )
										LEFT JOIN product Pr1 ON (SI.color_product_id_fk = Pr1.product_id )
					 	 				LEFT JOIN customer C ON (C.customer_id = I.customer_id_fk)

										WHERE I.invoice_id='$id'  AND I.is_deleted = 0");
			if ($res) {
				//$row = $res->fetch_all();
				//echo json_encode($row);

				$op  = array('invoice'=>array(),'details'=>array());
				while ($row = $res->fetch_assoc()) {

					

					$generatorPNG = new Picqer\Barcode\BarcodeGeneratorPNG();

							

				   	$result['invoice_barcode1']  = '<img src="data:image/png;base64,'.base64_encode($generatorPNG->getBarcode($row['invoice_number'], $generatorPNG::TYPE_CODE_128,2)) . '">';

				   	$result['item_barcode']  = '<img src="data:image/png;base64,'.base64_encode($generatorPNG->getBarcode($row['sell_item_barcode'], $generatorPNG::TYPE_CODE_128,1)) . '">';



					$result['invoice_id']  					= $row['invoice_id'];
					$result['invoice_number']  				= $row['invoice_number'];
					
					$result['author']  						= $row['author'];
					
					$result['sell_item_width']  			= $row['sell_item_width'];
					$result['sell_item_height']  			= $row['sell_item_height'];
					$result['sell_item_height_production']  = $row['sell_item_height_production'];
					$result['sell_item_width_production']  	= $row['sell_item_width_production'];
					
					$result['invoice_barcode']  			= $row['invoice_barcode'];
					$result['customer_id_fk']  				= $row['customer_id_fk'];
					$result['sell_item_id']  				= $row['sell_item_id'];
					$result['sell_item_quantity']  			= $row['sell_item_quantity'];
					
					$result['sell_item_barcode']  			= $row['sell_item_barcode'];
					$result['sell_item_notes']  			= $row['sell_item_notes'];
					$result['sell_item_comment']  			= $row['sell_item_comment'];
					$result['sell_item_status_id']  		= $row['sell_item_status_id'];
					$result['sell_item_id_fk']  			= $row['sell_item_id_fk'];
					
					$result['model_id_fk']  				= $row['model_id_fk'];
					$result['color_product_id_fk']  		= $row['color_product_id_fk'];
					$result['customer_full_name']  			= $row['customer_full_name'];
					$result['customer_phone']  				= $row['customer_phone'];
					$result['customer_address']  			= $row['customer_address'];
					$result['customer_email']  				= $row['customer_email'];
					$result['customer_company']  			= $row['customer_company'];
					
					$result['model_name']  					= $row['model_name'];
					$result['model_code']  					= $row['model_code'];
					$result['model_type']  					= $row['model_type'];
					$result['product_name_color']  			= $row['product_name_color'];
					$result['product_code_color']  			= $row['product_code_color'];
					$result['product_type_color']  			= $row['product_type_color'];
					
					
					
					array_push($op['invoice'],$result);
			
				}		
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


		


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

			
			
			$curent_stage			= $_POST["curent_stage"];
			$recieved_barcode		= $_POST["recieved_barcode"];
			// $completed_barcode		= $_POST["completed_barcode"];
			


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

			$cur_stage 				= $curent_stage;
			$bar_code 				= "ABCD"; // if barcode were wrong nothing will update

			$timess  				= "";

			$start_stg				= "st_stage_".$curent_stage;

			$bar_code 				= $recieved_barcode;

			$res = $db->query("SELECT 	invoice_id_fk,
										sell_item_id_fk,
										sell_item_status_id,
										$start_stg,
										item_production_stage 
								FROM sell_item_status 
								WHERE sell_item_barcode = '$bar_code' AND is_deleted=0");

			$row = $res->fetch_assoc();
			
			$invoice_id_fk 			= $row['invoice_id_fk'];
			$sell_item_id_fk 		= $row['sell_item_id_fk'];
			$sell_item_status_id 	= $row['sell_item_status_id'];
			$item_production_stage 	= $row['item_production_stage'];

			$st_stage_ 				= $row['st_stage_'.$curent_stage];


			if($st_stage_ == NULL){
				$cur_stage 			= $curent_stage; // CNC Stage

				$timess  			= "st_stage_".$curent_stage." = '$reg_date',";
				
			}else{
				$cur_stage 			= $curent_stage + 1; // Cleaning Wood Stage
				$timess  			= "et_stage_".$curent_stage." = '$reg_date',";
			}



			if($sell_item_status_id =='' || $sell_item_status_id == NULL){
				$chek_insertion = false;
				$db->rollback();
				$op['is_success'] = false;
				$op['data'] 	  = "هناك خطأ : الباركود الذي تم ادخاله غير مسجل في النظام الرجاء التحقق والمحاولة من جديد";
				echo json_encode($op);
				exit;
			}

			// prevent returning item to previous stage
			if($item_production_stage > $cur_stage ){
				$chek_insertion = false;
				$db->rollback();
				$op['is_success'] = false;
				$op['data'] 	  = "هناك خطأ : العنصر الحالي انهى مرحلة CNC لا يمكن اعادته الى هذه المرحلة";
				echo json_encode($op);
				exit;
			}

			$sql2 ="UPDATE sell_item_status SET  
												
												
											item_production_stage 	= '$cur_stage',
											".$timess."
											updated_at				= '$reg_date',
											last_action 			= '$lastaction',
											last_action_by 			= '".$_SESSION['user_id']."'
							WHERE sell_item_status_id = '$sell_item_status_id'";

			$res2 = $db->query($sql2);

			if ($res2) {


				// now we should get back the information related to this barcode

				$res = $db->query("SELECT 	invoice_number,
											invoice_id,
										  	sell_item_quantity,
										  	sell_item_height_production,
										  	sell_item_width_production,
										  	sell_item_notes,
										  	sell_item_comment, 
										  
										  	M.model_code,
										  	Pr1.product_code AS product_code_color,
										  	
										  	SIS.sell_item_barcode,
										  	SIS.item_production_stage,
										  	
										  	sell_item_status_id,

										  	TIMESTAMPDIFF(SECOND, st_stage_".$curent_stage.", et_stage_".$curent_stage.") AS elapsed_time,

										  	COALESCE((SELECT COUNT(*) FROM sell_item_status SIS1  
														WHERE  SIS1.sell_item_id_fk ='$sell_item_id_fk' AND  SIS1.item_production_stage ='$curent_stage' AND SIS1.is_deleted=0),0) AS recieved_qty,

											COALESCE((SELECT COUNT(*) FROM sell_item_status SIS1  
														WHERE  SIS1.sell_item_id_fk ='$sell_item_id_fk' AND  SIS1.item_production_stage >'$curent_stage' AND SIS1.is_deleted=0),0) AS completed_qty

								   FROM sell_item_status SIS 

								   		LEFT JOIN invoice I ON (SIS.invoice_id_fk = I.invoice_id  AND I.is_deleted=0)

										LEFT JOIN sell_item SI ON (SI.invoice_id_fk = I.invoice_id AND SIS.sell_item_id_fk = SI.sell_item_id AND SI.is_deleted=0)
										
										LEFT JOIN model M ON (SI.model_id_fk = M.model_id )
										LEFT JOIN product Pr1 ON (SI.color_product_id_fk = Pr1.product_id )
					 	 				LEFT JOIN customer C ON (C.customer_id = I.customer_id_fk)

										WHERE I.invoice_id='$invoice_id_fk' AND SIS.sell_item_status_id ='$sell_item_status_id'  AND SIS.is_deleted = 0");


				$row = $res->fetch_assoc();

				if($row['elapsed_time'] =='' || $row['elapsed_time'] == NULL || $row['elapsed_time'] < 1){
					$tim = 1;
				}else{
					$tim= $row['elapsed_time'];
				}
				
				$op['invoice_number'] 	  					= $row['invoice_number'];
				$op['sell_item_quantity'] 	  				= $row['sell_item_quantity'];
				$op['sell_item_height_production'] 	  		= $row['sell_item_height_production'];
				$op['sell_item_width_production'] 	  		= $row['sell_item_width_production'];
				$op['sell_item_notes'] 	  					= $row['sell_item_notes'];
				$op['sell_item_comment'] 	  				= $row['sell_item_comment'];
				$op['model_code'] 	  						= $row['model_code'];
				$op['product_code_color'] 	  				= $row['product_code_color'];
				$op['item_production_stage'] 	  			= $row['item_production_stage'];
				$op['sell_item_status_id'] 	  				= $row['sell_item_status_id'];
				$op['sell_item_barcode'] 	  				= $row['sell_item_barcode'];
				$op['recieved_qty'] 	  					= $row['recieved_qty'];
				$op['completed_qty'] 	  					= $row['completed_qty'];
				$op['invoice_id'] 	  						= $row['invoice_id'];
				$op['elapsed_time'] 	  					= secondsToTime($tim);
				

				// check if completed quantity = item quanity then we should update sell_item table to set the stage for those items where moved to next stage

				if($row['completed_qty'] >= $row['sell_item_quantity'] ){
					
					$next_stage = $curent_stage + 1;

					$lastaction = "Move all quantity to Next Stage ($next_stage)";
					
					$sql3 ="UPDATE sell_item SET  
												item_production_stage 	= '$next_stage',
												updated_at				= '$reg_date',
												last_action 			= '$lastaction',
												last_action_by 			= '".$_SESSION['user_id']."'
 								WHERE sell_item_id = '$sell_item_id_fk'";

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

					// also we need to check if all order item we finished some stage to move order stauts to next stage


					$res_I = $db->query("SELECT 	invoice_number,
										  			sell_item_quantity,
										  	
										  			SIS.item_production_stage,
										  	
										  	

										  	COALESCE((SELECT COUNT(*) FROM sell_item SIS1  
														WHERE  SIS1.invoice_id_fk ='$invoice_id_fk' AND  SIS1.item_production_stage ='$curent_stage' AND SIS1.is_deleted=0),0) AS recieved_qty,

											COALESCE((SELECT COUNT(*) FROM sell_item SIS1  
														WHERE  SIS1.invoice_id_fk ='$invoice_id_fk'  AND SIS1.is_deleted=0),0) AS total_qty,

											COALESCE((SELECT COUNT(*) FROM sell_item SIS1  
														WHERE  SIS1.invoice_id_fk ='$invoice_id_fk' AND  SIS1.item_production_stage >'$curent_stage' AND SIS1.is_deleted=0),0) AS completed_qty

								   FROM sell_item SIS 

								   		LEFT JOIN invoice I ON (SIS.invoice_id_fk = I.invoice_id  AND I.is_deleted=0)

										

										WHERE I.invoice_id='$invoice_id_fk'  AND SIS.is_deleted = 0");


					$row_I = $res_I->fetch_assoc();

					if($row_I['completed_qty'] >= $row_I['total_qty'] ){
					
						
						$lastaction = "Move Invoice to Next Stage ($next_stage)";
						
						$sql3i ="UPDATE invoice SET  
													delivery_status 		= '$next_stage',
													updated_at				= '$reg_date',
													last_action 			= '$lastaction',
													last_action_by 			= '".$_SESSION['user_id']."'
	 								WHERE invoice_id = '$invoice_id_fk'";

						$res3i = $db->query($sql3i);

					}

				
				}

				// end checking

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


			}else{
						echo $sql2;

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


			


		}

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