<?php

/*
 * @name        JMY CMS
 * @link        https://jmy.su/
 * @copyright   Copyright (C) 2012-2025 JMY LTD
 * @license     LICENSE.txt (see attached file)
 * @version     VERSION.txt (see attached file)
 * @author      Orlov Alexsey
 */

if (!defined('ADMIN_SWITCH')) {
    header('Location: /');
    exit;
}
global $adminTpl, $core, $db, $url, $page, $admin_conf, $includ_chart_conf, $lang;
loadConfig('includ_chart');
switch ($url[3] ?? null) {
    default:
        InitCheck();
        init_count_text();
        Scroll('statistic');
        $errors = 0;
        $where = '';
        $order = '';
        if (isset($url[3]) && $url[3] == 'order') {
            switch ($url[4]) {
                case 'id':
                    $order .= 'id ASC';
                    break;
                case 'time':
                    $order .= 'time DESC';
                    break;
                case 'clicks':
                    $order .= 'clicks DESC';
                    break;
            }
        } else {
            $order .= 'time DESC';
        }
        $adminTpl->admin_head($lang['counter_visits']);
        $query = $core->select_data('counter_ip', $where, $order . ' LIMIT ' . limit_page());
        if ($db->numRows($query) > 0) {
            echo '<div id="content" class="table-layout animated fadeIn">
   <div class="tray tray-center">';
            alert_info('includ_chart');
            echo '<div class="panel panel-dark panel-border top">
         <div class="panel-heading">';
            modal_form_delete('clear' . 'exactly', '', $lang['db_truncate'] . ' - ' . $lang['counter_visits'], 'name', $lang['db_clear_text'], '{MOD_LINK}/truncate/exactly/', $lang['base_clear'], 'clear');
            echo ' <span class="panel-title">' . $lang['schedule_visits'] . '</span> 
            <div class="widget-menu pull-right section-divider">
               <select style="width: 200px; display: inline-block;" class="form-control bootstrap-select" onchange="top.location=this.value">
               <option value="{MOD_LINK}" ' . choice_selected(4) . '>' . $lang['choose_sort'] . '</option>
               <option value="{MOD_LINK}/order/id" ' . choice_selected(4, 'id') . '>' . $lang['sort_asc'] . '</option>
               <option value="{MOD_LINK}/order/time" ' . choice_selected(4, 'time') . '>' . $lang['sort_time'] . '</option>
               <option value="{MOD_LINK}/order/clicks" ' . choice_selected(4, 'clicks') . '>' . $lang['sort_clicks'] . '</option>
               </select>
            </div>
         </div>
         <div class="heading-hr"></div>              
         <div class="panel-body pn table-responsive">
            <form id="tablesForm" style="margin:0; padding:0" method="POST" action="{MOD_LINK}/action" onclick="lihtTable(getSource(event))">
               <table class="table table-xs table-striped">
                  <thead>
                     <tr>
                        <th class="text-center col-md-7">' . $lang['url'] . '</th>
                        <th class="text-center col-md-2">' . $lang['date'] . '</th>
                        <th class="text-center">' . faSpan('fa-hand-pointer-o', true, false, false, $lang['n_clicks']) . '</th>';
            init_checkbox('th', false, false, true);
            echo '</tr>
                  </thead>
                  <tbody>';
            while ($rows = $db->getRow($query)) {
                if ($rows['time'] && !$rows['redir'] || !$rows['time'] || date('d.m.Y', $rows['time']) == '1.01.1970') {
                    $errors++;
                    $core->del_data('counter_ip', 'id ="' . $rows['id'] . '"');
                    header("Refresh:5");
                }
                if ($errors <> 0) $adminTpl->alert('info', $lang['info'], $lang['clear_counter']);
                $count = $core->sum_data('counter_ip', 'redir ="' . $rows['redir'] . '"');
                if ($count > 1) {
                    $core->upd_data('counter_ip', 'clicks = clicks + 1, time ="' . time() . '"', 'redir ="' . $rows['redir'] . '"');
                    $core->del_data('counter_ip', 'id ="' . $rows['id'] . '"');
                }
                echo '<tr>
                        <td style="width:65%;">
                           <a href="' . $rows['redir'] . '" target="_blank" data-toggle="tooltip" data-original-title="">
                              <pre><code>' . $rows['redir'] . '</code></pre>
                           </a>';
                if ($includ_chart_conf['stat_link'] == 1) init_Ajax_count('urs', 'includ_chart', false, $rows['id'], true, 'status_url');
                echo '</td>
                      <td class="text-center"> ' . formatDate($rows['time'], true) . '</td>
                      <td class="text-center"> ' . formatCounter($rows['clicks']) . '</td>';
                modal_form_delete($rows['id'], $rows['redir'], $lang['counter_delete_title'], 'redir', $lang['counter_delete_text'], '{MOD_LINK}/delete/' . $rows['id']);
                init_checkbox('td', $rows['id'], false, '<li><a href="' . $core->fullURL() . '#" onclick="modal_o(\'#modal-form-' . $rows['id'] . '\')">' . faSpan('fa-trash-o text-danger', true, $lang['delete']) . '</a></li>');
                echo '</tr>';
            }
            echo '</tbody>';
            init_tfoot(true, 'fa-trash-o', 'delete');
            echo '</table>
            </form>
         </div>
      </div>';
            page_list('urs', 'includ_chart', 'counter_ip', $where);
            echo '</div>
    <aside data-tray-height="match" class="panel tray-right tray-rescale tray290">
      <form id="statistic" role="form" method="POST" action="">';
            init_Ajax_count('urs', 'includ_chart', 'statistics', false, false, 'statistics');
            echo '</form>
   </aside>';
        } else {
            $adminTpl->info($lang['counter_empty'], 'empty', null, $lang['counter_visits']);
        }
        echo '</div>';
        $adminTpl->admin_foot();
        break;
    case 'action':
        $type = $_POST['submit'];
        if (isset($_POST['checks']) && is_array($_POST['checks'])) {
            if ($type == 'delete') {
                foreach ($_POST['checks'] as $id) {
                    $core->del_data('counter_ip', 'id ="' . $id . '"');
                }
            }
        }
        location(ADMIN . '/module/includ_chart');
        break;
    case 'delete':
        $id = isset($url[4]) ? intval($url[4]) : 0;
        if ($id) {
            delCounter($id);
            action_alert('urs', 'success', 'includ_chart');
        } else {
            action_alert('urs', 'danger', 'includ_chart', false, 'unknown_error');
        }
        break;
    case 'truncate':
        $id = $url[4] ?? 0;
        if ($id == 'exactly') {
            if ($core->sum_data('counter_stat') > 0) $core->truncate_data('counter_stat');
            if ($core->sum_data('counter_ip') > 0) $core->truncate_data('counter_ip');
            action_alert('urs', 'success', 'includ_chart', false, str_replace(array('[name]'), array($id), $lang['db_clear_ok']), true);
        } else {
            action_alert('urs', 'danger', 'includ_chart', false, 'unknown_error');
        }
        break;
    case 'schedule':
        init_count_text();
        $query = $core->select_data('counter_stat');
        $id = false;
        $timesd = '';
        $resultat = '';
        $del_time = '';
        $adminTpl->admin_head($lang['counter_visits']);
        if ($db->numRows($query) > 0) {
            $url_link = $url[4] ?? null;
            $current_month = date('m');
            $current_year = date('Y');
            while ($times = $db->getRow($query)) {
                $timesd = $times['date'];
                $del_time = $times['del_date'];
                $id = $times['id'];
            }
            if ($url_link == 'all') {//Все:
                $where = "";
            } elseif ($url_link == 'today') {//За сегодня:
                $where = "WHERE date ='" . date('d.m.Y') . "'";
            } elseif ($url_link == 'yesterday') {//За вчера:
                $where = "WHERE date BETWEEN '" . date('d.m.Y', strtotime("-1 day")) . "' AND '" . date('d.m.Y') . "'";
            } elseif ($url_link == 'week') {//За неделю:
                $where = "WHERE date BETWEEN '" . date('d.m.Y', strtotime("-7 day")) . "' AND '" . date('d.m.Y') . "'";
            } elseif ($url_link == 'month') {//За месяц:
                $where = "WHERE date BETWEEN '" . date('d.m.Y', strtotime("-30 day")) . "' AND '" . date('d.m.Y') . "'";
            } elseif ($url_link == 'quarter1' && $current_month >= 1 && $current_month <= 3) {//За I квартал:
                $where = "WHERE date BETWEEN '" . date('d.m.Y', strtotime('1-January-' . $current_year)) . "' AND '" . date('d.m.Y', strtotime('1-April-' . $current_year)) . "'";
            } elseif ($url_link == 'quarter2' && $current_month >= 4 && $current_month <= 6) {//За II квартал:
                $where = "WHERE date BETWEEN '" . date('d.m.Y', strtotime('1-April-' . $current_year)) . "' AND '" . date('d.m.Y', strtotime('1-July-' . $current_year)) . "'";
            } elseif ($url_link == 'quarter3' && $current_month >= 7 && $current_month <= 9) {//За III квартал:
                $where = "WHERE date BETWEEN '" . date('d.m.Y', strtotime('1-July-' . $current_year)) . "' AND '" . date('d.m.Y', strtotime('1-October-' . $current_year)) . "'";
            } elseif ($url_link == 'quarter4' && $current_month >= 10 && $current_month <= 12) {//За IV квартал:
                $where = "WHERE date BETWEEN '" . date('d.m.Y', strtotime('1-October-' . $current_year)) . "' AND '" . date('d.m.Y', strtotime('1-January-' . ($current_year + 1))) . "'";
            } elseif ($url_link == 'year') {//За год:
                $where = "WHERE date BETWEEN '" . date('d.m.Y', strtotime('1-January-' . $current_year)) . "' AND '" . date('d.m.Y', strtotime('1-January-' . ($current_year + 1))) . "'";
            } else {
                $where = "";
            }
            $get_info_stats = $core->select_data('counter_stat', $where, 'date DESC');
            if ($db->numRows($get_info_stats) > 0) {
                $array_day = "";
                $array_views = "";
                $array_people = "";
                $array_all = array();
                $array_date = array();
                $final_array = array();
                $errors = 0;
                if (date('d.m.Y') == $del_time) {
                    $core->del_data('counter_stat', 'del_date ="' . $del_time . '"');
                } elseif (!$core->sum_data('counter_stat')) {
                    $core->del_data('counter_ip', 'id ="' . $id . '"');
                }
                echo '<div id="content" class="table-layout animated fadeIn">
   <div class="tray tray-center">';
                alert_info('includ_chart');
                echo '<div class="panel panel-yellow panel-border top">
         <div class="panel-heading">
            <span class="panel-title">' . $lang['schedule_visits'] . '</span>
         </div>
         <div class="heading-hr"></div>
         <div class="panel-body pn table-responsive">
      <div class="widget-menu pull-left mr5 text-center" style="margin: 8px;width: 100%;height: 100%;top: 0;left: 0;z-index: 2;">';
                $resultat .= $timesd > 0 ? but_link('/module/includ_chart/schedule/all', $lang['all1']) : '';
                $resultat .= $timesd == date('d.m.Y') ? but_link('/module/includ_chart/schedule/today', $lang['ctodays']) : '';
                $resultat .= $timesd >= date('d.m.Y', strtotime("-1 day")) ? but_link('/module/includ_chart/schedule/yesterday', $lang['cyesterday']) : '';
                $resultat .= $timesd >= date('d.m.Y', strtotime("-7 day")) ? but_link('/module/includ_chart/schedule/week', $lang['cweek']) : '';
                $resultat .= $timesd >= date('d.m.Y', strtotime("-30 day")) ? but_link('/module/includ_chart/schedule/month', $lang['cmonth']) : '';
                if ($includ_chart_conf['quarter'] == 1) {
                    $resultat .= $timesd >= date('d.m.Y', strtotime("-90 day")) ? but_link('/module/includ_chart/schedule/quarter1', $lang['cquarter1']) : '';
                    $resultat .= $timesd >= date('d.m.Y', strtotime("-181 day")) ? but_link('/module/includ_chart/schedule/quarter2', $lang['cquarter2']) : '';
                    $resultat .= $timesd >= date('d.m.Y', strtotime("-273 day")) ? but_link('/module/includ_chart/schedule/quarter3', $lang['cquarter3']) : '';
                    $resultat .= $timesd >= date('d.m.Y', strtotime("-365 day")) ? but_link('/module/includ_chart/schedule/quarter4', $lang['cquarter4']) : '';
                }
                $resultat .= $timesd >= date('d.m.Y', strtotime("-365 day")) ? but_link('/module/includ_chart/schedule/year', 'Год') : '';
                echo $resultat . '</div>
      <div class="row">
         <div class="col-lg-12">
            <div class="panel-body pn table-responsive">';
                while ($row = $db->getRow($get_info_stats)) {
                    $array_date[] = $row["date"];
                    $array_all[] = $row;
                }
                $new_array_date = array_unique($array_date);
                foreach ($new_array_date as $key_date) {
                    $i = 0;
                    $sum = 0;
                    foreach ($array_all as $key_all) {
                        if ($key_date == $key_all["date"]) {
                            $sum = $sum + $key_all["views"];
                            $i++;
                        }
                    }
                    $final_array[] = array($key_date, $i, $sum);
                }
                usort($final_array, "sort_date");
                foreach ($final_array as $rows) {
                    $name_date = $rows[0] == date('d.m.Y') ? $lang['ctodays'] : substr($rows[0], 0, -5);
                    $array_day .= "'" . $name_date . "',";
                    $array_views .= $rows[2] . ",";
                    $array_people .= $rows[1] . ",";
                }
                echo '<div id="container" style="min-width: 310px; max-width: 965px; height: 420px; margin: 0 auto"></div>';
                schedule($array_day, $array_views, $array_people);
                echo '<script src="usr/plugins/js/liteChart/liteChart.min.js"></script>
            </div>
         </div>
      </div>
   <br/>
   <div class="panel-footer-lines"></div>
</div>';
            } else {
                $adminTpl->info($lang['error_time_schedule'], 'error', null, $lang['error'], $lang['go_back'], 'javascript:history.go(-1)');
            }
        } else {
            $adminTpl->info($lang['counter_empty'], 'empty', null, $lang['counter_visits']);
        }
        $adminTpl->admin_foot();
        break;
    case 'ajax':
        global $adminTpl, $core, $url, $db;
        ajaxInit();
        $status = $url[1] == 'module';
        $module = $status ? $url[2] : $url[1];
        $type = $status ? $url[4] : $url[3];
        $count = $status ? $url[5] : $url[4];
        $id = $status ? $url[6] : $url[5];
        $u7 = $url[7] ?? '';
        $where = $status ? ' WHERE ' . $u7 : ' WHERE ' . $url[6];
        $swhere = str_replace(array('WHERE'), array(''), $where);
        switch ($type) {
            case 'date':
                $rows = $core->row_data('counter_ip', $where);
                $counter = $count == 'core' ? $core->sum_data($module, $swhere) : $rows[$count];
                echo formatDate($counter, true);
                break;
            case 'count':
                $rows = $core->row_data('counter_ip', $where);
                $counter = $count == 'core' ? $core->sum_data($module, $swhere) : $rows[$count];
                echo formatCounter($counter);
                break;
            case 'status_url':
                $url_link = $core->row_data('counter_ip', 'id ="' . $count . '"');
                echo get_url_status($url_link['redir'] ?? '', $includ_chart_conf['answer_link']);
                break;
            case 'statistics':
                $query = $core->select_data('counter_stat');
                if ($db->numRows($query) > 0) {
                    echo '<div style="padding-right: 1px !important; top: 170px; position: fixed; margin-bottom: 20px; border-width: 0;" class="form-group admin-form">
   <h4 class="text-left pl20 pt10">' . $lang['counter_visit'] . '</h4>  
   <hr class="short">
   <div class="section mb5">
      <table class="table table-sm">
            <thead>
               <tr>
                  <th class="col-md-7"><span class="pd-l-sm"></span> ' . $lang['period'] . ' </th>
                  <th class="text-center">' . faSpan('fa-eye', true, false, false, $lang['cview']) . '</th>
                  <th class="text-center">' . faSpan('fa-user-o', true, false, false, $lang['users']) . '</th>
               </tr>
            </thead>
            <tbody>
               <tr>
                  <td class="col-md-5">' . $lang['for_all_time'] . '</td>
                  <td class="text-center">' . statistics('all', 'views') . '</td>
                  <td class="text-center">' . statistics('all', 'people') . '</td>
               </tr>';
                    if ($includ_chart_conf['quarter'] == 1) {
                        echo '<tr>
                  <td class="col-md-5">' . $lang['quarter_1'] . '</td>
                  <td class="text-center">' . statistics('quarter1', 'views') . '</td>
                  <td class="text-center">' . statistics('quarter1', 'people') . '</td>
               </tr>
               <tr>
                  <td class="col-md-5">' . $lang['quarter_2'] . '</td>
                  <td class="text-center">' . statistics('quarter2', 'views') . '</td>
                  <td class="text-center">' . statistics('quarter2', 'people') . '</td>
               </tr>
               <tr>
                  <td class="col-md-5">' . $lang['quarter_3'] . '</td>
                  <td class="text-center">' . statistics('quarter3', 'views') . '</td>
                  <td class="text-center">' . statistics('quarter3', 'people') . '</td>
               </tr>
               <tr>
                  <td class="col-md-5">' . $lang['quarter_4'] . '</td>
                  <td class="text-center">' . statistics('quarter4', 'views') . '</td>
                  <td class="text-center">' . statistics('quarter4', 'people') . '</td>
               </tr>';
                    }
                    echo '<tr>
                  <td class="col-md-5">' . $lang['for_a_year'] . '</td>
                  <td class="text-center">' . statistics('year', 'views') . '</td>
                  <td class="text-center">' . statistics('year', 'people') . '</td>
               </tr>
               <tr>
                  <td class="col-md-5">' . $lang['per_month'] . '</td>
                  <td class="text-center">' . statistics('month', 'views') . '</td>
                  <td class="text-center">' . statistics('month', 'people') . '</td>
               </tr>
               <tr>
                  <td class="col-md-5">' . $lang['for_a_week'] . '</td>
                  <td class="text-center">' . statistics('week', 'views') . '</td>
                  <td class="text-center">' . statistics('week', 'people') . '</td>
               </tr>
               <tr>
                  <td class="col-md-5">' . $lang['for_yesterday'] . '</td>';
                    $yesterday_views = (int)statistics('yesterday', 'views', false) ? ((int)statistics('yesterday', 'views', false) - (int)statistics('today', 'views', false)) : (int)statistics('yesterday', 'views', false);
                    $yesterday_people = (int)statistics('yesterday', 'people', false) ? ((int)statistics('yesterday', 'people', false) - (int)statistics('today', 'people', false)) : (int)statistics('yesterday', 'people', false);
                    echo '<td class="text-center">' . $yesterday_views . '</td>
                  <td class="text-center">' . $yesterday_people . '</td>
               </tr>
               <tr>
                  <td class="col-md-5">' . $lang['for_today'] . '</td>
                  <td class="text-center">' . statistics('today', 'views') . '</td>
                  <td class="text-center">' . statistics('today', 'people') . '</td>
               </tr>
         </table>
      </div>
          <div class="btn-group pt5">
          <button type="button" onclick="modal_o(\'#modal-form-clearexactly\')"' . btn_class('danger', true, 2) . '>' . faSpan('fa-eraser', true, $lang['db_clear_data']) . '</button>
          </div>
   </div>';
                } else {
                    $adminTpl->info($lang['counter_empty'], 'empty', null, $lang['counter_visits']);
                }
                break;
        }
        break;
    case 'config':
        global $includ_chart_conf, $lang;
        init_count_text();
        loadConfig('includ_chart');
        $configBox = array(
            'includ_chart' => array(
                'varName' => 'includ_chart_conf',
                'title' => $lang['type_chart'],
                'groups' => array(
                    'main' => array(
                        'title' => $lang['config_main'],
                        'vars' => array(
                            'quarter' => array(
                                'title' => $lang['quarter_chart'],
                                'description' => $lang['quarter_chart_descr'],
                                'content' => radio("quarter", $includ_chart_conf['quarter']),
                            ),
                            'change' => array(
                                'title' => $lang['type_chart'],
                                'description' => $lang['type_chart_descr'],
                                'content' => includ_chart(),
                            ),
                            'time' => array(
                                'title' => $lang['type_time'],
                                'description' => $lang['type_time_descr'],
                                'content' => time_chart(),
                            ),
                        )
                    ),
                    's_link' => array(
                        'title' => $lang['s_link'],
                        'vars' => array(
                            'stat_link' => array(
                                'title' => $lang['stat_link_chart'],
                                'description' => $lang['stat_link_chart_descr'],
                                'content' => radio("stat_link", $includ_chart_conf['stat_link']),
                            ),
                            'answer_link' => array(
                                'title' => $lang['answer_link_chart'],
                                'description' => $lang['answer_link_chart_descr'],
                                'content' => radio("answer_link", $includ_chart_conf['answer_link']),
                            ),
                        )
                    ),
                    'seo' => array(
                        'title' => $lang['seo'],
                        'vars' => array(
                            'keywords' => array(
                                'title' => $lang['seo_keywords'],
                                'description' => $lang['seo_settings'],
                                'content' => int_cong('textarea', '{varName}', '{var}', 'keywords'),
                            ),
                            'description' => array(
                                'title' => $lang['seo_description'],
                                'description' => $lang['seo_settings'],
                                'content' => int_cong('textarea', '{varName}', '{var}', 'description'),
                            ),
                        )
                    ),
                ),
            ),
        );
        $ok = false;
        if (isset($_POST['conf_file'])) $ok = true;
        generateConfig($configBox, 'includ_chart', '{MOD_LINK}/config', $ok);
        break;
}
function includ_chart(): string
{
    global $includ_chart_conf, $lang;
    return '<select class="form-control" name="schedule">
<option value="graphics" ' . ($includ_chart_conf['schedule'] == "graphics" ? "selected" : "") . '>' . $lang['graphics'] . '</option>
<option value="ruled" ' . ($includ_chart_conf['schedule'] == "ruled" ? "selected" : "") . '>' . $lang['ruled'] . '</option>
<option value="spot" ' . ($includ_chart_conf['schedule'] == "spot" ? "selected" : "") . '>' . $lang['spot'] . '</option>
</select>';
}

function statistics($time, $st, $formatCount = true)
{
    global $db, $core, $lang;
    $query = $core->select_data('counter_stat', false, 'date DESC');
    if ($db->numRows($query) > 0) {
        $array_all = array();
        $array_date = array();
        $final_array = array();
        $resultat = "";
        $current_month = date('m');
        $current_year = date('Y');
        $not_enough_data = faSpan('fa-window-minimize', false, false, false, $lang['not_enough_data']);
        while ($row = $db->getRow($query)) {
            $array_date[] = $row["date"];
            $array_all[] = $row;
        }
        $new_array_date = array_unique($array_date);
        foreach ($new_array_date as $key_date) {
            $i = 0;
            $sum = 0;
            foreach ($array_all as $key_all) {
                if ($key_date == $key_all["date"]) {
                    $sum = $sum + $key_all["views"];
                    $i++;
                }
            }
            $final_array[] = array($key_date, $i, $sum);
        }
        usort($final_array, "sort_date");
        foreach ($final_array as $rows) {
            $rows_2 = (int)$resultat + (int)$rows[2];
            $rows_1 = (int)$resultat + (int)$rows[1];
            $resultat = '';
            $st_views = ($st == 'views' ? $rows_2 : $rows_1);
            if ($time == 'all') {
                $resultat .= ($rows[0] > 0) ? $st_views : $not_enough_data;
            } elseif ($time == 'today') {
                $resultat .= ($rows[0] == date("d.m.Y")) ? $st_views : $not_enough_data;
            } elseif ($time == 'yesterday') {
                $resultat .= ($rows[0] >= date('d.m.Y', strtotime("-1 day")) && $rows[0] <= str_date()) ? $st_views : $not_enough_data;
            } elseif ($time == 'week') {
                if ($rows[0] < str_date('-7 day') && $rows[0] <= str_date()) {
                    $resultat .= $st_views;
                } elseif ($rows[0] >= str_date('-6 day') && $rows[0] <= str_date()) {
                    $resultat .= $st_views;
                } elseif ($rows[0] >= str_date('-5 day') && $rows[0] <= str_date()) {
                    $resultat .= $st_views;
                } elseif ($rows[0] >= str_date('-4 day') && $rows[0] <= str_date()) {
                    $resultat .= $st_views;
                } elseif ($rows[0] >= str_date('-3 day') && $rows[0] <= str_date()) {
                    $resultat .= $st_views;
                } elseif ($rows[0] >= str_date('-2 day') && $rows[0] <= str_date()) {
                    $resultat .= $st_views;
                } elseif ($rows[0] >= str_date('-1 day') && $rows[0] <= str_date()) {
                    $resultat .= $st_views;
                } else {
                    $resultat .= $not_enough_data;
                }
            } elseif ($time == 'month') {
                $resultat .= substr($rows[0], 0, -8) >= 1 && substr($rows[0], 0, -8) <= 31 && $rows[0] <= str_date() ? $st_views : $not_enough_data;
            } elseif ($time == 'quarter1') {
                $resultat .= $current_month >= 1 && $current_month <= 3 && $rows[0] >= str_date('1-January-' . $current_year) && $rows[0] <= date('d.m.Y', strtotime('1-April-' . $current_year)) ? $st_views : $not_enough_data;
            } elseif ($time == 'quarter2') {
                $resultat .= $current_month >= 4 && $current_month <= 6 && $rows[0] >= str_date('1-April-' . $current_year) && $rows[0] <= date('d.m.Y', strtotime('1-July-' . $current_year)) ? $st_views : $not_enough_data;
            } elseif ($time == 'quarter3') {
                $resultat .= $current_month >= 7 && $current_month <= 9 && $rows[0] >= str_date('1-July-' . $current_year) && $rows[0] <= date('d.m.Y', strtotime('1-October-' . $current_year)) ? $st_views : $not_enough_data;
            } elseif ($time == 'quarter4') {
                $resultat .= $current_month >= 10 && $current_month <= 12 && $rows[0] >= str_date('1-October-' . $current_year) && $rows[0] <= date('d.m.Y', strtotime('1-January-' . ($current_year + 1))) ? $st_views : $not_enough_data;
            } elseif ($time == 'year') {
                $resultat .= ($rows[0] > 0 && substr($rows[0], 0, -5) >= 1.01 && substr($rows[0], 0, -5) <= 31.12 && substr($rows[0], -4, 5) == getdate(time())['year']) ? $st_views : $not_enough_data;
            } else {
                $resultat .= $not_enough_data;
            }
        }
        return $resultat ? ($formatCount ? formatCounter($resultat) : $resultat) : false;
    }
}

function str_date($quarter = false): string
{
    return $quarter ? date('d.m.Y', strtotime("'.$quarter.'")) : date('d.m.Y');
}

function sort_date($a_new, $b_new): int
{
    $a_new = strtotime($a_new[0]);
    $b_new = strtotime($b_new[0]);
    return $a_new - $b_new;
}

function time_chart(): string
{
    global $includ_chart_conf, $lang;
    return '<select class="form-control" name="time">
<option value="86400" ' . ($includ_chart_conf['time'] == "86400" ? "selected" : "") . '>1 ' . $lang['day'] . '</option>
<option value="604800" ' . ($includ_chart_conf['time'] == "604800" ? "selected" : "") . '>1 ' . $lang['cweek'] . '</option>
<option value="2678400" ' . ($includ_chart_conf['time'] == "2678400" ? "selected" : "") . '>1 ' . $lang['month'] . '</option>
<option value="31536000" ' . ($includ_chart_conf['time'] == "31536000" ? "selected" : "") . '>1 ' . $lang['year'] . '</option>
</select>';
}

function delCounter($id): void
{
    global $core, $lang;
    $counter = $core->row_data('counter_ip', 'id ="' . $id . '"');
    $core->del_data('counter_ip', 'id ="' . $id . '"');
    $core->ins_log(false, $lang['logs_delete_delcounter'], 1, false, false, $counter['redir']);
}

function schedule($array_day = false, $array_views = false, $array_people = false): false|string
{
    global $adminTpl, $includ_chart_conf, $lang;
    if ($includ_chart_conf['schedule'] == "ruled") {
        $schedule = $adminTpl->footIncludes[] = '<script type="text/javascript">
   const pollsHighCharts = function ()
   {
   const highColors = [bgWarning, bgPrimary, bgInfo, bgAlert, bgDanger, bgSuccess, bgSystem, bgDark];
   const sparkColors = {
  "primary": [bgPrimary, bgPrimaryLr, bgPrimaryDr],
   		"info": [bgInfo, bgInfoLr, bgInfoDr],
   		"warning": [bgWarning, bgWarningLr, bgWarningDr],
   		"success": [bgSuccess, bgSuccessLr, bgSuccessDr],
   		"alert": [bgAlert, bgAlertLr, bgAlertDr]
   	};
   	const pollsHighCharts = function()
   {
   const pollsHighBars = function()
   {
   const bars1 = $("#container");
   if (bars1.length)
   {
   $("#container").highcharts({
   colors: highColors,
   credits: false,
   legend: {
   enabled: false,
   y: -5,
   verticalAlign:"top",
   useHTML: true
   },
   chart: {
   spacingLeft: 30,
   type:"bar",
   marginBottom: 0,
   marginTop: 0
   },
   title: {
   text: null
   },
   xAxis: {
   showEmpty: false,
   tickLength: 80,
   lineColor:"#fff",
   tickColor:"#eee",
   offset: 1,
   categories: [' . $array_day . '],
   title: {
   text: null
   },
   labels: {
   align:"right",
   }
   },
   yAxis: {
   min: 0,
   gridLineWidth: 0,
   showEmpty: false,
   title: {
   text: null
   },
   labels: {
   enabled: false,
   }
   },
   tooltip: {
   valueSuffix:" ' . $lang['polls_people'] . '"
   },
   plotOptions: {
   bar: {},
   column: {
   colorByPoint: true,
   }
   },
   series: [{
   name:" ' . $lang['cview'] . '",
    data: [' . $array_views . ']
      }, {
       name:" ' . $lang['visitors'] . '",
       data: [' . $array_people . ']
   }]
   });
   }
   };	pollsHighBars();
   };
   return {
   init: function () {
   pollsHighCharts();
   }
   }
   }();
</script>';
        $adminTpl->js_code[] = 'pollsHighCharts.init(); ';
    } elseif ($includ_chart_conf['schedule'] == "graphics") {
        $schedule = $adminTpl->footIncludes[] = '<script type="text/javascript">
   document.addEventListener("DOMContentLoaded", function(){
   		var chart = new Highcharts.Chart({
    	colors: [\'#ddd\', \'#2969b0\'],
   		chart: {
              renderTo: \'container\',
      marginBottom: 80
    },
   title: {
              text: \'\'
   },
   legend: {
              layout: \'vertical\',
   		align: \'left\',
   		verticalAlign: \'top\',
   		x: 100,
   		y: 50,
   		floating: true,
   		borderWidth: 1,
   		backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || \'#FFFFFF\'
   },
      xAxis: {
   		categories: [' . $array_day . '],
   },
   yAxis: {
   		title: {
   		text: \'\'
   }
   },
   tooltip: {
   		shared: true,
   		valueSuffix: \'\'
   },
   credits: {
   		enabled: false
   },
   plotOptions: {
   		areaspline: {
   		fillOpacity: 0.5
   }
   },
      series: [{
   			name:" ' . $lang['cview'] . '",
   		    data: [' . $array_views . ']
           }, {
   	        name:" ' . $lang['visitors'] . '",
   	        data: [' . $array_people . ']
   	    }]
   })
   });
</script>';
        $adminTpl->js_code[] = 'Highcharts.init(); ';
    } elseif ($includ_chart_conf['schedule'] == "spot") {
        $schedule = $adminTpl->footIncludes[] = '<script type="text/javascript">
   document.addEventListener("DOMContentLoaded", function(){
   			// Create liteChart.js Object
   			let d = new liteChart("chart");
   			// Set labels
   			d.setLabels([' . $array_day . '])
   			// Set legends and values
   			d.addLegend({"name":" ' . $lang['cview'] . '","stroke":"#CDDC39","fill":"#fff","values": [' . $array_views . ']})
   			d.addLegend({"name":" ' . $lang['visitors'] . '","stroke":"#3b95f7","fill":"#fff","values": [' . $array_people . ']})
   			// Inject chart into DOM object
   			let div = document.getElementById("container");
   			d.inject(div);
   			// Draw
   			d.draw();
   		});
</script>';
        $adminTpl->js_code[] = 'liteChart.init(); ';
    } else {
        $schedule = false;
    }
    return $schedule;
}

function but_link($link, $text): string
{
    return '<div class="btn btn-link btn-sm dropdown-toggle">
   <i class="pd-l-sm"><a href ="' . ADMIN . $link . '">' . faSpan('not', true, $text) . '</a></i>
</div>';
}