<?php
require_once('config.php');
//require_once('f_update_budget.php');

$error_message;
$valid = true;


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


$site_cd 	= $_REQUEST['site_cd'];
$ntf_log_to = $_REQUEST['ntf_log_to']; 


$sql_dvc_mst = "SELECT COUNT(*) as NTF_COUNT FROM ntf_log (NOLOCK)  WHERE site_cd = ? and ntf_log_to = ? and ntf_log_read_flag = ?";
$params_dvc_mst = array($site_cd,$ntf_log_to,'0');	
$stmt_dvc_mst = sqlsrv_query( $conn, $sql_dvc_mst,$params_dvc_mst);	

if( !$stmt_dvc_mst ) {
$error_message = "Error Select table (dvc_mst)";
returnError($error_message);
die( print_r( sqlsrv_errors(), true));
}

do {
 while ($row = sqlsrv_fetch_array($stmt_dvc_mst, SQLSRV_FETCH_ASSOC)) {
 
 $NTF_COUNT = $row['NTF_COUNT'];		
	
	 
}
} while ( sqlsrv_next_result($stmt_dvc_mst));

if($NTF_COUNT > 0 ){
	
	$sql_ntf_log = "Update ntf_log SET ntf_log_read_flag = ? WHERE site_cd = ? and ntf_log_to = ?";

		$params_ntf_log = array('1',$site_cd,$ntf_log_to);	
		$stmt_ntf_log = sqlsrv_query( $conn, $sql_ntf_log,$params_ntf_log);	
		
	if( !$stmt_ntf_log ) {
		$error_message = "Error Select table (dvc_mst)";
		returnError($error_message);
		die( print_r( sqlsrv_errors(), true));
	}
	$json= array();
	
	do {
		 while ($row = sqlsrv_fetch_array($stmt_ntf_log, SQLSRV_FETCH_ASSOC)) {
		 
		 $json[] = $row;		
			
			 
	   }
	} while ( sqlsrv_next_result($stmt_ntf_log));
	
	
	if( $stmt_ntf_log) {
		 sqlsrv_commit( $conn );
		 sqlsrv_close( $conn);	
		 returnData($json);	
	} else {
		 sqlsrv_rollback( $conn );
		 $error_message = "Transaction rolled back.<br />";
		 returnError($error_message);
	} 

	
	
}else{
	
	 sqlsrv_commit( $conn );
	 sqlsrv_close( $conn);	
	 noreturnData($NTF_COUNT);
		 
}


function noreturnData($NTF_COUNT){
	
	$returnData = array(
	'status' => 'SUCCESS',
	'message' => 'Successfully',
	'NTF_COUNT' => $NTF_COUNT);
	
	echo json_encode($returnData);
}

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

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