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

$dvc_last_user;
$dvc_token ;

$json = file_get_contents('php://input');

// Converts it into a PHP object
$data = json_decode($json, true);

$site_cd = $data['site_cd'];
$brand = $data['brand'];
$model = $data['model'];
$online = $data['online'];
$last_user = $data['last_user'];
$last_login_date = $data['DateTime'];
$token = $data['token'];
$dvc_id = $data['dvc_id'];


$sql_tkn_mst = "UPDATE	tkn_mst 
				SET 	tkn_logout = GetDate(),
						tkn_online = '0'							
				WHERE	tkn_dvc_id =? and tkn_online ='1' "  ;
		
	
	$params_tkn_mst = array($dvc_id);
	$stmt_tkn_mst = sqlsrv_query( $conn, $sql_tkn_mst,$params_tkn_mst);	
		
if( !$stmt_tkn_mst ) {
	$error_message = "Error update table (wko_sts)";
	returnError($error_message);
	die( print_r( sqlsrv_errors(), true));
}sqlsrv_free_stmt( $stmt_tkn_mst);


$sql_insert_tkn_mst = "	INSERT tkn_mst 
						(	tkn_dvc_id ,	tkn_brand,		tkn_model,		tkn_token,		tkn_user,
							tkn_site,		tkn_login,		tkn_logout,		tkn_online) 
				VALUES (	?,				?,				?,				?,				?,
							?,				GetDate(),		Null,			?)";

	$params_insert_tkn_mst = array($dvc_id,$brand,$model,$token,$last_user,$site_cd,$online);
	$stmt_insert_tkn_mst = sqlsrv_query( $conn, $sql_insert_tkn_mst,$params_insert_tkn_mst);	
	if( !$stmt_insert_tkn_mst ) {
	$error_message = "Error (INSERT Table tkn_mst)";
	returnError($error_message);
	die( print_r( sqlsrv_errors(), true));	
	
	}

if( $stmt_tkn_mst && $stmt_insert_tkn_mst) {
		 sqlsrv_commit( $conn );
		 sqlsrv_close( $conn);	
		 returnData();	
	} else {
		 sqlsrv_rollback( $conn );
		 $error_message = "Transaction rolled back.<br />";
		 returnError($error_message);
	}
	

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

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