<?php
if (!class_exists('Database')) require_once("common_cadline_libraries/crm_database.class.php");

try {
    $url = 'https://www.archline.hu/maintenance/check_server.php';

    $options = array(
        CURLOPT_RETURNTRANSFER => true,   // return web page
        CURLOPT_HEADER         => false,  // don't return headers
        CURLOPT_FOLLOWLOCATION => true,   // follow redirects
        CURLOPT_MAXREDIRS      => 10,     // stop after 10 redirects
        CURLOPT_ENCODING       => "",     // handle compressed
        CURLOPT_USERAGENT      => "test", // name of client
        CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,    // time-out on connect
        CURLOPT_TIMEOUT        => 120,    // time-out on response
    );

    $ch = curl_init($url);
    curl_setopt_array($ch, $options);

    $content = curl_exec($ch);

    curl_close($ch);

    $result = $content == 380335 ? 'Success' : 'Failed';
} catch (\Exception $e) {
    $result = 'Failed';
}

$filename = $_SERVER['DOCUMENT_ROOT'] . "/serverAlive.txt";
$closed = file_put_contents($filename, $result);

$i = 0;

while (!$closed && $i < 10) {
    $closed = file_put_contents($filename, $result);
    $i++;
}

try {
    if ($_SERVER['SERVER_NAME'] == 'secondary.cadline.hu') {
        $txtResult = $result == 'Success' ? 'Inactive' : 'Active';

        $filename = $_SERVER['DOCUMENT_ROOT'] . "/activateServer.txt";
        $closed = file_put_contents($filename, $txtResult);

        $i = 0;

        while (!$closed && $i < 10) {
            $closed = file_put_contents($filename, $txtResult);
            $i++;
        }
    }
} catch (\Throwable $th) {
    //throw $th;
}

try {
    // Update-eli a sync_crm.cron_check tablat, hogy megnezzuk, lefut-e a cron. A check_main_server_cron.php file-ba pedig ellenorizzuk
    Database::getInstance()->query("UPDATE sync_crm.cron_check SET modified = ? WHERE id = ?", array('ii', time(), 1));
} catch (\Throwable $th) {
    //throw $th;
}
