<?php
// 安全设置--------------------------boxmoe.com--------------------------
if(!defined('ABSPATH')){
    echo'Look your sister';
    exit;
}

// 设置菜单--------------------------boxmoe.com--------------------------
function boxmoe_options_menu_filter($menu) {
	$menu['mode'] = 'menu';
	$menu['page_title'] = 'Boxmoe主题设置';
	$menu['menu_title'] = 'Boxmoe主题设置';
	$menu['menu_slug'] = 'boxmoe-options';
	$menu['icon_url'] = 'dashicons-admin-generic';
	$menu['position'] = '61';
	return $menu;
}
add_filter('optionsframework_menu', 'boxmoe_options_menu_filter');

//编辑器TinyMCE增强
function enable_more_buttons($buttons)
{
	$buttons[] = 'boxmoe_emoji';
	$buttons[] = 'boxmoe_clearformat';
	$buttons[] = 'hr';
	$buttons[] = 'del';
	$buttons[] = 'sub';
	$buttons[] = 'sup';
	$buttons[] = 'fontselect';
	$buttons[] = 'fontsizeselect';
	$buttons[] = 'cleanup';
	$buttons[] = 'styleselect';
	$buttons[] = 'wp_page';
	$buttons[] = 'anchor';
	$buttons[] = 'backcolor';
	return $buttons;
}
add_filter("mce_buttons", "enable_more_buttons");

// 添加自定义表情按钮
function add_boxmoe_emoji_button($plugins) {
	$plugins['boxmoe_emoji'] = get_template_directory_uri() . '/assets/js/tinymce-emoji.js';
	return $plugins;
}
add_filter('mce_external_plugins', 'add_boxmoe_emoji_button');
function add_boxmoe_clearformat_button($plugins) {
    $plugins['boxmoe_clearformat'] = get_template_directory_uri() . '/assets/js/tinymce-clear-format.js';
    $plugins['boxmoe_precode_paste'] = get_template_directory_uri() . '/assets/js/tinymce-precode-paste.js';
    return $plugins;
}
add_filter('mce_external_plugins', 'add_boxmoe_clearformat_button');
function boxmoe_tinymce_emoji($init) {
	$emoji_list = array(
		'😀' => '笑脸',
		'😂' => '笑哭',
		'😍' => '爱心眼',
		'🤔' => '思考',
		'😊' => '害羞',
		'👍' => '点赞',
		'🎉' => '庆祝',
		'❤️' => '红心',
		'😎' => '酷',
		'😴' => '睡觉',
		'😭' => '大哭',
		'😡' => '生气',
		'🤮' => '呕吐',
		'🥳' => '派对',
		'😱' => '惊恐',
		'🤣' => '笑倒',
		'🥰' => '喜欢',
		'😇' => '天使',
		'🤩' => '星星眼',
		'🤪' => '搞怪'
	);	
	$init['boxmoe_emoji_list'] = json_encode($emoji_list, JSON_HEX_QUOT | JSON_HEX_TAG | JSON_UNESCAPED_UNICODE);
	return $init;
}
add_filter('tiny_mce_before_init', 'boxmoe_tinymce_emoji');

// 添加HTML编辑器表情按钮
function boxmoe_html_editor_emoji() {
	echo '<div class="quicktags-toolbar-emoji">
		<strong>表情：</strong>
		<button type="button" class="emoji-btn" data-emoji="😀" title="笑脸">😀</button>
		<button type="button" class="emoji-btn" data-emoji="😂" title="笑哭">😂</button>
		<button type="button" class="emoji-btn" data-emoji="😍" title="爱心眼">😍</button>
		<button type="button" class="emoji-btn" data-emoji="🤔" title="思考">🤔</button>
		<button type="button" class="emoji-btn" data-emoji="😊" title="害羞">😊</button>
		<button type="button" class="emoji-btn" data-emoji="👍" title="点赞">👍</button>
		<button type="button" class="emoji-btn" data-emoji="🎉" title="庆祝">🎉</button>
		<button type="button" class="emoji-btn" data-emoji="❤️" title="红心">❤️</button>
		<button type="button" class="emoji-btn" data-emoji="😎" title="酷">😎</button>
		<button type="button" class="emoji-btn" data-emoji="😴" title="睡觉">😴</button>
		<button type="button" class="emoji-btn" data-emoji="😭" title="大哭">😭</button>
		<button type="button" class="emoji-btn" data-emoji="😡" title="生气">😡</button>
		<button type="button" class="emoji-btn" data-emoji="🤮" title="呕吐">🤮</button>
		<button type="button" class="emoji-btn" data-emoji="🥳" title="派对">🥳</button>
		<button type="button" class="emoji-btn" data-emoji="😱" title="惊恐">😱</button>
		<button type="button" class="emoji-btn" data-emoji="🤣" title="笑倒">🤣</button>
		<button type="button" class="emoji-btn" data-emoji="🥰" title="喜欢">🥰</button>
		<button type="button" class="emoji-btn" data-emoji="😇" title="天使">😇</button>
		<button type="button" class="emoji-btn" data-emoji="🤩" title="星星眼">🤩</button>
		<button type="button" class="emoji-btn" data-emoji="🤪" title="搞怪">🤪</button>
	</div>
	<style>
.quicktags-toolbar-emoji{background:#f5f5f5;padding:5px;border-radius:3px;margin:5px 0;position:relative;z-index:100;clear:both;display:block;}.emoji-btn{padding:4px 8px;margin:0 2px;border:1px solid #ddd;background:#fff;border-radius:3px;cursor:pointer;}.emoji-btn:hover{background:#f0f0f0;}#wp-content-editor-container{margin-top:5px;}
	</style>
	<script>
		jQuery(document).ready(function($) {
			var $toolbar = $(".quicktags-toolbar-emoji");
			var $editorToolbar = $("#wp-content-editor-tools");
			if($editorToolbar.length) {
				$toolbar.insertAfter($editorToolbar);
			}
			
			$(".emoji-btn").click(function() {
				var emoji = $(this).data("emoji");
				var textarea = $("#content");
				var caretPos = textarea[0].selectionStart;
				var textAreaTxt = textarea.val();
				textarea.val(textAreaTxt.substring(0, caretPos) + emoji + textAreaTxt.substring(caretPos));
			});
		});
	</script>';
}
add_action('edit_form_after_title', 'boxmoe_html_editor_emoji');

// 评论回复编辑器上添加表情按钮
function add_comment_emoji_buttons() {
    $screen = get_current_screen();
    if ($screen->id !== 'edit-comments') {
        return;
    }
    echo '<div class="quicktags-toolbar-emoji comment-emoji-toolbar">
        <strong>表情：</strong>
        <button type="button" class="emoji-btn" data-emoji="😀" title="笑脸">😀</button>
        <button type="button" class="emoji-btn" data-emoji="😂" title="笑哭">😂</button>
        <button type="button" class="emoji-btn" data-emoji="😍" title="爱心眼">😍</button>
        <button type="button" class="emoji-btn" data-emoji="🤔" title="思考">🤔</button>
        <button type="button" class="emoji-btn" data-emoji="😊" title="害羞">😊</button>
        <button type="button" class="emoji-btn" data-emoji="👍" title="点赞">👍</button>
        <button type="button" class="emoji-btn" data-emoji="🎉" title="庆祝">🎉</button>
        <button type="button" class="emoji-btn" data-emoji="❤️" title="红心">❤️</button>
        <button type="button" class="emoji-btn" data-emoji="😎" title="酷">😎</button>
        <button type="button" class="emoji-btn" data-emoji="😴" title="睡觉">😴</button>
        <button type="button" class="emoji-btn" data-emoji="😭" title="大哭">😭</button>
        <button type="button" class="emoji-btn" data-emoji="😡" title="生气">😡</button>
        <button type="button" class="emoji-btn" data-emoji="🤮" title="呕吐">🤮</button>
        <button type="button" class="emoji-btn" data-emoji="🥳" title="派对">🥳</button>
        <button type="button" class="emoji-btn" data-emoji="😱" title="惊恐">😱</button>
        <button type="button" class="emoji-btn" data-emoji="🤣" title="笑倒">🤣</button>
        <button type="button" class="emoji-btn" data-emoji="🥰" title="喜欢">🥰</button>
        <button type="button" class="emoji-btn" data-emoji="😇" title="天使">😇</button>
        <button type="button" class="emoji-btn" data-emoji="🤩" title="星星眼">🤩</button>
        <button type="button" class="emoji-btn" data-emoji="🤪" title="搞怪">🤪</button>
    </div>
    <style>
.comment-emoji-toolbar{margin:5px 0;padding:5px;background:#f5f5f5;border-radius:3px;}.comment-emoji-toolbar .emoji-btn{padding:4px 8px;margin:0 2px;border:1px solid #ddd;background:#fff;border-radius:3px;cursor:pointer;}.comment-emoji-toolbar .emoji-btn:hover{background:#f0f0f0;}
    </style>
    <script>
        jQuery(document).ready(function($) {
            initEmojiButtons();        
            $(document).on("click", ".reply", function() {
                setTimeout(function() {
                    var $replyRow = $("#replyrow");
                    if ($replyRow.find(".comment-emoji-toolbar").length === 0) {
                        var $toolbar = $(".comment-emoji-toolbar").first().clone();
                        $replyRow.find("#replycontainer").prepend($toolbar);
                        initEmojiButtons();
                    }
                }, 100);
            });        
            function initEmojiButtons() {
                $(".comment-emoji-toolbar .emoji-btn").off("click").on("click", function() {
                    var emoji = $(this).data("emoji");
                    var $textarea = $(this).closest("tr, #replyrow").find("textarea");
                    var caretPos = $textarea[0].selectionStart;
                    var textAreaTxt = $textarea.val();
                    $textarea.val(textAreaTxt.substring(0, caretPos) + emoji + textAreaTxt.substring(caretPos));
                });
            }
        });
    </script>';
}
add_action('admin_footer', 'add_comment_emoji_buttons');

function boxmoe_admin_style() {
    echo '<style>
		.avatar{width:60px;height:60px;}.comment-emoji-toolbar{margin-bottom:10px;}.quicktags-toolbar input[type="button"]{margin:2px !important;padding:2px 8px !important;border-radius:3px !important;border:1px solid #ddd !important;background:#f7f7f7 !important;color:#666 !important;transition:all 0.3s ease;}.quicktags-toolbar input[type="button"]:hover{background:#0073aa !important;color:#fff !important;border-color:#006799 !important;}.quicktags-toolbar input[type="button"] i{margin-right:4px;}
    </style>';
}
add_action('admin_head', 'boxmoe_admin_style');

function example_footer_admin () {
	echo '<span id="footer-thankyou">感谢使用<a target="_blank" href="https://cn.wordpress.org/">WordPress</a>进行创作。Theme by <a target="_blank" href="https://www.boxmoe.com/" style="color:red;">Lolimeow</a></span> ';
	}
	add_filter('admin_footer_text', 'example_footer_admin');

function customize_login_logo(){         
echo '<style type="text/css">
.login{display:flex;min-height:100vh;justify-content:center;align-items:center;background:linear-gradient(-45deg,#ee7752,#e73c7e,#23a6d5,#23d5ab);background-size:400% 400%;animation:gradient 15s ease infinite;}@keyframes gradient{0%{background-position:0% 50%;}50%{background-position:100% 50%;}100%{background-position:0% 50%;}}#login{background:rgba(255,255,255,0.9);padding:40px 30px;border-radius:15px;box-shadow:0 0 20px rgba(0,0,0,0.1);width:350px;}@media (max-width:768px){#login{background:transparent;box-shadow:none;}}.login h1 a{background-image:url('.get_template_directory_uri() .'/assets/images/logo.png);width:180px;height:80px;margin:0 auto 20px;background-size:contain;background-repeat:no-repeat;background-position:center center;}.login form{background:transparent !important;padding:0 !important;border:none !important;box-shadow:none !important;}.login input[type="text"],.login input[type="password"]{border-radius:5px;border:1px solid #ddd;padding:10px;margin-bottom:15px;}.wp-core-ui .button-primary{background:#23a6d5;border:none;border-radius:5px;padding:5px 20px;height:auto;transition:all 0.3s ease;}.wp-core-ui .button-primary:hover{background:#1e8ab0;}.language-switcher{display:none;}
</style>';   
}  
add_action('login_head', 'customize_login_logo'); 	

function boxmoe_admin_favicon(){
    $src = get_boxmoe('boxmoe_favicon_src');
    if(!$src){
        $src = boxmoe_theme_url().'/assets/images/favicon.ico';
    }
    echo '<link rel="icon" href="'.esc_url($src).'" type="image/x-icon">';
}
add_action('admin_head', 'boxmoe_admin_favicon', 1);
add_action('login_head', 'boxmoe_admin_favicon', 1);

function boxmoe_admin_logo_sync_favicon(){
    $src = get_boxmoe('boxmoe_favicon_src');
    if(!$src){
        $src = boxmoe_theme_url().'/assets/images/favicon.ico';
    }
    echo '<style>#wpadminbar #wp-admin-bar-wp-logo > .ab-item .ab-icon:before{content:"" !important}#wpadminbar #wp-admin-bar-wp-logo > .ab-item .ab-icon{background-image:url(' . esc_url($src) . ') !important;background-size:contain !important;background-repeat:no-repeat !important;width:20px !important;height:20px !important;top:2px !important}</style>';
}
add_action('admin_head', 'boxmoe_admin_logo_sync_favicon', 11);

function boxmoe_admin_scrollbar_style(){
    echo '<style>
    *::-webkit-scrollbar{height:10px;width:10px}
    *::-webkit-scrollbar-track{border-radius:5px;background-color:#DFE9EB}
    *::-webkit-scrollbar-thumb{border-radius:10px;background:linear-gradient(180deg,#F472B6,#FB923C,#22D3EE);background-clip:padding-box;border:2px solid transparent}
    *{scrollbar-color:#F472B6 #DFE9EB;scrollbar-width:auto}
    @media (prefers-color-scheme: dark){
      *::-webkit-scrollbar-track{background-color:#2b2b2b}
      *::-webkit-scrollbar-thumb{background:linear-gradient(180deg,#7C3AED,#60A5FA,#F472B6);background-clip:padding-box;border:2px solid transparent}
      *{scrollbar-color:#7C3AED #2b2b2b}
    }
    </style>';
}
add_action('admin_head', 'boxmoe_admin_scrollbar_style', 20);
add_action('login_head', 'boxmoe_admin_scrollbar_style', 20);

// 👤 后台个人资料自定义头像字段
function boxmoe_admin_user_avatar_field($user) {
    wp_nonce_field('boxmoe_admin_avatar_nonce', 'boxmoe_admin_avatar_nonce_field'); // ⬅️ 保存时校验安全性
    $current = get_user_meta($user->ID, 'user_avatar', true); // ⬅️ 当前已设置的自定义头像地址
    $preview = $current ? esc_url($current) : esc_url(boxmoe_get_avatar_url($user->ID, 96)); // ⬅️ 优先自定义头像，否则使用统一策略的头像
    $default = esc_url(boxmoe_default_avatar_url()); // ⬅️ 主题默认头像地址
    echo '<h2>自定义头像</h2>';
    echo '<table class="form-table"><tr><th><label for="boxmoe_user_avatar">头像</label></th><td>';
    echo '<img id="boxmoe-user-avatar-preview" src="' . $preview . '" data-default="' . $default . '" class="avatar" alt="avatar" style="width:96px;height:96px;border-radius:50%;object-fit:cover;" />'; // ⬅️ 头像预览
    echo '<input type="hidden" name="boxmoe_user_avatar" id="boxmoe-user-avatar" value="' . esc_attr($current) . '" />'; // ⬅️ 隐藏字段保存 URL
    echo '<p class="description">支持媒体库选择或上传图片，建议正方形 96×96 以上</p>';
    echo '<p><button type="button" class="button" id="boxmoe-upload-avatar">选择或上传头像</button> '; // ⬅️ 打开媒体库选择
    echo '<button type="button" class="button" id="boxmoe-remove-avatar">移除自定义头像</button> ';
    echo '<button type="button" class="button" id="boxmoe-reset-avatar">重置为默认头像</button></p>'; // ⬅️ 设置为主题默认头像
    echo '</td></tr></table>';

    echo '<script>jQuery(function($){
        var frame;
        $("#boxmoe-upload-avatar").on("click", function(e){
            e.preventDefault();
            if(frame){ frame.open(); return; }
            frame = wp.media({ title: "选择或上传头像", button: { text: "使用此图片" }, multiple: false });
            frame.on("select", function(){
                var attachment = frame.state().get("selection").first().toJSON();
                $("#boxmoe-user-avatar").val(attachment.url); // ⬅️ 写入选中图片 URL
                $("#boxmoe-user-avatar-preview").attr("src", attachment.url); // ⬅️ 更新预览
            });
            frame.open();
        });
        $("#boxmoe-remove-avatar").on("click", function(){
            $("#boxmoe-user-avatar").val(""); // ⬅️ 清空自定义头像 URL
            var fallback = $("#boxmoe-user-avatar-preview").data("default");
            $("#boxmoe-user-avatar-preview").attr("src", fallback); // ⬅️ 恢复为默认预览
        });
        $("#boxmoe-reset-avatar").on("click", function(){
            var def = $("#boxmoe-user-avatar-preview").data("default");
            $("#boxmoe-user-avatar").val(def); // ⬅️ 直接设置为主题默认头像 URL
            $("#boxmoe-user-avatar-preview").attr("src", def); // ⬅️ 预览更新为默认
        });
    });</script>'; // ⬅️ 绑定媒体选择与移除逻辑
}
add_action('show_user_profile', 'boxmoe_admin_user_avatar_field'); // ⬅️ 自己的资料页显示
add_action('edit_user_profile', 'boxmoe_admin_user_avatar_field'); // ⬅️ 管理员编辑其他用户时显示

// 🛡️ 后台个人资料保存自定义头像
function boxmoe_admin_user_avatar_save($user_id){
    if (!current_user_can('edit_user', $user_id)) { return; } // ⬅️ 权限校验
    if (!isset($_POST['boxmoe_admin_avatar_nonce_field']) || !wp_verify_nonce($_POST['boxmoe_admin_avatar_nonce_field'], 'boxmoe_admin_avatar_nonce')) { return; } // ⬅️ nonce 校验
    $url = isset($_POST['boxmoe_user_avatar']) ? esc_url_raw($_POST['boxmoe_user_avatar']) : '';
    if ($url) {
        update_user_meta($user_id, 'user_avatar', $url); // ⬅️ 保存自定义头像 URL
    } else {
        delete_user_meta($user_id, 'user_avatar'); // ⬅️ 清除自定义头像，前端将回落到本地默认头像/QQ 头像
    }
}
add_action('personal_options_update', 'boxmoe_admin_user_avatar_save'); // ⬅️ 保存自己的资料
add_action('edit_user_profile_update', 'boxmoe_admin_user_avatar_save'); // ⬅️ 管理员保存他人资料

// 🔗 后台加载媒体库脚本
function boxmoe_admin_profile_enqueue($hook){
    if ($hook === 'profile.php' || $hook === 'user-edit.php') {
        wp_enqueue_media(); // ⬅️ 加载 WP 媒体库
    }
}
add_action('admin_enqueue_scripts', 'boxmoe_admin_profile_enqueue');

function boxmoe_admin_flat_rounded_enqueue($hook){
    wp_enqueue_style('lolimeow-admin-flat-rounded', get_template_directory_uri() . '/assets/css/admin-flat-rounded.css', array(), '1.0');
}
add_action('admin_enqueue_scripts', 'boxmoe_admin_flat_rounded_enqueue');

function boxmoe_admin_view_links_newtab_enqueue($hook){
    wp_enqueue_script('boxmoe-admin-view-newtab', get_template_directory_uri() . '/assets/js/admin-view-newtab.js', array(), THEME_VERSION, true);
}
add_action('admin_enqueue_scripts', 'boxmoe_admin_view_links_newtab_enqueue');
function boxmoe_admin_clear_format_scripts($hook){
	if ($hook === 'post.php' || $hook === 'post-new.php') {
		wp_enqueue_script('boxmoe-clear-format-quicktags', get_template_directory_uri() . '/assets/js/clear-format-quicktags.js', array('quicktags'), THEME_VERSION, true);
	}
}
add_action('admin_enqueue_scripts', 'boxmoe_admin_clear_format_scripts');

function boxmoe_adminbar_viewsite_newtab($wp_admin_bar){
    $node = $wp_admin_bar->get_node('view-site');
    if ($node) {
        $node->meta['target'] = '_blank';
        $node->meta['rel'] = 'noopener noreferrer';
        $wp_admin_bar->add_node($node);
    }
    $site = $wp_admin_bar->get_node('site-name');
    if ($site) {
        $site->meta['target'] = '_blank';
        $site->meta['rel'] = 'noopener noreferrer';
        $wp_admin_bar->add_node($site);
    }
}
add_action('admin_bar_menu', 'boxmoe_adminbar_viewsite_newtab', 100);

function boxmoe_adminbar_wp_logo_to_favicon($wp_admin_bar){
    $src = get_boxmoe('boxmoe_favicon_src');
    if(!$src){
        $src = boxmoe_theme_url().'/assets/images/favicon.ico';
    }
    $logo = $wp_admin_bar->get_node('wp-logo');
    if($logo){
        $logo->title = '<img src="'.esc_url($src).'" alt="favicon" style="width:20px;height:20px;display:inline-block;vertical-align:middle;border-radius:3px;" />';
        $wp_admin_bar->add_node($logo);
    }
}
add_action('admin_bar_menu', 'boxmoe_adminbar_wp_logo_to_favicon', 50);
function boxmoe_adminbar_new_post_newtab($wp_admin_bar){
    $node = $wp_admin_bar->get_node('new-post');
    if ($node) {
        $node->meta['target'] = '_blank';
        $node->meta['rel'] = 'noopener noreferrer';
        $wp_admin_bar->add_node($node);
    }
}
add_action('admin_bar_menu', 'boxmoe_adminbar_new_post_newtab', 100);
