<?php
// get these values from your DB.
require_once('config.php');
require_once('f_send_push_notification.php');
require_once('find_online_tablet.php');

$error_message;
$valid = true;


/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
     die( print_r( sqlsrv_errors(), true ));
}


$json = file_get_contents('php://input');

// Converts it into a PHP object
$data = json_decode($json, true);

$site_cd = $data['site_cd'];
$EmpID = $data['EmpID'];
$dvc_id = $data['dvc_id'];



$approval_limit = $data['approval_limit'];
$status = $data['status'];
$remark = $data['remark'];
$mtr_app_rowID = $data['mtr_app_rowID'];
$mtr_mst_rowID = $data['mtr_mst_rowID'];


$header_loop = $data['loop'];
$type = $data['type'];
$count = $data['count'];
$LOGINID = $data['LOGINID'];
$header_audit_date = $data['header_audit_date'];
$Mr_tot_cost = $data['Mr_tot_cost'];
$mtr_mst_mtr_no = $data['mtr_mst_mtr_no'];
$mst_costcenter = $data['mst_costcenter'];
$il_level = $data['cur_app_level'];//il_level
$ll_level = $data['level'];//ll_level
$total_level = $data['app_level'];



$sql_pur_mst ="Select audit_date from pur_mst (NOLOCK)  Where site_cd = ? and  pur_mst_porqnnum = ?";
			
	$params_pur_mst = array($site_cd,$mtr_mst_mtr_no);

	$stmt_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);

	if( !$stmt_pur_mst ) {
		
		 $error_message = "Error selecting mtr_mst";
		 returnError($error_message);
		 die( print_r( sqlsrv_errors(), true));
		 
	}	

	do {
		
		while ($row = sqlsrv_fetch_array($stmt_pur_mst, SQLSRV_FETCH_ASSOC)) {		
		
			$audit_date = $row['audit_date']->format('Y-m-d H:i:s');						
			//echo $audit_date;
		}
		
	} while ( sqlsrv_next_result($stmt_pur_mst) );
	  sqlsrv_free_stmt( $stmt_pur_mst);
			  
if($header_audit_date <> $audit_date){
	 //echo $header_audit_date;
	 //echo $audit_date;
				 
	sqlsrv_rollback( $conn );
	$error_message = "The PR audit date had been changed.~r~nThe record already updated by another user.~r~nPlease cancel and retrieve the record again.";
	returnError($error_message);
				
}else{
	
	
	if($header_loop == "1"){
		
		if($type == "my_level"){
			
			if($count == "1"){
				
				$sql_pur_app = "UPDATE 	pur_app 
								SET 	pur_app_date = getdate(), 
										pur_app_status = ?, 
										pur_app_desc = ?,
										audit_user=? ,
										audit_date=getdate(),
										mbl_audit_user=?,		
										mbl_audit_date=getdate() 
								WHERE 	site_cd=? 
								and 	RowID = ?";
					
				
					$params_pur_app = array($status,$remark,$LOGINID,$LOGINID,$site_cd,$mtr_app_rowID);
					$stmt_pur_app = sqlsrv_query( $conn, $sql_pur_app,$params_pur_app);	
						
					if( !$stmt_pur_app ) {
						$error_message = "Error update table (pur_app)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt($stmt_pur_app);
				
			}
			
			
		}else if($type == "my_limit"){
			
			if($count == "0"){
				
				$sql_insert_pur_app = "	INSERT pur_app 
										(	site_cd ,					mst_RowID ,					pur_app_level ,		pur_app_cost_center , 
											pur_app_empl_id ,			pur_app_pr_limit ,			pur_app_date ,		pur_app_status , 
											pur_app_desc,				pur_app_approval,			audit_user ,	 	audit_date,
											column1,					column2,					column3,			column4,		column5,	mbl_audit_user,mbl_audit_date) 
								VALUES 
										(	?,							?,							?,					?,
											?,							?,							GetDate(),			?,
											?,							NUll,						?,					GetDate(),
											NUll,						NUll,						NUll,				NUll,			NUll,?,					GetDate())";

						$params_pur_app = array($site_cd,$mtr_mst_rowID,$il_level+1,'***',$EmpID,$approval_limit,$status,$remark,$LOGINID,$LOGINID);
						$stmt_pur_app = sqlsrv_query( $conn, $sql_insert_pur_app,$params_pur_app);	
						if( !$stmt_pur_app ) {
						$error_message = "Error (INSERT Table pur_app)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
							
						}
						sqlsrv_free_stmt($stmt_pur_app);
				
			}
				
			
		}
		
		
		
		
		if(($il_level + 1 == $total_level) and ($approval_limit >= $Mr_tot_cost) ){
				//echo 'Last Level in the Approval Route';
				
				//echo '1';
				
					$sql_pur_mst = "UPDATE pur_mst SET 
									pur_mst_purq_approve = 'A', 
									pur_mst_cur_app_level = ?, 
									pur_mst_approver = Null,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and RowID = ?";
					
					
					$params_pur_mst = array($il_level +1 ,$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID);
					$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);	
							
					if( !$stmt_update_pur_mst ) {
						$error_message = "Error update table (pur_mst)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_mst);
					
					
					
					$sql_pur_app = "UPDATE pur_app SET 
									pur_app_date = GetDate() ,
									pur_app_status = 'Y',
									pur_app_desc = '** Auto Approved ***',									
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and mst_rowid = ?
									AND	pur_app_level = ? 
									AND	pur_app_status = 'P' ";
					
					
					$params_pur_app = array($LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID,$il_level +1);
					$stmt_update_pur_app = sqlsrv_query( $conn, $sql_pur_app,$params_pur_app);	
							
					if( !$stmt_update_pur_app ) {
						$error_message = "Error update table (pur_mst)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_app);
		
		
				
				
		} else if(($il_level + 1 > $total_level) and ($approval_limit >= $Mr_tot_cost)){
				//echo 'Additional Level from Global Limit';
				
				
					$sql_pur_mst = "UPDATE pur_mst SET 
										pur_mst_purq_approve = 'A', 
										pur_mst_app_level = ?, 
										pur_mst_cur_app_level=?,
										pur_mst_approver = Null,
										audit_user=? ,
										audit_date=getdate(),
										mbl_audit_user=?,		
										mbl_audit_date=getdate() 
										WHERE site_cd=? 
										and RowID = ?";
						
						
						$params_pur_mst = array($il_level +1 ,$il_level +1,$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID);
						$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);	
								
						if( !$stmt_update_pur_mst ) {
							$error_message = "Error update table (pur_mst)";
							returnError($error_message);
							die( print_r( sqlsrv_errors(), true));
						}sqlsrv_free_stmt( $stmt_update_pur_mst);
					
					
				
		}else if(($il_level + 1 == $total_level) and ($approval_limit < $Mr_tot_cost)){
						//echo 'Approval Route Final Level but Limit Not enough';
				
				
				
						$sql_emp_mst ="SELECT	TOP 1 emp_mst_empl_id
									FROM	emp_mst (NOLOCK), emp_det  (NOLOCK)
									WHERE	emp_mst.site_cd = emp_det.site_cd
									AND		emp_mst.RowID = emp_det.mst_RowID
									AND		emp_mst.site_cd = ?
									AND		emp_det.emp_det_pr_approver = '1'
									AND		emp_det_pr_approval_limit >= ?
								ORDER BY	emp_det_pr_approval_limit Asc,emp_mst_empl_id Asc ;";
					
					$params_emp_mst = array($site_cd,$Mr_tot_cost);

					$stmt_emp_mst = sqlsrv_query( $conn,$sql_emp_mst,$params_emp_mst);

					if( !$stmt_emp_mst ) {
						
						 $error_message = "Error selecting mtr_mst";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
						 
					}	

					do {
						
						while ($row = sqlsrv_fetch_array($stmt_emp_mst, SQLSRV_FETCH_ASSOC)) {		
						
							$emp_mst_empl_id = $row['emp_mst_empl_id'];						
						
						}
						
					} while ( sqlsrv_next_result($stmt_emp_mst) );
					  sqlsrv_free_stmt( $stmt_emp_mst);  
					  
					  
					  $sql_pur_mst = "UPDATE pur_mst SET 
									pur_mst_purq_approve = 'L', 
									pur_mst_cur_app_level = ?, 									
									pur_mst_approver = ?,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and RowID = ?";
					
					
					$params_pur_mst = array($il_level +1 ,$emp_mst_empl_id,$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID);
					$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);		
							
					if( !$stmt_update_pur_mst ) {
						$error_message = "Error update table (mtr_mst)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_mst);
					
					
					
				
		}else if(($il_level + 1 < $total_level)){
				//echo 'Total Level 3.. The current Approval Level is at Level 2';
				
				
				$sql_pur_app = "UPDATE pur_app SET 
									pur_app_date = GetDate() ,
									pur_app_status = 'Y',
									pur_app_desc = ?,	
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and mst_rowid = ?
									and pur_app_level = ?
									and pur_app_status = 'P'";
					
					
					$params_pur_app = array('** Approved ***',$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID,$il_level +1);
					$stmt_update_pur_app = sqlsrv_query( $conn, $sql_pur_app,$params_pur_app);		
							
					if( !$stmt_update_pur_app ) {
						$error_message = "Error update table (pur_app)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_app);
					
					
				
				
				$sql_pur_app ="SELECT	ll_empl_cnt = Count(pur_app_empl_id), ls_approver = Min(pur_app_empl_id)
									FROM	pur_app (NOLOCK)
									WHERE	site_cd = ?
									AND		mst_rowid = ?
									AND		pur_app_level= ?";
					
					$params_pur_app = array($site_cd,$mtr_mst_rowID,$il_level +2);

					$stmt_select_pur_app = sqlsrv_query( $conn, $sql_pur_app,$params_pur_app);	

					if( !$stmt_select_pur_app ) {
						
						 $error_message = "Error selecting mtr_mst";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
						 
					}	

					do {
						
						while ($row = sqlsrv_fetch_array($stmt_select_pur_app, SQLSRV_FETCH_ASSOC)) {		
						
							$ll_empl_cnt = $row['ll_empl_cnt'];		
							$ls_approver = $row['ls_approver'];

									//echo $ll_empl_cnt ;		
									//echo $ls_approver ;											
						
						}
						
					} while ( sqlsrv_next_result($stmt_select_pur_app) );
					  sqlsrv_free_stmt( $stmt_select_pur_app);  
					
					if($ll_empl_cnt == 1){
						
						$sql_pur_mst = "UPDATE pur_mst SET 
										pur_mst_purq_approve = 'N', 
										pur_mst_cur_app_level = ?,
										pur_mst_approver = ?,
										audit_user=? ,
										audit_date=getdate(),
										mbl_audit_user=?,		
										mbl_audit_date=getdate() 
										WHERE site_cd=? 
										and RowID = ?";
					
					
							$params_pur_mst = array($il_level +1,$ls_approver,$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID);
							//echo '<pre>'; print_r(array_merge_recursive($params_mtr_mst)); echo '</pre>'	;		
							$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);		
									
							if( !$stmt_update_pur_mst ) {
								$error_message = "Error update table (pur_mst =1)";
								returnError($error_message);
								die( print_r( sqlsrv_errors(), true));
							}sqlsrv_free_stmt( $stmt_update_pur_mst);
							
							$sql_header ="Select	pur_mst.pur_mst_porqnnum,   
													pur_mst.pur_mst_requested_by,      
													pur_mst.pur_mst_req_date,    
													pur_mst.pur_mst_chg_costcenter,   
													pur_mst.pur_mst_chg_account,   
													pur_mst.pur_mst_tot_cost,
													pur_mst.pur_mst_purq_approve,   
													pur_mst.pur_mst_notes
											FROM 	pur_mst (NOLOCK)
											WHERE 	pur_mst.site_cd = '".$site_cd."'
											and		pur_mst.RowID = '".$mtr_mst_rowID."'";

							$stmt_header = sqlsrv_query( $conn, $sql_header);

							if( !$stmt_header ) {
								
								 $error_message = "Error selecting pur_mst";
								 returnError($error_message);
								 die( print_r( sqlsrv_errors(), true));
								 
							}
							do {
								
								while ($row = sqlsrv_fetch_array($stmt_header, SQLSRV_FETCH_ASSOC)) {		
								
										$pur_mst_porqnnum = $row['pur_mst_porqnnum'];	
										$pur_mst_requested_by = $row['pur_mst_requested_by'];	
										$pur_mst_req_date = $row['pur_mst_req_date'];	
										$pur_mst_chg_costcenter = $row['pur_mst_chg_costcenter'];	
										$pur_mst_chg_account = $row['pur_mst_chg_account'];	
										$pur_mst_tot_cost = $row['pur_mst_tot_cost'];	
										$pur_mst_notes = $row['pur_mst_notes'];	
								
								}
								
							} while ( sqlsrv_next_result($stmt_header) );
							
							//Insert notification_log 
							$title = "PR Require approval";
							$body = "The Purchase Request ".$pur_mst_porqnnum." require your approval.";
							$module = "Purchase Request";
							$message ="PR No:".$pur_mst_porqnnum." 
							\r\nPR Amount:".$pur_mst_tot_cost."
							\r\nRequester:".$pur_mst_requested_by."
							\r\nRequest Date:".$pur_mst_req_date.".
							\r\nCost Center:".$pur_mst_chg_costcenter."
							\r\nAccount:".$pur_mst_chg_account."
							\r\nNotes:".$pur_mst_notes."";
							
							
							insert_notification_log($site_cd, $EmpID, $ls_approver, $pur_mst_porqnnum, $title, $body, $message, $module, $dvc_id, $LOGINID);
	
						
					}else if($ll_empl_cnt > 1){
						
						
						$sql_pur_mst = "UPDATE pur_mst SET 
									pur_mst_purq_approve = 'N', 
									pur_mst_cur_app_level = ?,
									pur_mst_approver = ?,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and RowID = ?";
					
					
							$params_pur_mst = array($il_level +1,$ls_approver+ '...',$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID);
							$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);	
									
							if( !$stmt_update_pur_mst ) {
								$error_message = "Error update table (pur_mst >1)";
								returnError($error_message);
								die( print_r( sqlsrv_errors(), true));
							}sqlsrv_free_stmt( $stmt_update_pur_mst);
					
					
						
					}else if($ll_empl_cnt == 0){
						
						
						$sql_pur_mst = "UPDATE pur_mst SET 
									pur_mst_purq_approve = 'N' ,
									pur_mst_cur_app_level = ?,
									pur_mst_approver = ?,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and RowID = ?";
					
					
							$params_pur_mst = array($il_level +1,Null,$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID);
							$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);	
									
							if( !$stmt_update_pur_mst ) {
								$error_message = "Error update table (pur_mst ==0)";
								returnError($error_message);
								die( print_r( sqlsrv_errors(), true));
							}sqlsrv_free_stmt( $stmt_update_pur_mst);
					
						
					}				
					
					
		}
		
		
		
		
	}else{
		//open loop (0)
		
		
		if($type == "my_level"){
			
			if($count == "1"){
				
				$sql_mtr_app = "UPDATE 	pur_app 
								SET 	pur_app_date = getdate(), 
										pur_app_status = ?, 
										pur_app_desc = ?,
										audit_user=? ,
										audit_date=getdate(),
										mbl_audit_user=?,		
										mbl_audit_date=getdate()  
								WHERE 	site_cd=? 
								and 	RowID = ?";
					
				
					$params_mtr_app = array($status,$remark,$LOGINID,$LOGINID,$site_cd,$mtr_app_rowID);
					$stmt_mtr_app = sqlsrv_query( $conn, $sql_mtr_app,$params_mtr_app);	
						
					if( !$stmt_mtr_app ) {
						$error_message = "Error update table (wko_sts)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_mtr_app);
				
			}
			
		}else if($type == "my_limit"){
			
			if($count == "0"){
				
				$sql_insert_pur_app = "	INSERT pur_app 
										(	site_cd ,					mst_RowID ,					pur_app_level ,		pur_app_cost_center , 
											pur_app_empl_id ,			pur_app_pr_limit ,			pur_app_date ,		pur_app_status , 
											pur_app_desc,				pur_app_approval,			audit_user ,	 	audit_date,
											column1,					column2,					column3,			column4,		column5,mbl_audit_user,mbl_audit_date) 
								VALUES 
										(	?,							?,							?,					?,
											?,							?,							GetDate(),			?,
											?,							NUll,						?,					GetDate(),
											NUll,						NUll,						NUll,				NUll,			NUll,?,					GetDate())";

						$params_pur_app = array($site_cd,$mtr_mst_rowID,$il_level+1,'***',$EmpID,$approval_limit,$status,$remark,$LOGINID,$LOGINID);
						$stmt_pur_app = sqlsrv_query( $conn, $sql_insert_pur_app,$params_pur_app);	
						if( !$stmt_pur_app ) {
						$error_message = "Error (INSERT Table pur_app)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
							
						}
						sqlsrv_free_stmt($stmt_pur_app);
				
			}
			
			
		}else if($type == "all_level"){
			
			if($count == "1"){
				
				$sql_mtr_app = "UPDATE 	pur_app 
								SET 	pur_app_date = getdate(), 
										pur_app_status = ?, 
										pur_app_desc = ?,
										audit_user=? ,
										audit_date=getdate(),
										mbl_audit_user=?,		
										mbl_audit_date=getdate()  
								WHERE 	site_cd=? 
								and 	RowID = ?";
					
				
					$params_mtr_app = array($status,$remark,$LOGINID,$LOGINID,$site_cd,$mtr_app_rowID);
					$stmt_mtr_app = sqlsrv_query( $conn, $sql_mtr_app,$params_mtr_app);	
						
					if( !$stmt_mtr_app ) {
						$error_message = "Error update table (wko_sts)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_mtr_app);
				
			}
			
			
			
			
		}
		
		
		
		if(($ll_level == $total_level) and ($approval_limit >= $Mr_tot_cost) ){
				//echo 'Last Level in the Approval Route';
				
				//echo '1';
				
					$sql_pur_mst = "UPDATE pur_mst SET 
									pur_mst_purq_approve = 'A', 
									pur_mst_cur_app_level = ?, 
									pur_mst_approver = Null,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and RowID = ?";
					
					
					$params_pur_mst = array($ll_level ,$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID);
					$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);	
							
					if( !$stmt_update_pur_mst ) {
						$error_message = "Error update table (pur_mst)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_mst);
					
					
					$sql_pur_app = "UPDATE pur_app SET 
									pur_app_date = GetDate() ,
									pur_app_status = 'Y',
									pur_app_desc=?,									
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and mst_RowID = ?
									AND	pur_app_level <= ?
									AND	pur_app_status = 'P' ";
					
					
					$params_pur_app = array('** Auto Approved ***',$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID,$ll_level);
					$stmt_update_pur_app = sqlsrv_query( $conn, $sql_pur_app,$params_pur_app);	
							
					if( !$stmt_update_pur_app ) {
						$error_message = "Error update table (mtr_ls1)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_app);
					
					
					
		
				
				
		} else if(($ll_level > $total_level) and ($approval_limit >= $Mr_tot_cost)){
				//echo 'Additional Level from Global Limit';
				//echo '2';
				
				
				$sql_pur_mst = "UPDATE pur_mst SET 
									pur_mst_purq_approve = 'A',
									pur_mst_app_level = ?, 									
									pur_mst_cur_app_level = ?, 
									pur_mst_approver = Null,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and RowID = ?";
					
					
					$params_pur_mst = array($ll_level,$ll_level ,$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID);
					$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);	
							
					if( !$stmt_update_pur_mst ) {
						$error_message = "Error update table (pur_mst)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_mst);
					
					
					$sql_pur_app = "UPDATE pur_app SET 
									pur_app_date = GetDate() ,
									pur_app_status = 'Y',
									pur_app_desc=?,									
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and mst_RowID = ?
									AND	pur_app_level <= ?
									AND	pur_app_status = 'P' ";
					
					
					$params_pur_app = array('** Auto Approved ***',$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID,$ll_level);
					$stmt_update_pur_app = sqlsrv_query( $conn, $sql_pur_app,$params_pur_app);	
							
					if( !$stmt_update_pur_app ) {
						$error_message = "Error update table (mtr_ls1)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_app);
					
					
					
					
					
				
		}else if(($ll_level == $total_level) and ($approval_limit < $Mr_tot_cost)){
				//echo 'Approval Route Final Level but Limit Not enough';
				//echo '3';
				
				
						$sql_emp_mst ="SELECT	TOP 1 emp_mst_empl_id
									FROM	emp_mst (NOLOCK), emp_det  (NOLOCK)
									WHERE	emp_mst.site_cd = emp_det.site_cd
									AND		emp_mst.RowID = emp_det.mst_RowID
									AND		emp_mst.site_cd = ?
									AND		emp_det.emp_det_pr_approver = '1'
									AND		emp_det_pr_approval_limit >= ?
								ORDER BY	emp_det_pr_approval_limit Asc,emp_mst_empl_id Asc ;";
					
					$params_emp_mst = array($site_cd,$Mr_tot_cost);

					$stmt_emp_mst = sqlsrv_query( $conn,$sql_emp_mst,$params_emp_mst);

					if( !$stmt_emp_mst ) {
						
						 $error_message = "Error selecting mtr_mst";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
						 
					}	

					do {
						
						while ($row = sqlsrv_fetch_array($stmt_emp_mst, SQLSRV_FETCH_ASSOC)) {		
						
							$emp_mst_empl_id = $row['emp_mst_empl_id'];						
						
						}
						
					} while ( sqlsrv_next_result($stmt_emp_mst) );
					  sqlsrv_free_stmt( $stmt_emp_mst);  
					  
					  
					  $sql_pur_mst = "UPDATE pur_mst SET 
									pur_mst_purq_approve = 'L', 
									pur_mst_cur_app_level = ?, 									
									pur_mst_approver = ?,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and RowID = ?";
					
					
					$params_pur_mst = array($ll_level,$emp_mst_empl_id,$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID);
					$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);		
							
					if( !$stmt_update_pur_mst ) {
						$error_message = "Error update table (mtr_mst)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_mst);
					
						
						
						$sql_pur_app = "UPDATE pur_app SET 
									pur_app_date = GetDate(),
									pur_app_status = 'Y',
									pur_app_desc = ?,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									AND mst_rowid = ?
									AND	pur_app_level <= ?
									AND	pur_app_status = 'P'";					
					
					$params_pur_app = array('** Approved ***',$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID,$ll_level);
					$stmt_update_pur_app = sqlsrv_query( $conn, $sql_pur_app,$params_pur_app);	
							
					if( !$stmt_update_pur_app ) {
						$error_message = "Error update table (pur_app)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_app);
					
					
					
				
		}else if(($ll_level < $total_level) and ($approval_limit < $Mr_tot_cost) ){
				//echo 'Total Level 3.. The current Approval Level is at Level 2';
				//echo '4';
				
				$sql_pur_app = "UPDATE pur_app SET 
									pur_app_date = GetDate(),
									pur_app_status = 'Y',
									pur_app_desc = ?,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									AND mst_rowid = ?
									AND	pur_app_level <= ?
									AND	pur_app_status = 'P'";					
					
					$params_pur_app = array('** Approved ***',$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID,$ll_level);
					$stmt_update_pur_app = sqlsrv_query( $conn, $sql_pur_app,$params_pur_app);	
							
					if( !$stmt_update_pur_app ) {
						$error_message = "Error update table (pur_app)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_app);
					
					
				
				
				$sql_pur_app ="SELECT	ll_empl_cnt = Count(pur_app_empl_id), ls_approver = Min(pur_app_empl_id)
									FROM	pur_app (NOLOCK)
									WHERE	site_cd = ?
									AND		mst_rowid = ?
									AND		pur_app_level= ?";
					
					$params_pur_app = array($site_cd,$mtr_mst_rowID,$ll_level +1);

					$stmt_select_pur_app = sqlsrv_query( $conn, $sql_pur_app,$params_pur_app);	

					if( !$stmt_select_pur_app ) {
						
						 $error_message = "Error selecting mtr_mst";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
						 
					}	

					do {
						
						while ($row = sqlsrv_fetch_array($stmt_select_pur_app, SQLSRV_FETCH_ASSOC)) {		
						
							$ll_empl_cnt = $row['ll_empl_cnt'];		
							$ls_approver = $row['ls_approver'];

									//echo $ll_empl_cnt ;		
									//echo $ls_approver ;											
						
						}
						
					} while ( sqlsrv_next_result($stmt_select_pur_app) );
					  sqlsrv_free_stmt( $stmt_select_pur_app);  
					
					if($ll_empl_cnt == 1){
						
						$sql_pur_mst = "UPDATE pur_mst SET 
									pur_mst_purq_approve = 'N', 
									pur_mst_cur_app_level = ?,
									pur_mst_approver = ?,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and RowID = ?";
					
					
							$params_pur_mst = array($ll_level,$ls_approver,$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID);
							//echo '<pre>'; print_r(array_merge_recursive($params_mtr_mst)); echo '</pre>'	;		
							$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);		
									
							if( !$stmt_update_pur_mst ) {
								$error_message = "Error update table (mtr_mst =1)";
								returnError($error_message);
								die( print_r( sqlsrv_errors(), true));
							}sqlsrv_free_stmt( $stmt_update_pur_mst);$sql_header ="Select	pur_mst.pur_mst_porqnnum,   
													pur_mst.pur_mst_requested_by,      
													pur_mst.pur_mst_req_date,    
													pur_mst.pur_mst_chg_costcenter,   
													pur_mst.pur_mst_chg_account,   
													pur_mst.pur_mst_tot_cost,
													pur_mst.pur_mst_purq_approve,   
													pur_mst.pur_mst_notes
											FROM 	pur_mst (NOLOCK)
											WHERE 	pur_mst.site_cd = '".$site_cd."'
											and		pur_mst.RowID = '".$mtr_mst_rowID."'";

							$stmt_header = sqlsrv_query( $conn, $sql_header);

							if( !$stmt_header ) {
								
								 $error_message = "Error selecting pur_mst";
								 returnError($error_message);
								 die( print_r( sqlsrv_errors(), true));
								 
							}
							do {
								
								while ($row = sqlsrv_fetch_array($stmt_header, SQLSRV_FETCH_ASSOC)) {		
								
										$pur_mst_porqnnum = $row['pur_mst_porqnnum'];	
										$pur_mst_requested_by = $row['pur_mst_requested_by'];	
										$pur_mst_req_date = $row['pur_mst_req_date'];	
										$pur_mst_chg_costcenter = $row['pur_mst_chg_costcenter'];	
										$pur_mst_chg_account = $row['pur_mst_chg_account'];	
										$pur_mst_tot_cost = $row['pur_mst_tot_cost'];	
										$pur_mst_notes = $row['pur_mst_notes'];	
								
								}
								
							} while ( sqlsrv_next_result($stmt_header) );
							
							//Insert notification_log 
							$title = "PR Require approval";
							$body = "The Purchase Request ".$pur_mst_porqnnum." require your approval.";
							$module = "Purchase Request";
							$message_withdraw ="PR No:".$pur_mst_porqnnum." 
							\r\nPR Amount:".$pur_mst_tot_cost."
							\r\nRequester:".$pur_mst_requested_by."
							\r\nRequest Date:".$pur_mst_req_date.".
							\r\nCost Center:".$pur_mst_chg_costcenter."
							\r\nAccount:".$pur_mst_chg_account."
							\r\nNotes:".$pur_mst_notes."";
							
							$insert_ntf1 = insert_notification_log($site_cd, $EmpID, $ls_approver, $pur_mst_porqnnum, $title, $body, $message_withdraw, $module, 'exynos850', $LOGINID);
							
							// foreach($insert_ntf1 as $x => $val) {
			
								// $row = $x = $val["row"];
								// $insert_ntf = $x = $val["insert_ntf"];
								
								// //echo '<pre>'; print_r($row); echo '</pre>';
								// //echo '<pre>'; print_r($insert_ntf); echo '</pre>';		
								
							
							// }
	
	
							//Get New Value Assignto Online Token
							$tkn_token_1 = get_online($ls_approver, $site_cd);
							
							//echo '<pre>'; print_r($tkn_token_1); echo '</pre>';
							
							//Notify token user
							if (sizeof($tkn_token_1) > 0){		
		
		
								foreach($tkn_token_1 as $x => $val) {			
									$tokenlist = $x = $val["token"];
									$RowID = $x = $val["RowID"];
									$tkn_site = $x = $val["tkn_site"];
									
									//echo '<pre>'; print_r($tkn_site); echo '</pre>';
									//echo '<pre>'; print_r($RowID); echo '</pre>';			
									
									push_notification_android( $tokenlist,'PR Require approval',"The Purchase Request ".$pur_mst_porqnnum." require your approval.",$site_cd,$tokenlist,$RowID,$row,$tkn_site,$LOGINID);			
									
								
								}		
								
							}
							
							
							
							
						
					}else if($ll_empl_cnt > 1){
						
						
						$sql_pur_mst = "UPDATE pur_mst SET 
									pur_mst_purq_approve = 'N', 
									pur_mst_cur_app_level = ?,
									pur_mst_approver = ?,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and RowID = ?";
					
					
							$params_pur_mst = array($ll_level,$ls_approver + '...',$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID);
							//echo '<pre>'; print_r(array_merge_recursive($params_mtr_mst)); echo '</pre>'	;		
							$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);		
									
							if( !$stmt_update_pur_mst ) {
								$error_message = "Error update table (mtr_mst =1)";
								returnError($error_message);
								die( print_r( sqlsrv_errors(), true));
							}sqlsrv_free_stmt( $stmt_update_pur_mst);
							
							
						
					}else if($ll_empl_cnt == 0){
						
						
						$sql_pur_mst = "UPDATE pur_mst SET 
									pur_mst_purq_approve = 'N', 
									pur_mst_cur_app_level = ?,
									pur_mst_approver = Null,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and RowID = ?";
					
					
							$params_pur_mst = array($ll_level,$ls_approver,$LOGINID,$site_cd,$mtr_mst_rowID);
							//echo '<pre>'; print_r(array_merge_recursive($params_mtr_mst)); echo '</pre>'	;		
							$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);		
									
							if( !$stmt_update_pur_mst ) {
								$error_message = "Error update table (mtr_mst =1)";
								returnError($error_message);
								die( print_r( sqlsrv_errors(), true));
							}sqlsrv_free_stmt( $stmt_update_pur_mst);
							
							
							
						
						
					}
					
					
					
		}else if(($ll_level < $total_level) and ($approval_limit >= $Mr_tot_cost) ){
			
			//echo'5';
			
			
					$sql_pur_mst = "UPDATE pur_mst SET 
									pur_mst_purq_approve = 'A', 
									pur_mst_cur_app_level = ?, 									
									pur_mst_approver = ?,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									and RowID = ?";
					
					
					$params_pur_mst = array($ll_level,Null,$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID);
					$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);		
							
					if( !$stmt_update_pur_mst ) {
						$error_message = "Error update table (mtr_mst)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_mst);
					
						
						
						$sql_pur_app = "UPDATE pur_app SET 
									pur_app_date = GetDate(),
									pur_app_status = 'Y',
									pur_app_desc = ?,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									AND mst_rowid = ?
									AND	pur_app_level <= ?
									AND	pur_app_status = 'P'";					
					
					$params_pur_app = array('** Auto Approved ***',$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID,$ll_level);
					$stmt_update_pur_app = sqlsrv_query( $conn, $sql_pur_app,$params_pur_app);	
							
					if( !$stmt_update_pur_app ) {
						$error_message = "Error update table (pur_app)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_app);
					
					
					
					
					$sql_pur_app = "UPDATE pur_app SET 
									pur_app_date = GetDate(),
									pur_app_status = 'Y',
									pur_app_desc = ?,
									audit_user=? ,
									audit_date=getdate(),
									mbl_audit_user=?,		
									mbl_audit_date=getdate() 
									WHERE site_cd=? 
									AND mst_rowid = ?
									AND	pur_app_level > ?
									AND	pur_app_status = 'P'";					
					
					$params_pur_app = array('** Auto Approved ***',$LOGINID,$LOGINID,$site_cd,$mtr_mst_rowID,$ll_level);
					$stmt_update_pur_app1 = sqlsrv_query( $conn, $sql_pur_app,$params_pur_app);	
							
					if( !$stmt_update_pur_app1 ) {
						$error_message = "Error update table (pur_app)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}sqlsrv_free_stmt( $stmt_update_pur_app1);
					
			
		}
		
		
		
	}
	
}
	



if($stmt_pur_mst){
	
	if($header_audit_date <> $audit_date){
				 
				
			
	}else{
		
		if($header_loop == "1"){
			//il_level
			if(($il_level + 1 == $total_level) and ($approval_limit >= $Mr_tot_cost) ){
									
				if($stmt_update_pur_mst && $stmt_update_pur_app){
					 sqlsrv_commit( $conn );
					 sqlsrv_close( $conn);	
					 returnData();
			
				}else{
					sqlsrv_rollback( $conn );
					$error_message = "Transaction rolled back.<br />";
					returnError($error_message);
				}
				
			}else if(($il_level + 1 > $total_level) and ($approval_limit >= $Mr_tot_cost)){
				
				if($stmt_update_pur_mst){
					 sqlsrv_commit( $conn );
					 sqlsrv_close( $conn);	
					 returnData();
					
				}else{
					sqlsrv_rollback( $conn );
					$error_message = "Transaction rolled back.<br />";
					returnError($error_message);
				}
				
			}else if(($il_level + 1 == $total_level) and ($approval_limit < $Mr_tot_cost)){
				
				if($stmt_emp_mst && $stmt_update_pur_mst){
					 sqlsrv_commit( $conn );
					 sqlsrv_close( $conn);	
					 returnData();
					
				}else{
					sqlsrv_rollback( $conn );
					$error_message = "Transaction rolled back.<br />";
					returnError($error_message);
				}
				
			}else if(($il_level + 1 < $total_level)){
				
				if($stmt_update_pur_app && $stmt_select_pur_app){
					
					if($ll_empl_cnt == 1){
						if($stmt_update_pur_mst){
							 sqlsrv_commit( $conn );
							 sqlsrv_close( $conn);	
							 returnData();
					
						}else{
							sqlsrv_rollback( $conn );
							$error_message = "Transaction rolled back.<br />";
							returnError($error_message);
						}
					}else if($ll_empl_cnt > 1){
						if($stmt_update_pur_mst){
							 sqlsrv_commit( $conn );
							 sqlsrv_close( $conn);	
							 returnData();
					
						}else{
							sqlsrv_rollback( $conn );
							$error_message = "Transaction rolled back.<br />";
							returnError($error_message);
						}
					}else if($ll_empl_cnt == 0){
						if($stmt_update_pur_mst){
							 sqlsrv_commit( $conn );
							 sqlsrv_close( $conn);	
							 returnData();
					
						}else{
							sqlsrv_rollback( $conn );
							$error_message = "Transaction rolled back.<br />";
							returnError($error_message);
						}
					}
					
				}else{
					sqlsrv_rollback( $conn );
					$error_message = "Transaction rolled back.<br />";
					returnError($error_message);
				}
			}
			
			
		}else{
			
			if(($ll_level == $total_level) and ($approval_limit >= $Mr_tot_cost) ){
								
				if($stmt_update_pur_mst && $stmt_update_pur_app){
					
						 sqlsrv_commit( $conn );
						 sqlsrv_close( $conn);	
						 returnData();
				}else{
						 sqlsrv_rollback( $conn );
						 $error_message = "Transaction rolled back.<br />";
						 returnError($error_message);
				}
				
			}else if(($ll_level > $total_level) and ($approval_limit >= $Mr_tot_cost)){
				
				if($stmt_update_pur_mst && $stmt_update_pur_app){
					
						 sqlsrv_commit( $conn );
						 sqlsrv_close( $conn);	
						 returnData();
				}else{
						 sqlsrv_rollback( $conn );
						 $error_message = "Transaction rolled back.<br />";
						 returnError($error_message);
				}
				
			}else if(($ll_level == $total_level) and ($approval_limit < $Mr_tot_cost)){
				
				if($stmt_emp_mst && $stmt_update_pur_mst && $stmt_update_pur_app){
					
						 sqlsrv_commit( $conn );
						 sqlsrv_close( $conn);	
						 returnData();
				}else{
						 sqlsrv_rollback( $conn );
						 $error_message = "Transaction rolled back.<br />";
						 returnError($error_message);
				}
				
			}else if(($ll_level < $total_level) and ($approval_limit < $Mr_tot_cost) ){
				
				if($stmt_update_pur_app && $stmt_select_pur_app){
					
					if($ll_empl_cnt == 1){
							if($stmt_update_pur_mst){
								 sqlsrv_commit( $conn );
								 sqlsrv_close( $conn);	
								 returnData();
						
							}else{
								sqlsrv_rollback( $conn );
								$error_message = "Transaction rolled back.<br />";
								returnError($error_message);
							}
						}else if($ll_empl_cnt > 1){
							if($stmt_update_pur_mst){
								 sqlsrv_commit( $conn );
								 sqlsrv_close( $conn);	
								 returnData();
						
							}else{
								sqlsrv_rollback( $conn );
								$error_message = "Transaction rolled back.<br />";
								returnError($error_message);
							}
						}else if($ll_empl_cnt == 0){
							if($stmt_update_pur_mst){
								 sqlsrv_commit( $conn );
								 sqlsrv_close( $conn);	
								 returnData();
						
							}else{
								sqlsrv_rollback( $conn );
								$error_message = "Transaction rolled back.<br />";
								returnError($error_message);
							}
						}
					
					
				}else{
						 sqlsrv_rollback( $conn );
						 $error_message = "Transaction rolled back.<br />";
						 returnError($error_message);
				}
				
			}else if(($ll_level < $total_level) and ($approval_limit >= $Mr_tot_cost) ){
				
				if($stmt_update_pur_mst && $stmt_update_pur_app && $stmt_update_pur_app1){
					
						 sqlsrv_commit( $conn );
						 sqlsrv_close( $conn);	
						 returnData();
				}else{
						 sqlsrv_rollback( $conn );
						 $error_message = "Transaction rolled back.<br />";
						 returnError($error_message);
				}
			}
		}		
		
		
}
	
}else{
	sqlsrv_rollback( $conn );
	$error_message = "Transaction rolled back.<br />";
	returnError($error_message);
	
}

function returnData(){
	$returnData = array(
		'status' => 'SUCCESS',
		'message' => 'The Purchase Request Successfully Approved.');
	echo json_encode($returnData);
}

function returnError($error_message){
	$json = array();
	
	$returnData = array(
	'status' => 'ERROR',
	'message' => $error_message);
	
	echo json_encode($returnData);
		
}


 
?>