<?php
header("Access-Control-Allow-Origin: *");

if (!class_exists('Authenticate')) require_once("common_cadline_libraries/crm_test.class.php");

error_reporting(E_ERROR | E_PARSE);

header('Cache-Control: no-store, no-cache, must-revalidate');

$action         = isset($_POST["action"]) ? $_POST["action"] : $_GET["action"];
$encodedSession = isset($_POST["session"]) ? $_POST["session"] : $_GET["session"];
$authCode       = isset($_POST["authCode"]) ? $_POST["authCode"] : $_GET["authCode"];
$session        = base64_decode($encodedSession);
$privatekey     = Webform::GetWebformPrivateKey();

$auth = new Authenticate();
$auth->setAuthCode($authCode);
$auth->setAuthSession($encodedSession);
$auth->auth();

$data           = "";
$result         = "";
$resultForm     = "";
$message        = "";
$button         = "";
$lang           = "";
$useResultForm  = false; // Amennyiben stringkent akarjuk kezelni a formot, false-ra kell allitani

if (isset($_POST["result_ok"])) $result = "result_ok";
elseif (isset($_POST["result_cancel"])) $result = "result_cancel";

switch ($action) {
    case 'login':
        require_once '../PasswordHash.php';

        $needToken  = false;
        $email      = '';

        if (isset($_POST['param'])) { // Custom Login
            $decoded_data   = base64_decode($_POST['param']);
            $data           = json_decode($decoded_data);
            $encodedSession = $data->session;
            $session        = base64_decode($data->session);
            $decoded_param  = '?' . Webform::decode($privatekey, $session, $data->id);

            $user       = json_decode(base64_decode($_POST['data']));
            $seatID     = Webform::get_valueFromStringUrl($decoded_param, "seatID");
            $npid       = Webform::get_valueFromStringUrl($decoded_param, "npid");
            $isTrial    = Webform::get_valueFromStringUrl($decoded_param, "trial");
            $ver8and9   = $data->ver;
            $custom     = Webform::get_valueFromStringUrl($decoded_param, "custom");
            $userID     = crm_hardlock::GetRegistration($user, $npid, $isTrial, $ver8and9, $custom);
            $nUserID    = -$userID;
            $name       = $user->name;
            $needToken  = true;

            $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

            $msg = "URL: " . $actual_link;
            crm_hardlock::AddToDebugTable($msg, "Custom Login");
        } else { // Belso Login
            $username   = $_POST['username'];
            $password   = $_POST['password'];
            $seatID     = $_POST['seatID'];
            $lang       = $_POST['lang'];

            $query = "SELECT * FROM `" . JMLADATBAZIS . "`.`jml_users` WHERE username = ? OR email = ?";
            Database::getInstance()->query($query, array('ss', $username, $username));
            $res = Database::getInstance()->fetchNext();

            if (!empty($res)) {
                $db_password    = $res['password'];
                $nUserID        = $res['nUserID'];
                $name           = $res["name"];

                $phpass = new PasswordHash(10, true);
                $ok     = $phpass->CheckPassword($password, $db_password);

                if ($ok) {
                    $crmEmailQuery = "SELECT * FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE nUserID = ? LIMIT 1;";
                    Database::getInstance()->query($crmEmailQuery, array('i', $nUserID));
                    $crmEmail = Database::getInstance()->fetchNext();

                    $email = $crmEmail['email'];

                    $needToken  = true;
                } else {
                    $result = 'result_cancel';
                    $data   = "<Login><Error>password_error</Error></Login>";
                }
            } else {
                $result = 'result_cancel';
                $data   = "<Login><Error>username_error</Error></Login>";
            }
        }

        if ($needToken) {
            $tokenID    = crm_hardlock::GetOrGenerateToken($seatID, $nUserID);
            $result     = 'result_ok';

            $data = "<Login>
                <UserName>{$name}</UserName>
                <TokenID>{$tokenID}</TokenID>
                <Email>{$email}</Email>
            </Login>";
        }

        $param = Webform::encode($privatekey, $session, $data);

        Webform::SetWebformResult($session, $result, $param, $message, $button);

        if (isset($_POST['ex']) && $_POST['ex'] == 'true') {
            header('Location: https://www.archline.hu/maintenance/webform/loginresult.php?lang=' . $lang . '&result=' . $result);
        } else {
            $resultForm .= "<form name='encode' method='GET', action='blank_result.php'>";
            $resultForm .= "<input type='hidden' name='session' value='{$encodedSession}' />";
            $resultForm .= "<input type='hidden' name='{$result}' value='{$param}' />";
            $resultForm .= "</form>";
            $resultForm .= "<script>
                window.onload = function() {
                    document.forms['encode'].submit();
                }
            </script>'";
            echo $resultForm;
        }

        die();
        break;

    case 'ext_browser':
        $result = 'result_cancel';
        $data   = "<Login><Error>external_login</Error></Login>";

        $param = Webform::encode($privatekey, $session, $data);

        Webform::SetWebformResult($session, $result, $param, $message, $button);

        if (isset($ex) && $ex == "true") {
            $useResultForm = false;
        } else {
            $resultForm .= "<form name='encode' method='GET', action='blank_result.php'>";
            $resultForm .= "<input type='hidden' name='session' value='{$encodedSession}' />";
            $resultForm .= "<input type='hidden' name='{$result}' value='{$param}' />";
            $resultForm .= "</form>";
            $resultForm .= "<script>
                window.onload = function() {
                    document.forms['encode'].submit();
                }
            </script>'";
            echo $resultForm;
        }
        break;

    case 'cancel_login':
        $result = 'result_cancel';
        $data   = "<Login><Error>cancel_login</Error></Login>";

        $param = Webform::encode($privatekey, $session, $data);

        Webform::SetWebformResult($session, $result, $param, $message, $button);

        if (isset($_POST['ex']) && $_POST['ex'] == 'true') {
        } else {
            $resultForm .= "<form name='encode' method='GET', action='blank_result.php'>";
            $resultForm .= "<input type='hidden' name='session' value='{$encodedSession}' />";
            $resultForm .= "<input type='hidden' name='{$result}' value='{$param}' />";
            $resultForm .= "</form>";
            $resultForm .= "<script>
                window.onload = function() {
                    document.forms['encode'].submit();
                }
            </script>'";
            echo $resultForm;
        }

        die();
        break;

    case 'sample':
        $data = $_POST["param"];
        break;

    case 'register':
        $param          = $_GET["param"]; // Encode-olt adat
        $param          = Webform::decode($privatekey, $session, $param); // Adat decode-olása

        $param      = "?" . $param;
        $serial     = Webform::get_valueFromStringUrl($param, "password");
        $npid       = Webform::get_valueFromStringUrl($param, "npid");
        $isid       = Webform::get_valueFromStringUrl($param, "isid");
        $comp_name  = Webform::get_valueFromStringUrl($param, "name");
        $ex         = Webform::get_valueFromStringUrl($param, "ex");
        $instcode   = Webform::get_valueFromStringUrl($param, "instcode");
        $lang       = Webform::get_valueFromStringUrl($param, "lang");
        $isTwTw     = Webform::get_valueFromStringUrl($param, "twtw") == 'true';
        $seatID     = Webform::get_valueFromStringUrl($param, "seatid");
        $build      = Webform::get_valueFromStringUrl($param, "build");
        $ver8And9   = crm_hardlock::GetVer8And9FromPassword($serial);
        $isFloating = 'false';
        $isOffline  = 'false';

        if (crm_hardlock::isEmergencyServer($_GET['secondary'])) {
            $error = crm_hardlock::GetActivationError(crm_hardlock::SERVER_DOWN);
            $result = 'result_ok';
            $data = '<Register>
                    <npid>true</npid>
                    <error>' . $error . '</error>
                </Register>';
            goto resultBack;
        }

        crm_hardlock::InsertLog($serial);

        if (isset($instcode) && Codegen::IsValidTimeCode($instcode)) { // 2020-tol a telepites ota eltelt idot jelzi a regisztracio
            // Amennyiben a telepitesi kod es a password parban all, akkor a valos eltelt idot jelzi
            $countryNotOK = Codegen::IsSoftwareKey($serial) ? false : Codegen::GetCountryFromTimeCode($installationCode) != Codegen::GetCountryFromPassword($serial);
            if (substr($instcode, 0, 4) != substr($serial, 2, 4) || $countryNotOK) {
                // Az installalasi kod nincs parban a passwordel, ilyenkor le kell generalni az installalasi kodot
                $instcode   = '';
                $numOfDays  = 0;
                $registrationDate = crm_hardlock::GetInstallationDate_noRegisterAndValidate($serial, $isid, $instcode, $isTwTw);
                if ($registrationDate != '') { // Ha nem sikerult megallapitani a telepitesi datumot, akkor a mai napot allitjuk be
                    if (strpos($registrationDate, 'error:') === false) {
                        $dateNow = new DateTime(date('Y-m-d'));
                        if ($isTwTw) $numOfDays = Codegen::GetDayInterval(crm_hardlock::getTwTwRootTimeString(), $dateNow->format('Y-m-d'));
                        else $numOfDays = Codegen::GetDayInterval($registrationDate, $dateNow->format('Y-m-d'));
                        $instcode = Codegen::GenerateTimeCode($serial, $isid, $numOfDays);
                    }
                }
            }
        } else $instcode = '';

        if (isset($ex) && $ex == "true") $useResultForm = true;

        // isid kiegeszitese 0-val
        crm_hardlock::correctIsid($isid);

        $softwarekey = Codegen::IsSoftwareKey($serial);
        if (!$softwarekey) // A regisztracional a gepazonositot kuldi a program, ez hardware kulcsnal nem alkalmazhato
            $isid = crm_hardlock::GetIsidFromPasswordForHardwareKeys($serial);

        $register_result = crm_hardlock::RegisterProgram($serial, $isid, $instcode, $npid, $comp_name, $isTwTw, $seatID, $build);
        if (substr($register_result, 0, 6) == "error:") crm_hardlock::_Hibajelento("regisztracio", substr($serial, 0, 6), "isid: {$isid}, valasz: {$register_result}");

        if (substr($register_result, 0, 6) == "error:") $result = 'result_cancel';
        else $result = 'result_ok';

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`computers` WHERE computer_id = ?";
        Database::getInstance()->query($query, array('s', $npid));
        $computers = Database::getInstance()->fetchNext();

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`p_serial_isid` WHERE serial = ? AND isid = ? AND aktiv = ?";
        Database::getInstance()->query($query, array('ssi', $serial, $isid, 1));
        $p_serial_isid = Database::getInstance()->fetchNext();

        if (empty($p_serial_isid) || $p_serial_isid['computer_id'] == $computers['id']) $npidOK = 'true';
        else $npidOK = 'false';

        if (substr($register_result, 0, 6) != "error:") {
            if ($isTwTw) $aktkod = crm_hardlock::GetOrGenerateTimeCodeTWTW($serial, $isid, $instcode, $npid, $computers['computer_name'], $seatID, $build, false);
            else $aktkod = crm_hardlock::GetOrGenerateTimeCode($serial, $isid, $instcode, $npid, $computers['computer_name']);
        }

        if ($ver8And9 >= 40) {
            if ($ver8And9 > 40 || ($ver8And9 == 40 && $build > '255' && $build != '')) {
                $query = "SELECT isFloating FROM `" . CRMADATBAZIS . "`.`hardlock` WHERE hlNum = ?";
                Database::getInstance()->query($query, array('s', substr($serial, 0, 6)));
                $key = Database::getInstance()->fetchNext();

                if ($key['isFloating'] == 1) {
                    $isFloating = 'true';

                    $query = "SELECT * FROM `" . SYNCADATBAZIS . "`.`floating_licenses` WHERE hlNum = ? AND seatID = ?";
                    Database::getInstance()->query($query, array('ss', substr($serial, 0, 6), $seatID));
                    $floatingLic = Database::getInstance()->fetchNext();

                    if (!empty($floatingLic) && $floatingLic['offline_expiration_date'] != '') {
                        $isOffline  = 'true';
                        $days       = Codegen::GetDayInterval(crm_hardlock::getTwTwRootTimeString(), $floatingLic['offline_expiration_date']);
                        $aktkod     = Codegen::GenerateTimeCode($serial, $isid, $days);
                    }
                }
            }
        }

        $data = '<Register>
            <npid>' . $npidOK . '</npid>
            ' . ((isset($aktkod)) && substr($register_result, 0, 6) != "error:" ? '<swcode>' . $aktkod . '</swcode>' : '') . '
            ' . ((isset($register_result)) && substr($register_result, 0, 6) == "error:" ? '<error>' . $register_result . '</error>' : '') . '
            <floating>' . $isFloating . '</floating>
            <offline>' . $isOffline . '</offline>
        </Register>';

        if ($lang == 'hun') {
            $message    = 'Nyomja meg az alábbi gombot, hogy licencét ezen a gépen regisztrálja:';
            $button     = "LICENC REGISZTRÁLÁS";
        } else {
            $message    = 'To register your license on this computer, please press the following button:';
            $button     = "REGISTER MY LICENSE";
        }
        break;

    case 'unregister':
        $param          = $_GET["param"]; // Encode-olt adat
        $param          = Webform::decode($privatekey, $session, $param); // Adat decode-olása

        $param  = "?" . $param;
        $serial = Webform::get_valueFromStringUrl($param, "password");
        $isid   = Webform::get_valueFromStringUrl($param, "isid");
        $npid   = Webform::get_valueFromStringUrl($param, "npid");
        $ex     = Webform::get_valueFromStringUrl($param, "ex");
        $lang   = Webform::get_valueFromStringUrl($param, "lang");

        if (crm_hardlock::isEmergencyServer($_GET['secondary'])) {
            $error = crm_hardlock::GetActivationError(crm_hardlock::SERVER_DOWN);
            $result = 'result_ok';
            $data = '<Unregister>
                    <npid>true</npid>
                    <error>' . $error . '</error>
                </Unregister>';
            goto resultBack;
        }

        if (isset($ex) && $ex == "true") $useResultForm = true;

        // isid kiegeszitese 0-val
        crm_hardlock::correctIsid($isid);

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`computers` WHERE computer_id = ?";
        Database::getInstance()->query($query, array('s', $npid));
        $computers = Database::getInstance()->fetchNext();

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`p_serial_isid` WHERE serial = ? AND isid = ? AND aktiv = ?";
        Database::getInstance()->query($query, array('ssi', $serial, $isid, 1));
        $p_serial_isid = Database::getInstance()->fetchNext();

        if (empty($p_serial_isid) || $p_serial_isid['computer_id'] == $computers['id']) $npidOK = 'true';
        else $npidOK = 'false';

        $register_result = crm_hardlock::UnRegisterProgram($serial, $isid, '', $computers['computer_name'], '', 36, false);
        if (!$register_result) {
            $error  = crm_hardlock::GetActivationError(crm_hardlock::UNREGISTER_FAILED);
            $result = 'result_cancel';
        } else $result = 'result_ok';

        $data = '<Unregister>
            <npid>' . $npidOK . '</npid>
            ' . ((isset($error)) ? '<error>' . $error . '</error>' : '') . '
        </Unregister>';

        if ($lang == 'hun') {
            $message    = 'Ha el akarja távolítani a licencét a számítógépről, kérjük nyomja meg az alábbi gombot:';
            $button     = "LICENC ELTÁVOLÍTÁSA";
        } else {
            $message    = 'If You want to remove Your license from this computer, please press the following button:';
            $button     = "RELEASE MY LICENSE";
        }
        break;

    case 'selectProgramDialog':
        $result = isset($_POST['result_ok']) && isset($_POST['prPass']) && $_POST['prPass'] != '' && Codegen::IsValidPassword($_POST['prPass']) ? 'result_ok' : 'result_cancel';
        $prPass = isset($_POST['prPass']) ? $_POST['prPass'] : '';

        $restartRequired = Codegen::IsValidPassword($prPass) && isset($_POST['result_ok']) ? 'true' : 'false';

        if (isset($ex) && $ex == "true") $useResultForm = true;

        if ($restartRequired && isset($_POST['param'])) {
            $param          = $_POST["param"]; // Encode-olt adat
            $param          = Webform::decode($privatekey, $session, $param); // Adat decode-olása
            $param          = "?" . $param;
            $token          = Webform::get_valueFromStringUrl($param, "tokenid");
            $userID         = crm_hardlock::GetUserIdFromToken($token);

            if ($userID < 0) {
                Database::getInstance()->update(
                    CRMADATBAZIS . ".custom_login_licenses",
                    array(
                        'serial' => $prPass
                    ),
                    array('id' => abs($userID)),
                    'si'
                );
            }

            if ($userID == false) {
                die();
            }
        }

        $data = '<ManageAccountResult RestartRequired="' . $restartRequired . '">
            <Serial>' . $prPass . '</Serial>
            </ManageAccountResult>';

        $param = Webform::encode($privatekey, $session, $data);

        Webform::SetWebformResult($session, $result, $param, $message, $button);

        if (isset($_POST['ex']) && $_POST['ex'] == 'true') {
            //header('Location: https://www.archline.hu/maintenance/webform/loginresult.php?lang=' . $lang . '&result=' . $result);
        } else {
            $resultForm .= "<form name='encode' method='GET', action='blank_result.php'>";
            $resultForm .= "<input type='hidden' name='session' value='{$encodedSession}' />";
            $resultForm .= "<input type='hidden' name='{$result}' value='{$param}' />";
            $resultForm .= "</form>";
            $resultForm .= "<script>
                    window.onload = function() {
                        document.forms['encode'].submit();
                    }
                </script>'";
            echo $resultForm;
        }
        break;

    case 'exchange_registration':
        $param          = $_GET["param"]; // Encode-olt adat
        $param          = Webform::decode($privatekey, $session, $param); // Adat decode-olása
        $param          = "?" . $param;

        $serial     = Webform::get_valueFromStringUrl($param, "password");
        $npid       = Webform::get_valueFromStringUrl($param, "npid");
        $isid       = Webform::get_valueFromStringUrl($param, "isid");
        $comp_name  = Webform::get_valueFromStringUrl($param, "name");
        $ex         = Webform::get_valueFromStringUrl($param, "ex");
        $instcode   = Webform::get_valueFromStringUrl($param, "instcode");
        $lang       = Webform::get_valueFromStringUrl($param, "lang");
        $isTwTw     = Webform::get_valueFromStringUrl($param, "twtw") == 'true';
        $seatID     = Webform::get_valueFromStringUrl($param, "seatid");

        if (isset($ex) && $ex == "true") $useResultForm = true;

        // isid kiegeszitese 0-val
        crm_hardlock::correctIsid($isid);

        $softwarekey = Codegen::IsSoftwareKey($serial);
        if (!$softwarekey) // A regisztracional a gepazonositot kuldi a program, ez hardware kulcsnal nem alkalmazhato
            $isid = crm_hardlock::GetIsidFromPasswordForHardwareKeys($serial);

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`p_serial_isid` WHERE serial = ? AND aktiv = ?";
        Database::getInstance()->query($query, array('si', $serial, 1));
        $p_serial_isid = Database::getInstance()->fetchNext();
        $old_isid       = $p_serial_isid['isid'];
        $old_comp_id    = $p_serial_isid['computer_id'];

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`computers` WHERE id = ?";
        Database::getInstance()->query($query, array('i', $old_comp_id));
        $computers = Database::getInstance()->fetchNext();

        $register_result = crm_hardlock::UnRegisterProgram($serial, $old_isid, '', $comp_name);
        if (!$register_result) {
            $error  = crm_hardlock::GetActivationError(crm_hardlock::UNREGISTER_FAILED);
            $result = 'result_cancel';
        } else $result = 'result_ok';

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`p_serial_isid` WHERE serial = ? AND isid = ? AND aktiv = ?";
        Database::getInstance()->query($query, array('ssi', $serial, $isid, 1));
        $p_serial_isid = Database::getInstance()->fetchNext();

        if (empty($p_serial_isid) || $p_serial_isid['computer_id'] == $computers['id']) $npidOK = 'true';
        else $npidOK = 'false';

        $register_result = crm_hardlock::RegisterProgram($serial, $isid, $instcode, $npid, $comp_name, $isTwTw, $seatID);
        if (substr($register_result, 0, 6) == "error:")
            crm_hardlock::_Hibajelento("regisztracio", substr($serial, 0, 6), "isid: {$isid}, valasz: {$register_result}");

        if (substr($register_result, 0, 6) == "error:") $result = 'result_cancel';
        else $result = 'result_ok';

        if (substr($register_result, 0, 6) != "error:") {
            if ($isTwTw) $aktkod = crm_hardlock::GetOrGenerateTimeCodeTWTW($serial, $isid, $instcode, $npid, $comp_name, $seatID);
            else $aktkod = crm_hardlock::GetOrGenerateTimeCode($serial, $isid, $instcode, $npid, $comp_name);
        }

        $data = '<Register>
            <npid>' . $npidOK . '</npid>
            ' . ((isset($aktkod)) && substr($register_result, 0, 6) != "error:" ? '<swcode>' . $aktkod . '</swcode>' : '') . '
            ' . ((isset($register_result)) && substr($register_result, 0, 6) == "error:" ? '<error>' . $register_result . '</error>' : '') . '
        </Register>';

        if ($lang == 'hun') {
            $message    = 'Nyomja meg az alábbi gombot, hogy licencét ezen a gépen regisztrálja:';
            $button     = "LICENC REGISZTRÁLÁS";
        } else {
            $message    = 'To register your license on this computer, please press the following button:';
            $button     = "REGISTER MY LICENSE";
        }
        break;

    case 'select_distributor':
        $userID = $_POST['userID'];
        $distID = $_POST['distID'];

        if ($userID > 0 && $distID != '') {
            Database::getInstance()->update(
                CRMADATBAZIS . ".users",
                array(
                    'distID_by_user' => $distID
                ),
                array('nUserID' => $userID),
                'ii'
            );
        }

        if (isset($_POST['ex']) && $_POST['ex'] == 'true') {
        } else {
            $resultForm .= "<form name='encode' method='GET', action='blank_result.php'>";
            $resultForm .= "<input type='hidden' name='result_ok' value='true' />";
            $resultForm .= "<input type='hidden' name='needDialog' value='true' />";
            $resultForm .= "<input type='hidden' name='cnt' value='" . $_POST['cnt'] . "' />";
            $resultForm .= "</form>";
            $resultForm .= "<script>
                window.onload = function() {
                    document.forms['encode'].submit();
                }
            </script>'";
            echo $resultForm;
        }
        die();
        break;

    case 'unlockLicense':
        $param = $_GET["param"]; // Encode-olt adat
        $param = Webform::decode($privatekey, $session, $param); // Adat decode-olása
        $param = "?" . $param;

        $serial = Webform::get_valueFromStringUrl($param, "password");
        $seatID = Webform::get_valueFromStringUrl($param, "seatid");

        if (!crm_hardlock::isEmergencyServer($_GET['secondary'])) {
            crm_hardlock::floatingUnlock($serial, $seatID);
        }

        $result = 'result_ok';

        $data = '<Unlock>
            <seatid>' . $seatID . '</seatid>
        </Unlock>';
        break;

    case 'lockLicense':
        $param = $_GET["param"]; // Encode-olt adat
        $param = Webform::decode($privatekey, $session, $param); // Adat decode-olása
        $param = "?" . $param;

        $serial = Webform::get_valueFromStringUrl($param, "password");
        $seatID = Webform::get_valueFromStringUrl($param, "seatid");
        $isid   = Webform::get_valueFromStringUrl($param, "isid");
        $npid   = Webform::get_valueFromStringUrl($param, "npid");
        $ex     = Webform::get_valueFromStringUrl($param, "ex");
        $build  = $_GET['build'];

        if (crm_hardlock::isEmergencyServer($_GET['secondary'])) {
            $floatingLock = true;
            crm_hardlock::secondaryServerLog($serial, 'lockLicense', 'A floating lock lefutott');
        } else {
            $floatingError  = '';
            $computerID     = crm_hardlock::getComputerIdFromNpid($npid);
            $floatingLock   = crm_hardlock::floatingLock($serial, $seatID, $computerID, $floatingError);
        }

        $message = 'Floating Lock message';
        $button = 'Floating Lock button';

        if (isset($ex) && $ex == "true") {
            $useResultForm = true;
        }

        $error = '';
        $result = 'result_ok';

        if (!$floatingLock) {
            $verID = crm_hardlock::GetVerIdFromPassword($serial);
            $error = crm_hardlock::convertFloatingErrorCodeToString($floatingError, $verID, $build);
        }

        $data = '<Lock>
                <seatid>' . $seatID . '</seatid>
                ' . ((isset($error)) ? '<error>' . $error . '</error>' : '') . '
            </Lock>';
        break;

    case 'offlineFloating':
        $serial     = $_POST['serial'];
        $seatID     = $_POST['seatID'];
        $actDate    = date("Y-m-d", strtotime($_POST['actDate']));

        // TODO: errorokat lekezelni (pl. aktivalasi kod)
        $error = ''; // error: invalid date
        $message = '';
        $button = '';
        $result = 'result_ok';

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`h_programs` WHERE prPass = ?";
        Database::getInstance()->query($query, array('s', $serial));
        $program = Database::getInstance()->fetchNext();

        if ($actDate > $program['prFizetve'])
            $actDate = $program['prFizetve'];

        Database::getInstance()->update(
            SYNCADATBAZIS . ".floating_licenses",
            array(
                'offline_expiration_date' => date("Y-m-d", strtotime($_POST['actDate']))
            ),
            array('seatID' => $seatID),
            'ss'
        );

        $query = "SELECT * FROM `" . SYNCADATBAZIS . "`.`floating_licenses` WHERE seatID = ?";
        Database::getInstance()->query($query, array('s', $seatID));
        $floatingLic = Database::getInstance()->fetchNext();

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`p_serial_isid` WHERE serial = ? AND computer_id = ?";
        Database::getInstance()->query($query, array('si', $serial, $floatingLic['computer_id']));
        $serialIsid = Database::getInstance()->fetchNext();

        $napok = Codegen::GetDayInterval(crm_hardlock::getTwTwRootTimeString(), $actDate, true);

        if ($actDate >= '2050-01-01') $napok = 3583;

        $actCode = Codegen::GenerateTimeCode($serial, $serialIsid['isid'], $napok);

        Database::getInstance()->insert(
            'local_crm.floating_log',
            array(
                "seatID"        => $seatID,
                "hlNum"         => substr($serial, 0, 6),
                "inserted"      => date('Y-m-d H:i:s'),
                "isid"          => $serialIsid['isid'],
                "eventID"       => 3,
                "computerID"    => $floatingLic['computer_id']
            ),
            'ssssii'
        );

        $data = "<ManageOfflineResult>
                <ActCode>{$actCode}</ActCode>
                <offlineMode>true</offlineMode>
                " . ((isset($error) && $error != '') ? '<error>' . $error . '</error>' : '') . "
            </ManageOfflineResult>";

        $param = Webform::encode($privatekey, $session, $data);

        Webform::SetWebformResult($session, $result, $param, $message, $button);

        if (isset($_POST['ex']) && $_POST['ex'] == 'true') {
            //header('Location: https://www.archline.hu/maintenance/webform/loginresult.php?lang=' . $lang . '&result=' . $result);
        } else {
            $resultForm .= "<form name='encode' method='GET', action='blank_result.php'>";
            $resultForm .= "<input type='hidden' name='session' value='{$encodedSession}' />";
            $resultForm .= "<input type='hidden' name='{$result}' value='{$param}' />";
            $resultForm .= "</form>";
            $resultForm .= "<script>
                        window.onload = function() {
                            document.forms['encode'].submit();
                        }
                    </script>'";
            echo $resultForm;
        }

        die();
        break;

    case 'removeOffline':
        $serial     = $_POST['serial'];
        $seatID     = $_POST['seatID'];

        Database::getInstance()->update(
            SYNCADATBAZIS . ".floating_licenses",
            array(
                'offline_expiration_date' => ''
            ),
            array('seatID' => $seatID),
            'ss'
        );

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`h_programs` WHERE prPass = ?";
        Database::getInstance()->query($query, array('s', $serial));
        $program = Database::getInstance()->fetchNext();
        $actCode = $program['prActCode'];

        $query = "SELECT * FROM `" . SYNCADATBAZIS . "`.`floating_licenses` WHERE seatID = ?";
        Database::getInstance()->query($query, array('s', $seatID));
        $key = Database::getInstance()->fetchNext();

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`p_serial_isid` WHERE serial = ? AND computer_id = ?";
        Database::getInstance()->query($query, array('si', $serial, $key['computer_id']));
        $p_serial_isid = Database::getInstance()->fetchNext();

        Database::getInstance()->insert(
            'local_crm.floating_log',
            array(
                "seatID"        => $seatID,
                "hlNum"         => substr($serial, 0, 6),
                "inserted"      => date('Y-m-d H:i:s'),
                "isid"          => $p_serial_isid['isid'],
                "eventID"       => 4,
                "computerID"    => $key['computer_id']
            ),
            'ssssii'
        );

        $result = 'result_ok';

        $data = "<ManageOfflineResult>
                <ActCode>{$actCode}</ActCode>
                <offlineMode>false</offlineMode>
            </ManageOfflineResult>";

        $param = Webform::encode($privatekey, $session, $data);

        Webform::SetWebformResult($session, $result, $param, $message, $button);

        if (isset($_POST['ex']) && $_POST['ex'] == 'true') {
            //header('Location: https://www.archline.hu/maintenance/webform/loginresult.php?lang=' . $lang . '&result=' . $result);
        } else {
            $resultForm .= "<form name='encode' method='GET', action='blank_result.php'>";
            $resultForm .= "<input type='hidden' name='session' value='{$encodedSession}' />";
            $resultForm .= "<input type='hidden' name='{$result}' value='{$param}' />";
            $resultForm .= "</form>";
            $resultForm .= "<script>
                        window.onload = function() {
                            document.forms['encode'].submit();
                        }
                    </script>'";
            echo $resultForm;
        }
        die();
        break;

    case 'hlPin':
        $serial = $_POST['serial'];
        $pin    = hash('sha256', $_POST['pin-code']);
        $seatID = $_POST['seatID'];

        $query = "SELECT * FROM `" . SYNCADATBAZIS . "`.`hardlock_ext` WHERE hlNum = ? AND pin = ?";
        Database::getInstance()->query($query, array('ss', substr($serial, 0, 6), $pin));
        $hardlockExt = Database::getInstance()->fetchNext();

        $result = 'result_ok';
        $error = '';

        if (empty($hardlockExt)) {
            $error = 'error: wrong pin code';
        } elseif (!crm_hardlock::isEmergencyServer($_POST['secondary'])) {
            $query = "SELECT * FROM local_crm.hardlock_ext WHERE hlNum = ?";
            Database::getInstance()->query($query, array('s', substr($serial, 0, 6)));
            $localHardlockExtExist = Database::getInstance()->fetchNext();

            if (empty($localHardlockExtExist)) {
                Database::getInstance()->insert(
                    "local_crm.hardlock_ext",
                    array(
                        "seatIDs"   => $seatID,
                        "hlNum"     => substr($serial, 0, 6)
                    ),
                    'ss'
                );
            } else {
                if (strpos($localHardlockExtExist['seatIDs'], $seatID) === false) {
                    $seatIDString = $localHardlockExtExist['seatIDs'] . ';' . $seatID;

                    Database::getInstance()->update(
                        "local_crm.hardlock_ext",
                        array(
                            'seatIDs' => $seatIDString
                        ),
                        array('hlNum' => substr($serial, 0, 6)),
                        'ss'
                    );
                }
            }
        }

        $data = "<PIN>
                <seatid>{$seatID}</seatid>
                " . ((isset($error)) ? '<error>' . $error . '</error>' : '') . "
            </PIN>";

        $param = Webform::encode($privatekey, $session, $data);

        Webform::SetWebformResult($session, $result, $param, $message, $button);

        if (isset($_POST['ex']) && $_POST['ex'] == 'true') {
            //header('Location: https://www.archline.hu/maintenance/webform/loginresult.php?lang=' . $lang . '&result=' . $result);
        } else {
            $resultForm .= "<form name='encode' method='GET', action='blank_result.php'>";
            $resultForm .= "<input type='hidden' name='session' value='{$encodedSession}' />";
            $resultForm .= "<input type='hidden' name='{$result}' value='{$param}' />";
            $resultForm .= "</form>";
            $resultForm .= "<script>
                        window.onload = function() {
                            document.forms['encode'].submit();
                        }
                    </script>'";
            echo $resultForm;
        }
        die();
        break;

    case 'changeComputerName':
        Database::getInstance()->update(
            CRMADATBAZIS . ".computers",
            array(
                'custom_name' => $_POST['computerName']
            ),
            array('id' => $_POST['computerID']),
            'si'
        );

        header("Location: " . $_SERVER['HTTP_REFERER']);
        die();
        break;

    case 'get_trial':
        $result = 'result_ok';
        $error = '';
        $captchaError = true;
        $ver = $_POST['ver'];

        $resource = new Resource($_POST['ctrID']);

        if ($_SERVER['REMOTE_ADDR'] == '106.120.112.154') {
            $checkCaptcha = true;
        } else {
            $checkCaptcha = crm_hardlock::checkCaptcha($_POST['g-recaptcha-response']);
        }

        if (!$checkCaptcha) {
            $error = $resource->getDlgString('12109');
        }

        if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $error = $resource->getDlgString('12106');
            $captchaError = false;
        }

        $query = "SELECT id, captcha, versionInfo, seatID FROM local_crm.trial_requests WHERE email = ?;";
        Database::getInstance()->query($query, array('s', $_POST['email']));
        $trialUser = Database::getInstance()->fetchNext();

        $captcha = $checkCaptcha ? 'success' : 'failed';

        $prod       = $_POST['se'] == 'LT' ? 0 : (int)$_POST['prod'];
        $product    = crm_hardlock::getProduction($se, $prod);

        if (empty($trialUser) && ($error == '' || $captchaError)) {
            $versionInfoArray[$product]                 = array();
            $versionInfoArray[$product][$ver]           = array();
            $versionInfoArray[$product][$ver]['count']  = 1;

            $versionInfo = $error == '' ? json_encode($versionInfoArray, JSON_UNESCAPED_SLASHES) : '';

            Database::getInstance()->insert(
                'local_crm.trial_requests',
                array(
                    "firstname"     => $_POST['firstname'],
                    "lastname"      => $_POST['lastname'],
                    "email"         => $_POST['email'],
                    "phone"         => $_POST['phone'],
                    "distID"        => $_POST['distID'],
                    "insert_date"   => date('Y-m-d H:i:s'),
                    "seatID"        => $_POST['seatID'],
                    "captcha"       => $captcha,
                    "versionInfo"   => $versionInfo,
                    "update_date"   => date('Y-m-d H:i:s')
                ),
                'ssssisssss',
                false
            );
        }

        if (!empty($trialUser)) {
            $versionInfoArray   = json_decode(stripslashes($trialUser['versionInfo']), true);
            $currentVersionInfo = $versionInfoArray[$product];
            $currentVersion     = $currentVersionInfo[$ver];

            if ($error == '' && $currentVersion != null) {
                if ($trialUser['seatID'] != $_POST['seatID']) {
                    $currentYear    = crm_hardlock::GetLaunchYearFromVer8And9($ver);
                    $error          = $resource->getDlgString('12110', $currentYear);
                }
            }

            if ($error == '' && $currentVersion == null) {
                if (array_key_exists($product, $versionInfoArray)) {
                    $versionInfoArray[$product][$ver]['count'] = 1;
                } else {
                    $versionInfoArray[$product]                 = array();
                    $versionInfoArray[$product][$ver]           = array();
                    $versionInfoArray[$product][$ver]['count']  = 1;
                }
            }

            if ($currentVersion != null && $checkCaptcha) {
                $versionInfoArray[$product][$ver]['count']++;
            }

            if (($error == '' && $currentVersion == null) || ($currentVersion != null && $checkCaptcha)) {
                $versionInfo = json_encode($versionInfoArray, JSON_UNESCAPED_SLASHES);

                Database::getInstance()->update(
                    "local_crm.trial_requests",
                    array(
                        'versionInfo' => $versionInfo,
                        'update_date' => date('Y-m-d H:i:s')
                    ),
                    array('id' => $trialUser['id']),
                    'ssi',
                    false
                );
            }
        }

        if (!empty($trialUser) && $error == '') {
            Database::getInstance()->update(
                "local_crm.trial_requests",
                array(
                    'captcha'   => $captcha,
                    'distID'    => $_POST['distID'],
                    'seatID'    => $_POST['seatID'],
                    "firstname" => $_POST['firstname'],
                    "lastname"  => $_POST['lastname'],
                    "phone"     => $_POST['phone']
                ),
                array('id' => $trialUser['id']),
                'sissssi'
            );
        }

        if ($error == '') {
            $prodName   = crm_hardlock::getProductNameByID($prod);
            $year       = crm_hardlock::GetLaunchYearFromVer8And9($ver);

            $subject = 'ARCHLine.XP ' . $year . ' Trial Request';
            $headers = "Content-Type: text/html; charset=utf-8\r\n";
            //$headers .= 'Bcc: tamas@cadline.hu, mate.nagy@cadline.hu' . "\r\n";

            $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`distributors` WHERE id = ?";
            Database::getInstance()->query($query, array('i', $_POST['distID']));
            $dealer = Database::getInstance()->fetchNext();

            if (!empty($dealer) && $dealer['email'] != '') {
                $message = "Dear Distributor, <br><br>

                    This message is automatically generated because we have received an ARCHLine.XP Trial download with the following user details: <br><br>
                    
                    Name: <b>" . $_POST['firstname'] . " " . $_POST['lastname'] . "</b> <br>
                    Email: <b>" . $_POST['email'] . "</b> <br>
                    Phone: <b>" . $_POST['phone'] . "</b> <br>
                    Product: <b>" . $prodName . "</b> <br>
                    Version: <b>" . $year . "</b> <br><br>
                    
                    During installation, the user selected you as the local representative to contact. <br>
                    " . $dealer['name'] . "
                    
                    Best regards, <br><br>
                    
                    partnering@archlinexp.com <br>
                    www.archlinexp.com <br>
                    CadLine Ltd. <br>
                    1037 Budapest, Montevideo street 3/b <br>
                    Hungary. ";

                mail($dealer['email'], $subject, $message, $headers);
            } else {
                $message = "Name: <b>" . $_POST['firstname'] . " " . $_POST['lastname'] . "</b> <br>
                    Email: <b>" . $_POST['email'] . "</b> <br>
                    Phone: <b>" . $_POST['phone'] . "</b> <br>
                    Distributor: <b>" . $dealer['name'] . "</b> <br>
                    Product: <b>" . $prodName . "</b> <br>
                    Version: <b>" . $year . "</b>";

                mail('mate.nagy@cadline.hu', $subject, $message, $headers);
            }

            $emailSubject = $_POST['ctrID'] == '36' ? "Üdvözlünk az ARCHLine.XP programban! Kezdjük el ...!" : "Welcome to ARCHLine.XP! Let's get started";
            crm_hardlock::sentTrialEmail($_POST['email'], $_POST['firstname'] . " " . $_POST['lastname'], $_POST['phone'], $dealer['name'], $prodName, $year, $emailSubject, $_POST['ctrID']);

            $crmEmailQuery = "SELECT nUserID FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE email = ? LIMIT 1;";
            Database::getInstance()->query($crmEmailQuery, array('s', $_POST['email']));
            $crmEmail = Database::getInstance()->fetchNext();
            if (!empty($crmEmail)) {
                $topicID = $_POST['ctrID'] == '36' ? 395 : 396;

                Database::getInstance()->insert(
                    CRMADATBAZIS . ".u_history",
                    array(
                        "nUserID"       => $crmEmail['nUserID'],
                        "nTopicID"      => $topicID,
                        "dateEvent"     => date('Y-m-d'),
                        "strPlace"      => "web",
                        "strInfo"       => "regisztrált",
                        "nManagerID"    => 36,
                        "insertDate"    => date('Y-m-d H:i:s')
                    ),
                    'iisssis'
                );

                $phone = $_POST['phone'];
                $phone = str_replace('-', '', $phone);
                $phone = str_replace(' ', '', $phone);
                $phone = str_replace('+', '', $phone);
                $phone = str_replace('/', '', $phone);
                $phone = str_replace('.', '', $phone);
                $phone = str_replace('  ', '', $phone);

                $userQuery = "SELECT nUserID, strTel FROM `" . CRMADATBAZIS . "`.`users` WHERE nUserID = ? LIMIT 1;";
                Database::getInstance()->query($userQuery, array('i', $crmEmail['nUserID']));
                $crmUser = Database::getInstance()->fetchNext();

                if (!empty($crmUser) && ($crmUser['strTel'] == '' || !strpos($crmUser['strTel'], $phone))) {
                    if ($crmUser['strTel'] != '') {
                        $strTel = $crmUser['strTel'] . ';' . $phone;
                    } else {
                        $strTel = ';' . $phone;
                    }
                    $updateUserQuery = "UPDATE `" . CRMADATBAZIS . "`.`users` SET strTel = ? WHERE nUserID = ? LIMIT 1;";
                    Database::getInstance()->query($updateUserQuery, array('si', $strTel, $crmUser['nUserID']));
                }
            }

            if (!empty($dealer) && $dealer['custom_trial_api'] != '') {
                $jsonUser           = new stdClass();
                $jsonUser->name     = $_POST['firstname'] . " " . $_POST['lastname'];
                $jsonUser->email    = $_POST['email'];
                $jsonUser->prodName = $prodName;
                $jsonUser->year     = $year;
                $jsonUser->phone    = $_POST['phone'];

                $jsonString     = json_encode($jsonUser);
                $encodedJson    = base64_encode($jsonString); // base64 encode-olt JSON

                $postData = [
                    'data' => $encodedJson
                ];

                $cURLConnection = curl_init($dealer['custom_trial_api']);
                curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $postData);
                curl_exec($cURLConnection);
            }
        }

        $data = "<TrialResult>
                " . ((isset($error)) ? '<error>' . $error . '</error>' : '') . "
            </TrialResult>";

        $param = Webform::encode($privatekey, $session, $data);

        Webform::SetWebformResult($session, $result, $param, $message, $button);

        if (isset($_POST['ex']) && $_POST['ex'] == 'true') {
            //header('Location: https://www.archline.hu/maintenance/webform/loginresult.php?lang=' . $lang . '&result=' . $result);
        } else {
            $resultForm .= "<form name='encode' method='GET', action='blank_result.php'>";
            $resultForm .= "<input type='hidden' name='session' value='{$encodedSession}' />";
            $resultForm .= "<input type='hidden' name='{$result}' value='{$param}' />";
            $resultForm .= "</form>";
            $resultForm .= "<script>
                        window.onload = function() {
                            document.forms['encode'].submit();
                        }
                    </script>'";
            echo $resultForm;
        }
        die();
        break;

    case 'aiRender':
        if (!isset($_POST['param']) || $_POST['param'] == '') {
            die();
        }

        set_time_limit(600);

        $privatekey     = Webform::GetWebformPrivateKey();
        $decoded_param  = Webform::decode($privatekey, $session, $_POST['param']);
        $decoded_param  = "?{$decoded_param}";
        $alToken        = Webform::get_valueFromStringUrl($decoded_param, "tokenid");
        $fileName       = Webform::get_valueFromStringUrl($decoded_param, "fileName");
        $serial         = Webform::get_valueFromStringUrl($decoded_param, "serial");
        $baseUrl        = 'https://www.archlinexp.com/maintenance/webform/ai_render_upload.php?';
        $baseUrl        .= 'session=' . $_POST['session'] . '&param=' . $_POST['param'] . '&cnt=' . $_POST['cnt'];
        $promptEng      = isset($_POST['prompt']) && $_POST['prompt'] != '' ? $_POST['prompt'] : 'Modern';

        $nUserID = crm_hardlock::GetUserIdFromToken($alToken);
        if ($nUserID < 0) {
            $crmUserId = crm_hardlock::checkJoomlaAccount($serial);
            if (!$crmUserId) {
                $resource = new Resource($_POST['cnt']);

                echo '<style>
                    h1 {
                        text-align: center;
                        margin-top: 45vh;
                        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
                        font-weight: 500;
                    }
                </style>';

                echo '<h1>' . $resource->getDlgString('12519') . '</h1>';
                die();
            }

            $nUserID = $crmUserId;
        }

        $remainingCredits = crm_hardlock::getRemainingCredits($nUserID);
        $creditNumber = $_POST['type'] == 'video' ? 10 : 1;

        if ($remainingCredits < $creditNumber) {
            header('Location: ' . $baseUrl);
            die();
        }

        if (substr($serial, 0, 2) == '99') {
            $query = "SELECT * FROM mobileview.ai_render_credit_history WHERE nUserID = ?;";
            Database::getInstance()->query($query, array('i', $nUserID));
            $res = Database::getInstance()->fetchNext();

            if (empty($res)) {
                header('Location: ' . $baseUrl);
                die();
            }
        }

        $viewerUrl      = 'https://mobileview.archlinexp.com';
        $authorization  = 'Authorization: al-jHfdBNh458754bnfgjhsdfj834j54bndFjSFsdb348hN98jngUnjngRTbjngjn4x';
        $token          = '';
        $fileUrl        = isset($_POST['fileUrl']) ? $_POST['fileUrl'] : '';
        $renderId       = '';
        $guid           = '';
        $roomType       = isset($_POST['roomType']) ? $_POST['roomType'] : '';
        $roomStyle      = isset($_POST['roomStyle']) ? $_POST['roomStyle'] : '';
        $movementType   = isset($_POST['movementType']) ? $_POST['movementType'] : '';
        $direction      = isset($_POST['direction']) ? $_POST['direction'] : '';
        $error_msg      = '';

        $loginResult            = array();
        $loginResult['tokenId'] = $alToken;
        $loginJsonContent       = json_encode($loginResult);

        $curl = curl_init($viewerUrl . '/api/al-login');
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json", $authorization));
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($curl, CURLOPT_POSTFIELDS, $loginJsonContent);

        $json_login_response = curl_exec($curl);
        curl_close($curl);

        if ($json_login_response) {
            $loginResponse = json_decode($json_login_response);
            if (isset($loginResponse->token) && $loginResponse->token != '') {
                $token = $loginResponse->token;
            }
        }

        if ($token == '') {
            // TODO: Hiba
            echo 'An Error occured. Missing token.';
            die();
        }

        if ($fileUrl == '') {
            $imageResult                = array();
            $imageResult['fileName']    = $fileName;
            $imageJsonContent           = json_encode($imageResult);

            $curl = curl_init($viewerUrl . '/api/render/getRenderImage');
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json", $authorization));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($curl, CURLOPT_POSTFIELDS, $imageJsonContent);

            $json_image_response = curl_exec($curl);
            curl_close($curl);

            if ($json_image_response) {
                $imageResponse = json_decode($json_image_response);
                if (isset($imageResponse->fileUrl) && $imageResponse->fileUrl != '') {
                    $fileUrl = $imageResponse->fileUrl;
                }
            }
        }

        if ($fileUrl == '') {
            // TODO: Hiba
            echo 'An Error occured. Missing file.';
            die();
        }

        $renderFields = [
            'fileUrl'       => $fileUrl,
            'external'      => true,
            'prompt'        => $promptEng,
            'scenario'      => strtolower($_POST['scenario']),
            'style'         => strtolower($_POST['style']),
            'type'          => strtolower($_POST['type']),
            'imgType'       => strtolower($_POST['imgType']),
            'roomType'      => $roomType,
            'roomStyle'     => $roomStyle,
            'movementType'  => $movementType,
            'direction'     => $direction
        ];

        $curl = curl_init($viewerUrl . '/api/render/renderImage');
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token));
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $renderFields);

        $json_render_response = curl_exec($curl);
        curl_close($curl);

        if ($json_render_response) {
            $renderResponse = json_decode($json_render_response);
            if (isset($renderResponse->renderId) && $renderResponse->renderId != '') {
                $guid       = $renderResponse->guid;
                $renderId   = $renderResponse->renderId;
            } else {
                if (isset($renderResponse->errors)) {
                    $curl = curl_init($viewerUrl . '/api/logout');
                    curl_setopt($curl, CURLOPT_HEADER, false);
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token));
                    curl_setopt($curl, CURLOPT_POST, true);
                    curl_exec($curl);
                    curl_close($curl);

                    echo $renderResponse->errors->message;
                    die();
                }
            }
        }

        if ($guid == '' || $renderId == '') {
            if (substr($serial, 0, 6) == 950298) {
                echo $json_render_response;
                die();
            }
            echo 'An Error occured.';
            die();
        }

        $imageFields = [
            'renderId'  => $renderId,
            'guid'      => $guid,
            'fileName'  => $fileName,
            'type'      => strtolower($_POST['type'])
        ];
        $imageStatus    = 'pending';
        $error          = false;
        $message        = '';

        $curl = curl_init($viewerUrl . '/api/render/getAiRenderImage');
        do {
            sleep(10);

            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token));
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $imageFields);

            $json_rendered_image_response = curl_exec($curl);

            if ($json_rendered_image_response) {
                $renderedImageResponse = json_decode($json_rendered_image_response);
                if (isset($renderedImageResponse->status) && $renderedImageResponse->status != '') {
                    $imageUrl       = $renderedImageResponse->url;
                    $imageStatus    = $renderedImageResponse->status;

                    if ($imageStatus == 'error') {
                        $error = true;
                        break;
                    }

                    if ($imageStatus == 'success') {
                        $error = false;
                        break;
                    }
                } else {
                    $error = true;
                    break;
                }
            } else {
                $error = true;
                break;
            }
        } while ($imageStatus != 'success' && $imageStatus != 'error');
        curl_close($curl);

        if ($error) {
            echo 'An Error occured.';
            die();
        }

        $curl = curl_init($viewerUrl . '/api/logout');
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token));
        curl_setopt($curl, CURLOPT_POST, true);
        curl_exec($curl);
        curl_close($curl);

        $baseUrl .= $baseUrl . '&render=' . $guid;

        header('Location: ' . $baseUrl);
        die();
        break;

    default:
        die();
        break;
}

resultBack:
if ($data != '') {
    $param = Webform::encode($privatekey, $session, $data);

    if (!crm_hardlock::isEmergencyServer($_GET['secondary'])) {
        Webform::SetWebformResult($session, $result, $param, $message, $button);
    }

    /*if (crm_hardlock::isEmergencyServer($_GET['secondary'])) {
        var_dump('session=' . $encodedSession . '&' . $result . '=' . $param);
        die();
    }*/

    if ($useResultForm) {
        $resultForm .= "<form name='encode' method='POST', action='result.php'>";

        if ($lang != '') $resultForm .= "<input type='hidden' name='lang' value='{$lang}' />";
        if ($action == 'exchange_registration') $resultForm .= "<input type='hidden' name='note' value='true' />";

        $resultForm .= "<input type='hidden' name='session' value='{$session}' />";
        $resultForm .= "<input type='hidden' name='{$result}' value='{$param}' />";
        $resultForm .= "</form>";
        $resultForm .= "<script>
                window.onload = function(){
                    document.forms['encode'].submit();
                }
            </script>'";
        echo $resultForm;
    } else {
        $resultXml .= '<' . '?' . 'xml version="1.0"' . '?' . '><WebFormResult>';
        $resultXml .= '?session=' . $encodedSession . '&' . $result . '=' . $param . '&';
        $resultXml .= '</WebFormResult>';

        header('Content-Type: text/xml; charset=utf-8');
        header('Content-Disposition: inline; filename=response.xml');

        echo $resultXml;
    }
}



/* 
- kapott adatok (serial, seatid)
- xml visszateres
- ActCode az XML-be
*/
