<?php

namespace Mnv\Admin\Controllers;

if (!defined('MNV_CMS')) {
    die('Hacking attempt!');
}

use Mnv\Core\AdminMnv;

use Mnv\Models\Stats;

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

    public function fetch()
    {
        $stats = new Stats();

        $this->smarty->assign('activeItem', 'main');
        $this->smarty->assign('title', 'Dashboard');

        $notice = $this->request->get('notice', '');

        $stats->updateStatsCacheDaily();

        /** запись в базу (заметки) */
        if ($this->action === 'notice') {
            $this->updateNotice($this->manager['userId'], $notice);
            $response = array('status' => 200);

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

        $date = new \DateTime();
        $date->modify('-1 year');

        $dateStart  = $date->format("Y-m-d");
        $dateEnd    = date('Y-m-d H:i:s');

        /** получение самой ранней даты */
        $minDate = connect()->table('stats_cache_daily')->min('cacheDate', 'cacheDate')->get('array');
        if ($minDate['cacheDate']) $dateStart = $minDate['cacheDate'];


        $stats->days = connect()->table('stats_cache_daily')
            ->select('cacheDate, newVisitors, retVisitors, sectionVisits, articleVisits, searchVisits, errorVisits, rssVisits')
            ->between('cacheDate', $dateStart, $dateEnd)
            ->orderBy('cacheDate')
            ->getAll('array');

        $stats->stat['visitors']  = 0;
        $stats->stat['visits']    = 0;

        if (!empty($stats->days)) {
            foreach ($stats->days as $i => $row) {
                $stats->days[$i]['date'] = langDate(date("Y-m-d", strtotime($row['cacheDate'])));
                $stats->stat['visitors'] += $row['newVisitors'] + $row['retVisitors'];
                $stats->stat['visits'] += $row['articleVisits'] + $row['sectionVisits'] + $row['searchVisits'];
            }
        }

        $this->smarty->assign('days', $stats->days);
        $this->smarty->assign('totals', $stats->stat);

        /** Операционная система */
        $this->smarty->assign('os_version',  @php_uname( "s" ) . " " . @php_uname( "r" ));
        /** Версия PHP */
        $this->smarty->assign('php_version', PHP_VERSION);
        /** Версия MySQL */
        $this->smarty->assign('mysql_version',  $this->mysql_version());
        /** Размер базы данных */
        $this->smarty->assign('mysql_size',  $this->mysql_size());
        /** Module mod_rewrite */
        $this->smarty->assign('mod_rewrite',  $this->apache_modules());
        /** Обработчик изображений */
        $this->smarty->assign('gd_version', $this->gd_version());
        /** Выделено оперативной памяти */
        $this->smarty->assign('max_memory',  (@ini_get( 'memory_limit' ) != '') ? @ini_get( 'memory_limit' ) : "Не определено");
        /** Отключенные функции */
        $this->smarty->assign('disabled_functions',  (strlen( ini_get( 'disable_functions' ) ) > 1) ? @ini_get( 'disable_functions' ) : "Не определено");
        /** Размер свободного места на диске */
        $this->smarty->assign('disk_free_space',  $this->disk_free_space());
        /** Блокнот (заметки) */
        $this->smarty->assign('notice',  $this->notice());


        try {
            return $this->smarty->fetch('views/main/index.tpl');
        } catch (\SmartyException | \Exception $e) {
            return $e->getMessage();
        }


    }

    private function notice(): string
    {
        $notice = '';
        if ($res = connect()->table('notice')->where('userId', $this->manager['userId'])->get()) {
            $notice = htmlspecialchars( $res->notice, ENT_QUOTES, $this->config['charset'] );
        }

        return $notice;
    }

    private function updateNotice($userId, $notice): void
    {
        if (connect()->table('notice')->where('userId', $userId)->get()) {
           connect()->table('notice')->where('userId', $userId)->update(['notice' => $notice]);
        } else {
            connect()->table('notice')->insert(['userId' => $userId, 'notice' => $notice]);
        }
    }



    private function apache_modules(): string
    {
        if( function_exists( 'apache_get_modules' ) ) {
            if( array_search('mod_rewrite', apache_get_modules(), true) !== false) {
                $mod_rewrite = "Включен";
            } else {
                $mod_rewrite = "<span class=\"text-danger\">Выключен</span>";
            }
        } else {
            $mod_rewrite = "Не определено";
        }
        return $mod_rewrite;
    }


    private function disk_free_space(): string
    {
        $dfs = @disk_free_space( "." );
        return formatsize( $dfs );
    }

    private function mysql_version()
    {
        return connect()->mysqlVersion();
    }

    private function mysql_size(): string
    {
        global $databaseConfig;

        $mysql_size = 0;
        $result = connect()->query( "SHOW TABLE STATUS FROM `" . $databaseConfig['database'] . "`" )->fetchAll();
        foreach ($result as $item) {
            if (strpos( $item->Name, $databaseConfig['prefix']) !== false ) $mysql_size += $item->Data_length + $item->Index_length;
        }
        return formatsize($mysql_size);
    }


    private function gd_version()
    {
        if ($this->config['image_library'] != 2) {
            if (extension_loaded('imagick') && class_exists('Imagick')) {
                $gd_version  =  'imagick';
                if (!\Imagick::queryFormats('WEBP') AND function_exists('imagewebp') AND $this->config['image_library'] != 1 ) {
                    $gd_version  =  'gd';
                }

            } else if ( function_exists( 'gd_info' ) ) {
                $gd_version  =  'gd';
            }

        } else if ( function_exists( 'gd_info' ) ) {
            $gd_version  =  'gd';
        }

        if ($gd_version == 'imagick') {
            $v = \Imagick::getVersion();
            $gd_version = $v['versionString'];

        } else if ( $gd_version  ==  'gd') {
            $array = gd_info();
            $gd_version = '';

            foreach ($array as $key=>$val) {
                if ($val === true) {
                    $val = "Enabled";
                }

                if ($val === false) {
                    $val = "Disabled";
                }

                $gd_version .= $key.":&nbsp;{$val}, ";
            }

        } else {
            $gd_version = "Не определено";
        }

        return $gd_version;
    }



}
