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

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods:  GET");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

if ( sqlsrv_begin_transaction( $conn ) === false ) {
    die( print_r( sqlsrv_errors(), true ));
}

$now = date("Ymdhisa");
$file_name = __DIR__ . "\mobile_log\_insert_time_card.log";

try {
    // Version query
    $sql = "SELECT sys_ver_customer_cd, sys_ver_mobile_ver, sys_ver_mobile_api_ver FROM sys_ver (NOLOCK)";

    // Execute the query
    $stmt = sqlsrv_query($conn, $sql);

    // Check for errors in the query execution
    if ($stmt === false)
	{
		if (($errors = sqlsrv_errors()) != null)
		{
			foreach ($errors as $error)
			{

				file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
			}
		}
		sqlsrv_rollback($conn);
		sqlsrv_close($conn);

		$error_message = "(".$now.") Error selecting and updating table (sys_ver)";
		returnError($error_message);
	}

    // Initialize variables
    $sys_ver_mobile_ver = null;
    $sys_ver_customer_cd = null;
    $sys_ver_mobile_api_ver = null;

    // Fetch data from the result set
    if ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {    
        $sys_ver_mobile_ver = $row['sys_ver_mobile_ver'];    
        $sys_ver_customer_cd = $row['sys_ver_customer_cd'];      
        $sys_ver_mobile_api_ver = $row['sys_ver_mobile_api_ver'];
    } else {
        throw new Exception("No records found in the sys_ver table.");
    }

    // Free the statement and close the connection
    sqlsrv_free_stmt($stmt);
    sqlsrv_close($conn);

    // Return the fetched data
    returnData($sys_ver_mobile_ver, $sys_ver_customer_cd, $sys_ver_mobile_api_ver);

} catch (Exception $e) {
    // Handle any exceptions
    $error_message = $e->getMessage();
    returnError($error_message);
}

function returnData($sys_ver_mobile_ver, $sys_ver_customer_cd, $sys_ver_mobile_api_ver) {
    $returnData = array(
        'status' => 'Update Alert',
        'message' => 'New version available. Please, update the app to New Version: ' . $sys_ver_mobile_ver,
        'customer_cd' => $sys_ver_customer_cd,
        'version' => $sys_ver_mobile_ver,
        'API_version' => $sys_ver_mobile_api_ver
    );

    echo json_encode($returnData);    
}

function returnError($error_message) {
    $returnData = array(
        'status' => 'ERROR',
        'message' => $error_message
    );

    echo json_encode($returnData);
    exit();    
}
?>
