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


// Begin transaction
if (sqlsrv_begin_transaction($conn) === false) {
    $error_message = "Transaction begin failed: " . print_r(sqlsrv_errors(), true);
    returnError($error_message);
}

// Get JSON data from input
$json = file_get_contents('php://input');
$data = json_decode($json, true);

// Extract data from JSON
$site_cd = $data['site_cd'] ?? '';
$brand = $data['brand'] ?? '';
$model = $data['model'] ?? '';
$online = $data['online'] ?? '';
$last_user = $data['last_user'] ?? '';
$token = $data['token'] ?? '';
$dvc_id = $data['dvc_id'] ?? '';
$version = $data['version'] ?? '';


//tkn_mst to logout the previous session
$sql_dft_mst = "SELECT dft_mst_mbl_single_login FROM dft_mst (NOLOCK) WHERE site_cd =?";
$params_dft_mst = array($site_cd);
$stmt_dft_mst = sqlsrv_query( $conn, $sql_dft_mst,$params_dft_mst);

if( !$stmt_dft_mst ) {
	 $error_message = "Error selecting (sys_ver) ";
	 returnError($error_message);
	 die( print_r( sqlsrv_errors(), true));
	 
}
$dft_mst_mbl_single_login;
do 	{
	 while ($row = sqlsrv_fetch_array($stmt_dft_mst, SQLSRV_FETCH_ASSOC)) {	
	 $dft_mst_mbl_single_login = $row['dft_mst_mbl_single_login'];
	
	}
} while ( sqlsrv_next_result($stmt_dft_mst) );


if($dft_mst_mbl_single_login === '0'){
	
	// Update tkn_mst to logout the previous session
	$sql_tkn_mst = "UPDATE tkn_mst 
					SET tkn_logout = GetDate(),
						tkn_online = '0'							
					WHERE tkn_site =?
					AND tkn_dvc_id = ? 
					AND tkn_user =?
					AND tkn_online = '1'";

	$params_tkn_mst = array($site_cd,$dvc_id,$last_user);
	$stmt_tkn_mst = sqlsrv_query($conn, $sql_tkn_mst, $params_tkn_mst);

	if (!$stmt_tkn_mst) {
		$error_message = "Error updating tkn_mst table: " . print_r(sqlsrv_errors(), true);
		sqlsrv_rollback($conn);
		returnError($error_message);
	}

	sqlsrv_free_stmt($stmt_tkn_mst);

	
}else{
	
	// Update tkn_mst to logout the previous session
	$sql_tkn_mst = "UPDATE tkn_mst 
					SET tkn_logout = GetDate(),
						tkn_online = '0'							
					WHERE tkn_site =?
					AND tkn_user =?";

	$params_tkn_mst = array($site_cd,$last_user);
	$stmt_tkn_mst = sqlsrv_query($conn, $sql_tkn_mst, $params_tkn_mst);

	if (!$stmt_tkn_mst) {
		$error_message = "Error updating tkn_mst table: " . print_r(sqlsrv_errors(), true);
		sqlsrv_rollback($conn);
		returnError($error_message);
	}

	sqlsrv_free_stmt($stmt_tkn_mst);
	
}


// Insert new record into tkn_mst
$sql_insert_tkn_mst = "INSERT INTO tkn_mst 
                        (tkn_dvc_id, tkn_brand, tkn_model, tkn_token, tkn_user, 
                         tkn_site, tkn_login, tkn_logout, tkn_online,tkn_mst_mobile_ver) 
                      VALUES 
                        (?, ?, ?, ?, ?, ?, GetDate(), NULL, ?,?)";

$params_insert_tkn_mst = array($dvc_id, $brand, $model, $token, $last_user, $site_cd, $online,$version);
$stmt_insert_tkn_mst = sqlsrv_query($conn, $sql_insert_tkn_mst, $params_insert_tkn_mst);

if (!$stmt_insert_tkn_mst) {
    $error_message = "Error inserting into tkn_mst table: " . print_r(sqlsrv_errors(), true);
    sqlsrv_rollback($conn);
    returnError($error_message);
}

// Commit or rollback transaction based on success
if ($stmt_tkn_mst && $stmt_insert_tkn_mst) {
    sqlsrv_commit($conn);
    sqlsrv_close($conn);
    returnData();
} else {
    sqlsrv_rollback($conn);
    $error_message = "Transaction rolled back.";
    returnError($error_message);
}

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

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