
/*
Plugin Name: wuchai-code-editor&吾侪代码编辑器
Description: 一个转移文章作者评论到其他地方的插件。显示最新一条评论内容，其余折叠起来。且简单地显示日期和内容。
Plugin URI: http://wuchai.net/plugins/
Version: 1.0
Author: 吾侪主题&易西
Author URI:http://wuchai.net/
Update URI: http://mirror.wuchai.net/wuchai/wordpress/plugins/wuchai-code-editor/latest/latest.zip
Textdomain: wuchai-code-editor&
License: GPLv2
Version: 1.0.0
*/




// 安全检测
defined('ABSPATH') || exit;


class Advanced_Comments_Manager {

private static $instance;

// 菜单slug
private $menu_slug = 'acs-comments';

public static function get_instance() {
    if (!isset(self::$instance)) {
        self::$instance = new self();
    }
    return self::$instance;
}

private function __construct() {
    // 初始化钩子
    add_action('admin_menu', [$this, 'setup_admin_menus']);
    add_action('admin_init', [$this, 'register_settings']);
    //add_action('admin_init', [$this, 'register_update']);
    add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
    
    // 短代码注册
    add_shortcode('display_comments', [$this, 'render_comments_shortcode']);
    
    // 插件设置链接
    add_filter('plugin_action_links', [$this, 'add_settings_link'], 10, 2);
}


public function init_plugin() {
        // 加载翻译文件
        load_plugin_textdomain('modular-plugin', false, dirname(plugin_basename(__FILE__)) . '/languages/');
        
        // 注册核心功能
        add_action('admin_menu', [$this, 'register_admin_menus']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
        
        // 模块加载钩子
        do_action('modular_plugin_loaded', $this);
    }
    

// 设置管理菜单
public function setup_admin_menus() {
    // 主菜单
    add_menu_page(
        '转移评论管理',
        '转移评论',
        'manage_options',
        $this->menu_slug,
        [$this, 'render_dashboard'],
        //'dashicons-admin-comments'
        'dashicons-admin-plugins',
        26
    );
    
    // 子菜单项
    $submenus = [
        [
            'title' => '仪表盘',
            'slug' => $this->menu_slug,
            'callback' => 'render_dashboard'
        ],
        [
            'title' => '样式设置',
            'slug' => 'comments-style',
            'callback' => 'render_style_page'
        ],
        [
            'title' => '批量转移',
            'slug' => 'comments-transfer',
            'callback' => 'render_transfer_page'
        ],
        [
            'title' => '使用说明',
            'slug' => 'acs-comments-instructions',
            'callback' => 'render_instructions_page'
        ],
        [
            'title' => '在线更新',
            'slug' => 'acs-comments-update',
            'callback' => 'render_updates_page'
        ],  
        [
            'title' => '❤️ 捐赠',
            'slug' => 'plugin-donation',
            'callback' => 'render_donation_page'
        ],  
        [
            'title' => '插件中心',
            'slug' => 'custom-plugin-library',
            'callback' => 'render_librarys_page'
        ],
        
    ];
    
    foreach ($submenus as $submenu) {
        add_submenu_page(
            $this->menu_slug,
            $submenu['title'],
            $submenu['title'],
            'manage_options',
            $submenu['slug'],
            [$this, $submenu['callback']]
        );
    }
    //add_action('admin_menu', [$this, 'register_menus']);
}



// 加载管理页面资源
public function enqueue_admin_assets($hook) {
    if (strpos($hook, $this->menu_slug) !== false) {
        wp_enqueue_style(
            'acm-admin-css',
            plugins_url('assets/css/admin.css', __FILE__)
        );
        wp_enqueue_script(
            'acm-admin-js',
            plugins_url('assets/js/admin.js', __FILE__),
            ['jquery'],
            false,
            true
        );
    }
}

// 渲染Tab导航
private function render_tabs() {
    $current_page = $_GET['page'] ?? $this->menu_slug;
    
    $tabs = [
        $this->menu_slug => '仪表盘',
        'comments-style' => '样式设置',
        'comments-transfer' => '批量转移',
        'acs-comments-instructions' => '使用说明',
        'acs-comments-update' => '在线更新',
        //'custom-plugin-library' => '插件中心',
        'plugin-donation'=> '捐赠',
        'custom-plugin-library' => '插件中心'
    ];
    
    echo '<nav class="nav-tab-wrapper">';
    foreach ($tabs as $slug => $title) {
        $active = $current_page === $slug ? 'nav-tab-active' : '';
        $url = add_query_arg('page', $slug, admin_url('admin.php'));
        printf(
            '<a href="%s" class="nav-tab %s">%s</a>',
            esc_url($url),
            esc_attr($active),
            esc_html($title)
        );
    }
    echo '</nav>';
    
     // 渲染Tab内容
        echo '<div class="modular-plugin-tab-content">';
        do_action("modular_plugin_tab_{$current_tab}");
        echo '</div>';
        
        echo '</div>';
    
}

// 页面渲染方法
public function render_dashboard() {
    $this->render_tabs();
    $this->load_template('dashboard');
}

public function render_updates_page() {
    $this->render_tabs();
    $this->load_template('updates');
}

public function render_style_page() {
    $this->render_tabs();
    $this->load_template('style-settings');
}

public function render_transfer_page() {
    $this->render_tabs();
    $this->load_template('transfer-tool');
}

public function render_instructions_page() {
    $this->render_tabs();
    $this->load_template('instructions');
}

public function render_librarys_page() {
    $this->render_tabs();
    $this->load_template('librarys');
}

public function render_donation_page() {
    $this->render_tabs();
    $this->load_template('donation');
}



// 辅助方法
private function load_template($name) {
    $path = plugin_dir_path(__FILE__) . "templates/{$name}.php";
    if (file_exists($path)) {
        include $path;
    } else {
        echo '<div class="error"><p>模板文件缺失: ' . esc_html($name) . '</p></div>';
    }
}

// 短代码渲染
public function render_comments_shortcode($atts) {
    $atts = shortcode_atts([
        'limit' => 5,
        'type' => 'recent',
        'post_id' => null
    ], $atts);
    
    ob_start();
    $this->load_template('comments-display');
    return ob_get_clean();
}

// 添加设置链接
public function add_settings_link($links, $file) {
    if (plugin_basename(__FILE__) === $file) {
        $links[] = sprintf(
            '<a href="%s">%s</a>',
            esc_url(admin_url("admin.php?page={$this->menu_slug}")),
            '设置'
        );
    }
    return $links;
}

  // 模块注册方法
    public function register_module($module_slug, $module_class) {
        if (!isset($this->modules[$module_slug])) {
            $this->modules[$module_slug] = new $module_class();
            return true;
        }
        return false;
    }
    
}


// 初始化插件
Advanced_Comments_Manager::get_instance();



// 注册设置组和字段
//function register_comment_style_settings() {
  //  register_setting(
    //    'acs_comment_style_group',  // 设置组名称
      //  'acs_comment_style',        // 选项名
       // ['sanitize_callback' => 'sanitize_text_field'] // 验证回调
  //  );
//}
//add_action('admin_init', 'register_comment_style_settings');




function comment_stats_shortcode($atts = []) {
    // 合并默认参数
    $atts = shortcode_atts([
        'days' => 30,
        'limit' => 5,
        'show_chart' => true
    ], $atts);

    // 权限检查
    if (!current_user_can('edit_posts')) return;

    // 缓存处理
    $cache_key = 'comment_stats_' . md5(serialize($atts));
    if (false === ($output = get_transient($cache_key))) {
        ob_start();
        
        // 获取热门文章
        $posts = new WP_Query([
            'orderby' => 'comment_count',
            'date_query' => [['after' => $atts['days'] . ' days ago']],
            'posts_per_page' => $atts['limit'],
            'fields' => 'ids'
        ]);

        // 获取最新评论
        $comments = get_comments([
            'number' => $atts['limit'],
            'status' => 'approve'
        ]);

        // 输出HTML
        echo '<div class="comment-stats-container">';
        echo '<div class="stats-column">';
        echo '<h3>热门评论文章</h3>';
        foreach ($posts->posts as $post_id) {
            echo '<div class="stat-item">';
            echo '<a href="' . get_permalink($post_id) . '">' . get_the_title($post_id) . '</a>';
            echo '<span class="count">(' . get_comments_number($post_id) . '条)</span>';
            echo '</div>';
        }
        echo '</div>';

        echo '<div class="stats-column">';
        echo '<h3>最新评论</h3>';
        foreach ($comments as $comment) {
            echo '<div class="stat-item">';
            echo '<span class="author">' . esc_html($comment->comment_author) . ':</span>';
            echo '<span class="excerpt">' . esc_html(mb_substr($comment->comment_content, 0, 20)) . '...</span>';
            echo '</div>';
        }
        echo '</div>';

        if ($atts['show_chart']) {
            echo '<div class="stats-chart">';
            echo '<canvas id="commentStatsChart"></canvas>';
            echo '</div>';
        }

        echo '</div>';

        // 图表JS
        if ($atts['show_chart']) {
            echo '<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>';
            echo '<script>
            document.addEventListener("DOMContentLoaded", function() {
                new Chart(document.getElementById("commentStatsChart"), {
                    type: "bar",
                    data: {
                        labels: ["热门文章", "最新评论"],
                        datasets: [{
                            label: "评论统计",
                            data: [' . $posts->found_posts . ', ' . count($comments) . '],
                            backgroundColor: ["#4f46e5", "#10b981"]
                        }]
                    }
                });
            });
            </script>';
        }

        $output = ob_get_clean();
        set_transient($cache_key, $output, 15 * MINUTE_IN_SECONDS);
    }

    return $output;
}
add_shortcode('comment_stats', 'comment_stats_shortcode');

// 加载样式
function comment_stats_styles() {
    echo '<style>
    
/* 基础容器样式 */
.comment-stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
  margin: 2rem auto;
  max-width: 1200px;
  padding: 0 1rem;
}

/* 栏目卡片样式 */
.stats-column {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  padding: 1.75rem;
  border-radius: 12px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 
              0 2px 4px -1px rgba(0, 0, 0, 0.06);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  border: 1px solid rgba(226, 232, 240, 0.7);
}

.stats-column:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 
              0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

/* 标题样式 */
.stats-column h3 {
  color: #1e293b;
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 1.25rem;
  padding-bottom: 0.75rem;
  border-bottom: 2px solid #e2e8f0;
}

/* 条目样式 */
.stat-item {
  margin: 1rem 0;
  padding: 0.75rem;
  border-radius: 8px;
  transition: background-color 0.2s ease;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-item:hover {
  background-color: #f1f5f9;
}

/* 链接样式 */
.stat-item a {
  color: #3b82f6;
  text-decoration: none;
  font-weight: 500;
  flex-grow: 1;
  transition: color 0.2s ease;
}

.stat-item a:hover {
  color: #2563eb;
  text-decoration: underline;
}

/* 计数样式 */
.stat-item .count {
  background: #e0e7ff;
  color: #4f46e5;
  padding: 0.25rem 0.5rem;
  border-radius: 9999px;
  font-size: 0.875rem;
  font-weight: 500;
}

/* 作者样式 */
.stat-item .author {
  color: #64748b;
  font-weight: 500;
  margin-right: 0.5rem;
}

/* 摘要样式 */
.stat-item .excerpt {
  color: #475569;
  font-size: 0.9375rem;
  flex-grow: 1;
}

/* 图表容器 */
.stats-chart {
  grid-column: 1 / -1;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  padding: 1.75rem;
  border-radius: 12px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 
              0 2px 4px -1px rgba(0, 0, 0, 0.06);
  margin-top: 1rem;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .comment-stats-container {
    grid-template-columns: 1fr;
  }
  
  .stats-column {
    padding: 1.5rem;
  }
}
    </style>';
}
add_action('wp_head', 'comment_stats_styles');





/*
Description: 提供网站和服务器信息的短代码功能
*/
//前台调用：[server_info type="wp" format="list"]
//PHP调用：echo do_shortcode('[server_info]');

class WP_Server_Info_Viewer {
    public function __construct() {
        add_shortcode('server_info', [$this, 'render_server_info']);
        add_action('admin_menu', [$this, 'add_admin_page']);
    }

    // 获取WordPress信息
    private function get_wp_info() {
        global $wp_version;
        
        return [
            'WordPress版本' => $wp_version,
            '站点标题' => get_bloginfo('name'),
            '站点描述' => get_bloginfo('description'),
            '当前主题' => wp_get_theme()->get('Name'),
            '主题版本' => wp_get_theme()->get('Version'),
            '插件数量' => count(get_plugins()),
            '用户数量' => count(get_users()),
            '文章数量' => wp_count_posts()->publish,
            '页面数量' => wp_count_posts('page')->publish,
            '评论总数' => wp_count_comments()->total_comments
        ];
    }

    // 获取服务器信息
    private function get_server_info() {
        return [
            '服务器软件' => $_SERVER['SERVER_SOFTWARE'],
            'PHP版本' => phpversion(),
            'MySQL版本' => $this->get_mysql_version(),
            '服务器协议' => $_SERVER['SERVER_PROTOCOL'],
            '服务器名称' => $_SERVER['SERVER_NAME'],
            '服务器IP' => $_SERVER['SERVER_ADDR'],
            '服务器端口' => $_SERVER['SERVER_PORT'],
            '最大上传限制' => ini_get('upload_max_filesize'),
            '内存限制' => ini_get('memory_limit'),
            '时区设置' => date_default_timezone_get()
        ];
    }

    // 获取MySQL版本
    private function get_mysql_version() {
        global $wpdb;
        return $wpdb->get_var("SELECT VERSION()");
    }

    // 短代码处理函数
    public function render_server_info($atts) {
        $atts = shortcode_atts([
            'type' => 'all', // all/wp/server
            'format' => 'table' // table/list
        ], $atts);

        ob_start();
        
        if ($atts['type'] === 'all' || $atts['type'] === 'wp') {
            echo '<h3>WordPress信息</h3>';
            $this->display_info($this->get_wp_info(), $atts['format']);
        }
        
        if ($atts['type'] === 'all' || $atts['type'] === 'server') {
            echo '<h3>服务器信息</h3>';
            $this->display_info($this->get_server_info(), $atts['format']);
        }

        return ob_get_clean();
    }

    // 信息显示方法
    private function display_info($data, $format) {
        if ($format === 'table') {
            echo '<table class="wp-server-info-table"><tbody>';
            foreach ($data as $key => $value) {
                echo '<tr><th>'.esc_html($key).'</th><td>'.esc_html($value).'</td></tr>';
            }
            echo '</tbody></table>';
        } else {
            echo '<ul class="wp-server-info-list">';
            foreach ($data as $key => $value) {
                echo '<li><strong>'.esc_html($key).':</strong> '.esc_html($value).'</li>';
            }
            echo '</ul>';
        }
    }

    // 后台管理页面
    public function add_admin_page() {
        add_submenu_page(
            'tools.php',
            '服务器信息',
            '服务器信息',
            'manage_options',
            'server-info',
            [$this, 'render_admin_page']
        );
    }

    public function render_admin_page() {
        echo '<div class="wrap"><h1>WordPress服务器信息</h1>';
        echo do_shortcode('[server_info type="all"]');
        echo '<h3>短代码用法：</h3>';
        echo '<p><code>[server_info type="all|wp|server" format="table|list"]</code></p>';
        echo '<p>参数说明：type-信息类型(all全部/wp信息/server信息)，format-显示格式(table表格/list列表)</p>';
        echo '</div>';
    }
}

new WP_Server_Info_Viewer();








/*
Description: 提供文章ID查看的短代码功能
*/

//短代码调用
//[show_post_ids]
//前台调用：[show_post_ids limit="5" order="ASC"]
// PHP调用：php echo do_shortcode('[show_post_ids]'); 

class Enhanced_Post_ID_Viewer {
    public function __construct() {
        add_shortcode('show_post_ids', [$this, 'render_post_ids_table']);
        add_action('admin_menu', [$this, 'add_admin_page']);
    }

    // 短代码处理函数（带评论数量）
    public function render_post_ids_table($atts) {
        $atts = shortcode_atts([
            'limit' => 10,
            'order' => 'DESC',
            'show_comments' => true
        ], $atts);

        $posts = get_posts([
            'numberposts' => intval($atts['limit']),
            'orderby' => 'ID',
            'order' => $atts['order'],
            'post_status' => 'publish'
        ]);

        ob_start();
        echo '<div class="post-id-viewer">';
        echo '<table class="post-id-table"><thead><tr><th>ID</th><th>标题</th><th>日期</th><th>评论数</th></tr></thead><tbody>';
        
        foreach ($posts as $post) {
            $comment_count = get_comments_number($post->ID);
            echo sprintf(
                '<tr><td>%d</td><td><a href="%s">%s</a></td><td>%s</td><td>%d</td></tr>',
                $post->ID,
                get_permalink($post),
                esc_html($post->post_title),
                get_the_date('', $post),
                $comment_count
            );
        }
        
        echo '</tbody></table></div>';
        return ob_get_clean();
    }

    // 后台管理页面
    public function add_admin_page() {
        add_submenu_page(
            'tools.php',
            '文章ID查看器',
            '文章ID查看',
            'manage_options',
            'post-id-viewer',
            [$this, 'render_admin_page']
        );
    }

    public function render_admin_page() {
        echo '<div class="wrap"><h1>文章ID查看器</h1>';
        echo do_shortcode('[show_post_ids limit="50" show_comments="true"]');
        echo '<h3>短代码用法：</h3>';
        echo '<code>[show_post_ids limit="10" order="DESC" show_comments="true"]</code>';
        echo '<p>参数说明：limit-显示数量，order-排序方式，show_comments-是否显示评论数</p>';
        echo '</div>';
    }
}

new Enhanced_Post_ID_Viewer();



/**
  * Description: 提供可定制的评论显示样式
 */

class Advanced_Comments_Style {
    public function __construct() {
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'register_settings']);
        add_shortcode('acs_comment_style', [$this, 'render_comment_style']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_assets']);
    }

    // 添加管理菜单
   // public function add_admin_menu() {
     //   add_options_page(
       //     '样式设置',
         //   '评论样式',
          //  'manage_options',
          //  'comments-style',
         //   [$this, 'render_settings_page']
      //  );
   // }
    
    
public function add_admin_menu() {
    add_submenu_page(
        $this->menu_slug, // 父菜单slug（评论管理页面）
        '样式设置',
        '样式设置',
        'manage_options',
        'comments-style',
        [$this, 'render_settings_page']
    );
}

    // 注册设置选项
    public function register_settings() {
        register_setting(
            'advanced_comments_style',
            'comments_style_settings',
            [$this, 'sanitize_settings']
        );

        add_settings_section(
            'style_section',
            '评论显示样式',
            [$this, 'render_style_section'],
            'comments-style'
        );

        $fields = [
            'highlight_color' => '高亮颜色',
            'font_size' => '字体大小',
            'border_style' => '边框样式',
            'custom_css' => '自定义CSS'
        ];

        foreach ($fields as $id => $title) {
            add_settings_field(
                $id,
                $title,
                [$this, 'render_settings_field'],
                'comments-style',
                'style_section',
                ['name' => $id]
            );
        }
    }

    // 渲染设置页面
    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1>样式设置</h1>
            <form method="post" action="options.php">
                <?php
                settings_fields('advanced_comments_style');
                do_settings_sections('comments-style');
                submit_button();
                ?>
            </form>
            <div class="style-preview">
                <h3>实时预览</h3>
                <div class="comment-preview">
                    <!-- 预览内容 -->
                </div>
            </div>
        </div></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br>
        <?php
    }

    // 渲染设置字段
    public function render_settings_field($args) {
        $name = $args['name'];
        $options = get_option('comments_style_settings');
        $value = $options[$name] ?? '';

        switch ($name) {
            case 'highlight_color':
                echo '<input type="color" name="comments_style_settings['.$name.']" value="'.esc_attr($value).'">';
                break;
            case 'font_size':
                echo '<input type="number" name="comments_style_settings['.$name.']" min="12" max="24" value="'.esc_attr($value).'"> px';
                break;
            case 'border_style':
                echo '<select name="comments_style_settings['.$name.']">';
                echo '<option value="solid" '.selected($value, 'solid', false).'>实线</option>';
                echo '<option value="dashed" '.selected($value, 'dashed', false).'>虚线</option>';
                echo '<option value="none" '.selected($value, 'none', false).'>无边框</option>';
                echo '</select>';
                break;
            case 'custom_css':
                echo '<textarea name="comments_style_settings['.$name.']" rows="10" cols="50">'.esc_textarea($value).'</textarea>';
                break;
        }
    }

    // 数据清理
    public function sanitize_settings($input) {
        $sanitized = [];
        
        if (isset($input['highlight_color'])) {
            $sanitized['highlight_color'] = sanitize_hex_color($input['highlight_color']);
        }
        
        if (isset($input['font_size'])) {
            $sanitized['font_size'] = absint($input['font_size']);
        }
        
        if (isset($input['border_style'])) {
            $sanitized['border_style'] = sanitize_text_field($input['border_style']);
        }
        
        if (isset($input['custom_css'])) {
            $sanitized['custom_css'] = wp_strip_all_tags($input['custom_css']);
        }
        
        return $sanitized;
    }

    // 渲染评论样式
    public function render_comment_style() {
        $settings = get_option('comments_style_settings');
        $css = '';
        
        if (!empty($settings['highlight_color'])) {
            $css .= '.comment-author { color: '.$settings['highlight_color'].'; }';
        }
        
        if (!empty($settings['font_size'])) {
            $css .= '.comment-content { font-size: '.$settings['font_size'].'px; }';
        }
        
        if (!empty($settings['border_style']) && $settings['border_style'] !== 'none') {
            $css .= '.comment { border: 1px '.$settings['border_style'].' #ddd; padding: 15px; }';
        }
        
        if (!empty($settings['custom_css'])) {
            $css .= $settings['custom_css'];
        }
        
        return $css ? '<style>'.esc_html($css).'</style>' : '';
    }

    // 加载前端资源
    public function enqueue_frontend_assets() {
        wp_enqueue_style(
            'advanced-comments-style',
            plugins_url('assets/css/style.css', __FILE__)
        );
    }
}

new Advanced_Comments_Style();







// 常量定义
//直接安装地址换成WordPress网站地址即可。
define('ACS_PLUGIN_VERSION', '1.0.0');
define('ACS_UPDATE_API_URL', 'http://wuchai.net/plugins/wp-content/uploads/sites/5/2025/09/transfer-comments.zip');

class ACS_Comments_Updater {
private $update_transient = 'acs_plugin_update_info';
//private $plugin_slug = 'acs-plugin';
//private $update_api_url = 'https://your-remote-site.com/wp-json/acs-updater/v1/check';
//private $direct_download_url = 'https://your-remote-site.com/wp-content/uploads/plugins/acs-plugin/latest.zip';


public function __construct() {
	//add_action('admin_menu', [$this, 'add_admin_menu']);
    //add_action('admin_init', [$this, 'handle_update_actions']);
    //add_filter('pre_set_site_transient_update_plugins', [$this, 'modify_update_transient']);
    //add_filter('plugin_action_links_' . plugin_basename(__FILE__), [$this, 'add_action_links']);
        
    add_action('admin_menu', [$this, 'add_admin_menus']);
    add_action('admin_init', [$this, 'check_updates']);
    
   
    add_action('admin_init', [$this, 'register_update']);
    //add_shortcode('acs_comment_style', [$this, 'render_comment_style']);
    //add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_assets']);
    
    add_filter('plugin_action_links_' . plugin_basename(__FILE__), [$this, 'add_action_links']);
    add_filter('pre_set_site_transient_update_plugins', [$this, 'modify_update_transient']);
}

public function add_admin_menus() {
    add_submenu_page(
        $this->menu_slug, 
        '插件更新',
        '在线更新',
        'manage_options',
        'acs-comments-update',
        [$this, 'render_update_page']
        //[$this, 'render_settings_page']
    );
}



public function render_update_page() {
    ?>
    <div class="wrap">
        <h1>插件更新 <span class="version-badge">v<?php echo ACS_PLUGIN_VERSION; ?></span></h1>
        
        <div class="card">
            <h2>更新状态</h2>
            <?php $this->display_update_status(); ?>
        </div>

        <div class="update-methods">
            <div class="method-card">
                <h3>标准更新</h3>
                <p>通过WordPress更新系统检查并安装更新</p>
                <form method="post" class="update-form">
                    <?php wp_nonce_field('acs_update_nonce'); ?>
                    <input type="hidden" name="acs_update_action" value="check_update">
                    <?php submit_button('检查更新', 'primary', 'submit', false); ?>
                    
                    <?php if(get_transient($this->update_transient)): ?>
                        <input type="hidden" name="acs_update_action" value="do_update">
                        <?php submit_button('立即更新', 'secondary', 'submit', false); ?>
                    <?php endif; ?>
                </form>
            </div>

            <div class="method-card">
                <h3>直接更新</h3>
                <p>直接从镜像服务器下载最新版本</p>
                <form method="post" class="update-form">
                    <?php wp_nonce_field('acs_update_nonce'); ?>
                    <input type="hidden" name="acs_update_action" value="direct_update">
                    <?php submit_button('直接下载安装', 'primary', 'submit', false); ?>
                   <a href="http://mirror.wuchai.net/wuchai/wordpress/plugins/wuchai-transfer-comments/latest/latest.zip" download class="button button-primary">直接下载插件</a>
                </form>
            </div>
        </div>
    </div>
    
    <style>
        .version-badge {
            background: #2271b1;
            color: white;
            padding: 3px 8px;
            border-radius: 10px;
            font-size: 0.8em;
        }
        .update-methods {
            display: flex;
            gap: 20px;
            margin-top: 20px;
        }
        .method-card {
            flex: 1;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .update-form {
            margin-top: 10px;
        }
    </style>
    <?php
}

private function display_update_status() {
    $update_info = get_transient($this->update_transient);
    if($update_info) {
        echo '<div class="notice notice-success"><p>有新版本可用: v'.$update_info->new_version.'</p></div>';
        echo '<p>更新内容: '.wp_kses_post($update_info->sections['changelog']).'</p>';
    } else {
        echo '<p>当前已是最新版本</p>';
    }
}

public function check_updates() {
    if(!isset($_POST['acs_update_action']) || !wp_verify_nonce($_POST['_wpnonce'], 'acs_update_nonce')) {
        return;
    }

    switch($_POST['acs_update_action']) {
        case 'check_update':
            $this->fetch_remote_version();
            break;
            
        case 'do_update':
            $this->perform_update();
            break;
            
        case 'direct_update':
            $this->perform_direct_update();
            break;
    }
}

private function fetch_remote_version() {
    $response = wp_remote_get(ACS_UPDATE_API_URL, [
        'timeout' => 15,
        'body' => [
            'action' => 'get_version',
            'slug' => plugin_basename(__FILE__),
            'installed_version' => ACS_PLUGIN_VERSION
        ]
    ]);

    if(!is_wp_error($response) && 200 === wp_remote_retrieve_response_code($response)) {
        $data = json_decode(wp_remote_retrieve_body($response));
        set_transient($this->update_transient, $data, 12 * HOUR_IN_SECONDS);
    }
}

private function perform_update() {
    $update_info = get_transient($this->update_transient);
    if(!$update_info) {
        return;
    }

    include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
    $upgrader = new Plugin_Upgrader(new Automatic_Upgrader_Skin());
    $result = $upgrader->install($update_info->package);

    if($result) {
        activate_plugin(plugin_basename(__FILE__));
        delete_transient($this->update_transient);
        add_action('admin_notices', function() {
            echo '<div class="notice notice-success"><p>更新成功！请刷新页面查看新功能</p></div>';
        });
    }
}

private function perform_direct_update() {
    include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
    $upgrader = new Plugin_Upgrader(new Automatic_Upgrader_Skin());
    $result = $upgrader->install(ACS_UPDATE_API_URL);

    if($result) {
        activate_plugin(plugin_basename(__FILE__));
        delete_transient($this->update_transient);
        add_action('admin_notices', function() {
            echo '<div class="notice notice-success"><p>直接更新成功！请刷新页面查看新功能</p></div>';
        });
    } else {
        add_action('admin_notices', function() {
            echo '<div class="notice notice-error"><p>直接更新失败，请检查网络连接或联系管理员</p></div>';
        });
    }
}

public function modify_update_transient($transient) {
    if(empty($transient->checked)) {
        return $transient;
    }

    $update_info = get_transient($this->update_transient);
    if($update_info) {
        $transient->response[plugin_basename(__FILE__)] = $update_info;
    }
    
    return $transient;
}

public function add_action_links($links) {
    //$links[] = '<a href="'.admin_url('admin.php?page=acs-comments').'">设置</a>';
    $links[] = '<a href="'.admin_url('admin.php?page=acs-comments-update').'">更新</a>';
    return $links;
}


    // 保留原有功能方法
    public function render_main_page() { /*...*/ }
    public function render_instructions_page() { /*...*/ }
    public static function shortcode_handler($atts) { /*...*/ }
}

new ACS_Comments_Updater();







/*
Description: 带重复下载确认功能的插件库，显示文件大小和作者信息
*/

// 注册管理菜单
function hide_submenu_items() {
    remove_submenu_page( 'acs-comments', 'custom-plugin-library' );
}
add_action('admin_menu', 'hide_submenu_items', 999);


add_action('admin_menu', 'custom_plugin_menu');

function custom_plugin_menu() {
   // add_menu_page(
      //  '插件中心', 
      //  '插件中心',
       // 'manage_options',
       // 'custom-plugin-library',
       // 'custom_plugin_library_page',
       // 'dashicons-admin-plugins'
   // );
    
     add_submenu_page(
    	'acs-comments',
        '插件中心', 
        '插件中心',
        'manage_options',
        'custom-plugin-library',
        'custom_plugin_library_page'
        //'dashicons-admin-comments'
    );
    
}

// 获取插件数据（带缓存）
function get_remote_plugins() {
    $transient_key = 'custom_plugin_library_cache';
    if (false === ($plugins = get_transient($transient_key))) {
        $response = wp_remote_get('http://wuchai.net/plugins/wp-json/wp/v2/media?mime_type=application/zip&_embed=1&per_page=100');
        
        if (is_wp_error($response)) {
            return false;
        }
        
        $plugins = json_decode(wp_remote_retrieve_body($response), true);
        set_transient($transient_key, $plugins, HOUR_IN_SECONDS);
    }
    return $plugins;
}

// 主页面内容
function custom_plugin_library_page() {
    $plugins = get_remote_plugins();
    ?>
    <div class="wrap">
        <h1>插件中心</h1>
        <?php if (empty($plugins)) : ?>
            <div class="notice notice-error"><p>无法加载插件列表</p></div>
        <?php else : ?>
            <div class="plugin-list">
                <?php foreach ($plugins as $plugin) : ?>
                    <?php
                    // 获取作者信息
                    $author = isset($plugin['_embedded']['author'][0]['name']) 
                        ? $plugin['_embedded']['author'][0]['name'] 
                        : (isset($plugin['author_name']) ? $plugin['author_name'] : '未知作者');
                    
                    // 格式化文件大小
                    $file_size = '未知大小';
                    if (isset($plugin['media_details']['filesize'])) {
                        $size = $plugin['media_details']['filesize'];
                        $file_size = size_format($size, 2);
                    }
                    
                    // 格式化日期
                    $date = date_i18n('Y-m-d H:i', strtotime($plugin['modified']));
                    ?>
                    <div class="plugin-card">
                        <h3><?php echo esc_html($plugin['title']['rendered']); ?></h3>
                        <div class="plugin-meta">
                            <p><span class="dashicons dashicons-admin-users"></span> 作者: <?php echo esc_html($author); ?></p>
                            <p><span class="dashicons dashicons-media-default"></span> 大小: <?php echo $file_size; ?></p>
                            <p><span class="dashicons dashicons-calendar"></span> 更新: <?php echo $date; ?></p>
                            <p><span class="dashicons dashicons-tag"></span> 版本: <?php echo esc_html($plugin['meta']['version'] ?? '1.0.0'); ?></p>
                        </div>
                        <button class="button button-primary install-plugin" 
                                data-url="<?php echo esc_url($plugin['source_url']); ?>"
                                data-name="<?php echo esc_attr($plugin['title']['rendered']); ?>">
                            安装插件
                        </button>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    <?php
}

// 插件检查接口
add_action('wp_ajax_check_plugin_installed', 'check_plugin_installed');
function check_plugin_installed() {
    $plugin_name = isset($_POST['plugin_name']) ? sanitize_text_field($_POST['plugin_name']) : '';
    
    if (empty($plugin_name)) {
        wp_send_json_error('无效的插件名称');
    }
    
    require_once ABSPATH . 'wp-admin/includes/plugin.php';
    $all_plugins = get_plugins();
    $installed = false;
    $version = '';
    
    foreach ($all_plugins as $path => $data) {
        if (strpos($data['Name'], $plugin_name) !== false) {
            $installed = true;
            $version = $data['Version'];
            break;
        }
    }
    
    wp_send_json_success([
        'installed' => $installed,
        'version' => $version
    ]);
}

// AJAX安装处理
add_action('wp_ajax_install_remote_plugin', 'handle_plugin_installation');
function handle_plugin_installation() {
    check_ajax_referer('install_plugin_nonce');
    
    if (!current_user_can('install_plugins')) {
        wp_send_json_error('权限不足');
    }
    
    $plugin_url = isset($_POST['plugin_url']) ? esc_url_raw($_POST['plugin_url']) : '';
    if (empty($plugin_url)) {
        wp_send_json_error('无效的插件URL');
    }
    
    require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
    require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
    require_once ABSPATH . 'wp-admin/includes/plugin.php';
    
    $upgrader = new Plugin_Upgrader(new Automatic_Upgrader_Skin());
    $result = $upgrader->install($plugin_url);
    
    if (is_wp_error($result)) {
        wp_send_json_error($result->get_error_message());
    }
    
    wp_send_json_success();
}

// 添加样式和脚本
add_action('admin_enqueue_scripts', 'plugin_library_assets');
function plugin_library_assets() {
    wp_enqueue_style('plugin-library-css', plugins_url('assets/css/style.css', __FILE__));
    wp_enqueue_script('plugin-library-js', plugins_url('assets/js/main.js', __FILE__), ['jquery'], null, true);
    wp_localize_script('plugin-library-js', 'pluginLibrary', [
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('install_plugin_nonce')
    ]);
}


// 添加样式
add_action('admin_head', 'plugin_library_styles');
function plugin_library_styles() {
    echo '<style>
    .plugin-list { 
        display: grid; 
        grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); 
        gap: 20px; 
        margin-top: 20px; 
    }
    .plugin-card { 
        background: #fff; 
        border: 1px solid #ddd; 
        padding: 20px; 
        border-radius: 4px; 
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        transition: transform 0.2s;
    }
    .plugin-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .plugin-card h3 { 
        margin-top: 0; 
        color: #23282d; 
        border-bottom: 1px solid #eee; 
        padding-bottom: 10px; 
    }
    .plugin-meta p { 
        margin: 8px 0; 
        color: #555; 
        display: flex; 
        align-items: center; 
    }
    .plugin-meta .dashicons { 
        margin-right: 5px; 
        color: #72777c; 
        width: 18px;
        height: 18px;
        font-size: 18px;
    }
    .install-plugin { 
        margin-top: 15px; 
        width: 100%; 
    }
    .button-success { 
        background-color: #46b450; 
        border-color: #46b450; 
    }
    .button-error { 
        background-color: #dc3232; 
        border-color: #dc3232; 
    }
    </style>';
}






/**
 * Description: 插件捐赠功能模块，直接使用本地图片
 * Version: 1.1.0
 */

if (!defined('ABSPATH')) exit;

class Plugin_Donation_Manager {
    private $image_dir = 'assets/donation/';
    
    public function __construct() {
        add_action('admin_init', [$this, 'init_settings']);
        add_action('admin_menu', [$this, 'add_menu']);
    }

    public function init_settings() {
        register_setting('donation_options', 'donation_active_methods');
    }

    public function add_menu() {
        add_submenu_page(
            $this->menu_slug,
            '支持开发者',
            '❤️ 捐赠',
            'manage_options',
            'plugin-donation',
            [$this, 'render_page']
        );
    }

    public function get_image_path($type) {
        return plugins_url($this->image_dir . $type . '.jpg', __FILE__);
    }

    public function render_page() {
        $methods = [
            'alipay' => '支付宝',
            'wechat' => '微信支付',
           // 'paypal' => 'PayPal'
        ];
        ?>
        <div class="wrap">
            <h1>支持插件开发</h1>
            <div class="card" style="max-width:700px; background-color: transparent;  border: 0px; " >
                <form method="post" action="options.php">
                    <?php settings_fields('donation_options'); ?>
                    
                    <h2>捐赠渠道</h2>
                    <table class="form-table">
                        <?php foreach ($methods as $id => $name): ?>
                        <tr>
                            <th><?php echo esc_html($name); ?></th>
                            <td>
                                <img src="<?php echo esc_url($this->get_image_path($id)); ?>" 
                                     alt="<?php echo esc_attr($name); ?>二维码"
                                     style="max-width:160px;border:0px solid #ddd;padding:30px; background-color: transparent; ">
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                    
                    <p class="description">您的支持将帮助插件持续更新和改进！</p>
                </form>
            </div>
        </div>
        <?php
    }
}

new Plugin_Donation_Manager();




