<?php

namespace core_next;

class Theme
{
    static $redis = null;
    static $page_templates;

    static function init()
    {
        global $core_next_set;
        add_action('admin_menu', array(static::class, 'regMenu'));
        add_action('widgets_init', array(static::class, 'regSidebar'));
        add_theme_support('top-nav-menus');
        register_nav_menus(array(
            'header_menu' => '顶部导航菜单',
            'footer_menu' => '底部导航菜单',
            //'header_sub_menu' => '顶部导航菜单【子菜单】',
        ));
        add_action('add_meta_boxes', function () {
            add_meta_box('corenext_post_meta', 'CoreNext文章设置', [static::class, 'addMetaBox'], 'page', 'advanced', 'high');
            add_meta_box('corenext_post_meta', 'CoreNext文章设置', [static::class, 'addMetaBox'], 'post', 'advanced', 'high');
        });
        add_theme_support('post-thumbnails');
        add_action('save_post', [static::class, 'saveMetaBoxData']);
        //add_action('save_post', [Optimize::class, 'updateCache']);

        add_editor_style('static/css/editor-style.css');

        add_action('init', [static::class, 'initTheme']);
        add_action('core_next_ad', [static::class, 'insertAd'], 10, 3);
        add_action('media_buttons', function () {
            if (!is_admin()) {
                return;
            }
            echo '<a href="javascript:;"  class="button core-next-editor-power">CoreNext编辑器增强</a>';
        });
        add_filter('admin_footer_text', function ($text) {
            return $text . '<span style="font-style: italic;">CoreNext主题为您提供建站增强</span>';
        });
        add_action('pre_get_posts', [static::class, 'searchExclude']);
        /*add_filter('the_content', function ($content) {
            return str_replace('{{', '{ {', $content);
        }, 10, 1);*/
        if ($core_next_set['comment_location_open']) {
            add_action('comment_post', array(static::class, 'addCommentIpPlace'), 10, 2);
        }

        self::mailSupport();
        self::faceSupport();
        self::regWidget();
        self::initPage();
        self::funSwitch();
        self::updateCache();
        add_action('init', [static::class, 'customAuthorUrl']);
        add_filter('the_password_form', [static::class, 'customPasswordForm']);
    }


    static function customPasswordForm($form)
    {
        return '<post-password-form id="password-form"></post-password-form>';
    }

    static function customAuthorUrl()
    {
        global $wp_rewrite;
        $author_slug = 'user';
        $wp_rewrite->author_base = $author_slug;
    }

    static function addCommentIpPlace($comment_id, $comment_approved)
    {
        global $core_next_set;
        $ip = Tools::getRealIP();
        if ($ip !== false) {
            $ip_pre = substr($ip, 0, 3);
            /* if ($ip_pre == '10.' || $ip_pre == '172' || $ip_pre == '192' || $ip_pre == '0.2' || $ip_pre == '0.0' || $ip_pre == '100' || $ip_pre == '127' || $ip_pre == '192' || $ip_pre == '203' || $ip_pre == '255') {
                 return;
             }*/
            $ip_info = self::getIPLocationInfo($core_next_set['comment_location_type'], $ip);
            if ($ip_info !== false) {
                add_comment_meta($comment_id, 'core_ip_place', $ip_info);
            }
        }
    }


    static function searchExclude($query)
    {
        if ($query->is_search) {
            $query->set('post_type', 'post');
        }
    }

    static function updateCache()
    {
        global $core_next_set, $core_next_expand_set;
        if ($core_next_set['home_post_list_cache']) {
            add_action('save_post', function () use ($core_next_expand_set) {
                $core_next_expand_set['update_home_post_list_cache'] = true;
                Options::saveExpandSet($core_next_expand_set);
            });
        }

    }

    static function funSwitch()
    {
        global $core_next_set;
        add_filter('gutenberg_use_widgets_block_editor', '__return_false');
        add_filter('use_widgets_block_editor', '__return_false');
        if ($core_next_set['close_gutenberg_editor']) {
            add_filter('use_block_editor_for_post', '__return_false');
        }
    }

    static function insertAd($position, $margin_top, $margin_bottom)
    {
        $ad = do_shortcode(self::_getAdCode($position));
        if ($ad != '') {
            $html = '<div style="z-index:10;margin-bottom: ' . $margin_bottom . 'px;margin-top:' . $margin_top . 'px">' . $ad . '</div>';
            print_r($html);
        }
    }

    static private function _getAdCode($name)
    {
        global $core_next_set;
        if (wp_is_mobile()) {
            $ad = $core_next_set["ad_{$name}_phone"];
        } else {
            $ad = $core_next_set["ad_{$name}"];
        }
        return $ad;
    }

    static function initPage()
    {
        self::$page_templates = array(
            array(
                "slug" => "core_next_user_center",
                "name" => "CoreNext用户中心",
                "path" => Config::$theme_dir . "/page/user-center.php",
            ),
            [
                "slug" => "core_next_full_page",
                "name" => "CoreNext全宽页面",
                "path" => Config::$theme_dir . "/page/full-page.php",
            ],
            [
                "slug" => "core_next_auth",
                "name" => "CoreNext第三方登录",
                "path" => Config::$theme_dir . "/page/auth.php",
            ],
        );
        add_filter('page_template', function ($page_template) {
            $slug = get_page_template_slug();
            foreach (self::$page_templates as $item) {
                if ($slug == $item['slug']) {
                    return $item['path'];
                }
            }
            return $page_template;
        });

        add_filter('theme_page_templates', function ($post_templates, $wp_theme, $post, $post_type) {
            foreach (self::$page_templates as $item) {
                $post_templates[$item['slug']] = $item['name'];
            }
            return $post_templates;
        }, 10, 4);
    }

    static function initTheme()
    {
        remove_theme_support('widgets-block-editor');

    }

    static function regWidget()
    {

        self::requireWidget('comment', 'comment');
        self::requireWidget('postList', 'postList');
        self::requireWidget('userInfo', 'userInfo');
        self::requireWidget('weather', 'weather');
        self::requireWidget('timeProgress', 'timeProgress');
        self::requireWidget('search', 'search');
        self::requireWidget('calendar', 'calendar');
        self::requireWidget('webmaster', 'webmaster');
        self::requireWidget('tagCloud', 'tagCloud');
    }


    static function requireWidget($name, $class_name)
    {
        $dir = Config::$theme_dir . "/widgets/$name.php";
        require_once $dir;
        add_action('widgets_init', function () use ($class_name) {
            register_widget("core_next\\$class_name");
        });
    }

    static function faceSupport()
    {

        add_filter('comment_text', function ($comment_content) {
            preg_match_all("/\[f=([^\]]+)\]/", $comment_content, $matches);
            foreach ($matches[0] as $key => $face_item) {
                $img_url = Config::$img_url . "/face/" . $matches[1][$key] . '.gif';
                $html = '<img class="comment-face" src="' . $img_url . '">';
                $comment_content = str_replace($face_item, $html, $comment_content);
            }
            return $comment_content;
        });
    }

    static function mailSupport()
    {
        global $core_next_set;
        $arr = $core_next_set;
        add_action('phpmailer_init', function ($phpmailer) use ($arr) {
            $phpmailer->isSMTP();
            $phpmailer->Host = $arr['mail_host'];
            $phpmailer->SMTPAuth = true;
            $phpmailer->Port = $arr['mail_port'];
            $phpmailer->Username = $arr['mail_user'];
            $phpmailer->Password = $arr['mail_password'];
            $phpmailer->SMTPSecure = $arr['mail_encrypt'] == 'ssl' ? 'ssl' : false;
            $phpmailer->From = $arr['mail_user'];
            $phpmailer->FromName = $arr['mail_from_name'];
        });
    }

    static function regMediaCat()
    {
        $labels = array(
            'name' => _x('Media Categories', 'taxonomy general name'),
            'singular_name' => _x('Media Category', 'taxonomy singular name'),
            'search_items' => __('Search Media Categories'),
            'all_items' => __('All Media Categories'),
            'parent_item' => __('Parent Media Category'),
            'parent_item_colon' => __('Parent Media Category:'),
            'edit_item' => __('Edit Media Category'),
            'update_item' => __('Update Media Category'),
            'add_new_item' => __('Add New Media Category'),
            'new_item_name' => __('New Media Category Name'),
            'menu_name' => __('Media Categories'),
        );

        $args = array(
            'hierarchical' => true,
            'labels' => $labels,
            'show_ui' => true,
            'show_admin_column' => true,
            'query_var' => true,
            'rewrite' => array('slug' => 'media-category'),
        );

        register_taxonomy('media_category', array('attachment'), $args);
    }

    static function saveMetaBoxData($post_id)
    {
        if (!current_user_can('edit_post', $post_id)) {
            return $post_id;
        }
        $meta_key = 'core_next_post_meta';
        if (isset($_POST['core_next_post_meta'])) {
            update_post_meta($post_id, $meta_key, $_POST['core_next_post_meta']);
        }
        return $post_id;
    }

    static function addMetaBox()
    {
        get_template_part('template/components/meta-box');
    }

    static function regMenu()
    {
        global $core_next_expand_set;
        add_menu_page('主题设置', '主题设置', 'administrator', 'core_next', function () {
            require_once Config::$theme_dir . '/page/admin/set-main.php';
        }, 'dashicons-icon-core-next');
        add_submenu_page('core_next', '主题更新', '主题更新', 'administrator', 'core_update', function () {
            require_once Config::$theme_dir . '/page/admin/update.php';
        });

        if ($core_next_expand_set['need_update']) {
            global $submenu;
            $parent_slug = 'core_next'; // 替换为您的父菜单的slug
            $submenu_slug = 'core_update'; // 替换为您的子菜单的slug
            foreach ($submenu[$parent_slug] as $key => $value) {
                if ($submenu_slug == $value[2]) {
                    $submenu[$parent_slug][$key][0] .= ' <span class="update-plugins count-1"><span class="update-count">new</span></span>';
                }
            }
            global $menu;
            $menu_slug = 'core_next';
            foreach ($menu as $key => $value) {
                if ($menu_slug == $value[2]) {
                    $menu[$key][0] .= ' <span class="update-plugins count-1"><span class="update-count">new</span></span>';
                }
            }
        }
    }

    static function regSidebar()
    {
        global $core_next_set;

        if ($core_next_set['aside_type'] === 'theme') {
            if ($core_next_set['aside_style'] == 'classic') {
                $aside_style_class = ' widget-title-classic';
            } else {
                $aside_style_class = ' widget-title-mac';
            }
            $aside_img = '';
        } else {
            $aside_style_class = '';
            $aside_img = "<img src='" . $core_next_set['aside_box_img'] . "' width='24'>";
        }
        register_sidebar(array(
            'id' => 'index_sidebar',
            'name' => '首页边栏',
            'before_title' => '<h2 class="widget-title' . $aside_style_class . '" v-pre>' . $aside_img,
            'before_widget' => '<div class="aside-box %2$s">',
            'after_widget' => '</div>'
        ));
        register_sidebar(array(
            'id' => 'author_sidebar',
            'name' => '用户页面边栏',
            'before_title' => '<h2 class="widget-title' . $aside_style_class . '" v-pre>' . $aside_img,
            'before_widget' => '<div class="aside-box %2$s">',
            'after_widget' => '</div>'
        ));
        register_sidebar(array(
            'id' => 'post_sidebar',
            'name' => '文章边栏',
            'before_title' => '<h2 class="widget-title' . $aside_style_class . '">' . $aside_img,
            'before_widget' => '<div class="aside-box %2$s">',
            'after_widget' => '</div>'
        ));
        register_sidebar(array(
            'id' => 'post_list_sidebar',
            'name' => '文章列表边栏',
            'before_title' => '<h2 class="widget-title' . $aside_style_class . '">' . $aside_img,
            'before_widget' => '<div class="aside-box %2$s">',
            'after_widget' => '</div>'
        ));
        register_sidebar(array(
            'id' => 'search_sidebar',
            'name' => '搜索文章列表边栏',
            'before_title' => '<h2 class="widget-title' . $aside_style_class . '">' . $aside_img,
            'before_widget' => '<div class="aside-box %2$s">',
            'after_widget' => '</div>'
        ));

        register_sidebar(array(
            'id' => 'page_sidebar',
            'name' => '页面边栏',
            'before_title' => '<h2 class="widget-title' . $aside_style_class . '">' . $aside_img,
            'before_widget' => '<div class="aside-box %2$s">',
            'after_widget' => '</div>'
        ));
        register_sidebar(array(
            'id' => 'footer_widget',
            'name' => '底部小工具[左侧]',
            'before_title' => '<h2 class="footer-widget-title">',
            'before_widget' => '<div class="footer-aside-box">',
            'after_widget' => '</div>'
        ));
        register_sidebar(array(
            'id' => 'footer_widget_right',
            'name' => '底部小工具[右侧]',
            'before_title' => '<h2 class="footer-widget-title">',
            'before_widget' => '<div class="footer-aside-box">',
            'after_widget' => '</div>'
        ));
    }

    static function getFaceList()
    {
        $dir = Config::$theme_dir . "/static/img/face";
        $files = glob($dir . "/*.gif");
        $list = [];
        foreach ($files as $name) {
            $_temp['url'] = Config::$img_url . "/face/" . basename($name);
            $_temp['name'] = basename($name, '.gif');
            $list[] = $_temp;
        }
        return $list;
    }

    static function getWidgetIcon()
    {
        return '<img src="' . Config::$img_url . '/icon/icp.svg">';
    }

    static function Cache($key, $call_back, $forced_update = false)
    {
        if ($forced_update === true) {
            $data = call_user_func($call_back);
            set_site_transient($key, $data, 60 * MINUTE_IN_SECONDS);
        } else {
            $data = get_site_transient($key);
            if ($data === false) {
                $data = call_user_func($call_back);
                set_site_transient($key, $data, 60 * MINUTE_IN_SECONDS);
            }
        }
        return $data;
    }


    static function echoKeywordsAndDescription($keywords, $description)
    {
        echo '<meta name="keywords" content="' . $keywords . '">';
        echo '<meta name="description" content="' . $description . '">';
    }

    static function getServeThemeInfo()
    {
        return false;
        $re = wp_remote_get(Config::$theme_info_url);
        if (is_wp_error($re)) {
            return false;
        }
        $info = json_decode($re['body'], true);
        if ($info === false) {
            return false;
        }
        return $info;
    }

    static function parseCopyrightStr($str)
    {
//#username# 当前文章作者名
//#postname# 当前文章标题
//#url# 当前文章地址
//#authorurl# 当前作者页面地址

        $par_name = '#username#';
        if (strpos($str, $par_name) !== false) {
            $username = WordPress::getUserDisplayName();
            $str = str_replace('#username#', $username, $str);
        }
        $par_name = '#postname#';
        if (strpos($str, $par_name) !== false) {
            $str = str_replace($par_name, get_the_title(), $str);
        }
        $par_name = '#url#';
        if (strpos($str, $par_name) !== false) {
            $str = str_replace($par_name, get_permalink(), $str);
        }
        $par_name = '#authorurl#';
        if (strpos($str, $par_name) !== false) {
            $author_id = get_the_author_meta('ID');
            $str = str_replace($par_name, get_author_posts_url($author_id), $str);
        }

        return $str;

    }

    static function getCanUpdateCache($cache_key)
    {
        global $core_next_expand_set;
        if ($core_next_expand_set['update_' . $cache_key]) {
            $core_next_expand_set['update_' . $cache_key] = false;
            Options::saveExpandSet($core_next_expand_set);
            return true;
        }
        return false;
    }


    static function handleRandomThumbnail($post_list)
    {
        global $core_next_set;
        if ($core_next_set['random_thumbnail_api']) {
            foreach ($post_list as &$item) {
                if (isset($item['thumbnail']) && strpos($item['thumbnail'], '?v=') === false) {
                    $item['thumbnail'] .= '?v=' . rand(1, 1000);
                }

            }
        }
        return $post_list;
    }

    static function handleRandomThumbnailOne($url)
    {
        global $core_next_set;
        if ($core_next_set['random_thumbnail_api']) {
            if (strpos($url, '?v=') === false && strpos($url, '?') === false) {
                $url .= '?v=' . rand(1, 1000);
            }
        }
        return $url;
    }


    static function isDark()
    {
        global $core_next_set;
        if ($core_next_set['dark_open']) {
            if (isset($_COOKIE['dark']) && $_COOKIE['dark'] == 1) {
                return true;
            } else {
                if ($core_next_set['default_dark']) {
                    return true;
                }
            }
        }
        return false;
    }

    static function checkOtherLogin($name)
    {
        global $core_next_set;
        if ($name == 'qq') {
            if (!$core_next_set['other_login_qq_open']) {
                die('未开启QQ登录功能');
            }
        }
    }

    /** 是否在白名单邮箱，在返回true
     * @param $mail
     * @return bool
     */
    static function verifyMailWhitelist($mail)
    {
        global $core_next_set;
        $mail_list = $core_next_set['mail_white_list'];
        $pattern = '/@(.+)$/';
        preg_match($pattern, $mail, $matches);
        $domain = $matches[1];
        $mail_list_arr = explode(',', $mail_list);
        return in_array($domain, $mail_list_arr);

    }


    static function getIPLocationInfo($type, $ip, $key = null)
    {
        global $core_next_set;

        if ($type === '365') {
            $url = "https://zjip.market.alicloudapi.com/lifeservice/QueryIpAddr/query?ip=$ip";
            if ($key === null) {
                $key = $core_next_set['comment_location_365_key'];
            }
            $re = wp_remote_get($url, ['headers' => ['Authorization' => "APPCODE $key"]]);

            if ($re['response']['code'] === 200) {
                $json = json_decode($re['body'], true);
                if ($json['error_code'] === 0) {
                    $data['country'] = $json['result']['country'];
                    $data['is_cn'] = 0;
                    if ($data['country'] === '中国') {
                        $data['is_cn'] = 1;
                    }
                    $data['province'] = $json['result']['province'];
                    $data['city'] = $json['result']['city'];
                    $data['operator'] = $json['result']['isp'];
                    return $data;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        return false;
    }

    static function loadLoading()
    {
        global $core_next_set;
        if ($core_next_set['loading_animations']) {
            get_template_part('template/module/loading');
        }
    }

    static function getWidgetStickyStyle()
    {
        return '<div style="position: sticky;top: 70px;z-index:100" ';
    }

    static function createAvatar($data, $user_mail)
    {
        $dir = Config::$avatar_path;
        if (!file_exists($dir)) {
            if (!mkdir($dir, 0755, true)) {
                return false;
            }
        }
        $file = $dir . '/' . md5($user_mail) . '.webp';
        $url = Config::$avatar_url . '/' . md5($user_mail) . '.webp';
        if (file_put_contents($file, base64_decode($data))) {
            return $url;
        }
        return false;
    }

    static function getUserAvatar($user_mail)
    {
        $file = Config::$avatar_path . '/' . md5($user_mail) . '.webp';
        $url = Config::$avatar_url . '/' . md5($user_mail) . '.webp';
        if (file_exists($file)) {
            return $url;
        } else {
            global $core_next_set;
            if ($core_next_set['local_avatar']) {
                return $core_next_set['default_avatar'];
            }
            return get_avatar_url($user_mail);
        }
    }
}