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

require_once('config.php');

$error_message;
$valid = true;

$site_cd = $_REQUEST['site_cd'];
$mtr_mst_mtr_no = $_REQUEST['mtr_mst_mtr_no'];
$mtr_mst_requester = $_REQUEST['mtr_mst_requester'];
$mtr_mst_req_date = $_REQUEST['mtr_mst_req_date'];
$mtr_mst_req_to_date = $_REQUEST['mtr_mst_req_to_date'];


if (!empty($mtr_mst_mtr_no)){	
	$where_mtr_mst_mtr_no = " AND mtr_mst.mtr_mst_mtr_no = '".$mtr_mst_mtr_no. "' ";	
}else{	
	$where_mtr_mst_mtr_no = "";	
}


if (!empty($mtr_mst_requester)){	
	$where_mtr_mst_requester = " AND mtr_mst.mtr_mst_requester = '".$mtr_mst_requester. "' ";	
}else{	
	$where_mtr_mst_requester = "";	
}


if (!empty($mtr_mst_req_date)){
	$where_req_date = " AND CONVERT(DATETIME, CONVERT(VARCHAR, mtr_mst.mtr_mst_req_date , 101)) >= CONVERT(DATETIME, CONVERT(VARCHAR, '".$mtr_mst_req_date."', 101)) 
						AND CONVERT(DATETIME, CONVERT(VARCHAR, mtr_mst.mtr_mst_req_date , 101)) < CONVERT(DATETIME, CONVERT(VARCHAR, '".$mtr_mst_req_to_date."', 101))  + 1 ";
}else{
	$where_req_date = " AND CONVERT(DATETIME, CONVERT(VARCHAR, '1900-01-01', 101)) < Getdate() ";
}


$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'".
$where_mtr_mst_requester.
$where_mtr_mst_mtr_no.
$where_req_date."";
		
$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();
}

 
?>