<?php
// Include the database configuration file
require_once('config.php');


try {
    // Version query
    $sql = "SELECT sys_ver_customer_cd, sys_ver_mobile_ver, sys_ver_apk_url, 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) {
        throw new Exception("Error selecting table (sys_ver): " . print_r(sqlsrv_errors(), true));
    }

    // Initialize variables
    $sys_ver_mobile_ver = null;
    $sys_ver_customer_cd = null;
    $sys_ver_apk_url = 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_apk_url = $row['sys_ver_apk_url'];        
        $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_apk_url, $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_apk_url, $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,
        'sys_ver_apk_url' => $sys_ver_apk_url,
        '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,
        'data' => ''
    );

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