{include file="./index_top.tpl"}
<style>
    div .sp-replacer {
        height: 20px;
        margin-top: -4px;
        box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
        border-radius: 3px;
    }
    div .sp-replacer .sp-preview {
        height: 16px;
    }
</style>
<script type="text/javascript">
    // значения для системной подсказки
    var help_section = 'Settings';
    var help_sub_section = 'Reports';
    var view_multitable = {$multitable};

    function checkPeriod() {
        let period = document.getElementById('period_val');
        let chunks = period.value.split(' ');
        let value_for_input = '';
        if(chunks.length > 5 || chunks.length < 5){
            period.style.backgroundColor = '#faa7a7';
            document.querySelector('#period_val').form.elements.save[1].setAttribute("disabled", "true");
        }
        else {
            let conformity = 0;
            for(let [i, value] of chunks.entries()){
                if(i == 0){
                    if(checkCronVar(value, 0, 59, 2)){
                        conformity++;
                    }
                }
                else if(i == 1){
                    if(checkCronVar(value, 0, 23, 2)){
                        conformity++;
                    }
                }
                else if(i == 2){
                    if(checkCronVar(value, 1, 31, 2)){
                        conformity++;
                    }
                }
                else if(i == 3){
                    let months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                    for(const [index, month] of months.entries()){
                        value = value.replace(new RegExp(month, 'g'), index + 1);
                    }
                    if(checkCronVar(value, 1, 12, 2)){
                        conformity++;
                    }
                }
                else {
                    let days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
                    for(const [index, day] of days.entries()){
                        value = value.replace(new RegExp(day, 'g'), index + 1);
                    }
                    if(checkCronVar(value, 1, 7, 1)){
                        conformity++;
                    }
                }
                value_for_input += i == chunks.length - 1 ? value : value + ' ';
            }
            if(conformity < 5){
                console.log('No');
                period.style.backgroundColor = '#faa7a7';
                document.querySelector('#period_val').form.elements.save[1].setAttribute("disabled", "true");
            }
            else {
                console.log('Yes');
                period.value = value_for_input;
            }
        }
    }

    function change_interval(select_obj) {
        var val = select_obj.options[select_obj.selectedIndex].value;
        if (val == "advanced") {
            document.getElementById('link_cron_task').style.display = "inline";
            document.getElementById('period_advanced').style.display = "block";
        }
        else {
            document.getElementById('link_cron_task').style.display = "none";
            document.getElementById('period_advanced').style.display = "none";
        }
        var r_obj = document.getElementById('period_val');
        if (val == "every_minute")        r_obj.value = "* * * * *";
        if (val == "every_5_minute")      r_obj.value = "1-59/5 * * * *";
        if (val == "every_15_minute")     r_obj.value = "1,15,30,45 * * * *";
        if (val == "every_hour")          r_obj.value = "1 * * * *";
        if (val == "every_day_3_oclock")  r_obj.value = "1 3 * * *";
        if (val == "every_day_9_oclock")  r_obj.value = "1 9 * * *";
        if (val == "every_day_12_oclock") r_obj.value = "1 12 * * *";
        if (val == "every_day_18_oclock")  r_obj.value = "1 18 * * *";
        if (val == "every_day_23_oclock") r_obj.value = "1 23 * * *";
    }

    async function check_form() {
        if (!document.getElementById('period_val').value.replace(/ /g, '') || !document.getElementById('name').value.replace(/ /g, '') || !document.getElementById('code').value.replace(/ /g, '') || !document.getElementById('form').value.replace(/ /g, '') ||
                (document.getElementById('edit_emails_and_cron_job').style.display != 'none' && !document.getElementById('emails').value.replace(/ /g, ''))) {
            jalert('{$lang.alert_not_all_report_data}');
            return false;
        }

        {if $user.group_id == 1 || $current_access_level}
        if ($('#report_mode_constructor').is(':visible')) {
            $('#form').val(ReportConstructor.val())
            $('#code').val('yaml')
        }
        {/if}

        {literal}
        if($('#ext_access_fixed_checkbox').is(':checked') && $('#alias_link-value').val().trim().length == 0){
            $('#alias_link-value').css('border-color', '#fd3b34');
            $('#alias_error').html(lang['Enter_short_id']);
            setTimeout(() => {
                $('#alias_link-value').css('border-color', '');
                $('#alias_error').html('');
            }, 3000);
            return false;
        }
        if($('#ext_access_fixed_checkbox').is(':checked')){
            let report_id = (new URLSearchParams(window.location.search)).get('report');
            let check_res = await fetch('edit_report.php?report='+report_id+'&check_alias='+$('#alias_link-value').val());
            check_res = await check_res.json();
            if(!check_res['success']){
                $('#alias_link-value').css('border-color', '#fd3b34');
                $('#alias_error').html(lang['Used_link_into_report'] + `<a href='edit_report.php?report=${check_res['report_id']}' target='_blank'>${check_res['report_name']}</a>`)
                setTimeout(() => {
                    $('#alias_link-value').css('border-color', '');
                    $('#alias_error').html('');
                }, 3000);
                return false;
            }
        }

        document.getElementById('edit_form').submit();
        {/literal}
    }
    function showModeConstructor() {
        $('#report_mode_constructor').show();
        if (ReportConstructor.mode()=='edit') $('#report_mode_editor').show();
        $('#report_mode_expert').hide();
        return true;
    }
    function showModeExpert() {
        $('#report_mode_constructor').hide();
        $('#report_mode_editor').hide();
        $('#report_mode_expert').show();
        return true;
    }
</script>
<div align=center><br>{if $no_save_mode}<img src="images/lock.svg" style="width:20px; padding-right:5px;" title="{$lang.Element_no_edit_msg}">{/if}{if $report_id eq -1}{$lang.create_report}{else}{$lang.edit_report} "{$report.name}"{/if}<br><br>
</div>
<form action="edit_report.php?cat={$cat_id}&report={$report_id}" method="post" id="edit_form" onsubmit="check_form(); return false">
    <table align="center" border=0 cellpadding=3 cellspacing=0>
        {if $error}
            <tr>
                <td align=center colspan=2 style="color:red;padding-bottom:15px">{$error}</td>
            </tr>
        {/if}
        {if $message}
            <tr>
                <td colspan=2 align=center>
                    <span id="edit_config__info-maessage" style="color:green">{$message}</span><br><br>
                </td>
            </tr>
        {/if}
        {if $save_complite}
            <tr>
                <td colspan=2 align=center><span style="color:green">{$lang.succes_settings_save}</span><br><br>
                </td>
            </tr>
        {/if}
        {if !$blocked}
        {if $sel_cat}
            <tr>
                <td align=right>{$lang.Category}<span class='help_bt' h_id='Category'></span>:</td>
                <td><select class="form-control form-control-250" name="cat_id">{$sel_cat}</select></td>
            </tr>
        {/if}
        <tr>
            <td align=right>{$lang.Name}<span class='help_bt' h_id='Name'></span>:</td>
            <td><input class="form-control form-control-250" type=text name="report_name" id="name" value="{$report.name|escape}" size=50></td>
        </tr>
        {if $user.group_id == 1 || $current_access_level}
            <tr id="calc_code">
                <td align=right>{$lang.Mode}<span class='help_bt' h_id='Mode'></span>:</td>
                <td>
                    <div class="flex-box">
                        <label class="radio-inline flex-box flex-direction--column flex-wrap--center" {if $report_id < 0}onclick="showExtSettings(); return showModeConstructor()"{/if}>
                            <input id="construct_mode" type="radio" {if ($report_id > 0)}disabled style="color: #999;"{/if} name="calc_mode" value=0 {if ($report.mode === 0)}checked{/if} />
                            <span {if $report_id > 0}style="color: #999;"{/if}>{$lang.construct_mode}</span>
                        </label>
                        <label class="radio-inline flex-box flex-direction--column flex-wrap--center" {if $report_id < 0 && $all_modules.pro_tariff}onclick="hideExtSettings(); return showModeExpert()"{/if}>
                            <input id="expert_mode" type="radio" {if $report_id > 0 || !$all_modules.pro_tariff}disabled style="color: #999;"{/if} name="calc_mode" value=1 {if ($report.mode === 1)}checked{/if} />
                            <span {if $report_id > 0 || !$all_modules.pro_tariff}style="color: #999;"{/if} 
                                  {if $report_id < 0 && !$all_modules.pro_tariff}title="{$lang.Pro_tariff_func_message}"{/if}>{$lang.Expert_mode}</span>
                        </label>
                    </div>
                </td>
            </tr>
        {/if}
        <tbody id="report_mode_constructor" {if ($report.mode === 1) }style="display:none"{/if}>
        </tbody>
        <tbody id="report_mode_editor" style="display:none">
            <tr>
                <td align=right>{$lang.Yaml_specification}</td>
                <td>
                    <div id="report_constructor_editor" style="border:1px solid #ccc;"></div>
                </td>
            </tr>
        </tbody>
        {if $user.group_id == 1 || $current_access_level}
            <tbody id="report_mode_expert" {if ($report.mode === 0)}style="display:none"{/if}>
                <tr>
                    <td align=right>{$lang.report_code}<span class='help_bt' h_id='report_code'></span>:</td>
                    <td>
                        {if $report_id==-1 or $report.mode === 0 or $report.code|strlen < "200"}
                            <textarea class="form-control" name="report_code" id="code" rows=10 cols=80>{$report.code}</textarea>
                        {else}
                            <a href="#"
                            onclick="open_calc('report={$report_id}&part=report_code',{$report.code|strlen});return false;">{$lang.Edit}</a>
                            <input type="hidden" name="report_code" id="code" value="dnot_save">
                        {/if}
                    </td>
                </tr>
                <tr>
                    <td align=right>{$lang.report_form}<span class='help_bt' h_id='report_form'></span>:</td>
                    <td>
                        {if $report_id==-1 or $report.mode === 0 or $report.form|strlen < "200"}
                            <textarea class="form-control" name="report_form" id="form" rows=10 cols=80>{$report.form}</textarea>
                        {else}
                            <a href="#"
                            onclick="open_calc('report={$report_id}&part=report_templ', {$report.form|strlen});return false;">{$lang.Edit}</a>
                            <input type="hidden" name="report_form" id="form" value="dnot_save">
                        {/if}
                    </td>
                </tr>
            </tbody>
        {/if}
        <tr>
            <td align=right>{$lang.Help}<span class='help_bt' h_id='Help'></span>:</td>
            <td><textarea class="form-control" name="help" rows=5 cols=80>{$report.help}</textarea></td>
        </tr>
        <tr>
            <td align=right>{$lang.Send_by_email}<span class='help_bt' h_id='Send_by_email'></span>:</td>
            <td>
                <div style="float: none; left: 5px; top: 2px;" class="switch-btn {if $report.cron_id}switch-on{/if}" onclick="if(this.classList.contains('switch-on')){ this.classList.remove('switch-on'); } else { this.classList.add('switch-on'); } document.getElementById('send_to_email').checked = !document.getElementById('send_to_email').checked; if (document.getElementById('send_to_email').checked) { document.getElementById('edit_emails_and_cron_job').style.display=''; document.getElementById('period_cron_job').style.display=''; document.getElementById('mail_template').style.display=''; } else { document.getElementById('edit_emails_and_cron_job').style.display='none'; document.getElementById('mail_template').style.display='none';  document.getElementById('period_cron_job').style.display='none'; }"><div></div></div>
                <input style="display: none;" type=checkbox name="send_to_email" id="send_to_email"
                       onclick=""
                       {if $report.cron_id}checked{/if}>
            </td>
        </tr>
        <tr id="edit_emails_and_cron_job" {if !$report.cron_id}style="display:none;"{/if}>
            <td align=right>{$lang.Address}<span class='help_bt' h_id='address_report'></span>:</td>
            <td>
                <input class="form-control form-control-250" type=text name="emails" id="emails" value="{$report.emails}" size=50 maxlenght=255>
                <a
                    id="link_cron_task"
                    href="#"
                    style="margin-left: 15px;{if $report.period neq "* * * * *" and $report.period neq "1-59/5 * * * *" and $report.period neq "1,15,30,45 * * * *" and $report.period neq "1 * * * *" and $report.period neq "1 3 * * *" and $report.period neq "1 9 * * *" and $report.period neq "1 12 * * *" and $report.period neq "1 18 * * *"  and $report.period neq "1 23 * * *"}{else}display:none{/if}"
                    onClick="document.getElementById('edit_cron_mode').value = 1; if (check_form()) document.getElementById('edit_form').submit(); return false;"
                >
                    {$lang.Edit_cron_job}
                </a>
            </td>
        </tr>
        <tr id="period_cron_job" {if !$report.cron_id}style="display:none;"{/if}>
            <td align=right>
                {$lang.Period}<span class='help_bt' h_id='Period'></span>:
            </td>
            <td>
                <select class="form-control form-control-160" onchange="change_interval(this)">
                    <option value="every_minute" {if $report.period eq "* * * * *"}selected{/if}>{$lang.Every_minute}</option>
                    <option value="every_5_minute" {if $report.period eq "1-59/5 * * * *"}selected{/if}>{$lang.Every_5_minute}</option>
                    <option value="every_15_minute" {if $report.period eq "1,15,30,45 * * * *"}selected{/if}>{$lang.Every_15_minute}</option>
                    <option value="every_hour" {if $report.period eq "1 * * * *"}selected{/if}>{$lang.Every_hour}</option>
                    <option value="every_day_3_oclock" {if $report.period eq "1 3 * * *"}selected{/if}>{$lang.Every_day_3_oclock}</option>
                    <option value="every_day_9_oclock" {if $report.period eq "1 9 * * *"}selected{/if}>{$lang.Every_day_9_oclock}</option>
                    <option value="every_day_12_oclock" {if $report.period eq "1 12 * * *"}selected{/if}>{$lang.Every_day_12_oclock}</option>
                    <option value="every_day_18_oclock" {if $report.period eq "1 18 * * *"}selected{/if}>{$lang.Every_day_18_oclock}</option>
                    <option value="every_day_23_oclock" {if $report.period eq "1 23 * * *"}selected{/if}>{$lang.Every_day_23_oclock}</option>
                    <option value="advanced" {if $report.period neq "* * * * *" and $report.period neq "1-59/5 * * * *" and $report.period neq "1,15,30,45 * * * *" and $report.period neq "1 * * * *" and $report.period neq "1 3 * * *" and $report.period neq "1 9 * * *"  and $report.period neq "1 12 * * *" and $report.period neq "1 18 * * *"  and $report.period neq "1 23 * * *"}
                        selected
                                {/if}>{$lang.Advanced}</option>
                </select>
                <div id="period_advanced"
                            {if $report.period neq "* * * * *" and $report.period neq "1-59/5 * * * *" and $report.period neq "1,15,30,45 * * * *" and $report.period neq "1 * * * *" and $report.period neq "1 3 * * *" and $report.period neq "1 9 * * *"  and $report.period neq "1 12 * * *" and $report.period neq "1 18 * * *"  and $report.period neq "1 23 * * *"}
                            {else}
                                style="display:none"
                            {/if}
                    >
                        {$lang.Enter_cron_interval}
                        <br>
                        <input class="form-control form-control-160" type=text id="period_val" name='period' value="{$report.period}" onblur="checkPeriod()" onfocus="editPeriod()">
                </div>
            </td>
        </tr>
        <tr id="mail_template" {if !$report.cron_id}style="display:none;"{/if}>
            <td align=right>{$lang.mail_template}<span class='help_bt' h_id='mail_template'></span>:</td>
            <td><select class="form-control form-control-250" name="mail_template">{$sel_template}</select></td>
        </tr>
        <tr id="ext_access_enabled" {if ($report.mode === 1) }style="display:none"{/if}>
            <td align=right>{$lang.Access_without_auth}<span class='help_bt' h_id='report_ext_access'></span>:</td>
            <td>
                <input
                    type=checkbox
                    name="report_ext_access"
                    id="report_ext_access"
                    style="display: none;"
                    {if $ext_access_enabled}checked{/if}
                >
                <div style="float: none; left: 5px; top: 2px;" class="switch-btn {if $ext_access_enabled}switch-on{/if}" onclick="if(this.classList.contains('switch-on')){ this.classList.remove('switch-on'); } else { this.classList.add('switch-on');  refreshHash();} document.getElementById('report_ext_access').checked = !document.getElementById('report_ext_access').checked; displayExtTimeSetting();"></div>
            </td>
        </tr>
        <tr id="ext_access_user" {if !$ext_access_enabled}style="display: none;"{/if}>
            <td style="vertical-align: top; padding-top: 8px;" align=right>{$lang.User}<span class='help_bt' h_id='report_ext_user'></span>:</td>
            <td>
                <select class="form-control form-control-250" id="ext_user" name="ext_user" onchange="changeTypeofTimeAccess()">
                    {$ext_access_users}
                </select>
            </td>
        </tr>
        <tr id="ext_access_time" {if !$ext_access_enabled}style="display: none;"{/if}>
            <td style="vertical-align: top; padding-top: 8px;" align=right>{$lang.Time_of_access}<span class='help_bt' h_id='report_ext_time'></span>:</td>
            <td>
                <select class="form-control form-control-250" id="ext_enabled" name="ext_enabled" onchange="changeTypeofTimeAccess()">
                    <option value="indefinitely" {if $ext_access_time_type == 'indefinitely'}selected{/if}>{$lang.Indefinitely}</option>
                    <option value="some_time"  {if $ext_access_time_type == 'some_time'}selected{/if}>{$lang.Limited_time}</option>
                </select>
                <div id="ext_access_time-time" style="margin-top: 6px; {if $ext_access_time_type == 'indefinitely'}display: none;{/if}">
                    <input
                        type="text"
                        id="ext_access_start_date"
                        name="ext_access_start_date"
                        class="form-control form-control-110 ext_access_time-input"
                        value="{$ext_access_time_start}"
                    > -
                    <input
                        type="text"
                        id="ext_access_end_date"
                        name="ext_access_end_date"
                        class="form-control form-control-110 ext_access_time-input"
                        value="{$ext_access_time_end}"
                    >
                </div>
            </td>
        </tr>
        <tr id="ext_access_link" {if !$ext_access_enabled}style="display: none;"{/if}>
            <td style="vertical-align: top; padding-top: 8px;" align=right>{$lang.External_link}<span class='help_bt' h_id='report_ext_link'></span>:</td>
            <td>
                <input
                    type="text"
                    id="ext_access_link-value"
                    class="form-control form-control-250"
                    style="width: 530px;"
                    value="{$ext_access_link}"
                    disabled
                />
                <input
                    type="hidden"
                    name="ext_access_link"
                    value="{$ext_access_link}"
                />
                <img
                    src="themes/default/images/copy_icon.png"
                    style="filter: invert(1); cursor: pointer;"
                    onclick="copyLink();"
                />
                <img
                    src="themes/clientbase/libs/ckeditor/skins/moono/images/refresh.png"
                    style="cursor: pointer;"
                    onclick="refreshHash()"
                />
            </td>
        </tr>
        <tr id="ext_report_code" {if !$ext_access_enabled}style="display: none;"{/if}>
            <td style="vertical-align: top; padding-top: 8px;" align=right>{$lang.External_report_code}<span class='help_bt' h_id='report_ext_code'></span>:</td>
            <td>
                <img
                    src="themes/default/images/copy_icon.png"
                    title="{$lang.Copy_external_report_code}"
                    style="filter: invert(1); cursor: pointer;"
                    onclick="copyExtCode();"
                />
            </td>
        </tr>
        <tr id="ext_access_fixed_link" {if !$ext_access_enabled}style="display: none;"{/if}>
            <td style="vertical-align: top; padding-top: 8px;" align=right>{$lang.Fixed_link}<span class='help_bt' h_id='report_fixed_link'></span>:</td>
            <td>
                <style>
                    #ext_access_fixed_link_content {
                        display: inline-block;
                        visibility: hidden;
                        margin-left: 13px;
                    }

                    #ext_access_fixed_checkbox:checked ~ #ext_access_fixed_link_content {
                        visibility: visible;
                    }
                </style>
                <input
                    type=checkbox
                    id="ext_access_fixed_checkbox"
                    style="display: none;"
                    {if $report['alias']|count_characters > 0}checked{/if}
                >
                <div style="float: none; left: 5px; top: 2px;" class="switch-btn {if $report['alias']|count_characters > 0}switch-on{/if}" onclick="if(this.classList.contains('switch-on')){ this.classList.remove('switch-on'); $('#alias_link-value').val(''); } else { this.classList.add('switch-on'); } document.getElementById('ext_access_fixed_checkbox').checked = !document.getElementById('ext_access_fixed_checkbox').checked;"></div>
                <div id="ext_access_fixed_link_content">
                    <span type="text" class="form-control left-chunk-input">
                    {$left_alias_link_chunk}
                    </span><input
                        type="text"
                        id="alias_link-value"
                        name="alias_link_value"
                        class="form-control form-control-250 right-chunk-input"
                        value="{$report['alias']}"
                        placeholder="{$lang['Enter_short_id']}"
                        onchange="onChangeAliasLink()"
                    />
                    <input
                        type="hidden"
                        id="left_chunk_link"
                        value="{$left_alias_link_chunk}"
                    />
                    <img
                        src="themes/default/images/copy_icon.png"
                        style="filter: invert(1); cursor: pointer;"
                        onclick="copyAliasLink();"
                    />
                </div>
                <div id="alias_error"></div>
            </td>
        </tr>

        {if $report_id != -1}
          <tr>
            <td align=right>
              {$lang.Last_run_time}<span class='help_bt' h_id='report_last_runtime'></span>:
            </td>
            <td>
              {$last_runtime} {$lang.seconds}
            </td>
          </tr>

          <tr>
            <td align=right>
              {$lang.Day_run_time}<span class='help_bt' h_id='report_day_runtime'></span>:
            </td>
            <td>
              {$day_runtime} {$lang.seconds}
            </td>
          </tr>

          <tr>
            <td allign=right name="go_to_access"></td>
            <td>
              {if $user.group_id == 1 || ($user.sub_admin_rights.access && $user.sub_admin_rights.set_rights.reports[$report_id])}
              <a href="edit_group.php?group={$user.group_id}&cat={$cat_id}&cat_item=r{$report_id}">{$lang.Go_access}</a>
              <span style="margin: 0 2px;">|</span>
              {/if}
              <a href="report.php?id={$report_id}" target="_blank">{$lang.view_report}</a>
              {if $config.protect_of_elements && $user.id == 1}
                <span style="margin: 0 2px;">|</span>
                <a href="" id="protect_switch" 
                   onclick="$('#protect_block').toggle(); this.innerHTML = this.innerHTML == '{$lang.Protect}' ? '{$lang.Hide}' : '{$lang.Protect}'; return false;">{$lang.Protect}</a>
              {/if}
            </td>
          </tr>
        {elseif $config.protect_of_elements && $user.id == 1}
          <tr>
            <td></td>
            <td>
                <a href="" id="protect_switch" 
                   onclick="$('#protect_block').toggle(); this.innerHTML = this.innerHTML == '{$lang.Protect}' ? '{$lang.Hide}' : '{$lang.Protect}'; return false;">{$lang.Protect}</a>
            </td>
          </tr>
        {/if}

        {if $config.protect_of_elements && $user.id == 1}
        <tbody id="protect_block" style="display:none">
            <tr>
                <td align="right">{$lang.Protected}<span class='help_bt' h_id='Protect_of_element'></span>:</td>
                <td>
                    <input type="checkbox" name="protected" {if $protected}checked{/if} onclick="$('[id^=pr_]').prop('disabled', !this.checked)">
                    <span class="access_param_wrapper">{$lang.View2}<span class='help_bt' h_id='protect_of_view'></span></span>
                    <span class="access_param_wrapper">{$lang.Edit3}<span class='help_bt' h_id='protect_of_edit'></span></span>
                    {if $config.access_protect_mode == 2}
                    <span class="access_param_wrapper">{$lang.Access}<span class='help_bt' h_id='protect_of_access'></span></span>
                    {/if}
                </td>
            </tr>
            <tr>
                <td align="right"></td>
                <td>
                    <div style="float: left; margin:0 34px; width: 60px; padding: 8px 0 6px 15px; text-align: center;">
                        <input type="checkbox" id="pr_view_all" {if !$protected}disabled{/if}
                               onclick="$('[id^=pr_view]').prop('checked', this.checked); if (!this.checked) $('[id^=pr_edit]').prop('checked', 0);">
                    </div>
                    <div style="float: left; margin:0 34px; width: 60px; padding: 8px 0 6px 0; text-align: center;">
                        <input type="checkbox" id="pr_edit_all" {if !$protected}disabled{/if}
                               onclick="$('[id^=pr_edit]').prop('checked', this.checked); if ( this.checked) $('[id^=pr_view]').prop('checked', 1);">
                    </div>
                    {if $config.access_protect_mode == 2}
                    <div style="float: left; margin:0 34px; width: 60px; padding: 8px 0 6px 0; text-align: center;">
                        <input type="checkbox" id="pr_acc_all" {if !$protected}disabled{/if}
                               onclick="$('[id^=pr_acc]').prop('checked', this.checked);">
                    </div>
                    {/if}
                </td>
            </tr>
            {foreach from=$protect key=gid item=acc}
                <tr>
                    <td align="right" style="padding-top: 11px;">{$acc.name}:</td>
                    <td style="display: flex; flex-wrap: nowrap;">
                        <div style="float: left; margin:0 34px; width: 60px; padding: 8px 0 6px 15px; text-align: center;">
                            <input type="checkbox" name="protect_rights[{$gid}][view]" id="pr_view{$gid}" value="1"
                                   {if $acc.view}checked{/if} {if !$protected}disabled{/if}
                                   onclick="if (!this.checked) $('#pr_edit{$gid}').prop('checked', 0)">
                        </div>
                        <div style="float: left; margin:0 34px; width: 60px; padding: 8px 0 6px 0; text-align: center;">
                            <input type="checkbox" name="protect_rights[{$gid}][edit]" id="pr_edit{$gid}" value="1"
                                   {if $acc.edit}checked{/if} {if !$protected}disabled{/if}
                                   onclick="if ( this.checked) $('#pr_view{$gid}').prop('checked', 1)">
                        </div>
                        {if $config.access_protect_mode == 2}
                        <div style="float: left; margin:0 34px; width: 60px; padding: 8px 0 6px 0; text-align: center;">
                            <input type="checkbox" name="protect_rights[{$gid}][acc]" id="pr_acc{$gid}" value="1"
                                   {if $acc.acc}checked{/if} {if !$protected}disabled{/if}>
                        </div>
                        {/if}
                    </td>
                </tr>
            {/foreach}
            <tr><td></td></tr>
            <tr>
                <td align=right>{$lang.Comment}<span class='help_bt' h_id='protect_comment'></span>:</td>
                <td><textarea class="form-control form-control-250" name="protect_comment" rows=5>{$protect_comment}</textarea></td>
            </tr>
        </tbody>
        {/if}

        <tr>
            <td colspan=2 align=center>
                <br>
                {if $user.group_id != 1 && !$user.sub_admin_rights.edit_php}
                    <input type="hidden" name="calc_mode" value="{$report.mode}">
                    {if !$current_access_level}
                      <input type="hidden" name="report_code" id="code" value="dnot_save">
                      <input type="hidden" name="report_form" id="form" value="dnot_save">
                    {/if}
                {/if}
                <input type=hidden name="edit_cron_mode" id="edit_cron_mode">
                <input type=hidden name="csrf" value="{$csrf}">
                <input type=hidden name=save value="1">
                <input class="btn btn-default btn-sm" type=submit value="{$lang.Save}"
                       {if $no_save_mode}disabled title="{$lang.Element_no_edit_msg}"{/if}>
                <br>
                <br>
                <a href="edit_tabrep.php?cat={$cat_id}">{$lang.return_to_reports_list}</a>
            </td>
        </tr>
        {else}
        <tr>
            <td colspan=2 align=center>
                <a href="edit_tabrep.php?cat={$cat_id}">{$lang.return_to_reports_list}</a>
            </td>
        </tr>
        {/if}
    </table>
</form><br>
<script type="text/javascript" src="themes/clientbase/libs/dragula.3.7.2.min.js?{$revision}"></script>
<script type="text/javascript" src="themes/clientbase/libs/mithril.min.js?{$revision}"></script>
<script type="text/javascript" src="themes/clientbase/libs/yaml.js?{$revision}"></script>
<script type="text/javascript" src="themes/clientbase/js/report-constructor.js?{$revision}"></script>
<script type="text/javascript">
    $('document').ready(() => {
        $('.ext_access_time-input').datetimepicker({
            showOn: "button",
            showAlways: true,
            dateFormat: lang.date_js_format,
            timeFormat: "HH:mm",
            buttonImage: "images/calbtn.png",
            buttonImageOnly: true,
            buttonText: "Calendar",
            showAnim: (('\v' == 'v') ? "" : "show"),  // в ie не включаем анимацию, тормозит
        }).attr('placeholder', lang.date_placeholder);
    });
    function displayExtTimeSetting(){
        if (document.getElementById('report_ext_access').checked) {
            document.getElementById('ext_access_user').style.display='';
            document.getElementById('ext_access_time').style.display='';
            document.getElementById('ext_access_link').style.display='';
            document.getElementById('ext_report_code').style.display='';
            document.getElementById('ext_access_fixed_link').style.display='';
        }
        else {
            document.getElementById('ext_access_user').style.display='none';
            document.getElementById('ext_access_time').style.display='none';
            document.getElementById('ext_access_link').style.display='none';
            document.getElementById('ext_report_code').style.display='none';
            document.getElementById('ext_access_fixed_link').style.display='none';
            document.querySelector('[name=ext_access_link]').value = '';
        }
    }
    function changeTypeofTimeAccess(){
        if(document.getElementById('ext_enabled').value == 'some_time') {
            let date = lang.date_js_format.indexOf('.') !== -1 ? moment().format('DD.MM.Y') : moment().format('DD/MM/Y');
            $('#ext_access_start_date').val(date + ' 00:00');
            $('#ext_access_end_date').val(date + ' 23:59');
            document.getElementById('ext_access_time-time').style.display='block';
        }
        else {
            document.getElementById('ext_access_time-time').style.display='none';
        }
    }
    function copyLink(){
        var $tmp = $("<textarea style='position: absolute; top: -1000;'>");
        $("body").append($tmp);
        $tmp.val($('#ext_access_link-value').val()).select();
        document.execCommand("copy");
        $tmp.remove();
        displayNotification(lang['Link_copied'], 1);
    }
    function onChangeAliasLink(){
        let value = $('#alias_link-value').val();
        value = value.replace(/[^\w\s!?]/g,'').replace(/\=/g,'').replace(/\?/g,'').replace(/\!/g,'');
        $('#alias_link-value').val(value);
    }
    function copyAliasLink(){
        var $tmp = $("<textarea style='position: absolute; top: -1000;'>");
        $("body").append($tmp);
        $tmp.val($('#left_chunk_link').val() + $('#alias_link-value').val()).select();
        document.execCommand("copy");
        $tmp.remove();
        displayNotification(lang['Link_copied'], 1);
    }
    async function refreshHash(){
        let hashLink = await fetch('edit_report.php?refresh_ext_link&report={$report_id}');
        hashLink = await hashLink.text();
        $('#ext_access_link-value').val(hashLink);
        $('#ext_access_link-value').attr('value', hashLink);
        $('[name=ext_access_link]').val(hashLink);
        $('[name=ext_access_link]').attr('value', hashLink);
        {if $report_id != -1}displayNotification(lang['Updated_link'], 1);{/if}
    }
    {literal}

    function copyExtCode(){
        var $tmp = $("<textarea style='position: absolute; top: -1000;'>");
        $("body").append($tmp);
        let val = `
            <div id="clientbase_container"><\/div>
            <script>
                var iframe = document.createElement('iframe');
                window.addEventListener('message', function (e) {
                    iframe.height = e.data;
                });
                iframe.src = '${$('#ext_access_link-value').val()}';
                iframe.scrolling = 'no';
                iframe.width = '100%';
                iframe.height = 300;
                document.getElementById('clientbase_container').appendChild(iframe);
            <\/script>
        `;
        $tmp.val(val).select();
        document.execCommand("copy");
        $tmp.remove();
        displayNotification(lang['Code_copied'], 1);
    }
    {/literal}
    function showExtSettings(){
        if($('#report_ext_access').prop('checked')){
           $('#report_ext_access').trigger('click');
        }
        $('#ext_access_link-value').val('');
        $('[name=ext_access_link]').val('');
        $('#ext_access_enabled').css('display', '');
    }
    function hideExtSettings(){
        if($('#report_ext_access').prop('checked')){
           $('#report_ext_access').trigger('click');
        }
        $('#ext_access_link-value').val('');
        $('[name=ext_access_link]').val('');
        $('#ext_access_enabled').css('display', 'none');
        $('#ext_access_user').css('display', 'none');
        $('#ext_access_time').css('display', 'none');
        $('#ext_access_link').css('display', 'none');
        $('#ext_report_code').css('display', 'none');
    }
    function deleteCollapseEntity() {
        let collapsed_items = JSON.parse($.cookie('cb_reports_collapsed') ?? '{}');

        let report_id = (new URL(window.location)).searchParams.get('report');

        if(collapsed_items[report_id]){
            delete collapsed_items[report_id];

            $.cookie('cb_reports_collapsed', JSON.stringify(collapsed_items),  { expires: 365, path: '/' });
        }
    }
    {literal}
    function getGroupValues(table_id, field_id, callback){
        if(table_id && field_id){
            fetch(`edit_report.php?get_values_of_group_field&table_id=${table_id}&field_id=${field_id}`)
            .then(res => res.json())
            .then(res => callback(res));
        }
        else {
            callback({});
        }
    }
    {/literal}

    {if $user.group_id == 1 || $current_access_level}
    var ReportConstructor = (function(params){
        var metadata = clientbaseMetaData({if ($report_id > 0 and $report.mode === 1)} { groups: [], tables:{}, fields:{}, filters:{} } {else}{$report.metadata}{/if}, {$report.show_block});
        var paper = YamlPaper($('#form').val(),metadata);
        var sight = paper.viewAsList();
        var rc_mode = 'construct';
        var codedit = CodeMirror(document.getElementById(params.editor_div_id), {
            mode:  'yaml',
            lineNumbers: false,
            autofocus: false,
        });
        function switchToConstruct() {
            rc_mode = 'construct';
            paper = YamlPaper(codedit.doc.getValue(),metadata);
            sight = paper.viewAsList();
            $('#'+params.editor_container_id).hide();
            init_chosen();
            return false;
        }
        function switchToEdit(e) {
            if (!e.ctrlKey) return false;
            rc_mode = 'edit';
            $('#'+params.editor_container_id).show();
            codedit.doc.setValue(paper.getYaml());
            return false;
        }
        if ($('select[name="mail_template"]').length > 0 &&
            $('select[name="mail_template"]').val() == '' &&
            $('select[name="mail_template"]').children().length > 1) {
                $('select[name="mail_template"]').children()[1].selected = true;
        }
        init_chosen();
        return {
            mode: function() { return rc_mode; },
            val: function() {
                return rc_mode=='edit' ? codedit.doc.getValue() : paper.getYaml();
            },
            view: function() {
                return rc_mode=='edit'
                    ? m('tr',m('td'),m('td',m('span.alaction',{ onclick:switchToConstruct },'[x]')))
                    : m(sight,{ hidden_action:switchToEdit })
            }
        }
    })({
        editor_container_id: 'report_mode_editor',
        editor_div_id: 'report_constructor_editor',
    });
    m.mount(document.getElementById('report_mode_constructor'),ReportConstructor);
    {/if}
</script>
