<?php
// get these values from your DB.
require_once('config.php');
require_once('f_send_push_notification.php');
require_once('find_online_tablet.php');
require_once('f_send_email_notification.php');
require_once('f_update_purchase_budget.php');
require_once('f_generate_po.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'];
$pur_app_rowID = $data['pur_app_rowID'];
$pur_mst_rowID = $data['pur_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'];
$pur_mst_porqnnum = $data['pur_mst_porqnnum'];
$mst_costcenter = $data['mst_costcenter'];
$il_level = $data['cur_app_level'];//il_level
$ll_level = $data['level'];//ll_level
$total_level = $data['app_level'];

$dft_mst_pur_email_approver = $data['dft_mst_pur_email_approver'];
$dft_mst_pur_email_requestor = $data['dft_mst_pur_email_requestor'];
$dft_mst_generate_po = $data['dft_mst_generate_po'];

//Get PR Information
$ls_requester = array();

$sql_get_pr_info = "Select pur_mst_porqnnum,
							pur_mst_requested_by,
							pur_mst_rqn_date,
							pur_mst_chg_costcenter,
							pur_mst_chg_account,
							pur_mst_crd_costcenter,
							pur_mst_crd_account,
							pur_mst_projectid,
							pur_mst_sub_tot_cost
		From 	pur_mst (NOLOCK)
		Where 	site_cd ='" . $site_cd . "'
		AND		pur_mst.rowid = ".$pur_mst_rowID;
		
$stmt_get_pr_info = sqlsrv_query($conn, $sql_get_pr_info);

if ($stmt_get_pr_info === false)
{
	$error_message = "Error selecting pur_mst";
	 returnError($error_message);
	 die( print_r( sqlsrv_errors(), true));
	
}

do
{
	while ($row = sqlsrv_fetch_array($stmt_get_pr_info, SQLSRV_FETCH_ASSOC))
	{

		$ls_pr_no = $row['pur_mst_porqnnum'];
		$ls_requester[] = $row['pur_mst_requested_by'];
		$ldt_pr_date = $row['pur_mst_rqn_date'];
		$ls_chg_costcenter = $row['pur_mst_chg_costcenter'];
		$ls_chg_account = $row['pur_mst_chg_account'];
		$ls_crd_costcenter = $row['pur_mst_crd_costcenter'];
		$ls_crd_account = $row['pur_mst_crd_account'];
		$ls_project = $row['pur_mst_projectid'];
		$ldc_pr_cost = $row['pur_mst_sub_tot_cost'];

	}
}
while (sqlsrv_next_result($stmt_get_pr_info));
sqlsrv_free_stmt($stmt_get_pr_info);

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

$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. The record already updated by another user. Please 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,$pur_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,$pur_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,$pur_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,$pur_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);
		
		
					if ($dft_mst_pur_email_requestor == "1"){
						$title = "Purchase Request: ".$ls_pr_no;
						$body = "The Purchase Request: ".$ls_pr_no." had been approved.\r\n\r\nPurchase Request Total Cost: ".$ldc_pr_cost."\r\nPurchase Requested By: ".$ls_requester[0];
						
						send_email($site_cd, $EmpID, $ls_requester, $title, $body, $LOGINID, $ls_pr_no, 'Purchase Request', 'PR Approved', 'Mobile', '', '', '');
					}
					
					If ($dft_mst_generate_po == '1'){
						generate_po($pur_mst_rowID, $site_cd, $LOGINID);	
					}else{
						f_update_purchase_budget($site_cd, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "MINUS_AWA_PR", $ldc_pr_cost, $conn, $LOGINID);
						f_update_purchase_budget($site_cd, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "ADD_PR", $ldc_pr_cost, $conn, $LOGINID);
					}
					//IfIf ($is_generate_po == '1'){ ($is_email_requestor = "1"){
					//	wf_email_requestor("A")
					//}
					
					//If ($is_generate_po == '1'){
					//	wf_generate_po(ll_rowid);
					//}else{
					//	wf_budget_update("APP_PR");
					//}
				
				
		} 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,$pur_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);
					
					
					if ($dft_mst_pur_email_requestor == "1"){
						$title = "Purchase Request: ".$ls_pr_no;
						$body = "The Purchase Request: ".$ls_pr_no." had been approved.\r\n\r\nPurchase Request Total Cost: ".$ldc_pr_cost."\r\nPurchase Requested By: ".$ls_requester[0];
						
						send_email($site_cd, $EmpID, $ls_requester, $title, $body, $LOGINID, $ls_pr_no, 'Purchase Request', 'PR Approved', 'Mobile', '', '', '');
					}
					
					If ($dft_mst_generate_po == '1'){
						generate_po($pur_mst_rowID, $site_cd, $LOGINID);	
					}else{
						f_update_purchase_budget($site_cd, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "MINUS_AWA_PR", $ldc_pr_cost, $conn, $LOGINID);
						f_update_purchase_budget($site_cd, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "ADD_PR", $ldc_pr_cost, $conn, $LOGINID);
					}
					//If ($is_email_requestor = "1"){
					//	wf_email_requestor("A")
					//}
					
					//If ($is_generate_po == '1'){
					//	wf_generate_po(ll_rowid);
					//}else{
					//	wf_budget_update("APP_PR");
					//}
				
		}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,$pur_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,$pur_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,$pur_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,$pur_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,      
													cast(pur_mst.pur_mst_req_date as varchar) as 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 = '".$pur_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) );
							
							// Email Approver
							//wf_email_app(il_RowID, il_level + 2)
							//Get PR Next APP empl_id
							$pur_app_empl_id = array();
							$sql_get_pr_next_app = "SELECT 	pur_app.site_cd,   
														pur_app.mst_RowID,   
														pur_app.pur_app_level,   
														pur_app.pur_app_cost_center,   
														pur_app.pur_app_empl_id,   
														pur_app.pur_app_pr_limit,   
														pur_app.pur_app_date,    
														pur_app.pur_app_status,   
														pur_app.pur_app_approval,   
														emp_det.emp_det_email_id,
														pur_app.RowID 
											FROM 	pur_app,
														emp_mst,
														emp_det
											WHERE	pur_app.site_cd = emp_mst.site_cd
											AND		pur_app.pur_app_empl_id = emp_mst.emp_mst_empl_id
											AND		emp_mst.site_cd = emp_det.site_cd
											AND		emp_mst.RowID = emp_det.mst_RowID
											AND		LEN(emp_det.emp_det_email_id) > 0
											AND		pur_app.site_cd ='" . $site_cd . "'
											AND		pur_app.mst_RowID = ".$pur_mst_rowID."
											AND		pur_app.pur_app_level = ".($il_level + 2);
									
							$stmt_get_pr_next_app = sqlsrv_query($conn, $sql_get_pr_next_app);

							if ($stmt_get_pr_next_app === false)
							{
								$error_message = "Error selecting pur_app";
								 returnError($error_message);
								 die( print_r( sqlsrv_errors(), true));
								
							}

							do
							{
								while ($row = sqlsrv_fetch_array($stmt_get_pr_next_app, SQLSRV_FETCH_ASSOC))
								{

									$pur_app_empl_id[] = $row['pur_app_empl_id'];

								}
							}
							while (sqlsrv_next_result($stmt_get_pr_next_app));
							sqlsrv_free_stmt($stmt_get_pr_next_app);
							
							$title = "Purchase Request: ".$ls_pr_no;
							$body = "Please approve the Purchase Request: ".$ls_pr_no.".\r\n\r\nPurchase Request Total Cost: ".$ldc_pr_cost."\r\nPurchase Requested By: ".$ls_requester[0];
						
							send_email($site_cd, $EmpID, $pur_app_empl_id, $title, $body, $LOGINID, $ls_pr_no, 'Purchase Request', 'PR Approval Next', 'Mobile', '', '', '');
							
							//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,$pur_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);
					
						// Email Approver
						//wf_email_app(il_RowID, il_level + 2)
						//Get PR Next APP empl_id
						$pur_app_empl_id = array();
						$sql_get_pr_next_app = "SELECT 	pur_app.site_cd,   
													pur_app.mst_RowID,   
													pur_app.pur_app_level,   
													pur_app.pur_app_cost_center,   
													pur_app.pur_app_empl_id,   
													pur_app.pur_app_pr_limit,   
													pur_app.pur_app_date,    
													pur_app.pur_app_status,   
													pur_app.pur_app_approval,   
													emp_det.emp_det_email_id,
													pur_app.RowID 
										FROM 	pur_app,
													emp_mst,
													emp_det
										WHERE	pur_app.site_cd = emp_mst.site_cd
										AND		pur_app.pur_app_empl_id = emp_mst.emp_mst_empl_id
										AND		emp_mst.site_cd = emp_det.site_cd
										AND		emp_mst.RowID = emp_det.mst_RowID
										AND		LEN(emp_det.emp_det_email_id) > 0
										AND		pur_app.site_cd ='" . $site_cd . "'
										AND		pur_app.mst_RowID = ".$pur_mst_rowID."
										AND		pur_app.pur_app_level = ".($il_level + 2);
								
						$stmt_get_pr_next_app = sqlsrv_query($conn, $sql_get_pr_next_app);

						if ($stmt_get_pr_next_app === false)
						{
							$error_message = "Error selecting pur_app";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
							
						}

						do
						{
							while ($row = sqlsrv_fetch_array($stmt_get_pr_next_app, SQLSRV_FETCH_ASSOC))
							{

								$pur_app_empl_id[] = $row['pur_app_empl_id'];

							}
						}
						while (sqlsrv_next_result($stmt_get_pr_next_app));
						sqlsrv_free_stmt($stmt_get_pr_next_app);
						
					}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,$pur_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,$pur_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,$pur_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,$pur_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,$pur_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,$pur_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);
					
					if ($dft_mst_pur_email_requestor == "1"){
						$title = "Purchase Request: ".$ls_pr_no;
						$body = "The Purchase Request: ".$ls_pr_no." had been approved.\r\n\r\nPurchase Request Total Cost: ".$ldc_pr_cost."\r\nPurchase Requested By: ".$ls_requester[0];
						
						send_email($site_cd, $EmpID, $ls_requester, $title, $body, $LOGINID, $ls_pr_no, 'Purchase Request', 'PR Approved', 'Mobile', '', '', '');
					}
					
					If ($dft_mst_generate_po == '1'){
						generate_po($pur_mst_rowID, $site_cd, $LOGINID);
					}else{
						f_update_purchase_budget($site_cd, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "MINUS_AWA_PR", $ldc_pr_cost, $conn, $LOGINID);
						f_update_purchase_budget($site_cd, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "ADD_PR", $ldc_pr_cost, $conn, $LOGINID);
					}
					
					// Email Requestor
					//If is_email_requestor = "1" Then
					//	wf_email_requestor("A")
					//End If
					
					// If is_generate_po = '1' Then 
						// wf_generate_po(ll_rowid)
					// Else
						// wf_budget_update("APP_PR")
					// End If
				
		} 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,$pur_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,$pur_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);
					
					
					if ($dft_mst_pur_email_requestor == "1"){
						$title = "Purchase Request: ".$ls_pr_no;
						$body = "The Purchase Request: ".$ls_pr_no." had been approved.\r\n\r\nPurchase Request Total Cost: ".$ldc_pr_cost."\r\nPurchase Requested By: ".$ls_requester[0];
						
						send_email($site_cd, $EmpID, $ls_requester, $title, $body, $LOGINID, $ls_pr_no, 'Purchase Request', 'PR Approved', 'Mobile', '', '', '');
					}
					
					If ($dft_mst_generate_po == '1'){
						generate_po($pur_mst_rowID, $site_cd, $LOGINID);
					}else{
						f_update_purchase_budget($site_cd, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "MINUS_AWA_PR", $ldc_pr_cost, $conn, $LOGINID);
						f_update_purchase_budget($site_cd, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "ADD_PR", $ldc_pr_cost, $conn, $LOGINID);
					}
					// Email Requestor
					//If is_email_requestor = "1" Then
					//	wf_email_requestor("A")
					//End If
					
					// If is_generate_po = '1' Then 
						// wf_generate_po(ll_rowid)
					// Else
						// wf_budget_update("APP_PR")
					// End If
					
				
		}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,$pur_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,$pur_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,$pur_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,$pur_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,$pur_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);
							
							// Email Approver
							//wf_email_app(il_RowID, ll_level + 1) 
							//Get PR Next APP empl_id
							$pur_app_empl_id = array();
							$sql_get_pr_next_app = "SELECT 	pur_app.site_cd,   
														pur_app.mst_RowID,   
														pur_app.pur_app_level,   
														pur_app.pur_app_cost_center,   
														pur_app.pur_app_empl_id,   
														pur_app.pur_app_pr_limit,   
														pur_app.pur_app_date,    
														pur_app.pur_app_status,   
														pur_app.pur_app_approval,   
														emp_det.emp_det_email_id,
														pur_app.RowID 
											FROM 	pur_app,
														emp_mst,
														emp_det
											WHERE	pur_app.site_cd = emp_mst.site_cd
											AND		pur_app.pur_app_empl_id = emp_mst.emp_mst_empl_id
											AND		emp_mst.site_cd = emp_det.site_cd
											AND		emp_mst.RowID = emp_det.mst_RowID
											AND		LEN(emp_det.emp_det_email_id) > 0
											AND		pur_app.site_cd ='" . $site_cd . "'
											AND		pur_app.mst_RowID = ".$pur_mst_rowID."
											AND		pur_app.pur_app_level = ".($ll_level + 1);
									
							$stmt_get_pr_next_app = sqlsrv_query($conn, $sql_get_pr_next_app);

							if ($stmt_get_pr_next_app === false)
							{
								$error_message = "Error selecting pur_app";
								 returnError($error_message);
								 die( print_r( sqlsrv_errors(), true));
								
							}

							do
							{
								while ($row = sqlsrv_fetch_array($stmt_get_pr_next_app, SQLSRV_FETCH_ASSOC))
								{

									$pur_app_empl_id[] = $row['pur_app_empl_id'];

								}
							}
							while (sqlsrv_next_result($stmt_get_pr_next_app));
							sqlsrv_free_stmt($stmt_get_pr_next_app);
						
							$sql_header ="Select	pur_mst.pur_mst_porqnnum,   
													pur_mst.pur_mst_requested_by,      
													cast(pur_mst.pur_mst_req_date as varchar) as 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 = '".$pur_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){
						// Email Approver
						//wf_email_app(il_RowID, ll_level + 1)
						$pur_app_empl_id = array();
						$sql_get_pr_next_app = "SELECT 	pur_app.site_cd,   
													pur_app.mst_RowID,   
													pur_app.pur_app_level,   
													pur_app.pur_app_cost_center,   
													pur_app.pur_app_empl_id,   
													pur_app.pur_app_pr_limit,   
													pur_app.pur_app_date,    
													pur_app.pur_app_status,   
													pur_app.pur_app_approval,   
													emp_det.emp_det_email_id,
													pur_app.RowID 
										FROM 	pur_app,
													emp_mst,
													emp_det
										WHERE	pur_app.site_cd = emp_mst.site_cd
										AND		pur_app.pur_app_empl_id = emp_mst.emp_mst_empl_id
										AND		emp_mst.site_cd = emp_det.site_cd
										AND		emp_mst.RowID = emp_det.mst_RowID
										AND		LEN(emp_det.emp_det_email_id) > 0
										AND		pur_app.site_cd ='" . $site_cd . "'
										AND		pur_app.mst_RowID = ".$pur_mst_rowID."
										AND		pur_app.pur_app_level = ".($ll_level + 1);
								
						$stmt_get_pr_next_app = sqlsrv_query($conn, $sql_get_pr_next_app);

						if ($stmt_get_pr_next_app === false)
						{
							$error_message = "Error selecting pur_app";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
							
						}

						do
						{
							while ($row = sqlsrv_fetch_array($stmt_get_pr_next_app, SQLSRV_FETCH_ASSOC))
							{

								$pur_app_empl_id[] = $row['pur_app_empl_id'];

							}
						}
						while (sqlsrv_next_result($stmt_get_pr_next_app));
						sqlsrv_free_stmt($stmt_get_pr_next_app);
						
						$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,$pur_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,$pur_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,$pur_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,$pur_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,$pur_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 ($dft_mst_pur_email_requestor == "1"){
						$title = "Purchase Request: ".$ls_pr_no;
						$body = "The Purchase Request: ".$ls_pr_no." had been approved.\r\n\r\nPurchase Request Total Cost: ".$ldc_pr_cost."\r\nPurchase Requested By: ".$ls_requester[0];
						
						send_email($site_cd, $EmpID, $ls_requester, $title, $body, $LOGINID, $ls_pr_no, 'Purchase Request', 'PR Approved', 'Mobile', '', '', '');
					}
					
					If ($dft_mst_generate_po == '1'){
						generate_po($pur_mst_rowID, $site_cd, $LOGINID);
					}else{
						f_update_purchase_budget($site_cd, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "MINUS_AWA_PR", $ldc_pr_cost, $conn, $LOGINID);
						f_update_purchase_budget($site_cd, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "ADD_PR", $ldc_pr_cost, $conn, $LOGINID);
					}
					// Email Requestor
					// If dft_mst_pur_email_requestor = "1" Then
						// wf_email_requestor("A")
					// End If
					
					// If dft_mst_generate_po = '1' Then 
						// wf_generate_po(ll_rowid)
					// ELSE
						// wf_budget_update("APP_PR")
					// END IF
					
			
		}
		
		
		
	}
	
}
	



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


 
?>