<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
ob_start();
session_start();
require_once("../../config/version.inc.php");
require_once("../../config/config.inc.php");
require_once("../functions.php");

if (!isset($_SESSION['id_user'])) {
    echo json_encode(['status' => 'error', 'msg' => 'Unauthorized']);
    exit;
}

$version = APP_VERSION;
$a3 = $_SERVER['SERVER_NAME'] ?? '';
$z0 = $_SERVER['SERVER_ADDR'] ?? '';
$i4 = $_SERVER['REQUEST_URI'] ?? '';

$response = [
    'update_available' => false
];

if (!isset($_SESSION['latest_version'])) {
    $url = "https://simpledemo.it/get_latest_sml_version.php?domain=$a3&ip=$z0&version=$version&request_uri=$i4";
    $latest = @file_get_contents($url, false, stream_context_create(["ssl" => ["verify_peer" => false]]));

    if (empty($latest) && function_exists('curl_version')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $latest = curl_exec($ch);
        curl_close($ch);
    }

    $_SESSION['latest_version'] = empty($latest) ? $version : $latest;
}

if (version_compare($version, $_SESSION['latest_version']) == -1) {
    $response['update_available'] = true;
}

ob_end_clean();
echo json_encode($response);
exit;