<?php
// get these values from your DB.

require_once('config.php');

$error_message;
$valid = true;

$site_cd = $_REQUEST['site_cd'];


$sql= "SELECT 	
mtr_mst.site_cd,   
mtr_mst.mtr_mst_mtr_no, 
mtr_mst.mtr_mst_costcenter,   
mtr_mst.mtr_mst_account, 
mtr_mst.mtr_mst_org_date,
mtr_mst.mtr_mst_req_date,
mtr_mst.mtr_mst_requester,
Requester_Name = (	SELECT 	emp_mst_2.emp_mst_name
										FROM		emp_mst (NOLOCK) emp_mst_2
										WHERE	emp_mst_2.site_cd = mtr_mst.site_cd
										AND		emp_mst_2.emp_mst_empl_id = mtr_mst.mtr_mst_requester ),
mtr_mst.RowID    
FROM 	mtr_mst (NOLOCK)   WHERE mtr_mst.site_cd = '".$site_cd."' AND mtr_mst_status = 'A' ";
		
$stmt = sqlsrv_query( $conn, $sql);

if( !$stmt ) {
     $error_message = "Error selecting table (dft_mst)";
	 returnError($error_message);
     die( print_r( sqlsrv_errors(), true));
}

$json = array();

do {
     while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
     $json[] = $row;
     }
} while ( sqlsrv_next_result($stmt) );

if ($valid) {
	sqlsrv_free_stmt( $stmt);
	sqlsrv_close( $conn);	
	
	returnData($json);	
}

function returnData($json){
	
	$returnData1 = convert_to_utf8_recursively($json);
	$returnData = array(
	'status' => 'SUCCESS',	
	'data' => $returnData1);
	
	echo json_encode($returnData);
}


function convert_to_utf8_recursively($dat){
	  if( is_string($dat) ){
		 return mb_convert_encoding($dat, 'UTF-8', 'UTF-8');
	  }
	  elseif( is_array($dat) ){
		 $ret = [];
		 foreach($dat as $i => $d){
		   $ret[$i] = convert_to_utf8_recursively($d);
		 }
		 return $ret;
	  }
	  else{
		 return $dat;
	  }
}

function returnError($error_message){
	$json = array();
	
	$returnData = array(
	'status' => 'ERROR',	
	'data' => $json);
	
	echo json_encode($returnData);
	
	sqlsrv_free_stmt( $stmt);
	sqlsrv_close( $conn);	
		
	exit();
}

 
?>