<form action="{$adminUrl}/telegrams" method="post" id="settings" autocomplete="off">

    {capture name="buttons"}
		<button class="btn btn-sm btn-primary" type="submit" name="action" value="save"><i class="ph-floppy-disk me-2"></i>{general:save}</button>
    {/capture}

    {capture name="breadcrumb"}
		<a href="{$adminUrl}/telegrams" class="breadcrumb-item">{$title}</a>
    {/capture}

    {capture name="showBy"}
        {*		<button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#modal_full"> Инструкция по настройке модуля </button>*}
		<button type="button" onclick="help('help_faq');" class="btn btn-sm link-danger border-danger"><i class="ph-question me-2"></i>Часто Задаваемые Вопросы</button>
    {/capture}

    {include file="components/page-header.tpl" buttons=$smarty.capture.buttons breadcrumb=$smarty.capture.breadcrumb showBy=$smarty.capture.showBy}

	<div class="content">

		<div class="card border shadow-sm">
			<div class="card-header d-flex justify-content-between m-0 p-0">
				<ul class="nav nav-tabs nav-tabs-overline nav-tabs-highlight fs-base border-top-0">

					<li class="nav-item">
						<a class="nav-link fs-sm active show" href="#general" data-bs-toggle="tab">
							<div class="d-flex align-items-center">
								<i class="ph-gear bg-primary text-primary bg-opacity-10 rounded p-1 me-2"></i>
								<span class="fw-semibold">{settings:tabs:general}</span>
							</div>
						</a>
					</li>
					<li class="nav-item">
						<a class="nav-link fs-sm" href="#users" data-bs-toggle="tab">
							<div class="d-flex align-items-center">
								<i class="ph-shield-check bg-primary text-primary bg-opacity-10 rounded p-1 me-2"></i>
								<span class="fw-semibold"> Настройки пользователей</span>
							</div>
						</a>
					</li>
					<li class="nav-item">
						<a class="nav-link fs-sm" href="#contacts" data-bs-toggle="tab">
							<div class="d-flex align-items-center">
								<i class="ph-identification-card bg-primary text-primary bg-opacity-10 rounded p-1 me-2"></i>
								<span class="fw-semibold"> Шаблоны уведомлений</span>
							</div>
						</a>
					</li>
					<li class="nav-item">
						<a class="nav-link fs-sm" href="#logs" data-bs-toggle="tab">
							<div class="d-flex align-items-center">
								<i class="ph-identification-card bg-primary text-primary bg-opacity-10 rounded p-1 me-2"></i>
								<span class="fw-semibold">Логи</span>
							</div>
						</a>
					</li>
				</ul>
			</div>

			<div class="card-body m-0 p-0">
				<div class="tab-content mb-0 p-3">
					<div class="tab-pane fade show active" id="general">
						<fieldset class="">
							<div class="row mb-3">
								<label class="col-form-label col-lg-4">{general:status}</label>
								<div class="col-lg-4">
                                    {html_options options=$statuses name="telegram[status]" id="status" selected=$telegram.status|default:'V' class="form-control select"}
								</div>
								<div class="col-lg-4">
									<button type="button" onclick="help('help_module');" class="btn link-primary border-primary"><i class="ph-check-square-offset me-2"></i>Инструкция по настройке модуля</button>
								</div>
							</div>
							<div class="row mb-3">
								<label class="col-form-label col-lg-4">Telegram Bot Ключ (токен)<a href="javascript:void(0);" onclick="help('help_bot_telegram');" class="ms-1"><i class="ph-question"></i></a></label>
								<div class="col-lg-8">
									<div class="input-group">
										<input class="form-control" type="text" name="telegram[telegram_key]" value="{$telegram.telegram_key|default:''}" id="telegram_key">
										<button class="btn btn-{if isset($telegram.webhook) && $telegram.webhook ne no}success{else}primary{/if} set_webhook" type="button" onclick="webhook('telegram');"><i class="ph-check-circle me-2"></i> Проверить</button>
									</div>
									<input type="hidden" name="telegram[webhook]" value="{if isset($telegram.webhook)}{$telegram.webhook}{else}no{/if}" />
								</div>
							</div>
							<div class="row mb-3">
								<label class="col-form-label col-lg-4">Длинное сообщение <a href="javascript:void(0);" onclick="help('help_trim_messages');" class="ms-1"><i class="ph-question"></i></a></label>
								<div class="col-lg-8">
									<div class="form-check form-check-inline mt-2">
										<input type="radio" class="form-check-input" name="telegram[trim_messages]" value="1" id="crop" {if isset($telegram.trim_messages) && $telegram.trim_messages eq 1}checked=""{/if}>
										<label class="form-check-label" for="crop">Обрезать</label>
									</div>
									<div class="form-check form-check-inline mt-2">
										<input type="radio" class="form-check-input" name="telegram[trim_messages]" value="0" id="smash" {if isset($telegram.trim_messages) && $telegram.trim_messages eq 0}checked=""{/if}>
										<label class="form-check-label" for="smash">Разбивать</label>
									</div>
								</div>
							</div>
							<div class="row mb-3">
								<label class="col-form-label col-lg-4">Таймаут соединения<a href="javascript:void(0);" onclick="help('help_timeout');" class="ms-1"><i class="ph-question"></i></a></label>
								<div class="col-lg-2">
									<input class="form-control" type="text" name="telegram[timeout]" value="{$telegram.timeout|default:5}" placeholder="5">
								</div>
							</div>
							<div class="row mb-3">
								<label class="col-form-label col-lg-4">Использовать прокси<a href="javascript:void(0);" onclick="help('help_proxy');" class="ms-1"><i class="ph-question"></i></a></label>
								<div class="col-lg-8">
									<div class="form-check form-check-inline mt-2">
										<input type="radio" class="form-check-input" name="telegram[proxy]" value="1" id="yes_proxy" {if isset($telegram.proxy) && $telegram.proxy eq 1}checked=""{/if} onclick="collapseProxy(this);">
										<label class="form-check-label" for="yes_proxy">Да</label>
									</div>
									<div class="form-check form-check-inline mt-2">
										<input type="radio" class="form-check-input" name="telegram[proxy]" value="0" id="not_proxy" {if isset($telegram.proxy) && $telegram.proxy eq 0}checked=""{/if} onclick="collapseProxy(this);">
										<label class="form-check-label" for="not_proxy">Нет</label>
									</div>
								</div>
							</div>
							<div class="row mb-3 collapse_proxy collapse {if isset($telegram.proxy) && $telegram.proxy eq 1}show{/if} ">
								<label class="col-form-label col-lg-4">Прокси (только Socks 5!)<br>
									<button type="button" class="btn btn-outline-primary my-2 add_proxy" onclick="addProxy();">Добавить прокси</button>
								</label>

								<div class="col-lg-8">
									<div class="table-responsive">
										<table class="table table_proxy" id="proxy_block">
											<thead id="header">
											<tr>
												<th width="30">Использовать</th>
												<th class="variant_name">IP-адрес</th>
												<th>Порт</th>
												<th>Логин</th>
												<th>Пароль</th>
												<th>Удалить</th>
											</tr>
											</thead>

											<tbody id="proxys" class="proxys">
                                            {assign var=count_telegram_proxydata value=0}
                                            {if isset($telegram.telegram_proxy_data)}
                                                {foreach $telegram.telegram_proxy_data as $proxy_data}
													<tr id="proxy-{$count_telegram_proxydata}">
														<td class="text-center">
															<div class="form-check mb-2">
																<input type="checkbox" class="form-check-input" name="telegram_proxy_data[{$count_telegram_proxydata}][status]" {if isset($proxy_data.status) && $proxy_data.status eq 'on'}checked{/if}>
															</div>
														</td>
														<td>
															<input type="text" name="telegram_proxy_data[{$count_telegram_proxydata}][ip]" value="{$proxy_data.ip|default:''}" placeholder="IP-адрес"  class="form-control" />
														</td>
														<td><input type="text" name="telegram_proxy_data[{$count_telegram_proxydata}][port]" value="{$proxy_data.port|default:''}" placeholder="Порт"  class="form-control" /></td>
														<td><input type="text" name="telegram_proxy_data[{$count_telegram_proxydata}][login]" value="{$proxy_data.login|default:''}" placeholder="Логин"  class="form-control" /></td>
														<td><input type="text" name="telegram_proxy_data[{$count_telegram_proxydata}][password]" value="{$proxy_data.password|default:''}" placeholder="Пароль"  class="form-control" /></td>
														<td class="text-center">
															<button type="button" class="btn btn-link text-danger del_proxy" onclick="confirm('Данное действие необратимо. Вы уверены?') ? $('#proxy-{$count_telegram_proxydata}').remove() : false;"><i class="ph-trash"></i></button>
														</td>
													</tr>

                                                    {assign var=count_telegram_proxydata value=$count_telegram_proxydata+1}
                                                {/foreach}
                                            {/if}
											</tbody>

										</table>
									</div>
								</div>
							</div>

						</fieldset>
					</div>

					<div class="tab-pane fade" id="users">
						<div class="mb-3">
							<div class="table-responsive">
								<table class="table table_users" id="users_block">
									<thead id="header">
									<tr>
										<th class="text-start" width="40%">Администратор</th>
										<th class="text-start">telegram ID <a href="javascript:void(0);" onclick="help_id('help_id_telegram');" class="ms-1"><i class="ph-question"></i></a></th>
										<th class="text-center">Уведомлять</th>
										<th class="text-center" width="30">Удалить</th>
									</tr>
									</thead>

									<tbody id="users" class="variants sortable-table">
                                    {assign var=groupdata_row value=0}
                                    {foreach from=$users item=user key=key}
										<tr id="user-{$key}">
											<td>{$user.loginName}</td>
											<td>
												<input type="text" name="telegram_user_data[{$key}][id_telegram]" value="{$telegram.telegram_user_data[$user.userId].id_telegram|default:''}" placeholder="telegram ID"  class="form-control" />
											</td>
											<td>
												<div class="d-flex align-items-center justify-content-center">
													<div class="form-check">
														<input type="checkbox" class="form-check-input" name="telegram_user_data[{$key}][checked]" {if isset($telegram.telegram_user_data[$user.userId].checked)}checked{/if}>
													</div>
												</div>
											</td>
											<td class="text-center"></td>
										</tr>
                                    {/foreach}

                                    {if !empty($telegram.telegram_user_groupdata)}

                                        {foreach from=$telegram.telegram_user_groupdata item=user key=key}
											<tr id="group-{$key}">
												<td><input type="text" name="telegram_user_groupdata[{$key}][name]" value="{$user.name}" placeholder="telegram ID"  class="form-control" /></td>
												<td><input type="text" name="telegram_user_groupdata[{$key}][id_telegram]" value="{$telegram.telegram_user_groupdata[{$key}].id_telegram|default:''}" placeholder="telegram ID"  class="form-control" /></td>
												<td>
													<div class="d-flex align-items-center justify-content-center">
														<div class="form-check">
															<input type="checkbox" class="form-check-input" name="telegram_user_groupdata[{$key}][checked]" {if isset($telegram.telegram_user_groupdata[{$key}].checked)}checked{/if}>
														</div>
													</div>
												</td>
												<td class="text-center"><button type="button" class="btn btn-link text-danger del_proxy" onclick="confirm('Данное действие необратимо. Вы уверены?') ? $('#group-{$key}').remove() : false;"><i class="ph-trash"></i></button></td>
											</tr>
                                            {assign var=groupdata_row value=$groupdata_row+1}
                                        {/foreach}
                                    {/if}

									</tbody>
									<tfoot>

									</tfoot>
								</table>
								<hr>
								<div class="text-start mt-2">
									<button type="button" class="btn btn-outline-primary add_user" onclick="addUser();">Добавить пользователя</button>
								</div>
							</div>


						</div>
					</div>

					<div class="tab-pane fade" id="contacts">
						<fieldset  class="mb-4">
							<legend class="fs-base fw-bold border-bottom pb-2 mb-3">Обратный звонок</legend>
							<div class="row mb-3">

								<div class="col-lg-7">
									<textarea rows="6" cols="3" class="form-control" name="telegram_langdata[call_me_telegram]" placeholder="{literal}#Обратный звонок {subject} от пользователя {name}, телефон {phone}.{/literal}">{$telegram.telegram_langdata.call_me_telegram|default:""}</textarea>
								</div>
								<div class="col-lg-5">
									<button type="button" class="btn btn-primary collapsed mb-2" data-bs-toggle="collapse" data-bs-target="#callMeVars" aria-expanded="false">Список поддерживаемых переменных</button>
									<div class="collapse collapse" id="callMeVars">
										<div class="table-responsive">
											<table class="table table-bordered table-striped">
												<tbody>
                                                {foreach from=$callMeVars item=var key=list}
													<tr>
														<td>{$var}</td>
														<td>{$list}</td>
													</tr>
                                                {/foreach}
												</tbody>
											</table>
										</div>
									</div>
								</div>
							</div>

							<legend class="fs-base fw-bold border-bottom pb-2 mb-3">Новое сообщение</legend>
							<div class="row mb-3">
								<div class="col-lg-7">
									<textarea rows="6" cols="3" class="form-control" name="telegram_langdata[feedback_telegram]" placeholder="{literal}Вы получили новый сообщение {subject} от пользователя {name}, телефон {phone}, email {email}. Сообщение: {message}{/literal}">{$telegram.telegram_langdata.feedback_telegram|default:""}</textarea>
								</div>
								<div class="col-lg-5">
									<button type="button" class="btn btn-primary collapsed mb-2" data-bs-toggle="collapse" data-bs-target="#feedbackVars" aria-expanded="false">Список поддерживаемых переменных</button>
									<div class="collapse collapse" id="feedbackVars">
										<div class="table-responsive">
											<table class="table table-bordered table-striped">
												<tbody>
                                                {foreach from=$feedbackVars item=var key=list}
													<tr>
														<td>{$var}</td>
														<td>{$list}</td>
													</tr>
                                                {/foreach}
												</tbody>
											</table>
										</div>
									</div>
								</div>
							</div>

							<legend class="fs-base fw-bold border-bottom pb-2 mb-3">Заявка на курс</legend>
							<div class="row mb-3">
								<div class="col-lg-7">
									<textarea rows="6" cols="3" class="form-control" name="telegram_langdata[service_telegram]" placeholder="{literal}Вы получили новый сообщение {subject} от пользователя {name}, телефон {phone}, email {email}. Сообщение: {message}{/literal}">{$telegram.telegram_langdata.service_telegram|default:""}</textarea>
								</div>
								<div class="col-lg-5">
									<button type="button" class="btn btn-primary collapsed mb-2" data-bs-toggle="collapse" data-bs-target="#serviceVars" aria-expanded="false">Список поддерживаемых переменных</button>
									<div class="collapse collapse" id="serviceVars">
										<div class="table-responsive">
											<table class="table table-bordered table-striped">
												<tbody>
                                                {foreach from=$serviceVars item=var key=list}
													<tr>
														<td>{$var}</td>
														<td>{$list}</td>
													</tr>
                                                {/foreach}
												</tbody>
											</table>
										</div>
									</div>
								</div>
							</div>

						</fieldset>
					</div>

					<div class="tab-pane fade" id="logs">
						<fieldset class="">
							<div class="mb-3">
								<p class="fw-semibold">Уровни логирования:</p>
								<ol class="fs-sm">
									<li>Выключены - логи не пишутся<span class="text-success"> - рекомендуемый режим!</span></li>
									<li>Только ошибки - в логи пишутся только ошибки соединения (ошибки cURL или ответ с ошибкой от сервера месседжера)</li>
									<li>Полные - в логи пишутся все запросы: успешные и ошибочные, также пишется тест уведомлений.<span class="text-danger"> Не рекомендуется использовать, только в режиме отладки!</span></li>
								</ol>
							</div>
							<div class="row mb-3">
								<label class="col-form-label col-lg-2">{general:status} <a href="javascript:void(0);" onclick="help('help_log');" class="ms-1"><i class="ph-question"></i></a></label>
								<div class="col-lg-6">
									<div class="input-group">
                                        {html_options options=$logs name="telegram[logs]" id="logs" selected=$telegram.logs|default:'0' class="form-control select"}
									</div>
								</div>
								<div class="col-lg-4">
									<div class="input-group">
										<button class="btn btn-danger" type="button" onclick="clearLog('telegram');"><i class="ph-download me-2"></i> Удалить</button>
										<button class="btn btn-primary" type="button" onclick="downloadLog('telegram');"><i class="ph-download me-2"></i> Скачать</button>
									</div>
								</div>
							</div>
							<div class="mb-3">
								<textarea id="log_telegram" rows="6" cols="3" class="form-control form-control-sm" disabled>{$logs_file nofilter}</textarea>
							</div>
						</fieldset>
					</div>

				</div>
			</div>
		</div>


		<div class="col-md-12 main main_buttons text-center">
            {$smarty.capture.buttons nofilter}
		</div>

	</div>

</form>

{* подгрузка документации *}
<div id="ModalBox" class="modal fade">
	<div class="modal-dialog modal-full">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title"></h5>
				<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
			</div>
			<div class="modal-body"></div>
			<div class="modal-footer">
				<button type="button" class="btn btn-link" data-bs-dismiss="modal">Закрыть</button>
			</div>
		</div>
	</div>
</div>
{* /подгрузка документации *}

<script>
    $(document).ready(function() {
        {if isset($errors.htaccess)} new Noty({ text: '{settings:errors:0}', type: 'error' }).show(); {/if}
        {if isset($errors.serializations)} new Noty({ text: '{settings:errors:1}', type: 'error' }).show(); {/if}
        {if isset($messages.saved)} new Noty({ text: '{settings:messages:0}', type: 'success' }).show(); {/if}

    });

    function collapseProxy(element) {
        const collapse_proxy = document.querySelector('.collapse_proxy');
        const currentProxy = element.value;
        if (currentProxy == 1) {
            collapse_proxy.classList.add('show');
        } else {
            collapse_proxy.classList.remove('show');
        }
    }

    var proxy_row = {$count_telegram_proxydata};

    function addProxy() {
        html = '    <tr id="proxy-' + proxy_row + '">';
        html += '       <td class="text-center"><div class="form-check mb-2"><input type="checkbox" class="form-check-input" name="telegram_proxy_data[' + proxy_row + '][status]"></div></td>';
        html += '       <td><input type="text" name="telegram_proxy_data[' + proxy_row + '][ip]" value="" placeholder="IP-адрес"  class="form-control" /></td>';
        html += '       <td><input type="text" name="telegram_proxy_data[' + proxy_row + '][port]" value="" placeholder="Порт"  class="form-control" /></td>';
        html += '       <td><input type="text" name="telegram_proxy_data[' + proxy_row + '][login]" value="" placeholder="Логин"  class="form-control" /></td>';
        html += '       <td><input type="text" name="telegram_proxy_data[' + proxy_row + '][password]" value="" placeholder="Пароль"  class="form-control" /></td>';
        html += '       <td class="text-center"><button type="button" class="btn btn-link text-danger del_proxy" onclick="confirm(\'Данное действие необратимо. Вы уверены?\') ? $(\'#proxy-' + proxy_row + '\').remove() : false;"><i class="ph-trash"></i></button></td>';
        html += '   </tr>';

        $('.table_proxy tbody').append(html);
        proxy_row++;
    }

    var group_row = {$groupdata_row};

    function addUser() {
        html = '    <tr id="group-' + group_row + '">';
        html += '       <td><input type="text" name="telegram_user_groupdata[' + group_row + '][name]" value="" placeholder="Имя получателя"  class="form-control" /></td>';
        html += '       <td><input type="text" name="telegram_user_groupdata[' + group_row + '][id_telegram]" value="" placeholder="telegram ID"  class="form-control" /></td>';
        html += '       <td class="text-center"><div class="d-flex align-items-center justify-content-center"><div class="form-check mb-2"><input type="checkbox" class="form-check-input" name="telegram_user_data[' + group_row + '][checked]"></div></div></td>';
        html += '       <td class="text-center"><button type="button" class="btn btn-link text-danger del_proxy" onclick="confirm(\'Данное действие необратимо. Вы уверены?\') ? $(\'#group-' + group_row + '\').remove() : false;"><i class="ph-trash"></i></button></td>';
        html += '   </tr>';

        $('.table_users tbody').append(html);
        group_row++;
    }

    function webhook(key) {

        var bot_key = $('#' + key + '_key').val(), proxy = $("input[name='telegram[proxy]']:checked").val(),
            timeout = $('input[name="telegram[timeout]"]').val(), proxydata = '';

        if (proxy == '1') {
            for (var i=0; i< proxy_row; i++) {
                if (($('input[name="telegram_proxy_data[' + i + '][status]"]').is(':checked')) && ($('input[name="telegram_proxy_data[' + i + '][ip]"]').val() !== '') && ($('input[name="telegram_proxy_data[' + i + '][port]"]').val() !== '')) {
                    proxydata += $('input[name="telegram_proxy_data[' + i + '][ip]"]').val() + ':' + $('input[name="telegram_proxy_data[' + i + '][port]"]').val();

                    if (($('input[name="telegram_proxy_data[' + i + '][login]"]').val() !== '') || ($('input[name="telegram_proxy_data[' + i + '][password]"]').val() !== '')) {
                        proxydata += '@' + $('input[name="telegram_proxy_data[' + i + '][login]"]').val() + ':' + $('input[name="telegram_proxy_data[' + i + '][password]"]').val();
                    }

                    proxydata += ';';
                }
            }
        }

        $.ajax({
            url: '{$adminUrl}/telegrams?action=set_webhook',
            type: 'post',
            dataType: 'json',
            data: { "telegram[key]": key, "telegram[telegram_key]": bot_key, "telegram[timeout]": timeout, "telegram[proxy]": proxy, "telegram[proxydata]": proxydata },
            success: function(response) {

                new Noty({ text: response.message, type: response.type }).show();

                if (response.webhook) {
                    $('input[name="telegram[webhook]"]').val(response.webhook);
                    if (response.webhook == 'no') {
                        $('.set_webhook').removeClass('btn-success').addClass('btn-primary')
                    } else {
                        $('.set_webhook').removeClass('btn-primary').addClass('btn-success')
                    }
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                // new Noty({ text: xhr.statusText, type: 'error' }).show();
                console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                // alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    }


    function help(key) {
        $("#ModalBox").modal('show');
        $.ajax({
            url: '{$adminUrl}/telegrams?action=help&key=' + key,
            type: 'post',
            dataType: 'json',
            success: function(json) {
                if (json['error']) {
                    $(".modal-title").html('Error!');
                    $(".modal-body").html('<div class="h4" style="color:red;text-align:center;">' + json['error'] + '</div>');
                }

                if (json['success']) {
                    $(".modal-title").html(json['header']);
                    $(".modal-body").html(json['success']);
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                $("#ModalBox").modal('hide');
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    }

    function help_id(key) {
        $(".modal-body").html('');
        $(".modal-title").html('');
        $("#ModalBox").modal('show');
        webhook = $('input[name="telegram[webhook]"]').val();
        $.ajax({
            url: '{$adminUrl}/telegrams?action=help&key=' + key + '&webhook=' + webhook,
            type: 'post',
            dataType: 'json',
            success: function(json) {
                if (json['error']) {
                    $(".modal-title").html('Error!');
                    $(".modal-body").html('<div class="h4" style="color:red;text-align:center;">' + json['error'] + '</div>');
                }

                if (json['success']) {
                    $(".modal-title").html(json['header']);
                    $(".modal-body").html(json['success']);
                }
            }    ,
            error: function(xhr, ajaxOptions, thrownError) {
                $("#ModalBox").modal('hide');
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    }

    function clearLog(key) {
        $(".modal-body").html('');

        $.ajax({
            url: '{$adminUrl}/telegrams?action=clear_log',
            type: 'post',
            dataType: 'json',
            data: 'key=' + key,
            success: function(response) {
                new Noty({ text: response.message, type: response.type }).show();

                if (response.status == 200) {
                    $('#log_' + key).val('');

                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    }

    function downloadLog(key) {
        $(".modal-body").html('');
        $.ajax({
            url: '{$adminUrl}/telegrams?action=download_log' + '&key=' + key,
            type: 'GET',
            success: function(json) {
                if (json['error']) {
                    $("#ModalBox").modal('show');
                    $(".modal-title").html('Error!');
                    $(".modal-body").html('<div class="h4" style="color:red;text-align:center;">' + json['error'] + '</div>');
                } else {
                    $("#ModalBox").modal('hide');
                    window.location = '{$adminUrl}/telegrams?action=download_log' + '&key=' + key;
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    }

</script>