<?php

namespace core_next;

class LoadFiles
{
    static function init()
    {
        require_once Config::$theme_dir . '/core/Tools.php';
        require_once Config::$theme_dir . '/core/Theme.php';
        require_once Config::$theme_dir . '/core/WordPress.php';
        require_once Config::$theme_dir . '/core/Route.php';
        require_once Config::$theme_dir . '/core/Options.php';
        require_once Config::$theme_dir . '/core/Ajax.php';
        require_once Config::$theme_dir . '/core/Template.php';
        require_once Config::$theme_dir . '/core/Optimize.php';
        require_once Config::$theme_dir . '/core/ShortCode.php';
        require_once Config::$theme_dir . '/core/auth/QQ.php';

        Ajax::init();
        global $core_next_set, $core_next_expand_set;
        $core_next_set = Options::getOptions();
        $core_next_expand_set = Options::getExpandOptions();
        if ($core_next_set['force_ssl']) {
            Config::$theme_url = str_replace('http://', 'https://', get_template_directory_uri());
        }
        add_action('admin_enqueue_scripts', array(static::class, '_LoadFileOnAdmin'));
        add_action('wp_enqueue_scripts', array(static::class, '_LoadFileOnSite'));

        add_action('admin_footer', function () {
            ?>
            <script>
                jQuery.post(core_next.ajax_url, {action: core_next.ajax_name, fun: 'checkUpdate'})
            </script>
            <?php
        });
        Optimize::init();
        Theme::init();
        ShortCode::init();
        self::insertCode();
    }


    static function insertCode()
    {
        global $core_next_set;
        add_action('wp_footer', function () use ($core_next_set) {
            print_r($core_next_set['footer_code']);
            print_r("<style>{$core_next_set['custom_css']}</style>");
        });
        add_action('wp_head', function () use ($core_next_set) {
            print_r($core_next_set['head_code']);
        });
    }

    static function _LoadFileOnSite()
    {
        global $core_next_set;
        WordPress::loadVue();
        WordPress::loadElementUI();
        WordPress::loadStrawberryIcon();
        WordPress::loadJQuery();

        wp_localize_script('vue2', Config::$theme_name, Options::getFrontOptions());

        WordPress::loadJS('core_next_global', 'global.min.js', true, [], true);
        WordPress::loadCss('core_next', 'main.css');
        if ($core_next_set['icon_font_js_url'] != '') {
            WordPress::loadJS('icon-front', $core_next_set['icon_font_js_url'], false);
        }
        if (is_home() || is_404()) {
            wp_enqueue_script('swiper', Config::$static_url . "/lib/swiper/swiper.min.js");
            WordPress::loadJS('core_next_home', 'home.min.js', true, [], true);
        } else if (is_single() || is_page()) {
            WordPress::loadJS('core_next_single_page', 'single-page.min.js', true, [], true);
            WordPress::loadJS('html2canvas', 'html2canvas.min.js', true, [], true);
            if ($core_next_set['single_code_highlight_open']) {
                WordPress::loadHighlight($core_next_set['single_code_highlight_theme']);
            }
        } else if (is_author()) {
            WordPress::loadVueRouter();
            WordPress::loadJS('core_next_author', 'author.min.js', true, [], true);

        } else if (is_archive()) {
            WordPress::loadJS('core_next_single_page', 'archive.min.js', true, [], true);
        } else if (is_search()) {
            WordPress::loadJS('core_next_single_page', 'search.min.js', true, [], true);
        }

        if (is_child_theme()) {
            //css加载
            $files = scandir(Config::$child_theme_path . '/css');
            foreach ($files as $file) {
                // 排除当前目录（.）和上级目录（..）
                if ($file != '.' && $file != '..') {
                    $file_info = pathinfo($file);
                    $file_extension = $file_info['extension'];
                    if ($file_extension === 'css') {
                        WordPress::loadCss("core_next_child_{$file_info['filename']}", Config::$child_theme_url . "/css/{$file}", false);
                    }
                }
            }
            //JS加载
            $files = scandir(Config::$child_theme_path . '/js');
            foreach ($files as $file) {
                if ($file != '.' && $file != '..') {
                    $file_info = pathinfo($file);
                    $file_extension = $file_info['extension'];
                    if ($file_extension === 'js') {
                        WordPress::loadJS("core_next_child_{$file_info['filename']}", Config::$child_theme_url . "/js/{$file}", false);
                    }
                }
            }
        }

        add_action('wp_footer', [static::class, 'echoCustomTheme']);
        add_action('wp_footer', [static::class, 'customFont']);
        //add_action('wp_footer', [static::class, 'addMoreFunction']);
    }


    static function customFont()
    {
        global $core_next_set;
        if ($core_next_set['font_name'] === 'default') {
            return;
        }
        $font = $core_next_set['font_name'];
        if ($font === 'NotoSansSC') {
            echo '<link rel="preconnect" href="https://fonts.googleapis.com/" />';
            echo '<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Noto+Sans+SC&display=swap" media="print" onload="this.media=\'all\'">';
            echo "<style>body {font-family: 'Noto Sans SC', system-ui;}</style>";
        }
        if ($font === 'HarmonyOS_Regular') {
            ?>
            <link rel="preconnect" href="https://s1.hdslb.com/"/>
            <link rel="stylesheet" href="//s1.hdslb.com/bfs/static/jinkela/long/font/regular.css" media="all"
                  onload="this.media='all'"/>
            <style>
                body {
                    font-family: 'HarmonyOS_Regular', system-ui;
                }
            </style>
            <?php
        }
        if ($font === 'HarmonyOS_Medium') {
            ?>
            <link rel="preconnect" href="https://s1.hdslb.com/">
            <link rel="stylesheet" href="//s1.hdslb.com/bfs/static/jinkela/long/font/medium.css" media="all"
                  onload="this.media='all'">
            <style>
                body {
                    font-family: 'HarmonyOS_Medium', system-ui;
                }
            </style>
            <?php
        }
        if ($font === 'MiSans') {
            ?>
            <link rel="stylesheet"
                  href="https://font.sec.miui.com/font/css?family=MiSans:400,500,700:Chinese_Simplify,Latin&display=swap"
                  media="all" onload="this.media='all'"/>
            <style>
                body {
                    font-family: 'MiSans', system-ui;
                }
            </style>
            <?php
        }
        if ($font === 'DFPKingGothicGB-Regular') {
            ?>
            <link rel="stylesheet"
                  href="https://fonts.bytedance.com/dfd/api/v1/css?family=DFPKingGothicGB-Regular&display=swap"
                  media="all" onload="this.media='all'"/>
            <style>
                body {
                    font-family: 'DFPKingGothicGB-Regular', system-ui;
                }
            </style>
            <?php
        }
        if ($font === 'DFPKingGothicGB-medium') {
            ?>
            <link rel="stylesheet"
                  href="https://fonts.bytedance.com/dfd/api/v1/css?family=DFPKingGothicGB-medium&display=swap"
                  media="all" onload="this.media='all'"/>
            <style>
                body {
                    font-family: 'DFPKingGothicGB-medium', system-ui;
                }
            </style>
            <?php
        }
        if ($font === 'DingTalkJinBuTi-Regular') {
            ?>
            <style>
                @font-face {
                    font-family: DingTalkJinBuTi-Regular;
                    font-display: swap;
                    src: url(https://puhuiti.oss-cn-hangzhou.aliyuncs.com/DingTalkJinBuTi/DingTalkJinBuTi-Regular/DingTalkJinBuTi-Regular.eot) format('embedded-opentype'),
                    url(https://puhuiti.oss-cn-hangzhou.aliyuncs.com/DingTalkJinBuTi/DingTalkJinBuTi-Regular/DingTalkJinBuTi-Regular.otf) format('opentype'),
                    url(https://puhuiti.oss-cn-hangzhou.aliyuncs.com/DingTalkJinBuTi/DingTalkJinBuTi-Regular/DingTalkJinBuTi-Regular.ttf) format('TrueType'),
                    url(https://puhuiti.oss-cn-hangzhou.aliyuncs.com/DingTalkJinBuTi/DingTalkJinBuTi-Regular/DingTalkJinBuTi-Regular.woff) format('woff'),
                    url(https://puhuiti.oss-cn-hangzhou.aliyuncs.com/DingTalkJinBuTi/DingTalkJinBuTi-Regular/DingTalkJinBuTi-Regular.woff2) format('woff2');
                }

                body {
                    font-family: 'DingTalkJinBuTi-Regular', system-ui;
                }
            </style>
            <?php
        }
        if ($font === 'LXGW_WenKai') {
            ?>
            <link rel="stylesheet"
                  href="https://cdn.staticfile.org/lxgw-wenkai-screen-webfont/1.6.0/lxgwwenkaiscreen.css"
                  media="all" onload="this.media='all'"/>
            <style>
                body {
                    font-family: 'LXGW WenKai Screen', system-ui;
                }
            </style>
            <?php
        }
    }

    static function echoCustomTheme()
    {
        global $core_next_set;
        $style = [];
        if ($core_next_set['post_img_shadow'] === true) {
            $style[] = '.content-warp img:not(.not-shadow){box-shadow: 0 0 5px 0 rgba(0, 0, 0, .1);}';
        }

        if ($core_next_set['background_image'] !== '') {
            if ($core_next_set['background_image_type'] === 'repeat') {
                $background_image_type = '';
            } else {
                $background_image_type = 'background-repeat: no-repeat;background-size: cover;';
            }
            echo "<script>const newDiv = document.createElement('div');newDiv.className = 'body-img';document.getElementById('core-next-app').appendChild(newDiv);</script>";
            $style[] = ".body-img{background-image:url('" . $core_next_set['background_image'] . "');$background_image_type";
        }
        $css['theme_main_color'] = $core_next_set['theme_main_color'];
        $css['box_border_radius'] = $core_next_set['box_border_radius'];
        $css['text_select_color'] = $core_next_set['text_select_color'];
        echo Template::getTemplateHtml('theme-style', $css);
        ?>
        <style>
            <?php
            foreach ($style as $item){
                print_r($item);
            }
            ?>
        </style>
        <?php
        //dark
        if (Theme::isDark()) {
            $dark_css = Config::$css_url . "/dark.css?v=" . Config::$theme_version;
            echo '<link rel="stylesheet" href="' . $dark_css . '" id="dark-css">';

        }
    }

    static function _LoadFileOnAdmin($hook)
    {
        WordPress::loadCss('core_next_admin', 'admin.css');
        wp_localize_script('jquery', Config::$theme_name, Options::getAdminOptions());
        if ($hook == 'post-new.php' || $hook == 'post.php') {
            WordPress::loadVue();
            WordPress::loadElementUI();
            WordPress::loadJS('core_next_post_meta', 'post-meta.min.js', true, [], true);
            WordPress::loadJS('core-next-editor', 'editor.min.js', true, ['jquery'], true);
            wp_enqueue_script('layer', Config::$lib_url . "/layer/layer.js");
        } elseif ($hook === 'widgets.php') {
            WordPress::loadCss('core_next_widgets', 'admin-widgets.css');
            WordPress::loadJS('core_next_admin_widget', 'admin-widget.js', true, [], true);
        } elseif ($hook === '%e4%b8%bb%e9%a2%98%e8%ae%be%e7%bd%ae_page_core_update') {
            WordPress::loadVue();
            WordPress::loadElementUI();
            WordPress::loadJS('core_next_update', 'page-update.min.js', true, [], true);
        }


    }
}

LoadFiles::init();