<?php
/**
 * Extra Config Features Manager
 * Manages individual feature modules
 *
 * @package AIAutoTool
 * @subpackage ExtraConfig
 * @since 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

/**
 * Features Manager class
 */
class Aiautotool_Extra_Config_Features_Manager {
    
    /**
     * Settings registry instance
     *
     * @var Aiautotool_Extra_Config_Settings_Registry
     */
    private $settings;
    
    /**
     * Registered features
     *
     * @var array
     */
    private $features = array();
    
    /**
     * Constructor
     *
     * @param Aiautotool_Extra_Config_Settings_Registry $settings Settings instance
     */
    public function __construct($settings) {
        $this->settings = $settings;
    }
    
    /**
     * Initialize all features
     *
     * @return void
     */
    public function init() {
        // Editor features
        $this->init_editor_features();
        
        // Speed optimization features
        $this->init_speed_features();
        
        // Security features
        $this->init_security_features();
        
        // Database optimization features
        $this->init_database_features();
        
        // Management features
        $this->init_management_features();
        
        // Allow other plugins to add features
        do_action('aiautotool_extra_config_init_features', $this);
    }
    
    /**
     * Initialize editor features
     *
     * @return void
     */
    private function init_editor_features() {
        // Block all comments
        if ($this->settings->is_enabled('tool-blockcomment')) {
            add_filter('pre_comment_approved', '__return_false');
            add_filter('wp_insert_post_data', array($this, 'disable_comments_on_post_save'), 10, 2);
        }
        
        // Enable classic editor
        if ($this->settings->is_enabled('tool-edit1')) {
            add_filter('use_block_editor_for_post', '__return_false');
        }
        
        // Add buttons to classic editor
        if ($this->settings->is_enabled('tool-edit11')) {
            add_filter('mce_buttons_2', array($this, 'add_mce_buttons'));
            add_filter('mce_external_plugins', array($this, 'add_mce_plugins'));
        }
        
        // Enable classic widgets
        if ($this->settings->is_enabled('tool-widget1')) {
            add_filter('gutenberg_use_widgets_block_editor', '__return_false');
            add_filter('use_widgets_block_editor', '__return_false');
        }
    }
    
    /**
     * Initialize speed optimization features
     *
     * @return void
     */
    private function init_speed_features() {
        // Remove jQuery Migrate
        if ($this->settings->is_enabled('speed-off1')) {
            add_action('wp_default_scripts', array($this, 'remove_jquery_migrate'));
        }
        
        // Remove Gutenberg CSS on homepage
        if ($this->settings->is_enabled('speed-off2')) {
            add_action('wp_enqueue_scripts', array($this, 'remove_gutenberg_css'), 100);
        }
        
        // Remove Classic CSS on homepage
        if ($this->settings->is_enabled('speed-off3')) {
            add_action('wp_enqueue_scripts', array($this, 'remove_classic_css'), 20);
        }
        
        // Disable emojis
        if ($this->settings->is_enabled('speed-off4')) {
            $this->disable_emojis();
        }
        
        // Enable Instant Page
        if ($this->settings->is_enabled('speed-link1')) {
            add_action('wp_enqueue_scripts', array($this, 'enqueue_instantpage'));
            add_filter('script_loader_tag', array($this, 'instantpage_loader_tag'), 10, 2);
        }
        
        // Enable Smooth Scroll
        if ($this->settings->is_enabled('speed-link2')) {
            add_action('wp_enqueue_scripts', array($this, 'enqueue_smooth_scroll'));
        }
        
        // Enable HTML compression
        if ($this->settings->is_enabled('speed-zip1')) {
            add_action('get_header', array($this, 'start_html_compression'));
        }
    }
    
    /**
     * Initialize security features
     *
     * @return void
     */
    private function init_security_features() {
        // Disable REST API for non-logged users
        if ($this->settings->is_enabled('scuri-off1')) {
            add_filter('rest_authentication_errors', array($this, 'restrict_rest_api'));
        }
        
        // Disable XML-RPC
        if ($this->settings->is_enabled('scuri-off2')) {
            add_filter('xmlrpc_enabled', '__return_false');
            add_filter('wp_xmlrpc_server_class', '__return_false');
        }
        
        // Disable WP Embed
        if ($this->settings->is_enabled('scuri-off3')) {
            add_action('wp_footer', array($this, 'deregister_embed_script'));
        }
        
        // Remove X-Pingback
        if ($this->settings->is_enabled('scuri-off4')) {
            add_filter('wp_headers', array($this, 'remove_pingback_header'));
        }
        
        // Remove unnecessary header info
        if ($this->settings->is_enabled('scuri-off5')) {
            $this->remove_header_info();
        }
        
        // Disable feeds
        if ($this->settings->is_enabled('scuri-off6')) {
            $this->disable_feeds();
        }
        
        // Remove CSS/JS versions
        if ($this->settings->is_enabled('scuri-verof1')) {
            add_filter('style_loader_src', array($this, 'remove_version_query'), 9999);
            add_filter('script_loader_src', array($this, 'remove_version_query'), 9999);
        }
        
        // Remove WordPress version
        if ($this->settings->is_enabled('scuri-verof2')) {
            add_filter('the_generator', '__return_empty_string');
        }
        
        // SQL injection protection
        if ($this->settings->is_enabled('scuri-sql1')) {
            add_action('init', array($this, 'security_check'));
        }
    }
    
    /**
     * Initialize database optimization features
     *
     * @return void
     */
    private function init_database_features() {
        // Limit post revisions
        if ($this->settings->is_enabled('speed-data1')) {
            add_filter('wp_revisions_to_keep', array($this, 'limit_post_revisions'), 10, 2);
        }
        
        // Change autosave interval
        if ($this->settings->is_enabled('speed-data2')) {
            $this->set_autosave_interval();
        }
    }
    
    /**
     * Initialize management features
     *
     * @return void
     */
    private function init_management_features() {
        // Redirect 404 to home
        if ($this->settings->is_enabled('tool-mana1')) {
            add_action('template_redirect', array($this, 'redirect_404_to_home'));
        }
        
        // Block copy content
        if ($this->settings->is_enabled('tool-mana2')) {
            add_action('wp_enqueue_scripts', array($this, 'enqueue_copy_protection'));
        }
        
        // Enable TinyMCE for category description
        if ($this->settings->is_enabled('tool-mana3')) {
            add_filter('category_edit_form_fields', array($this, 'add_tinymce_to_category'));
            add_filter('product_cat_edit_form_fields', array($this, 'add_tinymce_to_category'));
            add_action('admin_head', array($this, 'remove_default_category_description'));
            remove_filter('pre_term_description', 'wp_filter_kses');
            remove_filter('term_description', 'wp_kses_data');
        }
        
        // Disable auto-updates
        if ($this->settings->is_enabled('tool-upload1')) {
            add_filter('auto_update_core', '__return_false');
        }
        
        if ($this->settings->is_enabled('tool-upload2')) {
            add_filter('auto_update_translation', '__return_false');
        }
        
        if ($this->settings->is_enabled('tool-upload3')) {
            add_filter('auto_update_plugin', '__return_false');
        }
        
        if ($this->settings->is_enabled('tool-upload4')) {
            add_filter('auto_update_theme', '__return_false');
        }
        
        // Hide admin menu items
        add_action('admin_menu', array($this, 'hide_admin_menu_items'), 99999);
    }
    
    // ========== Feature Implementation Methods ==========
    
    /**
     * Disable comments on post save
     *
     * @param array $data    Post data
     * @param array $postarr Post array
     * @return array Modified post data
     */
    public function disable_comments_on_post_save($data, $postarr) {
        if ($data['post_type'] === 'post') {
            $data['comment_status'] = 'closed';
        }
        return $data;
    }
    
    /**
     * Add buttons to TinyMCE
     *
     * @param array $buttons Existing buttons
     * @return array Modified buttons
     */
    public function add_mce_buttons($buttons) {
        array_unshift($buttons, 'fontselect', 'fontsizeselect');
        array_push($buttons, 'unlink', 'separator', 'table');
        return $buttons;
    }
    
    /**
     * Add plugins to TinyMCE
     *
     * @param array $plugins Existing plugins
     * @return array Modified plugins
     */
    public function add_mce_plugins($plugins) {
        $plugin_url = AIAUTOTOOL_URI . 'js/tinyMCE/table/plugin.min.js';
        $plugins['table'] = $plugin_url;
        return $plugins;
    }
    
    /**
     * Remove jQuery Migrate
     *
     * @param WP_Scripts $scripts Scripts object
     * @return void
     */
    public function remove_jquery_migrate($scripts) {
        if (!is_admin() && isset($scripts->registered['jquery'])) {
            $script = $scripts->registered['jquery'];
            if ($script->deps) {
                $script->deps = array_diff($script->deps, array('jquery-migrate'));
            }
        }
    }
    
    /**
     * Remove Gutenberg CSS
     *
     * @return void
     */
    public function remove_gutenberg_css() {
        if (is_front_page()) {
            wp_dequeue_style('wp-block-library');
            wp_dequeue_style('wp-block-library-theme');
            wp_dequeue_style('wc-blocks-style');
        }
    }
    
    /**
     * Remove Classic CSS
     *
     * @return void
     */
    public function remove_classic_css() {
        if (is_front_page()) {
            wp_dequeue_style('classic-theme-styles');
        }
    }
    
    /**
     * Disable emojis
     *
     * @return void
     */
    private function disable_emojis() {
        remove_action('wp_head', 'print_emoji_detection_script', 7);
        remove_action('admin_print_scripts', 'print_emoji_detection_script');
        remove_action('wp_print_styles', 'print_emoji_styles');
        remove_action('admin_print_styles', 'print_emoji_styles');
        remove_filter('the_content_feed', 'wp_staticize_emoji');
        remove_filter('comment_text_rss', 'wp_staticize_emoji');
        remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
    }
    
    /**
     * Enqueue Instant Page script
     *
     * @return void
     */
    public function enqueue_instantpage() {
        wp_enqueue_script('instantpage', AIAUTOTOOL_URI . 'js/instantpage.js', array(), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '5.7.0', true);
    }
    
    /**
     * Modify Instant Page script tag
     *
     * @param string $tag    Script tag HTML
     * @param string $handle Script handle
     * @return string Modified script tag
     */
    public function instantpage_loader_tag($tag, $handle) {
        if ($handle === 'instantpage') {
            $tag = str_replace(' src=', " type='module' src=", $tag);
        }
        return $tag;
    }
    
    /**
     * Enqueue smooth scroll script
     *
     * @return void
     */
    public function enqueue_smooth_scroll() {
        wp_enqueue_script('smooth-scroll', AIAUTOTOOL_URI . 'js/smooth-scroll.min.js', array(), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : AIAUTOTOOL_VS, true);
    }
    
    /**
     * Start HTML compression
     *
     * @return void
     */
    public function start_html_compression() {
        if (!current_user_can('administrator')) {
            require_once plugin_dir_path(__FILE__) . 'class-html-compression.php';
            ob_start(array('Aiautotool_HTML_Compression', 'compress'));
        }
    }
    
    /**
     * Restrict REST API access
     *
     * @param WP_Error|null|bool $result Error from another authentication handler
     * @return WP_Error|null|bool
     */
    public function restrict_rest_api($result) {
        if (true === $result || is_wp_error($result)) {
            return $result;
        }
        
        if (!is_user_logged_in()) {
            return new WP_Error(
                'rest_not_logged_in',
                __('You are not currently logged in.', 'ai-auto-tool'),
                array('status' => 401)
            );
        }
        
        return $result;
    }
    
    /**
     * Deregister embed script
     *
     * @return void
     */
    public function deregister_embed_script() {
        wp_deregister_script('wp-embed');
    }
    
    /**
     * Remove X-Pingback header
     *
     * @param array $headers HTTP headers
     * @return array Modified headers
     */
    public function remove_pingback_header($headers) {
        if (isset($headers['X-Pingback'])) {
            unset($headers['X-Pingback']);
        }
        return $headers;
    }
    
    /**
     * Remove header info
     *
     * @return void
     */
    private function remove_header_info() {
        remove_action('wp_head', 'feed_links_extra', 3);
        remove_action('wp_head', 'rsd_link');
        remove_action('wp_head', 'wlwmanifest_link');
        remove_action('wp_head', 'wp_generator');
        remove_action('wp_head', 'start_post_rel_link');
        remove_action('wp_head', 'index_rel_link');
        remove_action('wp_head', 'parent_post_rel_link', 10, 0);
        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
    }
    
    /**
     * Disable feeds
     *
     * @return void
     */
    private function disable_feeds() {
        add_action('do_feed', array($this, 'disable_feed_callback'), 1);
        add_action('do_feed_rdf', array($this, 'disable_feed_callback'), 1);
        add_action('do_feed_rss', array($this, 'disable_feed_callback'), 1);
        add_action('do_feed_atom', array($this, 'disable_feed_callback'), 1);
        add_action('do_feed_rss2_comments', array($this, 'disable_feed_callback'), 1);
        add_action('do_feed_atom_comments', array($this, 'disable_feed_callback'), 1);
    }
    
    /**
     * Disable feed callback
     *
     * @return void
     */
    public function disable_feed_callback() {
        wp_die('<a href="' . esc_url(get_bloginfo('url')) . '">' . esc_html__('Home', 'ai-auto-tool') . '</a>');
    }
    
    /**
     * Remove version from query string
     *
     * @param string $src Source URL
     * @return string Modified URL
     */
    public function remove_version_query($src) {
        if (strpos($src, '?ver=')) {
            $src = remove_query_arg('ver', $src);
        }
        return $src;
    }
    
    /**
     * Security check for SQL injection
     *
     * @return void
     */
    public function security_check() {
        if (!current_user_can('administrator')) {
            $request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
            
            if (strlen($request_uri) > 255 ||
                stripos($request_uri, 'eval(') !== false ||
                stripos($request_uri, 'CONCAT') !== false ||
                stripos($request_uri, 'UNION+SELECT') !== false ||
                stripos($request_uri, 'base64') !== false) {
                wp_die('Security threat detected', 'Security Alert', array('response' => 414));
            }
        }
    }
    
    /**
     * Limit post revisions
     *
     * @param int     $num  Number of revisions
     * @param WP_Post $post Post object
     * @return int Modified number of revisions
     */
    public function limit_post_revisions($num, $post) {
        $limit = $this->settings->get('speed-data11', 3);
        return (int) $limit;
    }
    
    /**
     * Set autosave interval
     *
     * @return void
     */
    private function set_autosave_interval() {
        if (!defined('AUTOSAVE_INTERVAL')) {
            $minutes = $this->settings->get('speed-data21', 1);
            define('AUTOSAVE_INTERVAL', (int) $minutes * MINUTE_IN_SECONDS);
        }
    }
    
    /**
     * Redirect 404 to home
     *
     * @return void
     */
    public function redirect_404_to_home() {
        if (is_404()) {
            wp_safe_redirect(home_url());
            exit;
        }
    }
    
    /**
     * Enqueue copy protection scripts
     *
     * @return void
     */
    public function enqueue_copy_protection() {
        if (!is_admin()) {
            wp_enqueue_script('lockcop', AIAUTOTOOL_URI . 'js/lockcop.js', array(), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : AIAUTOTOOL_VS, true);
            wp_enqueue_style('lockcop', AIAUTOTOOL_URI . 'js/lockcop.css', array(), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : AIAUTOTOOL_VS);
        }
    }
    
    /**
     * Add TinyMCE to category description
     *
     * @param object $tag Category tag object
     * @return void
     */
    public function add_tinymce_to_category($tag) {
        ?>
        <table class="form-table">
            <tr class="form-field">
                <th scope="row" valign="top"><label for="description"></label></th>
                <td>
                    <?php
                    $settings = array(
                        'wpautop'        => true,
                        'media_buttons'  => true,
                        'quicktags'      => true,
                        'textarea_rows'  => 15,
                        'textarea_name'  => 'description'
                    );
                    wp_editor($tag->description, 'description', $settings);
                    ?>
                </td>
            </tr>
        </table>
        <?php
    }
    
    /**
     * Remove default category description
     *
     * @return void
     */
    public function remove_default_category_description() {
        global $current_screen;
        if (isset($current_screen->taxonomy) && 
            ($current_screen->taxonomy === 'category' || $current_screen->taxonomy === 'product_cat')) {
            echo '<style>textarea#description{display:none}</style>';
        }
    }
    
    /**
     * Hide admin menu items
     *
     * @return void
     */
    public function hide_admin_menu_items() {
        $hide_items = array(
            'tool-hiden1'  => 'index.php',
            'tool-hiden2'  => 'edit.php',
            'tool-hiden3'  => 'edit.php?post_type=page',
            'tool-hiden4'  => 'edit-comments.php',
            'tool-hiden5'  => 'upload.php',
            'tool-hiden6'  => 'themes.php',
            'tool-hiden7'  => 'plugins.php',
            'tool-hiden8'  => 'users.php',
            'tool-hiden9'  => 'tools.php',
            'tool-hiden10' => 'options-general.php',
            'tool-hifox1'  => 'ai-auto-tool',
        );
        
        foreach ($hide_items as $setting_key => $menu_slug) {
            if ($this->settings->is_enabled($setting_key)) {
                remove_menu_page($menu_slug);
            }
        }
    }
}


