<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\Config;
use Mnv\Core\Filesystem\Filesystem;
use Mnv\Core\Helpers;
use Mnv\Core\AdminMnv;
use Mnv\Core\UserInfo;
use Mnv\Core\Locale\Charset;
use Mnv\Core\Locale\LanguageSelection;

use Mnv\Models\Settings;

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

    public function fetch()
    {
        $filesystem = new Filesystem();

        $setting = new Settings($this->request);
        $date = $this->request->get('date', '');

        $this->smarty->assign('activeItem','settings');
        $this->smarty->assign('title', lang('settings:title'));

        /** очистка кеша */
        if  ($this->action == 'clear_cache') {
            $this->smarty->clearAllCache();
            exit;
        }
        /** удаление статистики */
        else if  ($this->action == 'delete_stats') {

            $setting->deleteStatsPriorTo($date);
            exit;
        }
        /** тестирование подключения smtp */
        else if ($this->action ==  'test_smtp') {

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

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


            if (empty($setting->setting['only_ssl'])) $setting->setting['only_ssl'] = 0;
            if (empty($setting->setting['convert_filename_to_lowercase'])) $setting->setting['convert_filename_to_lowercase'] = 0;
            if (empty($setting->setting['statistics_enabled'])) $setting->setting['statistics_enabled'] = 0;

            if (empty($setting->setting['comments_enabled']))                     $setting->setting['comments_enabled'] = 0;
            if (empty($setting->setting['comments_must_be_approved']))            $setting->setting['comments_must_be_approved'] = 0;
            if (empty($setting->setting['comments_whitelist_enabled']))           $setting->setting['comments_whitelist_enabled'] = 0;
            if (empty($setting->setting['comments_blacklist_enabled']))           $setting->setting['comments_blacklist_enabled'] = 0;
            if (empty($setting->setting['comments_editors_may_approve']))         $setting->setting['comments_editors_may_approve'] = 0;
            if (empty($setting->setting['comments_captcha_enabled']))             $setting->setting['comments_captcha_enabled'] = 0;
            if (empty($setting->setting['comments_strip_html']))                  $setting->setting['comments_strip_html'] = 0;
            if (empty($setting->setting['comments_convert_links']))               $setting->setting['comments_convert_links'] = 0;
            if (empty($setting->setting['comments_email_confirmation_required'])) $setting->setting['comments_email_confirmation_required'] = 0;

            if (empty($setting->setting['allow_watermark']))            $setting->setting['allow_watermark'] = 0;
            if (empty($setting->setting['save_original_image']))        $setting->setting['save_original_image'] = 0;
            if (empty($setting->setting['keep_original_image_name']))   $setting->setting['keep_original_image_name'] = 0;
            if (empty($setting->setting['save_thumbnail_image']))       $setting->setting['save_thumbnail_image'] = 0;
            if (empty($setting->setting['force_webp']))                 $setting->setting['force_webp'] = 0;
            if (empty($setting->setting['mail_bcc']))                   $setting->setting['mail_bcc'] = 0;

            if (empty($setting->setting['cache_enabled_index']))        $setting->setting['cache_enabled_index'] = 0;
            if (empty($setting->setting['cache_enabled_article']))      $setting->setting['cache_enabled_article'] = 0;
            if (empty($setting->setting['cache_enabled_section']))      $setting->setting['cache_enabled_section'] = 0;
            if (empty($setting->setting['cache_enabled_rss']))          $setting->setting['cache_enabled_rss'] = 0;
            if (empty($setting->setting['cache_enabled_sitemap']))      $setting->setting['cache_enabled_sitemap'] = 0;

            if (empty($setting->setting['feedback_captcha_enabled']))   $setting->setting['feedback_captcha_enabled'] = 0;
            if (empty($setting->setting['website_down']))               $setting->setting['website_down'] = 0;
            if (empty($setting->setting['compress_js_css']))            $setting->setting['compress_js_css'] = 0;
            if (empty($setting->setting['mod_deflate']))                $setting->setting['mod_deflate'] = 0;
            if (empty($setting->setting['mod_headers']))                $setting->setting['mod_headers'] = 0;
            if (empty($setting->setting['mod_expires']))                $setting->setting['mod_expires'] = 0;
            if (empty($setting->setting['www_redirect']))               $setting->setting['www_redirect'] = 0;
            if (empty($setting->setting['http_redirect']))              $setting->setting['http_redirect'] = 0;
            if (empty($setting->setting['website_language']))           $setting->setting['website_language'] = '';
            if (empty($setting->setting['telegram_send']))              $setting->setting['telegram_send'] = 0;
            if (empty($setting->setting['error_test']))                 $setting->setting['error_test'] = 0;
            if (empty($setting->setting['check_banned_ips']))           $setting->setting['check_banned_ips'] = 0;
            if (empty($setting->setting['twoFactorAuth']))              $setting->setting['twoFactorAuth'] = 0;

            if (empty($setting->setting['timezone'])) $setting->setting['timezone'] = Config::getValue('timezone');

            foreach (lang('langtimezones:timezone') as $key => $langtimezone) {
                if ($setting->setting['timezone'] == $key)  {
                    $timezone = explode(":", $langtimezone);
                    $setting->setting['hour_adjustment']   = $timezone[0];
                    $setting->setting['minute_adjustment'] = $timezone[1];
                }
            }
//            if (empty($setting->setting['site_url'])) $setting->setting['site_url'] = GLOBAL_URL;


            $updateSetting = array();
            $thumbSizeNames = array('small_thumb', 'medium_thumb', 'large_thumb');

//            if (!empty($setting->setting['old_site_url'])) $setting->updateUrl($setting->setting['old_site_url'], $setting->setting['site_url']);

            foreach ($setting->setting as $codename => $value) {
                if (!isset($this->config[$codename]) || $this->config[$codename] != $value) {

                    if (in_array($codename, $thumbSizeNames, true)) $value = (int)$value;

                    switch ($codename) {
                        case 'compress_js_css':
//                    $updateHtaccess = true;
                            break;

                        case 'admin_language':  /* control panel language has changed */
                            $adminLang = $value;
                            loadLanguage($adminLang);
                            $this->smarty->setCompileId('admin-' . $adminLang);
                            $this->smarty->assign('adminLang', $adminLang);
                            break;

                        case 'website_language':
                            $newWebsiteLang = $value;
                            $oldWebsiteLang = $this->config['website_language'];
                            $lang_dir = GLOBAL_ROOT.'/includes/languages/';
                            if (is_dir($lang_dir)) {
                                $src = $lang_dir . $oldWebsiteLang . '.json';
                                $dest = $lang_dir . $newWebsiteLang . '.json';
                                if ($filesystem->exists($src) && !$filesystem->exists($dest)) {
                                    $filesystem->copy($src, $dest);
//                                    copyFolder($src, $dest);
                                }
                            }
                            break;

                        case 'file_extension': /* file extension has been changed */
//                    $updateHtaccess = true;
                            $oldExtension = $this->config['file_extension'];
                            /* update all article and sections URLs */
                            $setting->updateExtension($oldExtension, $setting->setting['file_extension']);
                            break;

                        case 'bot_id_strings':
                            if ($bots = explode("\r\n", $value)) {
                                $bots = array_map('trim', $bots);
                                $bots = array_preg_quote($bots);
                                $bots = implode('|', $bots);
                            } else {
                                $bots = '';
                            }
                            $updateSetting['codename'] = 'bot_id_regexp';
                            $updateSetting['value'] = $bots;
                            $setting->update($updateSetting);
                            $setting->stats_user_agents($bots);
                            break;

                        case 'bot_id_regexp':
                        case 'query_fields_strings':
                            if ($queryFields = explode("\r\n", $value)) {
                                $queryFields = array_map('trim', $queryFields);
                                $queryFields = array_preg_quote($queryFields);
                                $queryFields = implode('|', $queryFields);
                            } else {
                                $queryFields = '';
                            }
                            $updateSetting['codename'] = 'query_fields';
                            $updateSetting['value'] = $queryFields;

                        $setting->update($updateSetting);
                        break;
                        case 'theme': /* theme has been changed */
                            $this->smarty->clearAllCache();
                            break;
                    }

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

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

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

            $this->messages['saved'] = true;

            if (!saveSerializations()) {
                $this->errors['serializations'] = true;
            }
            if (!writeHtaccess()) {
                $this->errors['htaccess'] = true;
            }

        }


        for($i = 100; $i >= 70; $i = $i - 5) $thumbQualityOptions[$i] = $i;
        $this->smarty->assign('thumbQualityOptions', $thumbQualityOptions);

        for($i = 1; $i <= 10; $i++) $sectionDepthOptions[$i] = $i;
        $this->smarty->assign('sectionDepthOptions', $sectionDepthOptions);

        /* caching time options */
        for($i = 1; $i <= 60; $i++) $cachingTimeOptions[$i] = $i;
        $this->smarty->assign('cachingTimeOptions', $cachingTimeOptions);

        $this->smarty->assign('cachingPeriodOptions', lang('general:cachingPeriodOptions'));

        $this->smarty->assign('adjustedTime', langDate(adjustTime(gmdate('Y-m-d H:i:s'), false, 'F j, Y - H:i')));
        $this->smarty->assign('gmtTime', langDate(gmdate('F j, Y - H:i')));

        $deleteStatsTime = ($deleteStatsTime = $setting->statsTime()) ? strtotime($deleteStatsTime) : time() - 60*60*24*365;
        $this->smarty->assign('deleteStatsTime', $deleteStatsTime);

        /** получить из папки themes языковые версии сайта(шаблоны) */
        $this->smarty->assign('themes', Helpers::getThemes());

        /** с файла ru.inc.php получить разные спадающие списки <select> */
        $this->smarty->assign('ports',          lang('settings:mails:ports'));
        $this->smarty->assign('secures',        lang('settings:mails:secures'));
        $this->smarty->assign('methods',        lang('settings:users:methods'));
        $this->smarty->assign('sms_providers',  lang('settings:users:providers'));
        $this->smarty->assign('mailTransports', lang('settings:mails:mailTransports'));
        $this->smarty->assign('langtimezones',  lang('langtimezones:langtimezone'));
        $this->smarty->assign('captchas',       lang('settings:captchas'));
        $this->smarty->assign('timeformats',    lang('settings:timeFormats'));
        $this->smarty->assign('fileExtension',  lang('settings:fileExtension'));
        $this->smarty->assign('separators',     lang('settings:separators'));
        $this->smarty->assign('driver',         lang('settings:driver'));
        $this->smarty->assign('imageGenerations',  lang('settings:generations'));
        $this->smarty->assign('works',          lang('general:works'));

        /** languages */
        $this->smarty->assign('adminLangs',         getLanguages());
        $this->smarty->assign('languageOptions',    LanguageSelection::$languageOptions);
        $this->smarty->assign('languageCharsets',   Charset::$languageCharsets);
        $this->smarty->assign('charsetOptions',     Charset::$charsetOptions);

        $this->smarty->assign('ADMINIP', UserInfo::get_ip());

        if(!empty($this->errors)) $this->smarty->assign('errors', $this->errors);
        if(!empty($this->messages)) $this->smarty->assign('messages', $this->messages);


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

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