<?php

namespace Mnv\Admin\Controllers;

use Mnv\Core\AdminMnv;
use Mnv\Models\TelegramNotification;

/**
 * Class TelegramNotificationAdmin
 * @package Mnv\Admin\Controllers
 */
class TelegramNotificationAdmin extends AdminMnv
{

    public function fetch()
    {

        $telegram = new TelegramNotification($this->request);
        $telegram->key = $this->request->get('key');

        $this->smarty->assign('activeItem','telegrams');
        $this->smarty->assign('title', 'Настройки телеграм');

        $this->smarty->assign('statuses', array('V' => 'Включено', 'H' => 'Отключено'));

        $this->smarty->assign('logs', $telegram->logs);
        $this->smarty->assign('users', $telegram->users());
        $this->smarty->assign('callMeVars', $telegram->callMeVar());
        $this->smarty->assign('feedbackVars', $telegram->feedbackVar());
        $this->smarty->assign('questionVars', $telegram->questionVar());
        $this->smarty->assign('serviceVars', $telegram->serviceVar());
        $this->smarty->assign('quickOrderVars', $telegram->quickOrderVar());
        $this->smarty->assign('agreePurchaseVars', $telegram->quickOrderVar());
        $this->smarty->assign('orderVars', $telegram->orderVars());

        /** setWebhook */
        if  ($this->action == 'set_webhook') {

            $timeout = !empty($telegram->setting['timeout']) ? $telegram->setting['timeout'] : '5';
            $result = $telegram->set_webhook($telegram->setting['telegram_key'], $timeout);

            if (!empty($result)) {
                $params = [
                    'telegram_key'  => $telegram->setting['telegram_key'],
                    'webhook'       => $result['webhook']
                ];

                foreach ($params as $codename => $value) {
                    $telegram->update(['codename' => $codename, 'value' => $value]);
                }
            }



            response()->json($result, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)->send();
            exit;
        }
        /** clear log */
        else if ($this->action == 'clear_log') {
            $result = array();
            // Check user has permission
            if (!$this->request->has('key')) {
                $result['status'] = 400;
                $result['message'] = 'У вас нет прав для управления модулем ';
                $result['type'] = 'error';
            }

            if (!$result) {
                $key = $this->request->get('key');

                if ($key == 'telegram') {
                    $file = GLOBAL_ROOT . '/temp/log/telegram.log';
                } elseif ($key == 'viber') {
                    $file = GLOBAL_ROOT . '/temp/log/viber.log';
                } else {
                    $file = false;
                }

                if ($file) {
                    $handle = @fopen($file, 'w+');

                    fclose($handle);

                    $result['status'] = 200;
                    $result['message'] = 'Логи успешно очищены!';
                    $result['type'] = 'success';
                } else {
                    $result['status'] = 400;
                    $result['message'] = 'У вас нет прав для управления модулем';
                    $result['type'] = 'error';
                }
            }

            response()->json($result, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)->send();
            exit;
        }

        /** download log */
        else if ($this->action == 'download_log') {
            $json = array();
            $file = false;

            if (!$this->request->has('key')) {
                $json['status'] = 400;
                $json['message'] = 'У вас нет прав для управления модулем ';
                $json['type'] = 'error';
            }

            if (!$json) {
                $key = $this->request->get('key');

                if ($key == 'telegram') {
                    $file = GLOBAL_ROOT . '/temp/log/telegram.log';
                }

                if (file_exists($file) && filesize($file) > 0) {
                    $json['success'] = 'ok';

                    response()->make(file_get_contents($file, FILE_USE_INCLUDE_PATH, null), \Mnv\Http\Response::HTTP_OK, [
                        'Pragma'                 =>  'public',
                        'Expires'                =>  '0',
                        'Content-Description'    =>  'File Transfer',
                        'Content-Type'           =>  'application/octet-stream',
                        'Content-Disposition'    =>  'attachment; filename="notifications_' . $key . '_error_' . date('Y-m-d_H-i-s', time()) . '.log"',
                        'Content-Transfer-Encoding' =>  'binary',
                    ])->send();
                    exit();

                } else {
                    $json['error'] = sprintf("Внимание: Ваш  файл ошибок %s имеет размер %s!", basename($file), '0B');
                }
            }


            if (!$json) {
                $json['error'] = sprintf("Внимание: Ваш  файл ошибок %s имеет размер %s!", basename($file), '0B');
            }

            if (!isset($json['success'])) {
                response()->json($json, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)->send();
                exit();
            }
        }

        /** сохранение настроек */
        else if ($this->action == 'save') {

//            print_r($telegram->telegram_user_data);

            $telegram->setting['telegram_user_data'] = json_encode($telegram->telegram_user_data);

            if (!empty($telegram->telegram_user_groupdata)) {
                $telegram->setting['telegram_user_groupdata'] = json_encode($telegram->telegram_user_groupdata);
            } else {
                $telegram->setting['telegram_user_groupdata'] = '';
            }

            if (!empty($telegram->telegram_proxy_data)) {
                $telegram->setting['telegram_proxy_data'] = json_encode($telegram->telegram_proxy_data);
            }

            if (!empty($telegram->telegram_langdata)) {
                $telegram->setting['telegram_langdata'] = json_encode($telegram->telegram_langdata);
            }

            foreach ($telegram->setting as $codename => $value) {

                $updateSetting['codename'] = $codename;
                $updateSetting['value'] = $value;

                $telegram->update($updateSetting);
            }
        }

        else if ($this->action == 'help')
        {
            $json = array();

            // Check user has permission
            if (!isset($telegram->key)) {
                $json['error'] = 'У вас нет прав для управления модулем ';
            }

            if (!$json) {
                if (isset($telegram->key) && !empty($telegram->key)) {
                    if ($telegram->key == 'help_module') {
                        $data['tab_template'] = $telegram->modal_headers['tab_template'] ;
                        $data['tab_users'] = $telegram->modal_headers['tab_users'];
                        $data['tab_logs'] = $telegram->modal_headers['tab_logs'];
                        $webhook = array();
                        if ($this->request->has('webhook') && ($this->request->post('webhook') != 'no') && ($this->request->post('webhook') != 'potential') && (strripos($this->request->post('webhook'), 'resolve?domain=') || strripos($this->request->post('webhook'), 'info?uri='))) {
                            $webhook['webhook'] = $this->request->post('webhook');
                        }

                        $data['entry_get_token_telegram'] = 'Как получить Telegram Bot Ключ (токен)';
                        $data['entry_id_telegram'] = 'Как получить ID пользователя в Telegram';
                        $data['help_bot_telegram'] = $this->smarty->fetch('views/telegrams/help/help_bot_telegram.tpl');
                        $data['help_id_telegram'] = $this->smarty->fetch('views/telegrams/help/help_id_telegram.tpl');

                        $data['help_trim_messages'] = $this->smarty->fetch('views/telegrams/help/help_trim_messages.tpl');
                        $data['help_timeout'] = $this->smarty->fetch('views/telegrams/help/help_timeout.tpl');
                        $data['help_proxy'] = $this->smarty->fetch('views/telegrams/help/help_proxy.tpl');
                        $data['help_log'] = $this->smarty->fetch('views/telegrams/help/help_log.tpl');


                        $data['tab_general'] = 'Общие';
                        $this->smarty->assign('webhook', $webhook);
                        $json['header'] = $telegram->modal_headers[$telegram->key];
                        $json['success'] = $this->smarty->fetch('views/telegrams/help/'. $telegram->key .'.tpl');

                    } elseif ($this->request->has('webhook')) {
                        $json['header'] = $telegram->modal_headers[$telegram->key];;
                        $json['success'] = $this->request->get('webhook');

                        if (($this->request->post('webhook') != 'no') && ($this->request->post('webhook') != 'potential') && (strripos($this->request->post('webhook'), 'resolve?domain=') || strripos($this->request->post('webhook'), 'info?uri='))) {
                            $data['webhook'] = $this->request->post('webhook');
                        } else {
                            $data['webhook'] = '';
                        }

                        $this->smarty->assign('webhook', $data);
                        $json['header'] = $telegram->modal_headers[$telegram->key];;
                        $json['success'] = $this->smarty->fetch('views/telegrams/help/'. $telegram->key .'.tpl');;
                    } else {
                        $json['header'] = $telegram->modal_headers[$telegram->key];;
                        $json['success'] = $telegram->modal_headers[$telegram->key];;
                        $json['header'] = $telegram->modal_headers[$telegram->key];;
                        $json['success'] = $this->smarty->fetch('views/telegrams/help/'. $telegram->key .'.tpl');;
                    }
                } else {
                    $json['error'] = 'У вас нет прав для управления модулем';
                }
            }


            response()->json($json, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)->send();
            exit();
        }

        /**  получить обновленные настройки */
        $this->smarty->assign('logs_file', $telegram->readlogs('telegram.log'));
        $this->smarty->assign('telegram', $telegram->all());

        if ($this->permissions('telegrams')) {
            return $this->smarty->fetch('views/telegrams/index.tpl');
        }

        $this->smarty->assign('title', 'Access Denied');
        return $this->smarty->fetch('accessIsDenied.tpl');

    }


}