<?php
/**
 * Plugin Name: EasyWP Mobile Featured Image
 * Plugin URI: https://life8882.com/
 * Description: 为文章添加移动端特色图片，不影响PC端显示
 * Version: 2.0.0
 * Author: life8882
 * License: GPL v2 or later
 * Text Domain: easywp-mfi
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

class EasyWP_Mobile_Featured_Image {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('add_meta_boxes', array($this, 'add_mobile_featured_image_meta_box'));
        add_action('save_post', array($this, 'save_mobile_featured_image'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        
        // 移动端检测和图片替换
        add_action('template_redirect', array($this, 'setup_mobile_hooks'));
        
        // 添加短代码支持
        add_shortcode('mobile_featured_image', array($this, 'mobile_featured_image_shortcode'));
    }
    
    /**
     * 设置移动端钩子
     */
    public function setup_mobile_hooks() {
        // 只在前端移动端执行
        if (wp_is_mobile() && !is_admin()) {
            // 替换文章列表中的特色图片
            add_filter('post_thumbnail_id', array($this, 'replace_post_thumbnail_id'), 10, 2);
            
            // 替换获取特色图片的函数
            add_filter('get_post_metadata', array($this, 'replace_featured_image_metadata'), 10, 4);
            
            // 替换缩略图HTML输出
            add_filter('post_thumbnail_html', array($this, 'replace_thumbnail_html'), 10, 5);
            
            // 替换WP_Query中的特色图片
            add_filter('the_posts', array($this, 'replace_posts_featured_images'), 10, 2);
            
            // 替换REST API中的特色图片
            add_filter('rest_prepare_post', array($this, 'replace_rest_featured_image'), 10, 3);
        }
    }
    
    /**
     * 添加移动端特色图片元框
     */
    public function add_mobile_featured_image_meta_box() {
        $post_types = get_post_types(array('public' => true));
        
        foreach ($post_types as $post_type) {
            add_meta_box(
                'easywp-mobile-featured-image',
                __('移动端特色图片', 'easywp-mfi'),
                array($this, 'render_mobile_featured_image_meta_box'),
                $post_type,
                'side',
                'low'
            );
        }
    }
    
    /**
     * 渲染移动端特色图片元框
     */
    public function render_mobile_featured_image_meta_box($post) {
        wp_nonce_field('easywp_mobile_featured_image_nonce', 'easywp_mobile_featured_image_nonce');
        
        $image_id = get_post_meta($post->ID, '_easywp_mobile_featured_image_id', true);
        $image_url = $image_id ? wp_get_attachment_image_url($image_id, 'thumbnail') : '';
        ?>
        <div class="easywp-mobile-featured-image-container">
            <div class="image-preview" style="margin-bottom: 10px;">
                <?php if ($image_url): ?>
                    <img src="<?php echo esc_url($image_url); ?>" style="max-width: 100%; height: auto;" />
                <?php endif; ?>
            </div>
            
            <input type="hidden" 
                   name="easywp_mobile_featured_image_id" 
                   id="easywp_mobile_featured_image_id" 
                   value="<?php echo esc_attr($image_id); ?>" />
            
            <button type="button" 
                    class="button easywp-upload-mobile-featured-image <?php echo $image_id ? 'hidden' : ''; ?>" 
                    id="easywp-upload-mobile-featured-image">
                <?php _e('选择图片', 'easywp-mfi'); ?>
            </button>
            
            <button type="button" 
                    class="button easywp-remove-mobile-featured-image <?php echo !$image_id ? 'hidden' : ''; ?>" 
                    id="easywp-remove-mobile-featured-image">
                <?php _e('移除图片', 'easywp-mfi'); ?>
            </button>
            
            <p class="description">
                <?php _e('为移动端设备设置专用特色图片，如果未设置则使用默认特色图片。', 'easywp-mfi'); ?>
            </p>
        </div>
        <?php
    }
    
    /**
     * 保存移动端特色图片
     */
    public function save_mobile_featured_image($post_id) {
        // 安全检查
        if (!isset($_POST['easywp_mobile_featured_image_nonce']) ||
            !wp_verify_nonce($_POST['easywp_mobile_featured_image_nonce'], 'easywp_mobile_featured_image_nonce')) {
            return;
        }
        
        // 检查自动保存
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // 检查用户权限
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // 保存图片ID
        if (isset($_POST['easywp_mobile_featured_image_id'])) {
            $image_id = intval($_POST['easywp_mobile_featured_image_id']);
            if ($image_id > 0) {
                update_post_meta($post_id, '_easywp_mobile_featured_image_id', $image_id);
            } else {
                delete_post_meta($post_id, '_easywp_mobile_featured_image_id');
            }
        }
    }
    
    /**
     * 加载管理端脚本
     */
    public function enqueue_admin_scripts($hook) {
        global $post;
        
        if (!in_array($hook, array('post.php', 'post-new.php'))) {
            return;
        }
        
        wp_enqueue_media();
        
        wp_enqueue_script(
            'easywp-mobile-featured-image-admin',
            plugin_dir_url(__FILE__) . 'js/admin.js',
            array('jquery'),
            '2.0.0',
            true
        );
        
        wp_localize_script('easywp-mobile-featured-image-admin', 'easywp_mfi', array(
            'title' => __('选择移动端特色图片', 'easywp-mfi'),
            'button' => __('设置为移动端特色图片', 'easywp-mfi')
        ));
        
        wp_enqueue_style(
            'easywp-mobile-featured-image-admin',
            plugin_dir_url(__FILE__) . 'css/admin.css',
            array(),
            '2.0.0'
        );
    }
    
    /**
     * 替换文章缩略图ID
     */
    public function replace_post_thumbnail_id($thumbnail_id, $post) {
        $post_id = is_object($post) ? $post->ID : $post;
        $mobile_image_id = get_post_meta($post_id, '_easywp_mobile_featured_image_id', true);
        
        if (!empty($mobile_image_id)) {
            return $mobile_image_id;
        }
        
        return $thumbnail_id;
    }
    
    /**
     * 替换特色图片元数据
     */
    public function replace_featured_image_metadata($value, $object_id, $meta_key, $single) {
        // 只处理特色图片的查询
        if ($meta_key !== '_thumbnail_id') {
            return $value;
        }
        
        // 获取移动端特色图片ID
        $mobile_image_id = get_post_meta($object_id, '_easywp_mobile_featured_image_id', true);
        
        // 如果有移动端特色图片，则使用它
        if (!empty($mobile_image_id)) {
            if ($single) {
                return $mobile_image_id;
            } else {
                return array($mobile_image_id);
            }
        }
        
        // 否则返回原值
        return $value;
    }
    
    /**
     * 替换缩略图HTML
     */
    public function replace_thumbnail_html($html, $post_id, $post_thumbnail_id, $size, $attr) {
        $mobile_image_id = get_post_meta($post_id, '_easywp_mobile_featured_image_id', true);
        
        if (!empty($mobile_image_id)) {
            // 生成移动端图片的HTML
            $mobile_html = wp_get_attachment_image($mobile_image_id, $size, false, $attr);
            
            // 如果移动端图片存在，则替换
            if (!empty($mobile_html)) {
                // 保留原有的CSS类
                if (preg_match('/class=["\']([^"\']+)["\']/', $html, $matches)) {
                    $original_classes = $matches[1];
                    // 将原始类添加到移动端图片
                    $mobile_html = str_replace(
                        'class="',
                        'class="' . $original_classes . ' ',
                        $mobile_html
                    );
                }
                return $mobile_html;
            }
        }
        
        return $html;
    }
    
    /**
     * 替换文章列表中的特色图片
     */
    public function replace_posts_featured_images($posts, $query) {
        // 只在主查询中处理
        if (!$query->is_main_query()) {
            return $posts;
        }
        
        // 处理每个文章的特色图片
        foreach ($posts as $post) {
            $mobile_image_id = get_post_meta($post->ID, '_easywp_mobile_featured_image_id', true);
            if (!empty($mobile_image_id)) {
                // 设置一个临时属性，供其他地方使用
                $post->mobile_featured_image_id = $mobile_image_id;
            }
        }
        
        return $posts;
    }
    
    /**
     * 替换REST API中的特色图片
     */
    public function replace_rest_featured_image($response, $post, $request) {
        $mobile_image_id = get_post_meta($post->ID, '_easywp_mobile_featured_image_id', true);
        
        if (!empty($mobile_image_id)) {
            // 替换featured_media字段
            if (isset($response->data['featured_media'])) {
                $response->data['featured_media'] = $mobile_image_id;
            }
            
            // 替换_featured_media字段
            if (isset($response->data['_embedded']['wp:featuredmedia'])) {
                $mobile_image_data = $this->get_image_data_for_rest($mobile_image_id);
                if ($mobile_image_data) {
                    $response->data['_embedded']['wp:featuredmedia'] = array($mobile_image_data);
                }
            }
        }
        
        return $response;
    }
    
    /**
     * 获取REST API图片数据
     */
    private function get_image_data_for_rest($image_id) {
        $image = get_post($image_id);
        if (!$image) {
            return null;
        }
        
        $image_src = wp_get_attachment_image_src($image_id, 'full');
        
        return array(
            'id' => $image_id,
            'date' => mysql_to_rfc3339($image->post_date),
            'slug' => $image->post_name,
            'type' => 'attachment',
            'link' => get_permalink($image),
            'title' => array(
                'rendered' => get_the_title($image)
            ),
            'author' => (int) $image->post_author,
            'caption' => array(
                'rendered' => wp_get_attachment_caption($image_id)
            ),
            'alt_text' => get_post_meta($image_id, '_wp_attachment_image_alt', true),
            'media_type' => 'image',
            'mime_type' => $image->post_mime_type,
            'media_details' => wp_get_attachment_metadata($image_id),
            'source_url' => $image_src ? $image_src[0] : '',
        );
    }
    
    /**
     * 移动端特色图片短代码
     */
    public function mobile_featured_image_shortcode($atts) {
        $atts = shortcode_atts(array(
            'id' => get_the_ID(),
            'size' => 'full',
            'class' => '',
            'alt' => '',
            'lazy' => true,
        ), $atts, 'mobile_featured_image');
        
        $post_id = $atts['id'];
        $mobile_image_id = get_post_meta($post_id, '_easywp_mobile_featured_image_id', true);
        
        if (empty($mobile_image_id)) {
            // 如果没有移动端图片，返回空或默认图片
            return '';
        }
        
        $size = $atts['size'];
        $class = $atts['class'];
        $alt = $atts['alt'];
        $lazy = filter_var($atts['lazy'], FILTER_VALIDATE_BOOLEAN);
        
        // 生成图片HTML
        $img_attrs = array(
            'class' => $class,
            'alt' => $alt ?: get_the_title($post_id),
        );
        
        if ($lazy) {
            $img_attrs['loading'] = 'lazy';
        }
        
        return wp_get_attachment_image($mobile_image_id, $size, false, $img_attrs);
    }
    
    /**
     * 辅助函数：获取移动端特色图片URL
     */
    public static function get_mobile_featured_image_url($post_id = null, $size = 'full') {
        if (!$post_id) {
            $post_id = get_the_ID();
        }
        
        $mobile_image_id = get_post_meta($post_id, '_easywp_mobile_featured_image_id', true);
        
        if ($mobile_image_id) {
            return wp_get_attachment_image_url($mobile_image_id, $size);
        }
        
        return false;
    }
    
    /**
     * 辅助函数：检查是否有移动端特色图片
     */
    public static function has_mobile_featured_image($post_id = null) {
        if (!$post_id) {
            $post_id = get_the_ID();
        }
        
        $mobile_image_id = get_post_meta($post_id, '_easywp_mobile_featured_image_id', true);
        
        return !empty($mobile_image_id);
    }
}

// 初始化插件
function easywp_mobile_featured_image_init() {
    return EasyWP_Mobile_Featured_Image::get_instance();
}
add_action('plugins_loaded', 'easywp_mobile_featured_image_init');

// 为模板提供便捷函数
if (!function_exists('has_mobile_featured_image')) {
    function has_mobile_featured_image($post_id = null) {
        return EasyWP_Mobile_Featured_Image::has_mobile_featured_image($post_id);
    }
}

if (!function_exists('the_mobile_featured_image')) {
    function the_mobile_featured_image($size = 'full', $attr = '') {
        $post_id = get_the_ID();
        $mobile_image_id = get_post_meta($post_id, '_easywp_mobile_featured_image_id', true);
        
        if ($mobile_image_id) {
            echo wp_get_attachment_image($mobile_image_id, $size, false, $attr);
        } elseif (has_post_thumbnail()) {
            the_post_thumbnail($size, $attr);
        }
    }
}

if (!function_exists('get_mobile_featured_image_url')) {
    function get_mobile_featured_image_url($post_id = null, $size = 'full') {
        return EasyWP_Mobile_Featured_Image::get_mobile_featured_image_url($post_id, $size);
    }
}

if (!function_exists('get_mobile_featured_image_id')) {
    function get_mobile_featured_image_id($post_id = null) {
        if (!$post_id) {
            $post_id = get_the_ID();
        }
        return get_post_meta($post_id, '_easywp_mobile_featured_image_id', true);
    }
}