<?php

class CabinetClass
{
    public $_billLink = Array();
    public $_cookieAuth = 'empty';
    public $_fileNameLog = 'log_debug.txt';
    public $_attributesOut = Array();
    public $_serverDate = Array();
    public $_outPage = 'login';
    public $_statusAuth = false;
    public $_paramsInput = Array();
    public $_blockCabinet = 0;
    public $_globalSetAuth = array('doauthonlypass' => 0);
    public $_debug = 0;
    public $_showChangeMac = false;
    public $_firstAfterAuth = false;
    public $_module = false;
    public $_db = null;
    private $_debug_mode = 0;
    private $_debug_http = array();

    /**
     * Конструтор класса
     **/
    public function __construct($billLink, $paramsInput, $debugMode = 0)
    {
        $this->_billLink = $billLink;
        $this->_paramsInput = $paramsInput;
        $this->_debug_mode = $debugMode;
        $this->getCookie();

        # Получаем конфиг кабинетаXML
        //$this->getConfigXml();

        # Получаем конфиг кабинета DB or conf.php
        $this->getCabinetConfig();
    }

    public function __destruct()
    {
        if($this->_debug_mode){
            $this->printDebugHttp();
        }
    }

    /**
     * Обработчик запросов
     **/
    public function proceedRequest()
    {
        # Получаем Подвал
        $this->getFooter();

        # Проверка авторизации
        $this->checkAuth();

        $params = $this->_paramsInput;

        if (isset($params['action']) and $params['action'] == 'restore') {
            $this->menuRestorePassword();
        } elseif (isset($params['action'], $params['type']) and $params['action'] == 'register') {
            $this->menuRegistration();
        } elseif (!$this->_statusAuth or (isset($params['action']) and $params['action'] == 'exit') or isset($params['auth_login']) or isset($params['l'], $params['p'])) {
            $this->loginAuth();
        }

        if ($this->_statusAuth) {

            # Если что только авторизовалаись
            if ($this->_firstAfterAuth) {
                $this->checkChangeMac();
            }

            # Получить данные пользователя.
            $this->getUserData();

            # Получаем Время сервера
            $this->getServerDate();

            $start_time = strtotime($this->_serverDate['now_date']. "23:55:00");
            $stop_time = strtotime('+1 day', strtotime($this->_serverDate['now_date']. "00:00:05"));
            $now_time =  strtotime($this->_serverDate['format']);

            # Блокировка кабинета на период перерасчетов
            if ($now_time > $start_time AND $now_time < $stop_time) {
                $this->_blockCabinet = 1;
                $this->loginAuth();
            } else {

                $action = $this->getAction();

                switch ($action) {
                    case "contact":
                        $this->menuContact();
                        break;
                    case "news":
                        $this->menuNews();
                        break;
                    case "historypayment":
                        $this->menuHistoryPayment();
                        break;
                    case "historysession":
                        $this->menuHistorySession();
                        break;
                    case "tariff":
                        $this->menuChangeTariff();
                        break;
                    case "payment":
                        $this->menuPayment();
                        break;
                    case "turbo":
                        $this->menuTurbo();
                        break;
                    case "credit":
                        $this->menuCredit();
                        break;
                    case "realip":
                        $this->menuRealip();
                        break;
                    case "freeze":
                        $this->menuFreeze();
                        break;
                    case "profile":
                        $this->menuProfile();
                        break;
                    case "perevod":
                        $this->menuPerevod();
                        break;
                    case "ticket":
                        $this->menuTicket();
                        break;
                    case "rentsoft":
                        $this->menuRentsoft();
                        break;
                    case "ticketall":
                        $this->menuTicketAll();
                        break;
                    case "getip":
                        $this->debug_GetIP();
                        break;
                    case "checkchangemac":
                        $this->debug_CheckChangeMac();
                        break;
                    case "gendogovor":
                        $this->genDogovor();
                        break;
                    case "geninvoice":
                        $this->genInvoice();
                        break;
                    case "services":
                        $this->menuOtherServices();
                        break;
                    case "omegatv":
                        $this->menuOmegaTvServices();
                        break;
                    case "trinitytv":
                        $this->menuTrinityTvServices();
                        break;
                    default:
                        $this->checkPageFromAction($action);
                }

                # Получаем Меню.
                # Строится самое последнее так как может измениться в процессе заказа услуг
                $this->getMenu();

                # Получаем Шапку
                $this->getHeader();
            }
        }
    }

    /**
     * Получить форматированную текующую дату
     **/
    public function getDate()
    {
        return date('d.m.Y H:i:s');
    }

    /**
     * Запись в лог-файл
     *
     * @param $textLog
     */
    public function doLog($textLog)
    {
        $open_file = fopen($this->_fileNameLog, 'a+');
        fwrite($open_file, $this->getDate() . ': ' . $textLog . "\r\n");
        fclose($open_file);
    }

    public function debug_GetIP()
    {

        echo "Your IP:" . $_SERVER['REMOTE_ADDR'];
        die();
    }

    public function debug_CheckChangeMac()
    {
        echo "Result:  " . print_r($this->getCheckChangeMac(), true);
        echo "<br> Your IP:" . $_SERVER['REMOTE_ADDR'];
        die();
    }


    /*
     * Запись языка в куки
     */
    public function setLanquaqe($lanq)
    {
    }

    public function checkAuth()
    {
        $url = $this->_billLink['checkloggedin'];
        $response = $this->sendQuery($url, 'get', '', 0);

//		var_dump($response);

        $responseJSON = json_decode($response, true);

        // Если не авторизован то пытаемся авторизоваться по IP
        if (isset($responseJSON['result'])) {
            $this->_statusAuth = true;
        } else {
            # Предположительно действие сразу после входа в ЛК
            $this->_statusAuth = false;
            $this->authByIp();
            $this->_firstAfterAuth = true;
        }
    }


    public function getCheckChangeMac()
    {
        $url = $this->_billLink['checkchangemac'];

//		$param = "user_ip=" . $_SERVER['REMOTE_ADDR'];
        $param = array("user_ip" => $_SERVER['REMOTE_ADDR']);

        $response = $this->sendQuery($url, 'post', $param, 0);
        $responseJSON = json_decode($response, true);

        return $responseJSON;
    }

    public function checkChangeMac()
    {

        $responseJSON = $this->getCheckChangeMac();

        if (isset($responseJSON['result'], $this->_attributesOut['config']['gui']['user_cab_reg_mac']) AND $this->_attributesOut['config']['gui']['user_cab_reg_mac'] == '1' AND $responseJSON['result'] == '0') {
            $this->_showChangeMac = true;
        }
    }

    private function genDogovor()
    {
        $url = $this->_billLink['gendogovorflex'];
        $response = $this->sendQuery($url, 'get', '', 0);

        echo $response;
        exit;
    }


    private function genInvoice()
    {
        $url = $this->_billLink['geninvoice'];
        $response = $this->sendQuery($url, 'get', '', 0);

        echo $response;
        exit;
    }

    public function authByIp()
    {

        $url = $this->_billLink['authip'];

        if ($this->_cookieAuth <> '' and $this->_cookieAuth <> 'empty') {
            $responseQuery = $this->sendQuery($url, 'post', '', 0);
        } else {
            $responseQuery = $this->sendQuery($url, 'post', '', 1);
//            $valueCookie = $this->parserCookie($responseQuery);
//            $this->setCookie($valueCookie);
        }

        $statusAuth = $this->xmlParser2($responseQuery);

        if (isset($statusAuth['user'][0])) {
            $result = $statusAuth['user'][0];
        }

        # Изменяем глобальный статус авторизации пользователя
        if (isset($result['enable']) and $result['enable'] == '1') {
            $this->_statusAuth = true;
        } else {
            $this->_statusAuth = false;
        }
    }

    public function getAction()
    {
        if (isset($this->_paramsInput['action'])) {
            $action = $this->_paramsInput['action'];
        } else {

            #Пополнение копейка (вернуть ссылку)
            if (isset($this->_paramsInput['nAmount'])) {
                $action = 'payment';
            } else {
                $action = '';
            }
        }

        # Если был вход в кабинет
        if ($this->_firstAfterAuth) {

            if ($this->_showChangeMac) {
                # Стартовая страница
                $action = 'index';
            } elseif (isset($this->_attributesOut['user']['blocked']) AND
                $this->_attributesOut['user']['credit_stop'] != '1' AND
                $this->_attributesOut['user']['blocked'] == '1' AND
                $this->_attributesOut['user']['deletedtable'] == '0' AND
                $this->_attributesOut['user']['otkluchentable'] == '0' AND

                $this->_attributesOut['config']['gui']['autoinit_enabled'] == '1' AND
                $this->_attributesOut['config']['gui']['autoinit_limit'] == '1' AND

//				$this->_attributesOut['xml']['autoinit']['@attributes']['enabled'] == '1' AND
//				$this->_attributesOut['xml']['autoinit']['@attributes']['limit'] == '1' AND
                ($this->_attributesOut['user']['do_credit_vremen_global'] == '1' OR
                    $this->_attributesOut['user']['do_credit_procent_vremen_global'] == '1' OR
                    $this->_attributesOut['user']['do_credit_swing_date'] == '1')
            ) {
                # Кредит
                $action = 'credit';
            } elseif (
                ($this->_attributesOut['config']['gui']['autoinit_enabled'] == '1') AND
                ($this->_attributesOut['config']['gui']['autoinit_unfreezing'] == '1') AND
//				($this->_attributesOut['xml']['autoinit']['@attributes']['enabled'] == '1') AND
//				($this->_attributesOut['xml']['autoinit']['@attributes']['unfreezing'] == '1') AND
                isset($this->_attributesOut['user']['frezetable']) AND
                ($this->_attributesOut['user']['frezetable'] == '1')
            ) {
                # Заморозка
                $action = 'freeze';
            } else {
                # Стартовая страница
                $action = $this->_attributesOut['config']['start_page'];
            }

            # Если авторизация после регистрации, то на пополнение
            if (isset($this->_paramsInput['auth_login_reg'])) {
                # Пополнение
                $action = 'payment';
            }
        }

        return $action;
    }


    public function checkPageFromAction($action)
    {
        if (!empty($this->_paramsInput['module']) AND file_exists($this->_attributesOut['config']['path_template'] . '/modules/' . $this->_paramsInput['module'] . '/' . $action . '.tpl')) {
            $this->_outPage = $action;
            $this->_module = $this->_paramsInput['module'];
        } elseif (file_exists($this->_attributesOut['config']['path_template'] . '/customtpls/' . $action . '.tpl')) {
            $this->_outPage = $action;
        } elseif (file_exists($this->_attributesOut['config']['path_template'] . '/' . $action . '.tpl')) {
            $this->_outPage = $action;
        } else {
            #Получаем новости
            $this->menuNews();
            $this->_outPage = 'index';
        }
    }

    public function getTpl($nameTpl, $paramArray = array())
    {
        # Создаем екземпляр класса
        $tpl = new TemplateClass($this->_attributesOut['config']['path_template']);
        $tpl->set('val', $paramArray);
        $outTpl = $tpl->out($nameTpl);

        # Уничтожаем екземпляр класса
        unset($tpl);

        return $outTpl;
    }


    /**
     * Формирование массива данных для шаблона
     **/
    public function attributesArrayOut()
    {

        $outArray = Array();

        $data = $this->_attributesOut;

        if (isset($data['logInAuth'])) {
            foreach ($data['logInAuth'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['user'])) {
            foreach ($data['user'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['config'])) {
            foreach ($data['config'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['header'])) {
            foreach ($data['header'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['footer'])) {
            foreach ($data['footer'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['main_menu'])) {
            foreach ($data['main_menu'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['payment'])) {
            foreach ($data['payment'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['tarif'])) {
            foreach ($data['tarif'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['turbo'])) {
            foreach ($data['turbo'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['freeze'])) {
            foreach ($data['freeze'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['news'])) {
            foreach ($data['news'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['historyPayment'])) {
            foreach ($data['historyPayment'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['historySession'])) {
            foreach ($data['historySession'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['profile'])) {
            foreach ($data['profile'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['ticket'])) {
            foreach ($data['ticket'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['ticketAll'])) {
            foreach ($data['ticketAll'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['realIp'])) {
            foreach ($data['realIp'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['credit'])) {
            foreach ($data['credit'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['perevod'])) {
            foreach ($data['perevod'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['restore'])) {
            foreach ($data['restore'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }

        if (isset($data['register'])) {
            foreach ($data['register'] as $k => $v) {
                $outArray[$k] = $v;
            }
        }


        if (isset($data['rentsoft'])) {
            $outArray['rentsoft'] = $data['rentsoft'];
        }

        if (isset($data['xml'])) {
            $outArray['xml'] = $data['xml'];
        }

        #Авторизация по паролю
        $outArray['do_auth_only_pass'] = $this->_globalSetAuth['doauthonlypass'];

        # Шаблон формы нового тикета
        $outArray['ticket_new_form'] = $this->getTpl('formticket', $outArray);

        $outArray['showChangeMac'] = $this->_showChangeMac;

        return $outArray;
    }


    /**
     * Отправка запроса на получение пароля
     *
     * @param $phone
     *
     * @return mixed
     */
    public function getRestorePassword($phone)
    {
        $url = $this->_billLink['restorepasswordsms'];
        $param = array("phone" => $phone);
        $tempResponse = $this->sendQuery($url, 'post', $param, 0);
        $response = json_decode($tempResponse, true);

        return $response;
    }


    /**
     * Меню востановление пароля
     *
     */
    public function menuRestorePassword()
    {
        $this->_outPage = 'restore';
        $step = 1;
        $restore_step_text = '';

        // Если пришел телефон
        if (isset($this->_paramsInput['phone'])) {

            $response = $this->getRestorePassword($this->_paramsInput['phone']);

            if (isset($response['result']) and $response['result'] == '0') {
                $restore_step_text = T_('На Ваш телефон отправлено сообщение с данными для авторизации.');
                $step = 2;
            } elseif (isset($response['result'])) {
                $restore_step_text = $this->getErrorText($response['result']);
            } else {
                $restore_step_text = $this->getErrorText(1000);
            }
        }

        $this->_attributesOut['restore'] = Array(
            'restore_step'      => $step,
            'restore_step_text' => $restore_step_text
        );
    }


    /**
     * Время на сервере МикБилл
     **/
    public function getServerDate()
    {
        $url = $this->_billLink['getserverdate'];
        $responseQuery = $this->sendQuery($url, 'get', '', 0);
        $responseQuery = json_decode($responseQuery, true);

        $this->_serverDate = $responseQuery['data'];
    }


    /**
     * Конфиг XML ЛК (old)
     **/
    public function getConfigXml()
    {
        $url = $this->_billLink['config_xml'];
        $responseQuery = $this->sendQuery($url, 'get', '', 0);
        $xmlArray = $this->xmlParser($responseQuery);

        $this->_attributesOut['xml'] = $xmlArray;
    }


    /**
     * Поулчение текущих куков в переменную
     **/
    public function getCookie()
    {
        if (isset($_COOKIE['PHPSESSID'])) {
            $this->_cookieAuth = $_COOKIE['PHPSESSID'];
        }
    }



    /**
     * Установка куков в браузере
     * @param $name
     */
    public function setCookie($name)
    {
        $this->_cookieAuth = $name;
        SetCookie("PHPSESSID", $name, time() + 3600);
    }

    /**
     * Удаление куков
     **/
    public function delCookie()
    {
        SetCookie("PHPSESSID", '');
    }


    /**
     * Парсер куков
     *
     * @param $input
     * @return null
     */
    public function parserCookie($input)
    {
        preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $input, $cookies);

        $Return_value = null;

        foreach ($cookies as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $key2 => $value2) {

                    $valueCookie = explode('=', $value2);
                    if ($valueCookie['0'] == 'Set-Cookie: PHPSESSID') {
                        $Return_value = $valueCookie['1'];
                    }
                }
            }
        }

        return $Return_value;
    }


    /**
     * Режим отображения скорости в ЛК  Мбит/Кбит/
     *
     * @param $param
     * @param $speed
     * @return string
     */
    public function speedView($param, $speed)
    {
        $result = $speed . ' Kbit/sec';
        if ($param == 1) {
            $result = round($speed / 1024, 2) . ' Mbit/sec';
        }

        if ($speed == 0) {
            $result = T_("Без ограничения");
        }

        return $result;
    }


    /**
     *
     * Транспорт запросов на BackEnd MikBILL
     * @param $url
     * @param $postGet
     * @param $param
     * @param int $newSession
     * @return string
     */
    public function sendQuery($url, $postGet, $param, $newSession = 0)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_REFERER, 'https://mikbill.pro');
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);

        if (isset($_SERVER['HTTP_USER_AGENT'])){
            curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_COOKIESESSION, true);
        curl_setopt($curl, CURLOPT_HEADER, 1);

        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            "X_FORWARDED_FOR:" . $this->getUserIP(),
            "X_FOWARDED_FOR:" . $this->getUserIP()
        ));

        if ($postGet == 'post') {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
        }

        # нестандартный порт
        if (isset($_SERVER['SERVER_PORT']) AND $_SERVER['SERVER_PORT'] != '80' AND $_SERVER['SERVER_PORT'] != '443') {
            curl_setopt($curl, CURLOPT_PORT, $_SERVER['SERVER_PORT']);
        }

        // Параметры $newSession
        // 0 - работать с текущей сессией из куков.
        // 1- получить новую сессию
        if ($newSession == 0) {
            if (($this->_cookieAuth <> '') and ($this->_cookieAuth <> 'empty')) {
                curl_setopt($curl, CURLOPT_COOKIE, "PHPSESSID=" . $this->_cookieAuth);
            }
        }

        $response = curl_exec($curl);

        // Then, after your curl_exec call:
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $header_size);
        $body = substr($response, $header_size);
        $errno = curl_errno($curl);

        // распарсить заголовок; найти в нем сессию; записать в куки
        if ($newSession == 1) {
            $valuePHPSESSID = $this->parserCookie($header);
            if (!empty($valuePHPSESSID)) {
                $this->setCookie($valuePHPSESSID);
            }
        }

        // Если была ошибка курла выведем ее в ответе
        if ($errno) {
            $body = json_encode(array("error" => $errno));
        }

        //Debug http mode
        if($this->_debug_mode){
            $this->debugHttp($url, $this->_cookieAuth, $postGet, $param, $header, $body);
        }

        curl_close($curl);

        return $body;
    }

    private function debugHttp($requestUrl, $requestPhpSessId, $requestMethod, $requestData, $responseHeader, $responseBody)
    {
        $this->_debug_http[] = array(
            "request" => array($requestUrl, $requestPhpSessId, $requestMethod, $requestData),
            "response" => array($responseHeader, $responseBody)
        );
    }

    private function printDebugHttp()
    {
        if(!empty($this->_debug_http)){

            echo "<hr> <h2>DEBUG HTTP MODE:</h2>";
            foreach ($this->_debug_http AS $queryRow){
                echo '
            <pre class="prettyprint linenums"><h4>Request: </h4>
    <b>URL: </b>'.$queryRow['request'][0].'
    <b>PHPSESSID: </b>'.$queryRow['request'][1].' 
    <b>METHOD: </b>'.$queryRow['request'][2].'
    <b>BODY: </b> ' . print_r($queryRow['request'][3], true).' <br><hr><h4>Response: </h4>
    <b>HEADER: </b>'.htmlspecialchars($queryRow['response'][0]).'
    <b>BODY: </b><code class="language-xml">'.htmlspecialchars($queryRow['response'][1]).'</code>
</pre>';
            }
            echo "<br><br><br>";
        }
    }

    /**
     * Узнаем IP клиента (откуда был запрос)
     *
     * @return mixed
     */
    public function getUserIP()
    {
	$ip = '0.0.0.0';
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip=$_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip=$_SERVER['REMOTE_ADDR'];
        }

        return $ip;
    }


    /**
     * Парсер XML
     *
     * @param $input_xml
     * @return mixed
     */
    public function xmlParser($input_xml)
    {
        $xml = simplexml_load_string($input_xml);
        $json = json_encode($xml);
        $result = json_decode($json, true);

        return $result;
    }


    /**
     * Parse XML data into an array structure
     * @param $input_xml
     * @return array
     */
    public function xmlParser2($input_xml)
    {
        $array = Array();
        $reg_exp = '/<(\w+)[^>]*>(.*?)<\/\\1>/s';

        preg_match_all($reg_exp, $input_xml, $match);

        foreach ($match[1] as $key => $val) {
            if (preg_match($reg_exp, $match[2][$key])) {
                $array[$val][] = $this->xmlParser2($match[2][$key]);
            } else {
                $array[$val] = html_entity_decode($match[2][$key]);
            }
        }

        return $array;
    }

    /**
     * Создание главного меню
     */
    public function getMenu()
    {
        $setMenu = array();

        $doPayment = false;
        $doChangeTtarif = false;
        $doTurbo = false;
        $doRealIp = false;
        $doFreeze = false;
        $doCredit = false;
        $doUslugi = false;
        $doPerevod = false;
        $doPaymentHistory = false;
        $doSessionHistory = false;
        $unFreeze = true;
        $userOtkluchen = true;
        $userDeleted = true;

        # Создаем обьект класса
        $tplMenu = new TemplateClass($this->_attributesOut['config']['path_template']);

        # Отключен ли пользователь
        if ($this->_attributesOut['user']['otkluchentable'] == '0') {
            $userOtkluchen = false;
        }

        # Отключен ли пользователь
        if ($this->_attributesOut['user']['deletedtable'] == '0') {
            $userDeleted = false;
        }

        # TODO Пополнение_1
        # Меню "пополнение"
        if (($this->_attributesOut['user']['use_cards'] == '1') OR
            ($this->_attributesOut['user']['use_privat24'] == '1') OR
            ($this->_attributesOut['user']['use_privat_v2'] == '1') OR
            ($this->_attributesOut['user']['use_liqpay'] == '1') OR
            ($this->_attributesOut['user']['use_paymaster'] == '1') OR
            ($this->_attributesOut['user']['use_onpay'] == '1') OR
            ($this->_attributesOut['user']['use_pscb'] == '1') OR
            ($this->_attributesOut['user']['use_robokassa'] == '1') OR
            ($this->_attributesOut['user']['use_wqiwiru'] == '1') OR
            ($this->_attributesOut['user']['use_stripe'] == '1') OR
            ($this->_attributesOut['user']['use_copayco'] == '1') OR
            ($this->_attributesOut['user']['use_paypal'] == '1') OR
            ($this->_attributesOut['user']['use_paykeeper'] == '1') OR
            ($this->_attributesOut['user']['use_ukrpays'] == '1') OR
            ($this->_attributesOut['user']['use_uniteller'] == '1') OR
            ($this->_attributesOut['user']['use_yandex'] == '1') OR
            ($this->_attributesOut['user']['use_portmone'] == '1') OR
            ($this->_attributesOut['user']['use_sberbankrumrch'] == '1') OR
            ($this->_attributesOut['user']['use_fondy'] == '1') OR
            ($this->_attributesOut['user']['use_ipay'] == '1') OR
            ($this->_attributesOut['user']['use_yandexmoney'] == '1') OR
            ($this->_attributesOut['user']['use_cloudpayments'] == '1') OR
            ($this->_attributesOut['user']['use_isbank'] == '1') OR
            ($this->_attributesOut['user']['use_tinkoff'] == '1') OR
            ($this->_attributesOut['user']['use_alfabankru'] == '1') OR
            ($this->_attributesOut['user']['use_paysoft'] == '1') OR
            ($this->_attributesOut['user']['use_ckassa'] == '1') OR
            ($this->_attributesOut['user']['use_masterpass'] == '1') OR
            ($this->_attributesOut['user']['use_simplepay'] == '1') OR
            ($this->_attributesOut['user']['use_lifecell'] == '1')

        ) {
            $doPayment = true;
        }

        # Меню смена тарифа
        if (($this->_attributesOut['user']['do_perevod_na_tarif'] == '1') AND (($this->_attributesOut['user']['zapret_uhoda_s_tarifa'] == '0'))) {
            $doChangeTtarif = true;
        }

        # Меню турбо
        if ($this->_attributesOut['user']['do_turbo'] <> '0') {
            $doTurbo = true;
        }

        # Меню Real IP
        if ($this->_attributesOut['user']['do_real_ip'] <> '0') {
            $doRealIp = true;
        }

        # Меню Perevod
        if ($this->_attributesOut['user']['use_perevod'] <> '0') {
            $doPerevod = true;
        }

        # Меню Заморозка
        if ($this->_attributesOut['user']['kabinet_do_freeze'] <> '0') {
            $doFreeze = true;
        }

        # Включена ли заморозка у абонента
        if ($this->_attributesOut['user']['frezetable'] == '1') {
            $unFreeze = false;
        }

        # Меню кредит
        if ($this->_attributesOut['user']['credit_stop'] != '1' and
            (($this->_attributesOut['user']['do_credit_vremen_global'] == '1') OR
                ($this->_attributesOut['user']['do_credit_procent_vremen_global'] == '1') OR
                ($this->_attributesOut['user']['do_credit_vremen_global'] == '1' AND $this->_attributesOut['user']['do_credit_swing_date'] == '1'))
        ) {
            $doCredit = true;
        }

        # Меню история платежей
        if (isset($this->_attributesOut['config']['gui']['menu_show_paymenthistory']) AND $this->_attributesOut['config']['gui']['menu_show_paymenthistory'] == 1) {
            $doPaymentHistory = true;
        }

        # Меню история сессий
        if (isset($this->_attributesOut['config']['gui']['menu_show_sessionshistory']) AND $this->_attributesOut['config']['gui']['menu_show_sessionshistory'] == 1) {
            $doSessionHistory = true;
        }

        # Условия показы меню Услуги
        if (!$userDeleted and !$userOtkluchen and ($doChangeTtarif or $doTurbo or $doCredit or $doRealIp or $doFreeze or $doPerevod) and $unFreeze) {
            $doUslugi = true;
        }

        # Меню Главная
        $setMenu = $tplMenu->addMenu($setMenu, 1, T_("Главная"), 'main.php', false, 'icon-home');

        if (!$userDeleted and !$userOtkluchen and $doPayment and $unFreeze) {
            $setMenu = $tplMenu->addMenu($setMenu, 10, T_("Пополнение"), 'main.php?action=payment', false, 'icon-money');
        }

        # Услуги
        if ($doUslugi and !$userOtkluchen) {
            $setMenu = $tplMenu->addMenu($setMenu, 20, T_("Услуги"), '#', false, 'icon-shopping-cart');

            if ($doChangeTtarif) {
                $setMenu = $tplMenu->addMenu($setMenu, 30, T_("Смена тарифа"), 'main.php?action=tariff', 20, false);
            }

            if ($doTurbo) {
                $setMenu = $tplMenu->addMenu($setMenu, 40, T_("Турбо"), 'main.php?action=turbo', 20, false);
            }

            if ($doRealIp) {
                $setMenu = $tplMenu->addMenu($setMenu, 50, T_("Реальный IP"), 'main.php?action=realip', 20, false);
            }

            if ($doFreeze) {
                $setMenu = $tplMenu->addMenu($setMenu, 60, T_("Заморозка"), 'main.php?action=freeze', 20, false);
            }

            if ($doCredit) {
                $setMenu = $tplMenu->addMenu($setMenu, 70, T_("Кредит"), 'main.php?action=credit', 20, false);
            }

            if ($doPerevod) {
                $setMenu = $tplMenu->addMenu($setMenu, 80, T_("Перевод средств"), 'main.php?action=perevod', 20, false);
            }
        }

        # Дополнительные услуги
        # Получаем все услуги доступные
        $getAllPersonalServicesUser = $this->getAllPersonalServicesUser();

        $ollTv = false;
        $megogo = false;
        $smotreshkaTv = false;
        $trinityTv = false;
        $omegaTv = false;
        $otherServiceMenu = false;

        foreach($getAllPersonalServicesUser AS $service){

            if($service['service_portal'] == '3'){
                $ollTv = true;
            }

            if($service['service_portal'] == '4'){
                $megogo = true;
            }

            if($service['service_portal'] == '5'){
                $smotreshkaTv = true;
            }

            if($service['service_portal'] == '6'){
                $trinityTv = true;
            }

            if($service['service_portal'] == '7'){
                $omegaTv = true;
            }

            if(in_array($service['service_portal'] , array(0,1,2,3,4,5,6)) ){
                $otherServiceMenu = true;
            }
        }

        if($omegaTv){
            $setMenu = $tplMenu->addMenu($setMenu, 22, T_("OmegaTV"), 'main.php?action=omegatv', false, 'icon-star');
        }

        if($trinityTv){
            $setMenu = $tplMenu->addMenu($setMenu, 23, T_("TRINITY-TV"), 'main.php?action=trinitytv', false, 'icon-star');
        }

        if ($otherServiceMenu) {
            $setMenu = $tplMenu->addMenu($setMenu, 21, T_("Доп. услуги"), 'main.php?action=services', false, 'icon-check');
        }



        # Меню Rentsoft
        if ($this->_attributesOut['user']['rentsoft_on'] == '1') {
            $setMenu = $tplMenu->addMenu($setMenu, 85, T_("Антивирусы и ПО"), 'main.php?action=rentsoft', false, 'icon-shield');
        }

        # Если Включена ли заморозка, то показываем меню разморозки
        if (!$unFreeze) {
            $setMenu = $tplMenu->addMenu($setMenu, 90, T_('Отмена заморозки'), 'main.php?action=freeze', false, 'icon-asterisk');
        }

        # Если включенна одна из "историй" то покаываем рут меню "История"
        if (!$userOtkluchen and ($doPaymentHistory or $doSessionHistory)) {
            # ROOT-MENU История
            $setMenu = $tplMenu->addMenu($setMenu, 100, T_('История'), '#', false, 'icon-time');

            if ($doPaymentHistory) {
                $setMenu = $tplMenu->addMenu($setMenu, 110, T_('История платежей'), 'main.php?action=historypayment', 100, false);
            }

            if ($doSessionHistory) {
                $setMenu = $tplMenu->addMenu($setMenu, 120, T_('История сессий'), 'main.php?action=historysession', 100, false);
            }
        }

        #Meню контакты если включено в опицях
        if (isset($this->_attributesOut['config']['contact_menu_show']) and $this->_attributesOut['config']['contact_menu_show'] == '1') {
            $setMenu = $tplMenu->addMenu($setMenu, 130, T_('Контакты'), 'main.php?action=contact', false, 'icon-envelope');
        }
        $full_path = $this->_attributesOut['config']['path_template'] . '/customtpls/mainMenu.php';

        if (file_exists($full_path)) {
            include($full_path);
        }

        $outValue['main_menu'] = $tplMenu->createMenu($setMenu);
        $outValue += $this->_attributesOut;

        $tplMenu->set("val", $outValue);
        $mainMenu = $tplMenu->out("menu");

        $this->_attributesOut['main_menu'] = Array(
            'main_menu'  => $mainMenu,
            'menu_value' => $outValue['main_menu']
        );
    }

    # Создание футера
    public function getFooter()
    {
        # Создаем обьект класса
        $tplFooter = new TemplateClass($this->_attributesOut['config']['path_template']);

        $outFooter = $this->_attributesOut;

        $tplFooter->set("val", $outFooter);
        $footer = $tplFooter->out("footer");

        $this->_attributesOut['footer'] = Array(
            'footer' => $footer
        );
    }

    # Создание хидера
    public function getHeader()
    {
        # Создаем обьект класса
        $tplHeader = new TemplateClass($this->_attributesOut['config']['path_template']);

        $this->_attributesOut['ticketMenu'] = $this->getMenuTicket();
        $outHeader = $this->_attributesOut;

        $tplHeader->set("val", $outHeader);
        $header = $tplHeader->out("header");

        $this->_attributesOut['header'] = Array(
            'header' => $header
        );
    }

    # Получить TicketList от MikBiLL
    public function getTicketList()
    {
        $ticketListArray = array();
        $url = $this->_billLink['getticketslist2x'];
//		$param = "useruid=" . $this->_attributesOut['user']['uid'];
        $param = array("useruid" => $this->_attributesOut['user']['uid']);
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $tempArray = $this->xmlParser($responseQuery);

        if (isset($tempArray['element'])) {
            if (count($tempArray['element']) == 1) {
                $ticketListArray[] = $tempArray['element']['@attributes'];
            } else {
                foreach ($tempArray['element'] as $key) {
                    $ticketListArray[] = $key['@attributes'];
                }
            }
        }

        return $ticketListArray;
    }

    # Создание меню тикетов
    public function getMenuTicket()
    {
        $activeTicket = array();
        $ticketListArray = $this->getTicketList();

        foreach ($ticketListArray as $key) {
            if ($key['statustypename'] == 'opened' OR $key['statustypename'] == 'in_work') {

                if (isset($key['cause'])) {
                    if (strlen($key['cause']) > 25) {
                        $key['cause'] = mb_substr($key['cause'], 0, 26, 'UTF-8') . '...';
                    }
                }

                $activeTicket[] = $key;
            }
        }

        $menuTicket['activeTicket'] = $activeTicket;
        $menuTicket['allTicketCount'] = count($ticketListArray);

        return $menuTicket;
    }

    public function getConfigHtml()
    {
        $url = $this->_billLink['getconfightml'];
        $resQuery = $this->sendQuery($url, 'get', '', 0);

        return $resQuery;
    }

    public function setDebug()
    {
        # Режим дебага
        if (isset($this->_attributesOut['config']['gui']['debug']) and $this->_attributesOut['config']['gui']['debug'] == '1') {
            error_reporting(E_ALL);
            $this->_debug = 1;
        } else {
            error_reporting(0);
            $this->_debug = 0;
        }
    }

    # Запись конфига в массив
    public function getCabinetConfig()
    {
        # TODO конфиг авторизации по паролю
        $config_xml_file = 'app/etc/config.xml';
        if (file_exists($config_xml_file)) {
            $xml = simplexml_load_file($config_xml_file);

            $AUTH_PASSW = (string)$xml->parameters->doauthonlypass;

            if ($AUTH_PASSW == '1') {
                $this->_globalSetAuth['doauthonlypass'] = 1;
            } else {
                $this->_globalSetAuth['doauthonlypass'] = 0;
            }

            $timezone = (string)$xml->parameters->timezone;

            if (trim($timezone) != '') {
                date_default_timezone_set($timezone);
                date_default_timezone_set($timezone);
            } else {
                date_default_timezone_set('Europe/Kiev');
            }
        }

        $response = $this->getConfigHtml();
        $arrayConfHtml = json_decode($response, true);
//        var_dump($arrayConfHtml);
        $outArray = $arrayConfHtml;

        # TODO Костыль. Если нет доступнух локалей из БД то берем из конфига кабинета
        if (!isset($outArray['locales']) or empty($outArray['locales'])) {

            # Все локали
            if (isset($this->_attributesOut['xml']['languages']['language'])) {
                $languageArray = $this->_attributesOut['xml']['languages']['language'];
            } else {
                $languageArray = array();
            }

            # Язык по умолчанию;
            if (isset($this->_attributesOut['xml']['languages']['@attributes']['default'])) {
                $_def_locale = $this->_attributesOut['xml']['languages']['@attributes']['default'];
            } else {
                $_def_locale = 'ru_RU';
            }

            # Автодетект языка
            if (isset($this->_attributesOut['xml']['languages']['@attributes']['visible'])) {
                $outArray['locales_options']['autoDetect'] = $this->_attributesOut['xml']['languages']['@attributes']['visible'];
            } else {
                $outArray['locales_options']['autoDetect'] = '0';
            }


            if ($_def_locale == 'ru_RU') {
                $outArray['locales_options']['default'] = 'ru_RU';
            } elseif ($_def_locale == 'ua_UA') {
                $outArray['locales_options']['default'] = 'uk_UA';
            } elseif ($_def_locale == 'en_US') {
                $outArray['locales_options']['default'] = 'en_GB';
            } else {
                $outArray['locales_options']['default'] = $_def_locale;
            }


            # Если количество локализаций больше 0
            if (count($languageArray) > 0) {

                if (count($languageArray) == 1) {
                    $lanqArray[] = $languageArray;
                } else {
                    $lanqArray = $languageArray;
                }

                # Локали для автодекта
                $int = 1;
                foreach ($lanqArray as $language) {
                    $_locale = $language['@attributes']['locale'];

                    if ($_locale == 'ru_RU') {
                        $locale_name = 'ru_RU';
                    } elseif ($_locale == 'ua_UA') {
                        $locale_name = 'uk_UA';
                    } elseif ($_locale == 'en_US') {
                        $locale_name = 'en_GB';
                    } else {
                        $locale_name = $_locale;
                    }

                    $outArray['locales']['name_' . $int] = $locale_name;

                    $outArray['locales']['file_' . $int] = 'original';

                    $outArray['locales']['enable_' . $int] = $language['@attributes']['enabled'];

                    $int++;
                }
            }
        }

        $configArray = array();

        # TODO Активация DEMO режима в ЛК
        if (isset($configArray['demo'])) {
            $outArray['demo'] = $configArray['demo'];
        }


        # TODO переходим на новый конфиг (если в бд нет отпции создаем ее)
        if (!empty($arrayConfHtml['gui']['path_template'])) {
            $outArray['path_template'] = $arrayConfHtml['gui']['path_template'];
        } else {
            $outArray['path_template'] = './data/template/olson';
        }

        if (!empty($arrayConfHtml['company_info']['company_name'])) {
            $outArray['company_name'] = $arrayConfHtml['company_info']['company_name'];
        } else {
            $outArray['company_name'] = 'ISP Company';
        }

        if (!empty($arrayConfHtml['company_info']['company_site'])) {
            $outArray['company_site'] = $arrayConfHtml['company_info']['company_site'];
        } else {
            $outArray['company_site'] = '#';
        }

        if (!empty($arrayConfHtml['company_info']['company_adress'])) {
            $outArray['company_adress'] = $arrayConfHtml['company_info']['company_adress'];
        } else {
            $outArray['company_adress'] = '';
        }

        if (!empty($arrayConfHtml['company_info']['company_email'])) {
            $outArray['company_e-mail'] = $arrayConfHtml['company_info']['company_email'];
        } else {
            $outArray['company_e-mail'] = '';
        }

        if (!empty($arrayConfHtml['company_info']['name_mobile_1'])) {
            $outArray['cab_name_mobile_1'] = $arrayConfHtml['company_info']['name_mobile_1'];
        } else {
            $outArray['cab_name_mobile_1'] = '';
        }

        if (!empty($arrayConfHtml['company_info']['phone_mobile_1'])) {
            $outArray['cab_phone_mobile_1'] = $arrayConfHtml['company_info']['phone_mobile_1'];
        } else {
            $outArray['cab_phone_mobile_1'] = '';
        }

        if (!empty($arrayConfHtml['company_info']['name_mobile_2'])) {
            $outArray['cab_name_mobile_2'] = $arrayConfHtml['company_info']['name_mobile_2'];
        } else {
            $outArray['cab_name_mobile_2'] = '';
        }

        if (!empty($arrayConfHtml['company_info']['phone_mobile_2'])) {
            $outArray['cab_phone_mobile_2'] = $arrayConfHtml['company_info']['phone_mobile_2'];
        } else {
            $outArray['cab_phone_mobile_2'] = '';
        }

        if (!empty($arrayConfHtml['company_info']['name_mobile_3'])) {
            $outArray['cab_name_mobile_3'] = $arrayConfHtml['company_info']['name_mobile_3'];
        } else {
            $outArray['cab_name_mobile_3'] = '';
        }

        if (!empty($arrayConfHtml['company_info']['phone_mobile_3'])) {
            $outArray['cab_phone_mobile_3'] = $arrayConfHtml['company_info']['phone_mobile_3'];
        } else {
            $outArray['cab_phone_mobile_3'] = '';
        }

        if (isset($arrayConfHtml['gui']['speed_mbit']) and $arrayConfHtml['gui']['speed_mbit'] <> '') {
            $outArray['speed_mbit'] = $arrayConfHtml['gui']['speed_mbit'];
        } else {
            $outArray['speed_mbit'] = 1;
        }

        if (isset($arrayConfHtml['gui']['start_page']) and $arrayConfHtml['gui']['start_page'] <> '') {
            $outArray['start_page'] = $arrayConfHtml['gui']['start_page'];
        } else {
            $outArray['start_page'] = 'main';
        }

        if (isset($arrayConfHtml['gui']['contact_menu_show']) and $arrayConfHtml['gui']['contact_menu_show'] <> '') {
            $outArray['contact_menu_show'] = $arrayConfHtml['gui']['contact_menu_show'];
        } else {
            $outArray['contact_menu_show'] = 0;
        }

        // Если нет типа ваучера занесем БД
        if (!isset($arrayConfHtml['gui']['user_vaucher_type']) or empty($arrayConfHtml['gui']['user_vaucher_type'])) {
            if (isset($this->_attributesOut['xml']['vaucher']['@attributes']['type'])) {
                $outArray['gui']['user_vaucher_type'] = $this->_attributesOut['xml']['vaucher']['@attributes']['type'];
            } else {
                $outArray['gui']['user_vaucher_type'] = 4;
            }
        }

        // Если нет длины ваучера занесем БД
        if (!isset($arrayConfHtml['gui']['user_vaucher_type']) or empty($arrayConfHtml['gui']['user_vaucher_length'])) {
            if (isset($this->_attributesOut['xml']['vaucher']['@attributes']['length'])) {
                $outArray['gui']['user_vaucher_length'] = $this->_attributesOut['xml']['vaucher']['@attributes']['length'];
            } else {
                $outArray['gui']['user_vaucher_length'] = 18;
            }
        }

        // Если нет параметра автозагрузки - занесем в БД
        if (!isset($arrayConfHtml['gui']['autoinit_enabled']) or empty($arrayConfHtml['gui']['autoinit_enabled'])) {
            if (isset($this->_attributesOut['xml']['autoinit']['@attributes']['enabled'])) {
                $outArray['gui']['autoinit_enabled'] = $this->_attributesOut['xml']['autoinit']['@attributes']['enabled'];
            } else {
                $outArray['gui']['autoinit_enabled'] = 1;
            }
        }


        // Если нет параметра автозагрузки кредита - занесем в БД
        if (!isset($arrayConfHtml['gui']['autoinit_limit']) or empty($arrayConfHtml['gui']['autoinit_limit'])) {
            if (isset($this->_attributesOut['xml']['autoinit']['@attributes']['limit'])) {
                $outArray['gui']['autoinit_limit'] = $this->_attributesOut['xml']['autoinit']['@attributes']['limit'];
            } else {
                $outArray['gui']['autoinit_limit'] = 1;
            }
        }

        // Если нет параметра автозагрузки разаморозки - занесем в БД
        if (!isset($arrayConfHtml['gui']['autoinit_unfreezing']) or empty($arrayConfHtml['gui']['autoinit_unfreezing'])) {
            if (isset($this->_attributesOut['xml']['autoinit']['@attributes']['unfreezing'])) {
                $outArray['gui']['autoinit_unfreezing'] = $this->_attributesOut['xml']['autoinit']['@attributes']['unfreezing'];
            } else {
                $outArray['gui']['autoinit_unfreezing'] = 1;
            }
        }

        // Если нет параметра отображения  абонплаты - занесем в БД
        if (!isset($arrayConfHtml['gui']['accountinfo_fee']) or empty($arrayConfHtml['gui']['accountinfo_fee'])) {
            if (isset($this->_attributesOut['xml']['accountinfo']['@attributes']['fee'])) {
                $outArray['gui']['accountinfo_fee'] = $this->_attributesOut['xml']['accountinfo']['@attributes']['fee'];
            } else {
                $outArray['gui']['accountinfo_fee'] = 1;
            }
        }

        // Если нет параметра отображения  абонплаты - занесем в БД
        if (!isset($arrayConfHtml['gui']['accountinfo_balance']) or empty($arrayConfHtml['gui']['accountinfo_balance'])) {
            if (isset($this->_attributesOut['xml']['accountinfo']['@attributes']['balance'])) {
                $outArray['gui']['accountinfo_balance'] = $this->_attributesOut['xml']['accountinfo']['@attributes']['balance'];
            } else {
                $outArray['gui']['accountinfo_balance'] = 1;
            }
        }


        // Если нет параметра отображения  кол-ва дней - занесем в БД
        if (!isset($arrayConfHtml['gui']['accountinfo_daysleft']) or empty($arrayConfHtml['gui']['accountinfo_daysleft'])) {
            if (isset($this->_attributesOut['xml']['accountinfo']['@attributes']['daysleft'])) {
                $outArray['gui']['accountinfo_daysleft'] = $this->_attributesOut['xml']['accountinfo']['@attributes']['daysleft'];
            } else {
                $outArray['gui']['accountinfo_daysleft'] = 1;
            }
        }


        // Если нет параметра отображения  даты окончания услуги - занесем в БД
        if (!isset($arrayConfHtml['gui']['accountinfo_enddate']) or empty($arrayConfHtml['gui']['accountinfo_enddate'])) {
            if (isset($this->_attributesOut['xml']['accountinfo']['@attributes']['enddate'])) {
                $outArray['gui']['accountinfo_enddate'] = $this->_attributesOut['xml']['accountinfo']['@attributes']['enddate'];
            } else {
                $outArray['gui']['accountinfo_enddate'] = 1;
            }
        }


        // Если нет параметра отображения  абонплату з ареальный айпи - занесем в БД
        if (!isset($arrayConfHtml['gui']['accountinfo_ipfee']) or empty($arrayConfHtml['gui']['accountinfo_ipfee'])) {
            if (isset($this->_attributesOut['xml']['accountinfo']['@attributes']['ipfee'])) {
                $outArray['gui']['accountinfo_ipfee'] = $this->_attributesOut['xml']['accountinfo']['@attributes']['ipfee'];
            } else {
                $outArray['gui']['accountinfo_ipfee'] = 1;
            }
        }

        // Если нет параметра отображения  суммы рекомендуего платежа - занесем в БД
        if (!isset($arrayConfHtml['gui']['accountinfo_payment']) or empty($arrayConfHtml['gui']['accountinfo_payment'])) {
            if (isset($this->_attributesOut['xml']['accountinfo']['@attributes']['payment'])) {
                $outArray['gui']['accountinfo_payment'] = $this->_attributesOut['xml']['accountinfo']['@attributes']['payment'];
            } else {
                $outArray['gui']['accountinfo_payment'] = 1;
            }
        }


        // Если нет параметра отображения  суммы рекомендуего платежа - занесем в БД
        if (!isset($arrayConfHtml['gui']['terminals_minimumamount']) or empty($arrayConfHtml['gui']['terminals_minimumamount'])) {
            if (isset($this->_attributesOut['xml']['terminals']['@attributes']['minimumamount'])) {
                $outArray['gui']['terminals_minimumamount'] = $this->_attributesOut['xml']['terminals']['@attributes']['minimumamount'];
            } else {
                $outArray['gui']['terminals_minimumamount'] = 1;
            }
        }

        // Если нет параметра w.qiwi.ru автозаполнение - занесем в БД
        if (!isset($arrayConfHtml['gui']['wqiwiru_prompt'])) {
            if (isset($this->_attributesOut['xml']['wqiwiru']['@attributes']['prompt'])) {
                $outArray['gui']['wqiwiru_prompt'] = $this->_attributesOut['xml']['wqiwiru']['@attributes']['prompt'];
            } else {
                $outArray['gui']['wqiwiru_prompt'] = '';
            }
        }

        // Если нет параметра w.qiwi.ru автозаполнение - занесем в БД
        if (!isset($arrayConfHtml['gui']['wqiwiru_length'])) {
            if (isset($this->_attributesOut['xml']['wqiwiru']['@attributes']['length'])) {
                $outArray['gui']['wqiwiru_length'] = $this->_attributesOut['xml']['wqiwiru']['@attributes']['length'];
            } else {
                $outArray['gui']['wqiwiru_length'] = '13';
            }
        }

        // Если нет параметра выбора когда сменить тариф - занесем в БД
        if (!isset($arrayConfHtml['gui']['changetariffoptions_visible'])) {
            if (isset($this->_attributesOut['xml']['changetariffoptions']['@attributes']['visible'])) {
                $outArray['gui']['changetariffoptions_visible'] = $this->_attributesOut['xml']['changetariffoptions']['@attributes']['visible'];
            } else {
                $outArray['gui']['changetariffoptions_visible'] = '1';
            }
        }


        // Если нет параметра выбора когда сменить тариф - занесем в БД
        if (!isset($arrayConfHtml['gui']['changetariffoptions_default'])) {
            if (isset($this->_attributesOut['xml']['changetariffoptions']['@attributes']['default'])) {
                $outArray['gui']['changetariffoptions_default'] = $this->_attributesOut['xml']['changetariffoptions']['@attributes']['default'];
            } else {
                $outArray['gui']['changetariffoptions_default'] = '1';
            }
        }

        $this->_attributesOut['config'] = $outArray;
    }


    # Получить параметры абонента от MikBiLL
    public function getUserData()
    {
        $url = $this->_billLink['getuserdatafl'];
        $responseQuery = $this->sendQuery($url, 'get', '', 0);

        if ($responseQuery <> '') {
            $buferArray = $this->xmlParser($responseQuery);
            $dataArray = $buferArray['user']['@attributes'];
        } else {
            $dataArray = array();
        }

        //Проверка авторизации
        if (isset($dataArray['uid']) and $dataArray['uid'] != '') {
            $this->_attributesOut['user'] = $dataArray;

            # Форматируем скорость с Мбит или Кбит
			$speed_attributes = array("shapers_dn_1_in", "shapers_dn_2_in", "shapers_dn_3_in", "shapers_dn_1_out", "shapers_dn_2_out", "shapers_dn_3_out");
			foreach($speed_attributes as $attr) {
				if(!isset($dataArray[$attr])) {
					continue;
				}
				$speed = $this->speedView($this->_attributesOut['config']['speed_mbit'], $dataArray[$attr]);
				$this->_attributesOut['user'][$attr] = $speed;
			}
			
            $tarifSpeedDw = $this->speedView($this->_attributesOut['config']['speed_mbit'], $dataArray['speed_rate']);
            $tarifSpeedUp = $this->speedView($this->_attributesOut['config']['speed_mbit'], $dataArray['speed_burst']);

            $this->_attributesOut['user'] += array(
                'tarif_speed_dw_format' => $tarifSpeedDw,
                'tarif_speed_up_format' => $tarifSpeedUp
            );

            $statusAuth = true;
        } else {
            $statusAuth = false;
        }

        return $statusAuth;
    }

    # Меню контакты
    public function menuContact()
    {
        $this->_outPage = 'contact';
    }


    public function doAuth($login, $pass)
    {
        $url = $this->_billLink['authfl'];
        $param = array(
            "login"    => $login,
            "password" => $pass
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 1);

        //Распарсим ответ
        $statusAuth = $this->xmlParser2($responseQuery);

        // Если не распарсилось пробуем JSON
        if (empty($statusAuth)) {
            $statusAuth = json_decode($responseQuery, true);
        }

        return $statusAuth;
    }

    public function loginAuth()
    {
        $cabinet_auth_alert = '';
        $cab_login_alert = '';
        $this->_statusAuth = false;
        $login = 'notLogin';
        $password = '';

        if ($_SERVER['REQUEST_METHOD'] == 'GET' AND !(isset($this->_paramsInput['action']) AND $this->_paramsInput['action'] == 'exit')) {
            SetCookie("AUTHREDIRECT", $_SERVER['QUERY_STRING'], time() + 100);
        }

        # Если был ввод пароля
        if (isset($this->_paramsInput['password']) or isset($this->_paramsInput['p'])) {

            # Если есть логина
            if (isset($this->_paramsInput['login'])) {
                $login = $this->_paramsInput['login'];
            } elseif (isset($this->_paramsInput['l'])) {
                $login = $this->_paramsInput['l'];
            }

            # Если есть логина
            if (isset($this->_paramsInput['password'])) {
                $password = $this->_paramsInput['password'];
            } elseif (isset($this->_paramsInput['p'])) {
                $password = $this->_paramsInput['p'];
            }

            # Отсылаем логин/пасс в бекенд
            $statusDoAuth = $this->doAuth($login, $password);

            # Если бекенд ничего не ответил то "Ошибка транспорта"
            if (!isset($statusDoAuth['user'][0]['enable'])) {

                if (isset($statusDoAuth['error'])) {
                    $cabinet_auth_alert = '<div class="alert alert-danger">' . T_('Проводятся технические работы.') . ' (#' . $statusDoAuth['error'] . ')</div>';
                } else {
                    $cabinet_auth_alert = '<div class="alert alert-danger">' . T_('Ошибка сетевого транспорта. Попробуйте зайти позже...') . '</div>';
                }
                $this->_outPage = 'login';
            } else {

                # Проверка авторизации
                if ($statusDoAuth['user'][0]['enable'] != '1') {

                    $this->_outPage = 'login';

                    if ($login <> 'notLogin') {
                        $cabinet_auth_alert = '<div class="alert alert-danger"> ' . T_("Ошибка. Логин или пароль неверный.") . '</div>';
                    } else {
                        $cabinet_auth_alert = '<div class="alert alert-danger"> ' . T_("Ошибка. Пароль неверный.") . '</div>';
                    }
                } else {

                    if (!empty($_COOKIE['AUTHREDIRECT'])) {
                        SetCookie("AUTHREDIRECT", '');
                        die(header('Location: main.php?' . $_COOKIE['AUTHREDIRECT']));
                    }

                    $this->_statusAuth = true;
                    $this->_firstAfterAuth = true;
                }
            }
        } else {
            $this->_outPage = 'login';
            $url = $this->_billLink['logoutfl'];
            $this->sendQuery($url, 'get', '', 0);
            $this->setCookie('');
        }

        if ($this->_blockCabinet == 1) {
            $cab_login_alert = '<div class="alert alert-warning" id="info_warning" ><i class="icon-warning-sign"></i>' . T_('Внимание! Кабинет будет доступен в') . ' 00:05:00.</div>';
            $this->_outPage = 'login';
        }

        $this->_attributesOut['logInAuth'] = Array(
            'cabinet_auth_alert' => $cabinet_auth_alert,
            'cab_login_alert'    => $cab_login_alert
        );
    }

    # Пополнение ваучером
    public function vaucherPayment()
    {
        $codeVaucher = '';

        if (isset($this->_paramsInput['card1'])) {
            $codeVaucher .= $this->_paramsInput['card1'];
        }

        if (isset($this->_paramsInput['card2'])) {
            $codeVaucher .= $this->_paramsInput['card2'];
        }

        if (isset($this->_paramsInput['card3'])) {
            $codeVaucher .= $this->_paramsInput['card3'];
        }

        if (isset($this->_paramsInput['card4'])) {
            $codeVaucher .= $this->_paramsInput['card4'];;
        }

        if (isset($this->_paramsInput['card5'])) {
            $codeVaucher .= $this->_paramsInput['card5'];
        }

        if (isset($this->_paramsInput['card6'])) {
            $codeVaucher .= $this->_paramsInput['card6'];
        }

        $arrayVacher = str_split($codeVaucher, 4);

        $card1 = (isset($arrayVacher[0]) ? $arrayVacher[0] : '');
        $card2 = (isset($arrayVacher[1]) ? $arrayVacher[1] : '');
        $card3 = (isset($arrayVacher[2]) ? $arrayVacher[2] : '');
        $card4 = (isset($arrayVacher[3]) ? $arrayVacher[3] : '');
        $card5 = (isset($arrayVacher[4]) ? $arrayVacher[4] : '');

        $url = $this->_billLink['usevaucherfl'];
//		$param = "card1=" . $card1 . "&card2=" . $card2 . "&card3=" . $card3 . "&card4=" . $card4 . "&card5=" . $card5;
        $param = array(
            "card1" => $card1,
            "card2" => $card2,
            "card3" => $card3,
            "card4" => $card4,
            "card5" => $card5
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $buferArray = $this->xmlParser($responseQuery);
        $paymentStatus = $buferArray['0'];

        return $paymentStatus;
    }

    public function getCopaycoUrl($namount, $us_uid)
    {
        $url = $this->_billLink['getcopaycourl'];
//		$param = "nAmount=" . $namount . "&us%5Fuid=" . $us_uid;
        $param = array(
            "nAmount" => $namount,
            "us_uid"  => $us_uid
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $buferArray = $this->xmlParser($responseQuery);
        $paymentStatus = $buferArray['response'];

        return $paymentStatus;
    }

    # Меню пополнения счета
    public function menuPayment()
    {
        $this->_outPage = 'payment';
        $depositOption = '';
        $paymentType = array();
        $cabinet_card_alert = '';
        $urlCopayco = '';

        if (isset($this->_paramsInput['card1'])) {
            $statusPayment = $this->vaucherPayment();

            if ($statusPayment == '1') {
                $cabinet_card_alert = '<div class="alert alert-success">' . T_('Ваш счет успешно пополнен.') . '</div>';
            } else {
                $cabinet_card_alert = '<div class="alert alert-danger">Ошибка.Карта не принята.</div>';
            }
        }

        # TODO Пополнение_2
        # Если копейка получаем ссылку
        if (isset($this->_paramsInput['nAmount'])) {
            $urlCopayco = $this->getCopaycoUrl($this->_paramsInput['nAmount'], $this->_paramsInput['us_uid']);
        }

        if (isset($this->_attributesOut['user']['use_cards']) and $this->_attributesOut['user']['use_cards'] == '1') {
            $paymentType[0] = T_('Пополнение ваучером');
        }

        if (isset($this->_attributesOut['user']['use_privat24']) and $this->_attributesOut['user']['use_privat24'] == '1') {
            $paymentType[1] = 'Приват24';
        }

        if (isset($this->_attributesOut['user']['use_liqpay']) and $this->_attributesOut['user']['use_liqpay'] == '1') {
            $paymentType[2] = 'LiqPay';
        }

        if (isset($this->_attributesOut['user']['use_onpay']) and $this->_attributesOut['user']['use_onpay'] == '1') {
            $paymentType[3] = 'OnPay';
        }

        if (isset($this->_attributesOut['user']['use_pscb']) and $this->_attributesOut['user']['use_pscb'] == '1') {
            $paymentType[4] = 'PSCB';
        }

        if (isset($this->_attributesOut['user']['use_paymaster']) and $this->_attributesOut['user']['use_paymaster'] == '1') {
            $paymentType[5] = 'PayMaster';
        }

        if (isset($this->_attributesOut['user']['use_robokassa']) and $this->_attributesOut['user']['use_robokassa'] == '1') {
            $paymentType[6] = 'RoboKassa';
        }

        if (isset($this->_attributesOut['user']['use_wqiwiru']) and $this->_attributesOut['user']['use_wqiwiru'] == '1') {
            $paymentType[7] = 'w.qiwi.ru';
        }

        if (isset($this->_attributesOut['user']['use_copayco']) and $this->_attributesOut['user']['use_copayco'] == '1') {
            $paymentType[8] = 'CoPayCo';
        }

        if (isset($this->_attributesOut['user']['use_stripe']) and $this->_attributesOut['user']['use_stripe'] == '1') {
            $paymentType[9] = 'Stripe';
        }

        if (isset($this->_attributesOut['user']['use_paypal']) and $this->_attributesOut['user']['use_paypal'] == '1') {
            $paymentType[10] = 'PayPal';
        }

        if (isset($this->_attributesOut['user']['use_paykeeper']) and $this->_attributesOut['user']['use_paykeeper'] == '1') {
            $paymentType[11] = 'PayKeeper';
        }

        if (isset($this->_attributesOut['user']['use_ukrpays']) and $this->_attributesOut['user']['use_ukrpays'] == '1') {
            $paymentType[12] = 'UkrPays';
        }

        if (isset($this->_attributesOut['user']['use_yandex']) and $this->_attributesOut['user']['use_yandex'] == '1') {
            $paymentType[13] = 'Яндекс.Касса';
        }

        if (isset($this->_attributesOut['user']['use_uniteller']) and $this->_attributesOut['user']['use_uniteller'] == '1') {
            $paymentType[14] = 'Uniteller';
        }

        if (isset($this->_attributesOut['user']['use_portmone']) and $this->_attributesOut['user']['use_portmone'] == '1') {
            $paymentType[15] = 'Portmone';
        }

        if (isset($this->_attributesOut['user']['use_ipay']) and $this->_attributesOut['user']['use_ipay'] == '1') {
            $paymentType[16] = 'iPay';
        }

        if (isset($this->_attributesOut['user']['use_sberbankrumrch']) and $this->_attributesOut['user']['use_sberbankrumrch'] == '1') {
            $paymentType[17] = 'SberBank.ru';
        }

        if (isset($this->_attributesOut['user']['use_fondy']) and $this->_attributesOut['user']['use_fondy'] == '1') {
            $paymentType[18] = 'Fondy';
        }

        if (isset($this->_attributesOut['user']['use_simplepay']) and $this->_attributesOut['user']['use_simplepay'] == '1') {
            $paymentType[19] = 'SimplePay';
        }

        if (isset($this->_attributesOut['user']['use_yandexmoney']) and $this->_attributesOut['user']['use_yandexmoney'] == '1') {
            $paymentType[20] = 'Яндекс.Деньги';
        }

        if (isset($this->_attributesOut['user']['use_cloudpayments']) and $this->_attributesOut['user']['use_cloudpayments'] == '1') {
            $paymentType[21] = 'CloudPayments';
        }

        if (isset($this->_attributesOut['user']['use_isbank']) and $this->_attributesOut['user']['use_isbank'] == '1') {
            $paymentType[22] = 'ISBANK';
        }

        if (isset($this->_attributesOut['user']['use_tinkoff']) and $this->_attributesOut['user']['use_tinkoff'] == '1') {
            $paymentType[23] = 'Tinkoff';
        }

        if (isset($this->_attributesOut['user']['use_alfabankru']) and $this->_attributesOut['user']['use_alfabankru'] == '1') {
            $paymentType[24] = 'Альфа-Банк';
        }

        if (isset($this->_attributesOut['user']['use_privat_v2']) and $this->_attributesOut['user']['use_privat_v2'] == '1') {
            $paymentType[25] = 'ПриватБанк';
        }

        if (isset($this->_attributesOut['user']['use_paysoft']) and $this->_attributesOut['user']['use_paysoft'] == '1') {
            $paymentType[26] = 'PaySoft';
        }

        if (isset($this->_attributesOut['user']['use_ckassa']) and $this->_attributesOut['user']['use_ckassa'] == '1') {
            $paymentType[27] = 'Центральная Касса';
        }

        if (isset($this->_attributesOut['user']['use_masterpass']) and $this->_attributesOut['user']['use_masterpass'] == '1') {
            $paymentType[28] = 'MasterPass';
        }

        if (isset($this->_attributesOut['user']['use_lifecell']) and $this->_attributesOut['user']['use_lifecell'] == '1') {
            $paymentType[29] = 'Lifecell';
        }

        $this->_attributesOut['payment'] = Array(
            'cab_ps_list'        => $depositOption,
            'paymentType'        => $paymentType,
            'cabinet_card_alert' => $cabinet_card_alert,
            'urlCopayco'         => $urlCopayco
        );
    }

    public function howMatchTarif($uid, $gid, $gidd)
    {
        $url = $this->_billLink['howmatchpayperehodflex'];
//		$param = "uid=" . $uid . "&gid=" . $gid . "&gidd=" . $gidd;
        $param = array(
            "uid"  => $uid,
            "gid"  => $gid,
            "gidd" => $gidd
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $buferArray = $this->xmlParser2($responseQuery);
        $matchArray = $buferArray['user']['0'];

        return $matchArray;
    }

    public function getTariff()
    {
        $url = $this->_billLink['tarifchangelistflex'];
        $responseQuery = $this->sendQuery($url, 'get', '', 0);
        $buferArray = $this->xmlParser2($responseQuery);
        $tarifArray = $buferArray['tarifs']['0']['tarif'];

        return $tarifArray;
    }

    public function doChangeTariff()
    {
        $gidd = $this->_paramsInput['gidd'];
        $oldpass = $this->_paramsInput['oldpass'];
        $from_next_month = $this->_paramsInput['from_next_month'];
        $uid = $this->_attributesOut['user']['uid'];

        $url = $this->_billLink['dochangetarifflex'];
//		$param = "gidd=" . $gidd . "&oldpass=" . $oldpass . "&uid=" . $uid . "&from_next_month=" . $from_next_month;
        $param = array(
            "gidd"            => $gidd,
            "oldpass"         => $oldpass,
            "uid"             => $uid,
            "from_next_month" => $from_next_month
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $bufferArray = $this->xmlParser2($responseQuery);
        $response = $bufferArray['ok'];

        return $response;
    }

    public function menuChangeTariff()
    {
        $this->_outPage = 'tariff';

        $uid = $this->_attributesOut['user']['uid'];
        $cabinet_tarif_alert = '';
        $tariff_list = '';

        if (isset($this->_paramsInput['gidd'])) {

            $statusDoChangeTariff = $this->doChangeTariff();

            if ($statusDoChangeTariff == '1') {
                $this->getUserData();
                $cabinet_tarif_alert = '<div class="alert alert-success">' . T_('Ваш тариф успешно изменён.') . '</div>';
            } elseif ($statusDoChangeTariff == '2') {
                $this->getUserData();
                $cabinet_tarif_alert = '<div class="alert alert-success">' . T_('Ваш тариф будет изменён со следующего месяца.') . '</div>';
            } else {
                $cabinet_tarif_alert = '<div class="alert alert-danger">' . T_('Ошибка смены тарифа.') . '</div>';
            }
        }

        $now_tariff = $this->_attributesOut['user']['gid'];
        $tarifArray = $this->getTariff();

        $fullTariff = array();
        foreach ($tarifArray as $key) {
            if ($key['gid'] <> $now_tariff) {

                $tariff_list .= '<option value="' . $key['gid'] . '">' . $key['packet'] . '</option>';
                $match = $this->howMatchTarif($uid, $now_tariff, $key['gid']);
                array_push($fullTariff, $key + $match);
            }
        }

        if (empty($tariff_list)) {
            $tariff_list = '<option value="0"> ' . T_('Нет доступных тарифов для смены') . '</option>';
        }

        # Создаем обьект класса
        $tplTariffItem = new TemplateClass($this->_attributesOut['config']['path_template']);

        $this->_attributesOut['tariffitem'] = $fullTariff;

        $tplTariffItem->set("tariffitem", $this->_attributesOut);

        $this->_attributesOut['tarif'] = Array(
            'cab_tariff_how_match' => $tplTariffItem->out("tariffitem"),
            'cab_tariff_list'      => $tariff_list,
            'cabinet_tarif_alert'  => $cabinet_tarif_alert
        );
    }


    public function doPerevod($oldPassword, $prim, $toLogin, $summa)
    {
        $url = $this->_billLink['doperevodfl'];
//		$param = "password2=" . $oldPassword . "&uid=" . $this->_attributesOut['user']['uid'] . "&prim=" . $prim . "&login2=" . $toLogin . "&summa=" . $summa;

        $param = array(
            "password2" => $oldPassword,
            "uid"       => $this->_attributesOut['user']['uid'],
            "prim"      => $prim,
            "login2"    => $toLogin,
            "summa"     => $summa
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $tempRespone = $this->xmlParser2($responseQuery);
        $response = $tempRespone['ok'];

        return $response;
    }

    public function menuPerevod()
    {
        $this->_outPage = 'perevod';
        $cabinet_perevod_alert = '';

        if (isset($this->_paramsInput['oldpass'])) {
            $statusDoPerevod = $this->doPerevod($this->_paramsInput['oldpass'], $this->_paramsInput['note'], $this->_paramsInput['to_uid'], $this->_paramsInput['summa']);

            if ($statusDoPerevod == '1') {
                $cabinet_perevod_alert = '<div class="alert alert-success">' . T_('Перевод успешно осуществлен.') . '</div>';
            } elseif ($statusDoPerevod == '2') {
                $cabinet_perevod_alert = '<div class="alert alert-danger">' . T_('Ошибка перевода средств. Абонент не найден.') . '</div>';
            } else {
                $cabinet_perevod_alert = '<div class="alert alert-danger">' . T_('Ошибка перевода средств.') . '</div>';
            }
        }

        $this->_attributesOut['perevod'] = Array(
            'cabinet_perevod_alert' => $cabinet_perevod_alert
        );
    }

    public function doTurbo($oldPassword)
    {
        $url = $this->_billLink['getturboflex'];
//		$param = "oldpass=" . $oldPassword . "&uid=" . $this->_attributesOut['user']['uid'];
        $param = array(
            "oldpass" => $oldPassword,
            "uid"     => $this->_attributesOut['user']['uid']
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $tempRespone = $this->xmlParser2($responseQuery);
        $response = $tempRespone['ok'];

        return $response;
    }

    public function menuTurbo()
    {
        $this->_outPage = 'turbo';
        $cabinet_turbo_alert = '';

        if (isset($this->_paramsInput['oldpass'])) {
            $statusDoTurbo = $this->doTurbo($this->_paramsInput['oldpass']);

            if ($statusDoTurbo == '1') {
                $cabinet_turbo_alert = '<div class="alert alert-success">' . T_('Услуга Турбо успешно активирована.') . '</div>';
            } elseif ($statusDoTurbo == '2') {
                $cabinet_turbo_alert = '<div class="alert alert-danger">' . T_('Ошибка. Услуга Турбо уже была подключена.') . '</div>';
            } else {
                $cabinet_turbo_alert = '<div class="alert alert-danger">' . T_('Ошибка активации услуги Турбо.') . '</div>';
            }
        }

        if ($this->_attributesOut['user']['turbo_speed_in'] == 0) {
            $turbo_speed_in_formate = T_('Без ограничения');
        } else {
            $turbo_speed_in_formate = $this->speedView($this->_attributesOut['config']['speed_mbit'], $this->_attributesOut['user']['turbo_speed_in']);
        }

        # Форматируем скорость с Мбит / Кбит / Без ограничений
        if ($this->_attributesOut['user']['turbo_speed_out'] == 0) {
            $turbo_speed_out_formate = T_('Без ограничения');
        } else {
            $turbo_speed_out_formate = $this->speedView($this->_attributesOut['config']['speed_mbit'], $this->_attributesOut['user']['turbo_speed_out']);
        }

        if (isset($this->_attributesOut['user']['turbo_active']) and $this->_attributesOut['user']['turbo_active'] == '1' AND $cabinet_turbo_alert == '') {
            $cabinet_turbo_active_alert = '<div class="alert alert-info" id="cabinet_turbo_active_alert">' . T_('Услуга Турбо уже активирована.') . '</div>';
        } else {
            $cabinet_turbo_active_alert = '';
        }

        $this->_attributesOut['turbo'] = Array(
            'cabinet_turbo_active_alert' => $cabinet_turbo_active_alert,
            'cabinet_turbo_alert'        => $cabinet_turbo_alert,
            'turbo_speed_in_formate'     => $turbo_speed_in_formate,
            'turbo_speed_out_formate'    => $turbo_speed_out_formate

        );
    }

    public function getOtp($phone)
    {
        $url = $this->_billLink['getotphtml'];
//		$param = "phone=" . $phone;
        $param = array("phone" => $phone);
        $tempResponse = $this->sendQuery($url, 'post', $param, 0);

        $response = json_decode($tempResponse, true);

        return $response;
    }

    public function statusApplyOtp()
    {
        $otp = '';
        $url = $this->_billLink['applyotphtml'];

        if (isset($this->_paramsInput['otp1'])) {
            $otp .= $this->_paramsInput['otp1'];
        }

        if (isset($this->_paramsInput['otp2'])) {
            $otp .= $this->_paramsInput['otp2'];
        }

        if (isset($this->_paramsInput['otp3'])) {
            $otp .= $this->_paramsInput['otp3'];
        }

        if (isset($this->_paramsInput['otp4'])) {
            $otp .= $this->_paramsInput['otp4'];
        }

//		$param = "otp=" . $otp;
        $param = array("otp" => $otp);
        $tempResponse = $this->sendQuery($url, 'post', $param, 0);
        $response = json_decode($tempResponse, true);

        return $response;
    }

    public function getRegistrationPacketList()
    {

        $url = $this->_billLink['getpacketslistregistrationhtml'];

        $tempResponse = $this->sendQuery($url, 'get', '', 0);
        $response = json_decode($tempResponse, true);

        return $response;
    }

    public function doRegistrationType2($phone, $packet_id, $mac = '', $address = '')
    {
        $url = $this->_billLink['registrationType2'];

        $param = array(
            "phone"     => $phone,
            "gid"       => $packet_id,
            "mac"       => $mac,
            "address"   => $address
        );
        $tempResponse = $this->sendQuery($url, 'post', $param, 0);
        $response = json_decode($tempResponse, true);

        return $response;
    }

    public function menuRegistration()
    {
        $this->_outPage = 'register';
        $register_response = array();
        $register_packet_list = array();
        $register_step_text = '';
        $registrationType = '99';
        $step = 1;
        $mac = '';
        $address = '';
        $address = '';

        // Тип регистрации 2.
        if (isset($this->_paramsInput['type'], $this->_attributesOut['config']['gui']['user_registration_type2_on']) AND $this->_attributesOut['config']['gui']['user_registration_type2_on'] == '1' AND $this->_paramsInput['type'] == '2') {

            $registrationType = '2';

            // Если пришел телефон и ID тарифа
            if (isset($this->_paramsInput['phone']) and isset($this->_paramsInput['packet_id'])) {

                if (isset($this->_paramsInput['mac'])) {
                    $mac = $this->_paramsInput['mac'];
                }

                if (isset($this->_paramsInput['address'])) {
                    $address = $this->_paramsInput['address'];
                }

                $response = $this->doRegistrationType2($this->_paramsInput['phone'], $this->_paramsInput['packet_id'], $mac, $address);

                if (isset($response['result']) and $response['result'] == '0') {
                    $register_step_text = T_('На Ваш телефон отправлено сообщение с данными для авторизации.');
                    $step = 3;
                } elseif (isset($response['result'])) {
                    $register_step_text = $this->getErrorText($response['result']);
                } else {
                    $register_step_text = $this->getErrorText(1000);
                }
            } else {
                $register_step_text = T_('Выберите тариф');
            }

            $result = $this->getRegistrationPacketList();
            if (isset($result['response'])) {
                $register_packet_list = $result['response'];
            }
        } elseif (isset($this->_paramsInput['type'], $this->_attributesOut['config']['gui']['user_registration_type1_on']) AND $this->_attributesOut['config']['gui']['user_registration_type1_on'] == '1' AND $this->_paramsInput['type'] == '1') {
            //Тип регистрации 1
            $registrationType = '1';

            $register_step_text = T_('Введите номер телефона для получения кода активации.');

            if (isset($this->_paramsInput['phone'])) {

                $response = $this->getOtp($this->_paramsInput['phone']);

                if (isset($response['result']) and $response['result'] == '0') {
                    $register_step_text = T_('На Ваш телефон отправлено смс с кодом активации.');
                    $step = 2;
                } elseif (isset($response['result']) and $response['result'] == '4') {
                    $register_step_text = $this->getErrorText($response['result']);
                    $step = 2;
                } elseif (isset($response['result'])) {
                    $register_step_text = $this->getErrorText($response['result']);
                } else {
                    $register_step_text = $this->getErrorText(1000);
                }
            } elseif (isset($this->_paramsInput['otp1'])) {

                $response = $this->statusApplyOtp();

                if (isset($response['result']) and $response['result'] == '0' or $response['result'] == '2') {
                    $register_step_text = T_('Регистрация успешно завершена.');
                    $register_response = $response['response'];
                    $step = 3;
                } elseif (isset($response['result'])) {
                    $register_step_text = $this->getErrorText($response['result']);
                } else {
                    $register_step_text = $this->getErrorText(1000);
                }
            }
        }

        $this->_attributesOut['register'] = Array(
            'register_step'        => $step,
            'register_step_text'   => $register_step_text,
            'register_response'    => $register_response,
            'register_packet_list' => $register_packet_list,
            'register_type'        => $registrationType
        );
    }

    public function getErrorText($status)
    {
        //	0 = Успешно
        //	1 = Регистрация не активна
        //	2 = СМС не отправлено
        //	3 = OTP не существует или не действителен
        //	4 = OTP был отправлен уже раннее на данный номер телефона
        //	5 = Не указан или не существует тарифный план для регистрации
        //	6 = Не указан номер телефона или неверный формат номера
        //  7 = К данному номеру уже привязана учетная запись
        //  8 = Система восстановления паролей не активна
        //  9 = Абонент с данным номером не обнаружен
        // 10 = Количество восстановления пароля в день исчерпано
        // 11 = Количество восстановления пароля в месяц исчерпано
        // 12 = Невозможно создать логин абоненту. Если тип генерации = UID, то проверьте, чтоб следующий логин не был уже занят

        switch ($status) {
            case "1":
                $errorText = T_('Ошибка SMS регистрации');
                break;
            case "2":
                $errorText = T_('Ошибка сервиса');
                break;
            case "3":
                $errorText = T_('Неверный код активации');
                break;
            case "4":
                $errorText = T_('На Ваш телефон уже ранее был отправлен код активации');
                break;
            case "5":
                $errorText = T_('Ошибка SMS регистрации');
                break;
            case "6":
                $errorText = T_('Неверный номер телефона');
                break;
            case "7":
                $errorText = T_('По данному номеру уже была зарегистрирована учетная запись');
                break;
            case "8":
                $errorText = T_('Система восстановления паролей не активна');
                break;
            case "9":
                $errorText = T_('Абонент с данным номером не обнаружен');
                break;
            case "10":
                $errorText = T_('Количество восстановления пароля в день исчерпано');
                break;
            case "11":
                $errorText = T_('Количество восстановления пароля в месяц исчерпано');
                break;
            case "12":
                $errorText = T_('Не заполнено поле адресс');
                break;
            default:
                $errorText = T_('Ошибка');
        }

        return $errorText . ' (' . $status . ')';
    }

    public function getNews()
    {
        $this->_outPage = 'news';
        $url = $this->_billLink['getcabinetnews'];
        $responseQuery = $this->sendQuery($url, 'get', '', 0);
        $tempArray = $this->xmlParser($responseQuery);
        $newsArray = array();

        if (isset($tempArray['element'])) {
            if (count($tempArray['element']) == 1) {
                $newsArray['@attributes'] = $tempArray['element'];
            } else {
                $newsArray = $tempArray['element'];
            }
            rsort($newsArray);
        }

        return $newsArray;
    }

    public function menuNews()
    {
        # Создаем обьект класса
        $tplNews = new TemplateClass($this->_attributesOut['config']['path_template']);

        $outItemNews = $this->getNews();

        $tplNews->set("newsitem", $outItemNews);
        $itemNews = $tplNews->out("newsitem");

        $this->_attributesOut['news'] = Array(
            'cab_company_news' => $itemNews
        );
    }

    public function getHistoryPayment()
    {
        $arrayHistoryPayment = array();
        $date_to = $this->_serverDate['year'] + 1;
        $date_from = $this->_serverDate['year'] - 2;
        $uid = $this->_attributesOut['user']['uid'];

        $url = $this->_billLink['statpaymfl'];
//		$param = "to%5Fdate=" . $date_to . "%2D12%2D31&uid=" . $uid . "&from%5Fdate=" . $date_from . "%2D01%2D01";
        $param = array(
            "uid"       => $uid,
            "to_date"   => $date_to . "-12-31",
            "from_date" => $date_from . "-01-01"
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $tempArray = $this->xmlParser($responseQuery);

        if (isset($tempArray['pay'])) {
            if (!isset($tempArray['pay'][0])) {
                $arrayHistoryPayment[0] = $tempArray['pay'];
            } else {
                $arrayHistoryPayment = $tempArray['pay'];
            }
        }

        return $arrayHistoryPayment;
    }

    public function menuHistoryPayment()
    {
        $result = '';
        $this->_outPage = 'historypayment';

        $historyArray = $this->getHistoryPayment();

        foreach ($historyArray as $key) {

            if (!empty($key['comment'])) {
                $comment = $key['comment'];
            } else {
                $comment = '';
            }

            $result .= '
		<tr>
			<td>' . $key['date'] . '</td>
			<td>' . $key['bughtypeid'] . '</td>
			<td>' . $key['before_billing'] . '</td>
			<td>' . $key['summa'] . '</td>
			<td>' . $comment . '</td>
		</tr>';
        }

        $this->_attributesOut['historyPayment'] = Array('cab_payment_history' => $result);
    }

    public function getHistorySession()
    {
        $date_to = $this->_serverDate['year'] + 1;
        $date_from = $this->_serverDate['year'] - 2;
        $uid = $this->_attributesOut['user']['uid'];
        $url = $this->_billLink['stattrafflex'];
//		$param = "respFormat=json&to%5Fdate=" . $date_to . "%2D12%2D31&uid=" . $uid . "&from%5Fdate=" . $date_from . "%2D01%2D01";

        $param = array(
            "respFormat" => "josn",
            "uid"        => $uid,
            "to_date"    => $date_to . "-12-31",
            "from_date"  => $date_from . "-01-01"
        );
        $response = $this->sendQuery($url, 'post', $param, 0);

        return $response;
    }

    /*
     * Получить историю сессий пользователя
     */
    public function menuHistorySession()
    {
        $this->_outPage = 'historysession';
        $respArray = array();

        $response = $this->getHistorySession();
        $respJSON = json_decode($response, true);

        # TODO Убрать XML после релиза
        // JSON / XML
        if (isset($respJSON['sessions'])) {
            $respArray = $respJSON['sessions'];
        } else {
            $buferArray = $this->xmlParser2($response);
            if (isset($buferArray['sessions']['0']['session'])) {
                $respArray = $buferArray['sessions']['0']['session'];
            }
        }

        $this->_attributesOut['historySession'] = Array('historySessionArray' => $respArray);
    }

    public function doCredit($oldPass, $typeCredit)
    {
        if ($typeCredit == 2) {
            $url = $this->_billLink['getcreditprocentflex'];
        } else {
            $url = $this->_billLink['getcreditflex'];
        }

//		$param = "oldpass=" . $oldPass . "&uid=" . $this->_attributesOut['user']['uid'];
        $param = array(
            "oldpass" => $oldPass,
            "uid"     => $this->_attributesOut['user']['uid']
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $buferRespone = $this->xmlParser2($responseQuery);
        $response = $buferRespone['ok'];

        return $response;
    }

    public function menuCredit()
    {
        $this->_outPage = 'credit';
        $alertInfoCredit = '';
        $day_limit = -1;
        $day_date_limit = -1;
        $day_limit_procent = -1;
        $type_limit = -1;
        $alertDoCredit = '';
        $summaCredit = '';
        $piceActivateCredit = '';

        # Если был запрос активации услуги
        if (isset($this->_paramsInput['oldpass'])) {

            $statusDoCredit = $this->doCredit($this->_paramsInput['oldpass'], $this->_paramsInput['typeCredit']);

            if ($statusDoCredit == '1') {
                $alertDoCredit = '<div class="alert alert-success" id="cabinet_credit_active_alert">' . T_('Услуга Кредит успешно активирована.') . '</div>';
            } else {
                $alertDoCredit = '<div class="alert alert-danger">' . T_('Ошибка активации услуги Кредит.') . '</div>';
            }
        }

        # Обычный кредит
        if ($this->_attributesOut['user']['do_credit_vremen_global'] == '1') {

            if (($this->_serverDate['dd'] >= $this->_attributesOut['user']['start_credit_date']) AND
                ($this->_serverDate['dd'] <= $this->_attributesOut['user']['stop_credit_date'] - 1) AND
                ($this->_attributesOut['user']['do_credit_vremen_use'] == '0') AND
                ($this->_attributesOut['user']['do_credit_procent_vremen_use'] == '0')
                AND ($this->_attributesOut['user']['do_credit_swing_date_use'] == '0')
            ) {
                $type_limit = 1;
            } else {
                if ($this->_serverDate['dd'] < $this->_attributesOut['user']['start_credit_date']) {
                    $day_limit = $this->_attributesOut['user']['start_credit_date'] - $this->_serverDate['dd'];
                } else {
                    $day_limit = 31 - $this->_serverDate['dd'] + $this->_attributesOut['user']['start_credit_date'];
                }
                $day_date_limit = $day_limit;
            }
        }

        # Процентный кредит
        if ($this->_attributesOut['user']['do_credit_procent_vremen_global'] == '1') {

            if (
                ($this->_serverDate['dd'] >= $this->_attributesOut['user']['start_credit_procent_date']) AND
                ($this->_serverDate['dd'] <= $this->_attributesOut['user']['stop_credit_procent_date'] - 1) AND
                ($this->_attributesOut['user']['do_credit_vremen_use'] == '0') AND
                ($this->_attributesOut['user']['do_credit_procent_vremen_use'] == '0') AND ($this->_attributesOut['user']['do_credit_swing_date_use'] == '0')
            ) {
                $type_limit = 2;
            } else {
                if ($this->_serverDate['dd'] < $this->_attributesOut['user']['start_credit_procent_date']) {
                    $day_limit_procent = $this->_attributesOut['user']['start_credit_procent_date'] - $this->_serverDate['dd'];
                } else {
                    $day_limit_procent = 31 - $this->_serverDate['dd'] + $this->_attributesOut['user']['start_credit_procent_date'];
                }
            }

            if ($day_limit == -1) {
                $day_date_limit = $day_limit_procent;
            } else {
                if ($day_limit < $day_limit_procent) {
                    $day_date_limit = $day_limit;
                } else {
                    $day_date_limit = $day_limit_procent;
                }
            }
        }

        # Кредит с плавающей датой
        if ($this->_attributesOut['user']['do_credit_vremen_global'] == '1' AND $this->_attributesOut['user']['do_credit_swing_date'] == '1') {
            if (
                ($this->_attributesOut['user']['do_credit_vremen_use'] == '0') AND
                ($this->_attributesOut['user']['do_credit_procent_vremen_use'] == '0') AND
                ($this->_attributesOut['user']['do_credit_swing_date_use'] == '0')
            ) {
                $type_limit = 3;
            } else {
                if ($this->_serverDate['dd'] < $this->_attributesOut['user']['start_credit_date']) {
                    $day_limit = $this->_attributesOut['user']['start_credit_date'] - $this->_serverDate['dd'];
                } else {
                    $day_limit = 31 - $this->_serverDate['dd'] + $this->_attributesOut['user']['start_credit_date'];
                }

                $day_date_limit = $day_limit;
            }
        }

        if ($type_limit == -1) {

            if ($this->_attributesOut['user']['do_credit_vremen_use'] == '1' or $this->_attributesOut['user']['do_credit_procent_vremen_use'] == '1'
                or $this->_attributesOut['user']['do_credit_swing_date_use'] == '1'
            ) {
                $alertCredit = '<div class="alert alert-info" id="cabinet_credit_active_alert">' . T_('Услуга кредит уже была активирована.') . '</div>';
            } else {
                $alertCredit = '<div class="alert alert-info" id="cabinet_credit_active_alert">' . sprintf(T_('Услуга кредит будет доступна через %d дней.'), $day_date_limit) . '</div>';
            }
        } else {
            $alertCredit = '';
        }

        if ($type_limit == 3) {
            $piceActivateCredit = $this->_attributesOut['user']['credit_active_cena'];
            $summaCredit = $this->_attributesOut['user']['do_fixed_credit_summa'];

            $alertInfoCredit = '<div class="alert alert-info">' . sprintf(T_('Кредит выдается 1 раз в течении 1 календарного месяца на период %d дней.'), $this->_attributesOut['user']['do_credit_swing_date_days']) . '</div>';
        } elseif ($type_limit == 2) {
            $piceActivateCredit = $this->_attributesOut['user']['credit_procent_active_cena'];
            $summaCredit = $this->_attributesOut['user']['do_fixed_credit_summa'];

            $alertInfoCredit = '<div class="alert alert-info">' . sprintf(T_('Кредит выдается на период с %d по %d число, под %d %% ежедневно и будет снят %d числа.'), $this->_attributesOut['user']['start_credit_procent_date'], $this->_attributesOut['user']['stop_credit_procent_date'], $this->_attributesOut['user']['credit_procent'], $this->_attributesOut['user']['stop_credit_procent_date']) . '</div>';
        } elseif ($type_limit == 1) {
            $piceActivateCredit = $this->_attributesOut['user']['credit_active_cena'];
            $summaCredit = $this->_attributesOut['user']['do_fixed_credit_summa'];

            $alertInfoCredit = '<div class="alert alert-info">' . sprintf(T_('Кредит выдается на период с %d по %d число, и будет снят %d числа.'), $this->_attributesOut['user']['start_credit_date'], $this->_attributesOut['user']['stop_credit_date'], $this->_attributesOut['user']['stop_credit_date']) . '.</div>';
        }

        $this->_attributesOut['credit'] = Array(
            'cab_credit_info_alert'     => $alertInfoCredit,
            'cab_credit_alert'          => $alertCredit,
            'cab_credit_active_cena'    => $piceActivateCredit,
            'cab_do_fixed_credit_summa' => $summaCredit,
            'typeCredit'                => $type_limit,
            'alertDoCredit'             => $alertDoCredit
        );
    }

    public function doUnfreeze($oldPass)
    {
        $url = $this->_billLink['dounfreezeuserfl'];
        $param = array(
            "password2" => $oldPass,
            "us_uid"    => $this->_attributesOut['user']['uid']
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $buferRespone = $this->xmlParser2($responseQuery);
        $response = $buferRespone['ok'];

        return $response;
    }

    public function doFreeze($oldPass, $freezeDoEver, $doFreezeNow, $freezeDateStart, $freezeDateStop, $freezeFixedMonthNum)
    {
        $url = $this->_billLink['dofreezeuserfl'];
        $param = array(
            "freeze_do_ever"      => $freezeDoEver,
            "do_freeze_now"       => $doFreezeNow,
            "do_return_abonplata" => $this->_attributesOut['user']['freeze_do_return_abonolata'],
            "password2"           => $oldPass,
            "freeze_date_start"   => $freezeDateStart,
            "us_uid"              => $this->_attributesOut['user']['uid'],
            "freeze_date_stop"    => $freezeDateStop,
            "freezefixedmonthnum" => $freezeFixedMonthNum
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $buferRespone = $this->xmlParser2($responseQuery);
        $response = $buferRespone['ok'];

        return $response;
    }


    /**
     *  Выпилить услуги указанных мидлвар из массива
     *
     * @param $services
     * @param $unsetServicePortal
     * @return array
     */
    private function unsetService($services, $unsetServicePortal)
    {
        $response = array();

        foreach($services AS $service){
            if(!in_array($service['service_portal'], $unsetServicePortal)){
                $response[] = $service;
            }
        }

        return $response;
    }

    /**
     * Оставить услуги указанных мидлвар из массива
     *
     * @param $services
     * @param $unsetServicePortal
     * @return array
     */
    private function filterService($services, $unsetServicePortal)
    {
        $response = array();

        foreach($services AS $service){
            if(in_array($service['service_portal'], $unsetServicePortal)){
                $response[] = $service;
            }
        }

        return $response;
    }

    /**
     * Остальные доп.услуги
     */
    public function menuOtherServices()
    {
        $this->_outPage = 'services';
        $megogo_info_on = 0;
        $megogo_info = array("on" => "0");

        /**
         * 7 - omegaTV
         * 6 - TRINITY-TV
         */
        $filterArray = array(6,7);

        // Получаем все услуги доступные
        $getAllPersonalServicesUser = $this->getAllPersonalServicesUser();
        // Отфильтруем мидлвары
        $getAllPersonalServicesUser = $this->unsetService($getAllPersonalServicesUser,$filterArray);

        // Получаем включенные услуги абонента
        $getPersonalServicesUser = $this->getPersonalServicesUser();
        // Отфильтруем мидлвары
        $getPersonalServicesUser = $this->unsetService($getPersonalServicesUser,$filterArray);

        //Получаем активные(оплаченные) услуги
        $getActiveServicesUser = $this->getActiveServicesUser();

        // Активные услуги
        $activeServicesId = array();
        foreach ($getActiveServicesUser as $item) {
            $activeServicesId[] = $item['serviceid'];
        }

        // Включенные услуги
        $usedServicesId = array();
        foreach ($getPersonalServicesUser as $item) {
            $usedServicesId[] = $item['serviceid'];
        }

        // Активация/деактивации услуг
        if (!empty($this->_paramsInput['services'])) {

            $inputEnableService = array();
            foreach ($this->_paramsInput as $key => $value) {
                $search = strpos($key, "service_select_");
                if ($search !== false) {
                    $inputEnableService[] = $value;
                }
            }

            // Список ID котрые необходимо деактивировать
            foreach ($usedServicesId as $item) {
                if (!in_array($item, $inputEnableService)) {
                    $this->unSetPersonalServiceUser($item);
                }
            }

            // Список ID котрые необходимо активировать
            foreach ($inputEnableService as $item) {
                if (!in_array($item, $usedServicesId)) {
                    $this->setPersonalServiceUser($item);
                }
            }

            // Получаем включенные услуги абонента
            $getPersonalServicesUser = $this->getPersonalServicesUser();
            // Отфильтруем мидлвары
            $getPersonalServicesUser = $this->unsetService($getPersonalServicesUser,$filterArray);


            //Получаем активные услуги
            $getActiveServicesUser = $this->getActiveServicesUser();

            // Активные услуги
            $activeServicesId = array();
            foreach ($getActiveServicesUser as $item) {
                $activeServicesId[] = $item['serviceid'];

            }

            // Включенные услуги
            $usedServicesId = array();
            foreach ($getPersonalServicesUser as $item) {
                $usedServicesId[] = $item['serviceid'];
            }
        }

        // Сформируем список всех услуг для фронта
        $tmp = array();
        foreach ($getAllPersonalServicesUser as $services) {

            if (in_array($services['serviceid'], $activeServicesId)) {
                $services['active'] = 1;
            } else {
                $services['active'] = 0;
            }

            if (in_array($services['serviceid'], $usedServicesId)) {
                $services['used'] = 1;

                if ($item['service_portal'] == 4) {
                    $megogo_info_on = 1;
                }
            } else {
                $services['used'] = 0;
            }

            if ($services['tarifservice'] == 1) {
                $type = '1_tariff';
            } elseif ($services['tarifservice'] == 2) {
                $type = '2_packet';
            } else {
                $type = '3_none';
            }
            $tmp[$services['service_groupid']][$type][] = $services;

        }

        // Сортировка
        $allservices = array();
        foreach ($tmp AS $key => $item) {
            ksort($item);
            $allservices[$key] = $item;
        }

        if ($megogo_info_on == 1) {
            $info = $this->getMegogoUserInfo();

            $megogo_info = array(
                "on"       => $megogo_info_on,
                "login"    => $info['login'],
                "password" => $info['password']
            );
        }

        if (!empty($this->_paramsInput['megogo_action']) AND $this->_paramsInput['megogo_action'] == 'resetpass') {
            $this->resetMegogoUserPass();
        }

        $this->_attributesOut['user']['services'] = array(
            "userservices"    => $allservices,
            "alluserservices" => $getAllPersonalServicesUser,
            "megogo_info"     => $megogo_info
        );
    }


    /**
     * OmegaTV Service
     */
    public function menuOmegaTvServices()
    {
        $this->_outPage = 'omegatv';

        /**
         * 7 - omegaTV
         */
        $filterArray = array(7);

        // Получаем пользователя из ОмегаТВ
        $customer = $this->getOmegaTvCustomer();


        // Получаем все услуги доступные
        $getAllPersonalServicesUser = $this->getAllPersonalServicesUser();
        // Отфильтруем мидлвары
        $getAllPersonalServicesUser = $this->filterService($getAllPersonalServicesUser,$filterArray);

        // Получаем включенные услуги абонента
        $getPersonalServicesUser = $this->getPersonalServicesUser();
        // Отфильтруем мидлвары
        $getPersonalServicesUser = $this->filterService($getPersonalServicesUser,$filterArray);

        //Получаем активные услуги
        $getActiveServicesUser = $this->getActiveServicesUser();

        // Активные услуги
        $activeServicesId = array();
        foreach ($getActiveServicesUser as $item) {
            $activeServicesId[] = $item['serviceid'];
        }

        // Включенные услуги
        $usedServicesId = array();
        foreach ($getPersonalServicesUser as $item) {
            $usedServicesId[] = $item['serviceid'];
        }

        // Активация/деактивации услуг
        if (!empty($this->_paramsInput['services'])) {

            $inputEnableService = array();
            foreach ($this->_paramsInput as $key => $value) {
                $search = strpos($key, "service_select_");
                if ($search !== false) {
                    $inputEnableService[] = $value;
                }
            }

            // Список ID котрые необходимо деактивировать
            foreach ($usedServicesId as $item) {
                if (!in_array($item, $inputEnableService)) {
                    $this->unSetPersonalServiceUser($item);
                }
            }

            // Список ID котрые необходимо активировать
            foreach ($inputEnableService as $item) {
                if (!in_array($item, $usedServicesId)) {
                    $this->setPersonalServiceUser($item);
                }
            }

            //Получаем активные услуги
            $getActiveServicesUser = $this->getActiveServicesUser();
            // Получаем включенные услуги абонента
            $getPersonalServicesUser = $this->getPersonalServicesUser();

            // Активные услуги
            $activeServicesId = array();
            foreach ($getActiveServicesUser as $item) {
                $activeServicesId[] = $item['serviceid'];
            }

            // Включенные услуги
            $usedServicesId = array();
            foreach ($getPersonalServicesUser as $item) {
                $usedServicesId[] = $item['serviceid'];

            }
        }

        // Сформируем список всех услуг для фронта
        $tmp = array();
        foreach ($getAllPersonalServicesUser as $services) {

            if (in_array($services['serviceid'], $activeServicesId)) {
                $services['active'] = 1;
            } else {
                $services['active'] = 0;
            }

            if (in_array($services['serviceid'], $usedServicesId)) {
                $services['used'] = 1;
            } else {
                $services['used'] = 0;
            }

            if ($services['tarifservice'] == 1) {
                $type = '1_tariff';
            } elseif ($services['tarifservice'] == 2) {
                $type = '2_packet';
            } else {
                $type = '3_none';
            }
            $tmp[$services['service_groupid']][$type][] = $services;
        }

        // Сортировка
        $allservices = array();
        foreach ($tmp AS $key => $item) {
            ksort($item);
            $allservices[$key] = $item;
        }

        $code = '';
        if (!empty($this->_paramsInput['code'])) {
            $code = $this->getOmegaTvCode();
        }

        if (!empty($this->_paramsInput['getplaylist'])) {
           $this->getOmegaTvUrlAdd();
            $customer = $this->getOmegaTvCustomer();
        }

        if(!empty($this->_paramsInput['remove_device'])){
            $this->delOmegaTvDevice($this->_paramsInput['remove_device']);
        }

        if(!empty($this->_paramsInput['remove_playlist'])){
            $this->delOmegaTvPlaylist($this->_paramsInput['remove_playlist']);

            $customer = $this->getOmegaTvCustomer();
        }


        // Редиректим на URL просмотра
        if(!empty($this->_paramsInput['geturl'])){
            if(!empty($customer['result']['web_url'])){
                $url = $customer['result']['web_url'];
                header("Location: ".$url);
                die();
            }
        }

        if(!empty($customer['result']['playlists'])){

            $playlists = $customer['result']['playlists'];
        } else {
            $playlists = array();
        }

        
        $devices = $this->getOmegaTvDevice();

        $this->_attributesOut['user']['services'] = array(
            "userservices"    => $allservices,
            "alluserservices" => $getAllPersonalServicesUser,
            "code_activation" => $code,
            "devices" => $devices,
            "playlists" => $playlists
        );
    }

    /**
     * TrinityTV Service
     */
    public function menuTrinityTvServices()
    {
        $this->_outPage = 'trinitytv';

        /**
         * 6 - TRINITY-TV
         */
        $filterArray = array(6);

        // Получаем все услуги доступные
        $getAllPersonalServicesUser = $this->getAllPersonalServicesUser();
        // Отфильтруем мидлвары
        $getAllPersonalServicesUser = $this->filterService($getAllPersonalServicesUser,$filterArray);

        // Получаем включенные услуги абонента
        $getPersonalServicesUser = $this->getPersonalServicesUser();
        // Отфильтруем мидлвары
        $getPersonalServicesUser = $this->filterService($getPersonalServicesUser,$filterArray);

        //Получаем активные услуги
        $getActiveServicesUser = $this->getActiveServicesUser();

        // Активные услуги
        $activeServicesId = array();
        foreach ($getActiveServicesUser as $item) {
            $activeServicesId[] = $item['serviceid'];
        }

        // Включенные услуги
        $usedServicesId = array();
        foreach ($getPersonalServicesUser as $item) {
            $usedServicesId[] = $item['serviceid'];
        }

        // Активация/деактивации услуг
        if (!empty($this->_paramsInput['services'])) {

            $inputEnableService = array();
            foreach ($this->_paramsInput as $key => $value) {
                $search = strpos($key, "service_select_");
                if ($search !== false) {
                    $inputEnableService[] = $value;
                }
            }

            // Список ID котрые необходимо деактивировать
            foreach ($usedServicesId as $item) {
                if (!in_array($item, $inputEnableService)) {
                    $this->unSetPersonalServiceUser($item);
                }
            }

            // Список ID котрые необходимо активировать
            foreach ($inputEnableService as $item) {
                if (!in_array($item, $usedServicesId)) {
                    $this->setPersonalServiceUser($item);
                }
            }

            //Получаем активные услуги
            $getActiveServicesUser = $this->getActiveServicesUser();
            // Получаем включенные услуги абонента
            $getPersonalServicesUser = $this->getPersonalServicesUser();

            // Активные услуги
            $activeServicesId = array();
            foreach ($getActiveServicesUser as $item) {
                $activeServicesId[] = $item['serviceid'];
            }

            // Включенные услуги
            $usedServicesId = array();
            foreach ($getPersonalServicesUser as $item) {
                $usedServicesId[] = $item['serviceid'];

            }
        }

        // Сформируем список всех услуг для фронта
        $tmp = array();
        foreach ($getAllPersonalServicesUser as $services) {

            if (in_array($services['serviceid'], $activeServicesId)) {
                $services['active'] = 1;
            } else {
                $services['active'] = 0;
            }

            if (in_array($services['serviceid'], $usedServicesId)) {
                $services['used'] = 1;
            } else {
                $services['used'] = 0;
            }

            if ($services['tarifservice'] == 1) {
                $type = '1_tariff';
            } elseif ($services['tarifservice'] == 2) {
                $type = '2_packet';
            } else {
                $type = '3_none';
            }
            $tmp[$services['service_groupid']][$type][] = $services;
        }

        // Сортировка
        $allservices = array();
        foreach ($tmp AS $key => $item) {
            ksort($item);
            $allservices[$key] = $item;
        }

        // Удалить ус-во
        if(!empty($this->_paramsInput['remove_device'])){
            $this->deleteUserDev($this->_paramsInput['remove_device']);
        }

        // Добавить ус-во
        if(!empty($this->_paramsInput['dev_mac']) AND !empty($this->_paramsInput['dev_type'])){
            $this->addUserDev($this->_paramsInput['dev_type'], $this->_paramsInput['dev_mac']);
        }

        // Добавить ус-во по коду
        if(!empty($this->_paramsInput['code']) AND !empty($this->_paramsInput['dev_type'])){
            $this->addUserDevByCode($this->_paramsInput['dev_type'], $this->_paramsInput['code']);
        }

        $deviceTypes = $this->getUserDeviceTypes(6);
        $devices = $this->getUserDevices(6);

        $this->_attributesOut['user']['services'] = array(
            "userservices"    => $allservices,
            "alluserservices" => $getAllPersonalServicesUser,
            "devices" => $devices,
            "device_types" => $deviceTypes
        );
    }

    private function resetMegogoUserPass()
    {
        $url = $this->_billLink['megogoserviceuserpass'];

        $responseQuery = $this->sendQuery($url, 'post', array(), 0);
        $response = json_decode($responseQuery, true);

        return $response['data'][0];
    }

    private function getMegogoUserInfo()
    {
        $url = $this->_billLink['megogoserviceuserinfo'];

        $responseQuery = $this->sendQuery($url, 'post', array(), 0);

        $response = json_decode($responseQuery, true);

        return $response['data'][0];
    }

    private function getOmegaTvCode()
    {
        $url = $this->_billLink['omegatvcode'];

        $responseQuery = $this->sendQuery($url, 'post', array(), 0);

        $response = json_decode($responseQuery, true);

        if(isset($response['code'])){
            return $response['code'];
        }else{
            return 'error';
        }
    }

    private function getOmegaTvCustomer()
    {
        $url = $this->_billLink['omegatvcustomer'];

        $responseQuery = $this->sendQuery($url, 'post', array(), 0);

        $response = json_decode($responseQuery, true);

        return $response;
    }


    private function delOmegaTvDevice($uniq)
    {
        $url = $this->_billLink['omegatvdevicedel'];

        $responseQuery = $this->sendQuery($url, 'post', array("uniq" => $uniq), 0);

        return $responseQuery;
    }

    private function delOmegaTvPlaylist($uniq)
    {
        $url = $this->_billLink['omegatvurldel'];

        $responseQuery = $this->sendQuery($url, 'post', array("uniq" => $uniq), 0);

        return $responseQuery;
    }



    /**
     * Получить типы ус-в пользователя
     *
     * @return array
     */
    private function getUserDeviceTypes($service_portal = 0)
    {
        $url = $this->_billLink['getdevtypeslist'];

        $responseQuery = $this->sendQuery($url, 'post', array("service_portal"=> $service_portal), 0);

        $response = json_decode($responseQuery, true);

        if(isset($response['data'])){
            return $response['data'];
        }else{
            return array();
        }
    }

    /**
     * Получить ус-ва пользователя
     *
     * @return array
     */
    private function getUserDevices($service_portal = 0)
    {
        $url = $this->_billLink['getuserdevices'];

        $responseQuery = $this->sendQuery($url, 'post', array("service_portal"=> $service_portal), 0);

        $response = json_decode($responseQuery, true);

        if(isset($response['data'])){
            return $response['data'];
        }else{
            return array();
        }
    }

    /**
     * Удалить ус-во пользователя
     *
     * @param $devid
     * @return string
     */
    private function deleteUserDev($devid)
    {
        $url = $this->_billLink['deleteuserdev'];

        $responseQuery = $this->sendQuery($url, 'post', array("devid" => $devid), 0);

        return $responseQuery;
    }


    /**
     * Добавить ус-во пользователя
     *
     * @param $devtypeid
     * @param $dev_mac
     * @return string
     */
    private function addUserDev($devtypeid, $dev_mac)
    {
        $url = $this->_billLink['adduserdev'];

        $responseQuery = $this->sendQuery($url, 'post', array("devtypeid" => $devtypeid, "dev_mac" =>$dev_mac), 0);

        return $responseQuery;
    }

    /**
     * Добавить ус-во по коду
     *
     * @param $devtypeid
     * @param $code
     * @return string
     */
    private function addUserDevByCode($devtypeid, $code)
    {
        $url = $this->_billLink['adduserdevbycode'];

        $responseQuery = $this->sendQuery($url, 'post', array("devtypeid" => $devtypeid, "code" => $code), 0);

        return $responseQuery;
    }

    private function  getOmegaTvUrlAdd()
    {
        $url = $this->_billLink['omegatvurladd'];

        $responseQuery = $this->sendQuery($url, 'post', array(), 0);

        $response = json_decode($responseQuery, true);

        return $response;
    }

    private function getOmegaTvDevice()
    {
        $url = $this->_billLink['omegatvdevice'];

        $responseQuery = $this->sendQuery($url, 'post', array(), 0);

        $response = json_decode($responseQuery, true);

        if(isset($response['device'])){
            return $response['device'];
        }else{
            return array();
        }
    }


    public function setPersonalServiceUser($serviceid)
    {
        $url = $this->_billLink['setpersonalserviceuser'];

        $param = array(
            "serviceid" => $serviceid
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);

        $response = json_decode($responseQuery, true);

        return $response['data'];
    }


    public function unSetPersonalServiceUser($serviceid)
    {
        $url = $this->_billLink['unsetpersonalserviceuser'];

        $param = array(
            "serviceid" => $serviceid
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);

        $response = json_decode($responseQuery, true);

        return $response['data'];
    }

    public function getPersonalServicesUser()
    {
        $url = $this->_billLink['getpersonalservicesuser'];

        $param = array();

        $responseQuery = $this->sendQuery($url, 'post', $param, 0);

        $response = json_decode($responseQuery, true);

        return $response['data'];
    }

    public function getAllPersonalServicesUser()
    {
        $url = $this->_billLink['getallpersonalservicesuser'];

        $param = array();

        $responseQuery = $this->sendQuery($url, 'post', $param, 0);

        $response = json_decode($responseQuery, true);

        return $response['data'];
    }

    public function getActiveServicesUser()
    {
        $url = $this->_billLink['getactiveservicesuser'];

        $param = array();

        $responseQuery = $this->sendQuery($url, 'post', $param, 0);

        $response = json_decode($responseQuery, true);

        return $response['data'];
    }

    public function menuFreeze()
    {
        $this->_outPage = 'freeze';

        $cab_freeze_alert = '';
        $freezeDateStart = '';
        $freezeDateStop = '';
        $oldPass = '';

        $cab_freeze_active_alert = '<div class="alert alert-info">' . T_("Внимание! При подтверждении заказа услуга Заморозка будет активирована с 1 числа следующего месяца!") . '</div>';

        if (isset($this->_paramsInput['freeze_date_start'])) {
            $freezeDateStart = $this->_paramsInput['freeze_date_start'];
        }

        if (isset($this->_paramsInput['freeze_date_stop'])) {
            $freezeDateStop = $this->_paramsInput['freeze_date_stop'];
        }

        if (isset($this->_paramsInput['oldpass'])) {
            $oldPass = $this->_paramsInput['oldpass'];
        }

        if (isset($this->_paramsInput['oldpass'])) {

            # Пользователь заморожен. Необходимо разморозить
            if (isset($this->_attributesOut['user']['frezetable']) and $this->_attributesOut['user']['frezetable'] == 1) {

                $statusDoUnFreeze = $this->doUnfreeze($this->_paramsInput['oldpass']);

                if ($statusDoUnFreeze == '1') {
                    $cab_freeze_alert = '<div class="alert alert-success">' . T_('Услуга Заморозка успешно деактивирована.') . '</div>';
                    $this->getUserData();
                } elseif ($statusDoUnFreeze == '5') {
                    $cab_freeze_alert = '<div class="alert alert-danger">' . T_('Ошибка деактивации услуги Заморозка. </br>Запрещено размораживаться раньше, чем минимальное количество дней действия услуги Заморозка. Обратитесь в тех. поддержку.') . '</div>';
                } else {
                    $cab_freeze_alert = '<div class="alert alert-danger">' . T_('Ошибка деактивации услуги Заморозка. Неверный пароль.') . '</div>';
                }
            } else {

                if (isset($this->_paramsInput['freeze_do_ever']) and $this->_paramsInput['freeze_do_ever'] <> 0) {
                    $freezeDoEver = 1;
                } else {
                    $freezeDoEver = 0;
                }

                if (isset($this->_paramsInput['do_freeze_now']) and $this->_paramsInput['do_freeze_now'] <> 0) {
                    $doFreezeNow = 1;
                } else {
                    $doFreezeNow = 0;
                }

                if (isset($this->_paramsInput['freezefixedmonthnum'])) {
                    $freezeFixedMonthNum = $this->_paramsInput['freezefixedmonthnum'];
                } else {
                    $freezeFixedMonthNum = 1;
                }

                # Заказ заморозки
                $statusDoFreeze = $this->doFreeze($oldPass, $freezeDoEver, $doFreezeNow, $freezeDateStart, $freezeDateStop, $freezeFixedMonthNum);

                if ($statusDoFreeze == '1') {
                    $this->getUserData();
                    $cab_freeze_alert = '<div class="alert alert-success">' . T_('Услуга Заморозка успешно активирована.') . '</div>';
                } elseif ($statusDoFreeze == '2') {
                    $cab_freeze_alert = '<div class="alert alert-danger">' . sprintf(T_('В активации услуги Заморозка отказано. Минимум дней для заморозки %d .'), $this->_attributesOut['user']['min_sutok_freeze']) . '</div>';
                } elseif ($statusDoFreeze == '3') {
                    $cab_freeze_alert = '<div class="alert alert-danger">' . T_('В активации услуги Заморозка отказано. Недостаточно средств.') . '</div>';
                } else {
                    $cab_freeze_alert = '<div class="alert alert-danger">' . T_('Ошибка активации услуги Заморозка. Неверный пароль.') . '</div>';
                }
            }
        }

        if ($this->_attributesOut['user']['freeze_do_ever'] == '1') {
            $cab_freeze_do_ever = '';
        } else {
            $cab_freeze_do_ever = 'disabled';
        }

        $this->_attributesOut['freeze'] = Array(
            'cab_freeze_do_ever'      => $cab_freeze_do_ever,
            'cab_freeze_alert'        => $cab_freeze_alert,
            'cab_freeze_active_alert' => $cab_freeze_active_alert,
        );
    }

    public function doRealIp($oldPass)
    {
        $url = $this->_billLink['dochangerealipflex'];
//		$param = "oldpass=" . $oldPass . "&uid=" . $this->_attributesOut['user']['uid'];
        $param = array(
            "oldpass" => $oldPass,
            "uid"     => $this->_attributesOut['user']['uid']
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $buferRespone = $this->xmlParser2($responseQuery);

        if (isset($buferRespone['ok'])) {
            $response = $buferRespone['ok'];
        } else {
            $response = array();
        }

        return $response;
    }

    public function menuRealip()
    {
        $cab_real_ip_alert = '';
        $this->_outPage = 'realip';

        if (isset($this->_paramsInput['oldpass'])) {

            $statusDoRealIp = $this->doRealIp($this->_paramsInput['oldpass']);

            if ($statusDoRealIp == '1') {
                if ($this->_attributesOut['user']['real_ip'] == '0') {
                    $cab_real_ip_alert = '<div class="alert alert-success">' . T_('Услуга Реальный IP успешно активирована.') . '</div>';
                } else {
                    $cab_real_ip_alert = '<div class="alert alert-success">' . T_('Услуга Реальный IP успешно деактивирована.') . '</div>';
                }

                # Получаем обновленные данные при успешном статусе
                $this->getUserData();
            } else {
                if ($this->_attributesOut['user']['real_ip'] == '0') {
                    $cab_real_ip_alert = '<div class="alert alert-danger">' . T_('Ошибка активации услуги Реальный IP.') . '</div>';
                } else {
                    $cab_real_ip_alert = '<div class="alert alert-danger">' . T_('Ошибка деактивации услуги Реальный IP.') . '</div>';
                }
            }
        }

        if ($this->_attributesOut['user']['real_ip'] == '1') {
            $cab_real_ip_active_alert = '<div class="alert alert-info" id="cab_real_ip_active_alert">' . sprintf(T_('Ваш Реальный IP: %s. Для деактивации услуги введите Ваш пароль.'), $this->_attributesOut['user']['framed_ip']) . '</div>';
        } else {
            $cab_real_ip_active_alert = '';
        }

        $this->_attributesOut['realIp'] = Array(
            'cab_real_ip_active_alert' => $cab_real_ip_active_alert,
            'cab_real_ip_alert'        => $cab_real_ip_alert
        );
    }

    public function changeBirth()
    {
        if (isset($this->_paramsInput['date_birth']) and $this->_paramsInput['date_birth'] <> '') {
            $date_birth = $this->_paramsInput['date_birth'];
        } else {
            $date_birth = '0000-00-00';
        }

        $oldpass = $this->_paramsInput['oldpass'];

        if (isset($this->_attributesOut['uid'])) {
            $uid = $this->_attributesOut['uid'];
        } else {
            $uid = 0;
        }

        $url = $this->_billLink['dochangedatebirthflex'];
//		$param = "&oldpass=" . $oldpass . "&date_birth=" . $date_birth . "&uid=" . $uid;
        $param = array(
            "oldpass"    => $oldpass,
            "date_birth" => $date_birth,
            "uid"        => $uid
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $buferArray = $this->xmlParser($responseQuery);
        $responseStatus = $buferArray['0'];

        return $responseStatus;
    }

    public function changeProfile()
    {
        $phone = $this->_paramsInput['phone'];
        $mob_tel = $this->_paramsInput['mob_tel'];
        $sms_tel = $this->_paramsInput['sms_tel'];
        $email = $this->_paramsInput['email'];
        $oldpass = $this->_paramsInput['oldpass'];

        if (isset($this->_attributesOut['uid'])) {
            $uid = $this->_attributesOut['uid'];
        } else {
            $uid = 0;
        }

        $url = $this->_billLink['dochangedataflex'];
//		$param = "phone=" . $phone . "&mob_tel=" . $mob_tel . "&oldpass=" . $oldpass . "&email=" . $email . "&uid=" . $uid . "&sms_tel=" . $sms_tel;
        $param = array(
            "phone"   => $phone,
            "mob_tel" => $mob_tel,
            "oldpass" => $oldpass,
            "email"   => $email,
            "uid"     => $uid,
            "sms_tel" => $sms_tel
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $buferArray = $this->xmlParser($responseQuery);
        $responseStatus = $buferArray['0'];

        return $responseStatus;
    }

    public function changePassword()
    {
        $newpass = $this->_paramsInput['newpass'];
        $newpass2 = $this->_paramsInput['newpass2'];
        $oldpass = $this->_paramsInput['oldpass'];

        if (isset($this->_attributesOut['uid'])) {
            $uid = $this->_attributesOut['uid'];
        } else {
            $uid = 0;
        }

        $url = $this->_billLink['dochangepassflex'];
//		$param = "uid=" . $uid . "&newpass=" . $newpass . "&oldpass=" . $oldpass . "&newpass2=" . $newpass2;

        $param = array(
            "uid"      => $uid,
            "newpass"  => $newpass,
            "oldpass"  => $oldpass,
            "newpass2" => $newpass2
        );
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $buferArray = $this->xmlParser($responseQuery);
        $responseStatus = $buferArray['0'];

        return $responseStatus;
    }

    public function menuProfile()
    {
        $this->_outPage = 'profile';
        $cabinet_profile_alert = '';
        $cabinet_profile_pass_alert = '';
        $statusChangeBirth = 1;

        # Изменение профиля и даты рождения
        if (isset($this->_paramsInput['changeprofile'])) {

            $statusChangeProfile = $this->changeProfile();

            # Изменение даты рождения
            if (isset($this->_paramsInput['date_birth'])) {
                $statusChangeBirth = $this->changeBirth();
            }

            if ($statusChangeProfile == '1' and $statusChangeBirth == '1') {
                $this->getUserData(); //Обновим полученные данные
                $cabinet_profile_alert = '<div class="alert alert-success">' . T_('Ваши данные успешно изменены.') . '</div>';
            } else {
                $cabinet_profile_alert = '<div class="alert alert-danger">' . T_('Ошибка изменения данных.') . '</div>';
            }
        }

        # Изменение пароля
        if (isset($this->_paramsInput['changepass'])) {
            $statusChangePass = $this->changePassword();

            if ($statusChangePass == '1') {
                $this->getUserData(); //Обновим полученные данные
                $cabinet_profile_pass_alert = '<div class="alert alert-success">' . T_('Ваш пароль успешно изменен.') . '</div>';
            } else {
                $cabinet_profile_pass_alert = '<div class="alert alert-danger">' . T_('Ошибка изменения пароля.') . '</div>';
            }
        }

        $this->_attributesOut['profile'] = Array(
            'cabinet_profile_alert'      => $cabinet_profile_alert,
            'cabinet_profile_pass_alert' => $cabinet_profile_pass_alert
        );
    }

    public function addTicket($uid, $idTicket, $textTicket)
    {
        $url = $this->_billLink['addmessage'];
//		$param = "useruid=" . $uid . "&ticketid=" . $idTicket . "&message=" . $textTicket . "&stuffid=0&unread=1";
        $param = array(
            "useruid"  => $uid,
            "ticketid" => $idTicket,
            "message"  => $textTicket,
            "stuffid"  => "0",
            "unread"   => "1"

        );
        $this->sendQuery($url, 'post', $param, 0);
    }

    public function newTicket($uid, $textTicket)
    {
        #Получаем ID для нового тикета
        $url = $this->_billLink['addticket'];
        $responseQuery = $this->sendQuery($url, 'get', '', 0);
        $response = $this->xmlParser($responseQuery);
        $idTicket = $response[0];

        #Присваеваем полученный ID тикета пользователю
        $url = $this->_billLink['updateticket'];
//		$param = "categoryid=4&prioritytypeid=2&statustypeid=1&useruid=" . $uid . "&note=" . $textTicket . "&created%5Fby%5Fuseruid=" . $uid . "&ticketid=" . $idTicket . "&note%5Fauthor=0";
        $param = array(
            "categoryid"         => "4",
            "prioritytypeid"     => "2",
            "statustypeid"       => "1",
            "useruid"            => $uid,
            "note"               => $textTicket,
            "created_by_useruid" => $uid,
            "ticketid"           => $idTicket,
            "note_author"        => "0"

        );
        $this->sendQuery($url, 'post', $param, 0);

        $this->addTicket($uid, $idTicket, $textTicket);

        return $idTicket;
    }

    public function getMessagesTicket($idTicket)
    {
        $ticketChatBody = array();

        //Получаем диалог с Бекенда
        $url = $this->_billLink['getmessages'];
//		$param = "ticketid=" . $idTicket;
        $param = array("ticketid" => $idTicket);
        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $tempArray = $this->xmlParser($responseQuery);

        $count_element = 0;
        if (isset($tempArray['element'])) {
            $count_element = count($tempArray['element']);
        }

        if ($count_element == 1) {
            $t_array['element'][0] = $tempArray['element'];
            $messTicketArray = $t_array['element'];
        } else {
            if (isset($tempArray['element'])) {
                $messTicketArray = $tempArray['element'];
            } else {
                $messTicketArray = array();
            }
        }

        $ticketBodyArray = $this->multisortArray($messTicketArray, 'messageid');

        if (!empty($ticketBodyArray)) {

            foreach ($ticketBodyArray as $tempKey) {
                $key = $tempKey['@attributes'];

                if ($key['useruid'] == 0) {
                    $key['fio'] = "Оператор";
//                    # Имя автора-админа сообщения, если фио пусто то подставляем логин
//                    if ($key['fio'] == '') {
//                        $key['fio'] = $key['login'];
//                    }
                } else {
                    # Имя автора-абонента сообщения, если пусто фио то подставляем логин
                    if ($this->_attributesOut['user']['fio'] == '') {
                        $key['fio'] = $this->_attributesOut['user']['user'];
                    } else {
                        $key['fio'] = $this->_attributesOut['user']['fio'];
                    }
                }
                $ticketChatBody[] = $key;
            }
        }

        return $ticketChatBody;
    }

    public function getInfoTicket($ticketID)
    {
        $status = 'closed';

        $url = $this->_billLink['getticketslist2x'];
//		$param = "ticketid=" . $ticketID . "&useruid=" . $this->_attributesOut['user']['uid'];
        $param = array(
            "ticketid" => $ticketID,
            "useruid"  => $this->_attributesOut['user']['uid']
        );

        $responseQuery = $this->sendQuery($url, 'post', $param, 0);
        $tempArray = $this->xmlParser($responseQuery);

        if (isset($tempArray['element'])) {
            $tempArray = $tempArray['element'];
        }

        foreach ($tempArray AS $ticket) {


            if (isset($ticket['@attributes']['ticketid']) AND $ticket['@attributes']['ticketid'] == $ticketID) {
                $status = $ticket['@attributes']['statustypename'];
            }elseif (isset($ticket['ticketid']) AND $ticket['ticketid'] == $ticketID){
                $status = $ticket['statustypename'];
            }
        }

        return $status;
    }

    public function menuRentsoft()
    {
        $this->_outPage = 'rentsoft';

        if ($this->_attributesOut['user']['rentsoft_on'] == '1') {

            if (file_exists("data/lib/Rentsoft.php")) {
                include_once("data/lib/Rentsoft.php");
            }

            $AG_NAME = $this->_attributesOut['user']['rentsoft_ag_name'];
            $SECRET = $this->_attributesOut['user']['rentsoft_secret'];

            $frame = Rentsoft::getIframe($_GET['rs_uri'], '', $AG_NAME, $this->_attributesOut['user']['uid'], '', $SECRET, '', '100%');

            $this->_attributesOut['rentsoft']['frame'] = $frame;
        }
    }


    public function menuTicket()
    {
        $this->_outPage = 'ticket';

        if (isset($this->_paramsInput['ticketid'])) {
            $idTicket = $this->_paramsInput['ticketid'];
        } else {
            $idTicket = '';
        }

        $uid = $this->_attributesOut['user']['uid'];
        if (isset($this->_paramsInput['new_ticket_text'])) {
            $textTicket = $this->_paramsInput['new_ticket_text'];
        } else {
            $textTicket = '';
        }
        if (isset($this->_paramsInput['add_ticket_text'])) {
            $addTextTicket = $this->_paramsInput['add_ticket_text'];
        } else {
            $addTextTicket = '';
        }

        # Создание нового тикета
        if (isset($this->_paramsInput['new_ticket_text'])) {
            if ($this->_paramsInput['new_ticket_text'] <> '') {
                $idTicket = $this->newTicket($uid, $textTicket);
                // Защита от дубликатов POST
                header("Location: main.php?action=ticket&ticketid=".$idTicket);
                die();
            } else {
                $this->_outPage = 'index';
            }
        }

        # Новое сообщение в тикете
        if (isset($this->_paramsInput['add_ticket_text']) AND $addTextTicket <> '' AND $idTicket <> '') {
            $this->addTicket($uid, $idTicket, $addTextTicket);
            // Защита от дубликатов POST
            header("Location: main.php?action=ticket&ticketid=".$idTicket);
            die();
        }

        # Старый вариант получения диалога (статический)
        $ticketChatBody = $this->getMessagesTicket($idTicket);

        // Статус тикета
        $ticketStatus = $this->getInfoTicket($idTicket);

        # Получить дилалог тикета в формате JSON (динамический)
        if (isset($this->_paramsInput['json'])) {
            die($this->json($ticketChatBody));
        }

        $this->_attributesOut['ticket'] = Array(
            'ticket_chat_body' => $ticketChatBody,
            'ticket_id'        => $idTicket,
            'ticket_status'    => $ticketStatus
        );
    }

    public function json($response = array())
    {
        header('Content-Type: application/json');

        return json_encode(array($response));
    }

    public function menuTicketAll()
    {
        $this->_outPage = 'ticketall';
        $result = '';
        $status = '';
        $ticketListArray = $this->getTicketList();

        foreach ($ticketListArray as $key) {

            if (isset($key['cause'])) {
                if (strlen($key['cause']) > 50) {
                    $subject = mb_substr($key['cause'], 0, 51, 'UTF-8') . '...';
                } else {
                    $subject = $key['cause'];
                }
            } else {
                $subject = '';
            }

            if ($key['statustypeid'] == 1) {
                $status = '<span class="label label-success">' . T_('Открыто') . '</span>';
            }

            if ($key['statustypeid'] == 2) {
                $status = '<span class="label label-danger">' . T_('Закрыто') . '</span>';
            }

            if ($key['statustypeid'] == 4) {
                $status = '<span class="label label-info">' . T_('Выполнено') . '</span>';
            }

            if ($key['statustypeid'] == 3) {
                $status = '<span class="label label-warning">' . T_('В работе') . '</span>';
            }

            $result .= '
				<tr>
					<td><a href="main.php?action=ticket&ticketid=' . $key['ticketid'] . '">' . $key['ticketid'] . '</a></td>
					<td><a href="main.php?action=ticket&ticketid=' . $key['ticketid'] . '">' . $subject . '</a></td>
					<td>' . $key['creationdate'] . '</td>
					<td>' . $status . '</td>
				</tr>';
        }

        $this->_attributesOut['ticketAll'] = Array(
            'ticket_all' => $result
        );
    }

    public function multisortArray($array, $index)
    {
        $result = Array();
        $i = 0;

        if ($array != $result) {
            while ($el_arr = $array[$i]['@attributes'][$index]) {
                $new_arr[] = $el_arr;
                $i++;
                if (!isset($array[$i])) {
                    break;
                }
            }

            asort($new_arr);
            $keys = array_keys($new_arr);
            for ($key = 0; $key < count($keys); $key++)
                $result[] = $array[$keys[$key]];
        }

        return $result;
    }
}
