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

$error_message;
$valid = true;
$message='';


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


$device_ID = $_REQUEST['dvc_usr_dvc_id'];




	//Checking existing license(uninstall before logout)
	$sql_tkn_mst= "SELECT 	existing_count = count(*)  
			FROM  	tkn_mst (NOLOCK)
			WHERE	tkn_dvc_id='".$device_ID."' and tkn_logout is NULL";

	$stmt_tkn_mst = sqlsrv_query( $conn, $sql_tkn_mst);

	if( !$stmt_tkn_mst ) {
		 $error_message = "Error selecting table (tkn_mst)";
		 returnError($error_message);
		 die( print_r( sqlsrv_errors(), true));
	}
	
	
	do {
		 while ($row = sqlsrv_fetch_array($stmt_tkn_mst, SQLSRV_FETCH_ASSOC)) {
			 
			$existing_count = $row['existing_count'];
		 }
	} while ( sqlsrv_next_result($stmt_tkn_mst) );
	
	if($existing_count > 0){
		
		
		
		
	}else{
		
		
		//Checking User license
		$sql_tkn_mst= "SELECT 	tkn_count = count(*)  
				FROM  	tkn_mst (NOLOCK)
				WHERE	tkn_logout is NULL";

		$stmt_tkn_mst = sqlsrv_query( $conn, $sql_tkn_mst);

		if( !$stmt_tkn_mst ) {
			 $error_message = "Error selecting table (tkn_mst)";
			 returnError($error_message);
			 die( print_r( sqlsrv_errors(), true));
		}
	
	
		do {
			 while ($row = sqlsrv_fetch_array($stmt_tkn_mst, SQLSRV_FETCH_ASSOC)) {
				 
				$tkn_count = $row['tkn_count'];
			 }
		} while ( sqlsrv_next_result($stmt_tkn_mst) );
	
	
	
		//Checking User license
		$sql_sys_ver = "SELECT 	sys_ver_mobile_license  FROM  sys_ver (NOLOCK)";

		$stmt_sys_ver = sqlsrv_query( $conn, $sql_sys_ver);

		if( !$stmt_sys_ver ) {
			 $error_message = "Error selecting table (sys_ver)";
			 returnError($error_message);
			 die( print_r( sqlsrv_errors(), true));
		}
	
	
		do {
			 while ($row = sqlsrv_fetch_array($stmt_sys_ver, SQLSRV_FETCH_ASSOC)) {
				 
				$sys_ver_mobile_license = $row['sys_ver_mobile_license'];
			 }
		} while ( sqlsrv_next_result($stmt_sys_ver) );
	
	
		if( $tkn_count < $sys_ver_mobile_license ){
			
			
			
			
		}else{

			returnError("License exceed, please contact system administrator.");
		}
		
	}
	
	


sqlsrv_commit( $conn );
sqlsrv_close( $conn);
returnData();

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

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