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

			// $limits = "LIMIT 0";
			$limits = "";
			if( $_GET['search']['value'] !=''){
				$limits =  "";
			}

			for($i=0; $i<6;$i++){

				if( $_GET['columns'][$i]['search']['value'] !=''){
					$limits =  "";
				}
			}


			$table  =  '(
				(
					SELECT
						invoice_id,
						invoice_number,
						invoice_date,
						invoice_status,
						invoice_usd_rate,
						invoice_currency,
						invoice_total_price_actual,
						invoice_total_net_balance,
						invoice_note,
						
						discount,
						discount_type,
						author,
						Inv.actual_discount,
						invoice_sequence_no,
						
						customer_id_fk,
						
						invoice_transaction,
						
											
						supplier_full_name AS name,
						
						supplier_phone AS phone,
						full_name,
						branch_name,
						saleman_full_name

					 FROM  orders Inv
					 		LEFT JOIN suppliers Cus 	ON (Inv.customer_id_fk 	= Cus.supplier_id) 
					 		LEFT JOIN staff Stf 	ON (Inv.created_by 		= Stf.staff_id) 
					 		LEFT JOIN saleman SM 	ON (Inv.saleman_id_fk 	= SM.saleman_id) 
					 		LEFT JOIN branch B 		ON (Inv.branch_id_fk 	= B.branch_id) 
					 
				WHERE
					(Inv.is_deleted = 0  '.$cond.' '.$cond1.') '.$limits.'
				)
			) 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' => 'name', 'dt' => 3 ),
			  	array( 'db' => 'invoice_note', 'dt' => 4 ),
				array( 'db' => 'full_name', 'dt' => 5 ),
				array( 'db' => 'customer_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']=="show_invoice") {

			$id = $_POST['id'];


			$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, 
										I.discount,
										I.discount_type, 
										I.actual_discount, 
										invoice_note,
										author,
										invoice_sequence_no,
										
										invoice_barcode,
										customer_id_fk, 
										sell_item_id,
										sell_item_quantity,
										sell_discount,
										sell_discount_type,
										SI.actual_discount as sell_actual_discount, 
										item_buy_price_per_unit, 
										item_sell_price_per_unit, 
										tax_per_unit, 
										sell_date,
										sell_item_barcode,
										sell_item_notes,
										product_id_fk, 
										supplier_full_name,
										supplier_email,
										supplier_phone,
										supplier_address,									  
									  	

									  	Pr1.product_name,
									  	
									  													
									  	(0 ) AS row_price,

									  	branch_name,
									  	saleman_full_name,
									  	I.branch_id_fk,
									  	saleman_id_fk,
									  	SI.invoice_id_fk
								  

										FROM orders I
										LEFT JOIN order_item SI ON (SI.invoice_id_fk = I.invoice_id AND SI.is_deleted=0)
										LEFT JOIN branch B ON (I.branch_id_fk = B.branch_id )
										LEFT JOIN product Pr1 ON (SI.product_id_fk = Pr1.product_id )
					 	 				LEFT JOIN suppliers C ON (C.supplier_id = I.customer_id_fk)
					 	 				LEFT JOIN saleman SM ON (I.saleman_id_fk = SM.saleman_id)

										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()) {

					
				   
					$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['invoice_barcode']  			= $row['invoice_barcode'];
					$result['customer_id_fk']  				= $row['customer_id_fk'];
					$result['branch_id_fk']  				= $row['branch_id_fk'];
					$result['saleman_id_fk']  				= $row['saleman_id_fk'];

					$result['sell_item_id']  				= $row['sell_item_id'];
					$result['sell_item_quantity']  			= $row['sell_item_quantity'];
					$result['sell_discount']  				= $row['sell_discount'];
					$result['sell_discount_type']  			= $row['sell_discount_type'];
					$result['sell_actual_discount']  		= $row['sell_actual_discount'];
					$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['sell_item_barcode']  			= $row['sell_item_barcode'];
					$result['sell_date']  					= $row['sell_date'];
					$result['sell_item_notes']  			= $row['sell_item_notes'];
					$result['customer_full_name']  			= $row['supplier_full_name'];
					$result['customer_phone']  				= $row['supplier_phone'];
					$result['customer_address']  			= $row['supplier_address'];
					$result['customer_email']  				= $row['supplier_email'];
					
					$result['product_id_fk']  				= $row['product_id_fk'];
					$result['invoice_id_fk']  				= $row['invoice_id_fk'];

					$result['product_name']  				= $row['product_name'];
					$result['branch_name']  				= $row['branch_name'];
					$result['saleman_full_name']  			= $row['saleman_full_name'];
					
					
					
					array_push($op['invoice'],$result);
			
				}		
				echo json_encode($op);
				exit;
			}else{
				echo $db->error;
				exit;
			}
		}


		


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

				
			$res = $db->query("SELECT 	invoice_id,
										invoice_number,
										invoice_date,
										customer_full_name,							  
									  	customer_company
										FROM invoice  I
										LEFT JOIN customer C ON (I.customer_id_fk = C.customer_id)
										WHERE  I.is_deleted = 0");
								
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array('is_success'=>false, 'data' => array());
				while ($row = $res->fetch_assoc()) {
				   
						$result['invoice_id']  			= $row['invoice_id'];
						$result['invoice_number']  		= $row['invoice_number'];
						$result['invoice_date']  		= date('Y-m-d',strtotime($row['invoice_date'])) ;
						$result['customer_full_name']  	= $row['customer_full_name'];
						$result['customer_company']  	= $row['customer_company'];
						
						array_push($op['data'],$result);
				}

			}else{
				echo 0;
				exit;
			}

			

			$op['is_success'] = true;

			echo json_encode($op);

			exit();
					
		}


		


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

			$id = $_POST['id'];


			$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, 
										I.discount,
										I.discount_type, 
										I.actual_discount, 
										invoice_note,
										author,
										invoice_sequence_no,
										invoice_transaction,
										
										invoice_barcode,
										customer_id_fk, 
										sell_item_id,
										sell_item_quantity,
										sell_discount,
										sell_discount_type,
										SI.actual_discount as sell_actual_discount, 
										item_buy_price_per_unit, 
										item_sell_price_per_unit, 
										tax_per_unit, 
										sell_date,
										sell_item_barcode,
										sell_item_notes,
										product_id_fk, 
										


									  	Pr1.product_name,
									  	
									  													
									  	(0 ) AS row_price,

									  	branch_name,
									  	saleman_full_name,
									  	I.branch_id_fk,
									  	saleman_id_fk,
									  	SI.invoice_id_fk,
									  	I.stock_id_fk
								  

									FROM orders I
										LEFT JOIN order_item SI ON (SI.invoice_id_fk = I.invoice_id AND SI.is_deleted=0)
										LEFT JOIN branch B ON (I.branch_id_fk = B.branch_id )
										LEFT JOIN product Pr1 ON (SI.product_id_fk = Pr1.product_id )
					 	 				LEFT JOIN suppliers C ON (C.supplier_id = I.customer_id_fk)
					 	 				LEFT JOIN saleman SM ON (I.saleman_id_fk = SM.saleman_id)

										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()) {


					$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['invoice_barcode']  			= $row['invoice_barcode'];
					$result['customer_id_fk']  				= $row['customer_id_fk'];
					$result['branch_id_fk']  				= $row['branch_id_fk'];
					$result['saleman_id_fk']  				= $row['saleman_id_fk'];

					$result['sell_item_id']  				= $row['sell_item_id'];
					$result['sell_item_quantity']  			= $row['sell_item_quantity'];
					$result['sell_discount']  				= $row['sell_discount'];
					$result['sell_discount_type']  			= $row['sell_discount_type'];
					$result['sell_actual_discount']  		= $row['sell_actual_discount'];
					$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['sell_item_barcode']  			= $row['sell_item_barcode'];
					$result['sell_date']  					= $row['sell_date'];
					$result['sell_item_notes']  			= $row['sell_item_notes'];
					
					$result['product_id_fk']  				= $row['product_id_fk'];
					$result['invoice_id_fk']  				= $row['invoice_id_fk'];

					$result['product_name']  				= $row['product_name'];
					$result['branch_name']  				= $row['branch_name'];
					$result['stock_id_fk']  				= $row['stock_id_fk'];
					$result['saleman_full_name']  			= $row['saleman_full_name'];
					
					
					

					array_push($op['invoice'],$result);
			
				}		
				echo json_encode($op);
				exit;
			}else{
				echo $db->error;
				exit;
			}
		}



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

			$p_id = $_POST['p_id'];

			// we should show item that can be sell 
			// 0 : avaialbe in store no damge
			// 2 : avaible in production no damge
			// 3 : in production used not finished
			// 5 : partially sold
			// 8 : avaiable in store with damage
			// 9 : used in production + partially sold
			// 11: available in production with damage
			// And we should also send the remianed length of each roll 

			$res = $db->query("SELECT purchase_item_detail_id, item_length,stock_id_fk, stock_name,item_status,
													(	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)
													WHERE (PID.item_status= 0 || PID.item_status= 2 || PID.item_status= 3 || PID.item_status= 5 || PID.item_status= 8 || PID.item_status= 9 || PID.item_status= 11  ) 
													AND PID.is_deleted=0 AND PID.product_id_fk = $p_id");
			if ($res) {
				
				$op  = array('data'=>array(),'stocks'=>array());
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['purchase_item_detail_id'];
						$result[1]  = $row['item_length'];
						$result[2]  = $row['stock_name'];
						$result[3]  = $row['stock_id_fk'];
						$result[4]  = $row['item_status'];
						$result[5]  = $row['remained_length'];
						
						
						array_push($op['data'],$result);
				}
				$res1 = $db->query("SELECT stock_id, stock_name, stock_type,
														(SELECT COUNT(*) FROM purchase_item_detail P WHERE P.stock_id_fk = S.stock_id AND P.is_deleted=0 AND (P.item_status= 0 || P.item_status= 2 || P.item_status= 3 || P.item_status= 5 || P.item_status= 8 || P.item_status= 9 || P.item_status= 11  ) AND P.product_id_fk = $p_id) AS roll_no
														FROM stock S
														WHERE  S.is_deleted = 0");
				
				while ($row1 = $res1->fetch_assoc()) {
				   
						$result1[0]  = $row1['stock_id'];
						$result1[1]  = $row1['stock_name'];
						$result1[2]  = $row1['stock_type'];
						$result1[3]  = $row1['roll_no'];
						array_push($op['stocks'],$result1);
				}

				echo json_encode($op);

				exit;
			}else{
				echo 0;
				exit;
			}
		}


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

			$id = $_POST['obj_id'];

			$res = $db->query("SELECT * FROM invoice_images WHERE is_deleted=0 AND invoice_id_fk = '$id'");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['image_id'];
						$result[1] = $row['image_path'];
						array_push($op,$result);
				}

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

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

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

			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Delete Image";

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

			

			

	  		$res = $db->query("UPDATE invoice_images SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE image_id=$id");
	    	if ($res){
	        $op['is_success'] = true;
	        		if(unlink('../'.$img_path)){

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

		

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

			
			$product_id						= $_POST["product_id"];
			$quantity						= $_POST["quantity"];
			$sell_item_note					= $_POST["sell_item_note"];
			
				
			
			$customer_id_fk 				= addslashes($_POST["customer_id_fk"]);
			$invoice_date			  		= addslashes($_POST["invoice_date"]);
			$invoice_note	  				= addslashes($_POST["invoice_note"]);
			
				
			$invoice_currency					= 1; //USD
			$term_and_conditions = "";

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

			

						

			

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

			
			

			if($invoice_date == null || $invoice_date ==''){
				$invoice_date = date("Y-m-d h:i:s", time());
			}

			$db->autocommit(FALSE); // to rollback insertion if update fail
			$sql ="UPDATE orders SET   
								invoice_date 				= '$invoice_date', 		
								invoice_note 				= '$invoice_note',
								customer_id_fk 				= '$customer_id_fk', 
								updated_at 					= '$reg_date', 
								last_action 				= '$lastaction', 
								last_action_by 				= '".$_SESSION['user_id']."'
						 		WHERE invoice_id = '$id'";
			
			$res = $db->query($sql);
			if ($res) {

				$invoice_inserted_id = $id;

				$chek_insertion = true;


				$delete_qry = "DELETE FROM order_item WHERE invoice_id_fk = $id";

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

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


				


				

				// insert into sell items the sold products
				$lastaction = "Update Order Product";
				

				for ($i=1;$i<count($product_id);$i++){

					

					$tax_per_unit 				= '';
					$sell_item_delivery_name 	= '';
					$barcode                   	= "";
					
					

					$sql2 ="INSERT INTO order_item (	sell_item_quantity, 
													
													sell_date,
													sell_item_notes,
													product_id_fk,
													invoice_id_fk,
													
													created_by,
													created_at,
													updated_at,
													last_action,
													last_action_by)

 								 			VALUES( '$quantity[$i]',
	 								 				
	 								 				'$invoice_date',
	 								 				'$sell_item_note[$i]',
	 								 				'$product_id[$i]',
	 								 				'$invoice_inserted_id',
	 								 				'".$_SESSION['user_id']."',
	 								 				'$reg_date',
	 								 				'$reg_date',
	 								 				'$lastaction',
	 								 				'".$_SESSION['user_id']."')";
					
					$res2 = $db->query($sql2);

					if ($res2) {
						
						$chek_insertion = true ;


					}else{
								// echo $db->error;

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

				} // for i


				


				if($chek_insertion == true ){

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

			}else{
				$db->rollback();
				$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 Order";

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


			$db->autocommit(FALSE); // to rollback update if update fail
			$res = $db->query("UPDATE orders SET 
											is_deleted = 1 ,
											deleted_at = '$reg_date',
											last_action='$lastaction',
											last_action_by='".$_SESSION['user_id']."' 
									WHERE invoice_id=$id");
			if ($res){

					// update Product table for sell price and avarage price

					$sql1 ="UPDATE order_item SET 
											is_deleted = '1',
								 			deleted_at='$reg_date', 
								 			last_action='$lastaction', 
								 			last_action_by='".$_SESSION['user_id']."'  
								 	WHERE invoice_id_fk = $id";

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

					if ($res1) {


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


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



		}

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

            $product_id						= $_POST["product_id"];
			$quantity						= $_POST["quantity"];
			$sell_item_note					= $_POST["sell_item_note"];
			
			
			
			
			$customer_id_fk 				= addslashes($_POST["customer_id_fk"]);

			$invoice_date			  		= addslashes($_POST["invoice_date"]);
			
			$invoice_note	  				= addslashes($_POST["invoice_note"]);
				
			
			$invoice_currency					= 1; //USD
			$term_and_conditions = "";

						


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

			$res = $db->query("SELECT invoice_sequence_no FROM orders ORDER BY invoice_id DESC LIMIT 1");
			$row = $res->fetch_assoc();
			$invoice_sequence_no 	= $row['invoice_sequence_no'] +1;

			$dd = date("y", time());
			
			
			$invoice_number = "OR-".($invoice_sequence_no);
			
			if($invoice_date == null || $invoice_date ==''){
				$invoice_date = date("Y-m-d H:i:s", time());
			}

			



			$db->autocommit(FALSE); // to rollback insertion if update fail
			$sql ="INSERT INTO orders (invoice_number,
										invoice_date, 		
										invoice_note,
										invoice_sequence_no, 
										customer_id_fk, 
										created_by, 
										last_action, 
										last_action_by)
						 		VALUES( '$invoice_number',
						 				'$invoice_date',
						 				'$invoice_note',
						 				'$invoice_sequence_no',
						 				'$customer_id_fk',
						 				'".$_SESSION['user_id']."',
						 				'$lastaction',
						 				'".$_SESSION['user_id']."')";
			
			$res = $db->query($sql);
			if ($res) {

				$invoice_inserted_id = $db->insert_id;

				$chek_insertion = true;



				// insert into sell items the sold products
				$lastaction = "Add New Order Product";
				$barcode    = "";

				for ($i=1;$i<count($product_id);$i++){


					$sql2 ="INSERT INTO order_item (sell_item_quantity, 
													
													sell_date,
													sell_item_notes,
													product_id_fk,
													invoice_id_fk,
													
													created_by,
													created_at,
													updated_at,
													last_action,
													last_action_by)

 								 			VALUES( '$quantity[$i]',
	 								 				
	 								 				'$invoice_date',
	 								 				'$sell_item_note[$i]',
	 								 				'$product_id[$i]',
	 								 				'$invoice_inserted_id',
	 								 				'".$_SESSION['user_id']."',
	 								 				'$reg_date',
	 								 				'$reg_date',
	 								 				'$lastaction',
	 								 				'".$_SESSION['user_id']."')";
					$res2 = $db->query($sql2);

					if ($res2) {

						$chek_insertion = true;
						


					}else{
								// echo $db->error;

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

				} // for i


				

				


				if($chek_insertion == true ){

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

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

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

		} // if create

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