<?php
error_reporting(E_ERROR | E_PARSE);
if (!class_exists('crm_hardlock')) require_once("common_cadline_libraries/crm_hardlock.class.php");

if (!crm_hardlock::isServerActive()) {
    http_response_code(549);
    die();
}

$function_id    = $_GET["id"];
$product_id     = $_GET["prod"];
$ver_id         = $_GET["ver"];
$country_id     = $_GET["cnt"];
$param          = $_GET["param"];
$build          = $_GET["bld"];
$test           = $_GET["test"] == 'true';
$year           = $_GET["year"];
$rgn            = isset($_GET["rgn"]) ? $_GET["rgn"] : "Int";

if ($function_id == '99') {
    echo 'ok';
    return;
}

$url = "";

$query = "SELECT * FROM `" . SYNCADATBAZIS . "`.`url_switch`
    WHERE function_id = ? AND (product_id = ? OR product_id = 0) AND (country_id = ? OR country_id = 0) AND
    (ver_id <= ? OR ver_id = 0) ORDER BY country_id DESC, ver_id DESC";
Database::getInstance()->query($query, array('iiii', $function_id, $product_id, $country_id, $ver_id));
$res = Database::getInstance()->fetchNext();

if (empty($res)) {
    print "No result found.";
} else {
    $param = base64_decode($param);

    if ($test && $res['test_url'] != '') {
        $url = $res['test_url'];

        $session    = Webform::get_valueFromStringUrl("?{$param}", "session");
        $privateKey = Webform::GetWebformPrivateKey();
        $encoded    = Webform::encode($privateKey, $session, base64_encode(date('Y-m-d')));
        $encoded    = base64_encode($encoded);

        $param .= "&authCode={$encoded}";
    } else {
        $url = $res['url'];
    }

    $url .= $param;

    if ($function_id == 8 || $function_id == 19) $url .= "&ver={$ver_id}";
    if ($function_id == 17 || $function_id == 20 || $function_id == 4 || $function_id == 24 || $function_id == 22 || $function_id == 30) $url .= "&prod={$product_id}&ver={$ver_id}&cnt={$country_id}";
    if ($function_id == 15 || $function_id == 32) $url .= "&cnt={$country_id}&ver={$ver_id}&build={$build}";
    if ($function_id == 25 || $function_id == 16) $url .= "&ver={$ver_id}&build={$build}";
    if ($function_id == 33) $url .= "&year={$year}&build={$build}";
    if ($function_id == 35) $url .= "&ver={$ver_id}";
    if ($function_id == 36) $url .= "&ver={$ver_id}&build={$build}";

    if ($function_id == 19) {
        $se = Webform::get_valueFromStringUrl("?{$param}", "se");
        $url .= "&se={$se}";
    }

    $url .= "&rgn=" . $rgn;

    if ($_SERVER['SERVER_NAME'] == 'secondary.dev.cadline.hu') {
        $url = str_replace('www.archline.hu/maintenance', 'secondary.dev.cadline.hu', $url);
        $url = str_replace('www.archlinexp.com/maintenance', 'secondary.dev.cadline.hu', $url);
    }
    header('Location: ' . $url);
}
