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

$action         = isset($_POST["action"]) ? $_POST["action"] : $_GET["action"];
$encodedSession = isset($_POST["session"]) ? $_POST["session"] : $_GET["session"];
$param          = isset($_POST['param']) ? $_POST['param'] : $_GET['param'];
$authCode       = isset($_POST["authCode"]) ? $_POST["authCode"] : $_GET["authCode"];
$session        = base64_decode($encodedSession);
$privatekey     = Webform::GetWebformPrivateKey();
$showDealerDlg  = 'true';
$showAccManDlg  = 'false';
$selectedDealer = -1;

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

$decoded_param = Webform::decode($privatekey, $session, $param);
$decoded_param = "?{$decoded_param}";

$token  = Webform::get_valueFromStringUrl($decoded_param, "tokenid");
$result = 'result_ok';

if (crm_hardlock::isEmergencyServer($_GET['secondary'])) {
    $res = array();
    $showDealerDlg = 'false';
    $showAccManDlg = 'false';
} else {
    $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`archline_tokens` WHERE tokenID = ?";
    Database::getInstance()->query($query, array('s', $token));
    $res = Database::getInstance()->fetchNext();
}

/*if (!empty($res) && $res['nUserID'] < 0)
    $showDealerDlg = 'false';*/

if (!empty($res) && $res['nUserID'] > 0) {
    $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`users` WHERE nUserID = ?";
    Database::getInstance()->query($query, array('i', $res['nUserID']));
    $user = Database::getInstance()->fetchNext();

    $selectedDealer = $user['distID_by_user'];

    // 25407, 84986, 26765
    if ($res['nUserID'] == 26765)
        $showAccManDlg = 'true';
}

$data = "<GetParameters>
    <ShowDealerDlg>{$showDealerDlg}</ShowDealerDlg>
    <SelectedDealer>{$selectedDealer}</SelectedDealer>
    <ShowAccManDlg>{$showAccManDlg}</ShowAccManDlg>
</GetParameters>";

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

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

$resultXml .= '<' . '?' . 'xml version="1.0"' . '?' . '><WebFormResult>';
$resultXml .= '?session=' . $encodedSession . '&' . $result . '=' . $result_param . '&';
$resultXml .= '</WebFormResult>';

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

echo $resultXml;
