<?php
/**
 * Extra Config Manager
 * Main controller class that coordinates all components
 *
 * @package AIAutoTool
 * @subpackage ExtraConfig
 * @since 1.0.0
 */

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

/**
 * Main Manager class
 */
class Aiautotool_Extra_Config_Manager extends rendersetting {
    
    /**
     * Singleton instance
     *
     * @var Aiautotool_Extra_Config_Manager
     */
    private static $instance = null;
    
    /**
     * Security instance
     *
     * @var Aiautotool_Extra_Config_Security
     */
    private $security;
    
    /**
     * Settings registry instance
     *
     * @var Aiautotool_Extra_Config_Settings_Registry
     */
    private $settings;
    
    /**
     * AJAX handler instance
     *
     * @var Aiautotool_Extra_Config_AJAX_Handler
     */
    private $ajax_handler;
    
    /**
     * Feature active status
     *
     * @var string
     */
    public $active = 'true';
    
    /**
     * Active option name
     *
     * @var string
     */
    public $active_option_name = 'Aiautotool_tool_extra_config_active';
    
    /**
     * Constructor
     */
    private function __construct() {
        // Load dependencies
        $this->load_dependencies();
        
        // Initialize components
        $this->security = new Aiautotool_Extra_Config_Security();
        $this->settings = Aiautotool_Extra_Config_Settings_Registry::instance();
        $this->ajax_handler = new Aiautotool_Extra_Config_AJAX_Handler($this->security, $this->settings);
        
        // Extra Config is always active (mandatory module)
        $this->active = 'true';
        
        // Initialize hooks
        $this->init_hooks();
        
        // Initialize features (always runs - mandatory)
        $this->init_features();
    }
    
    /**
     * Get singleton instance
     *
     * @return Aiautotool_Extra_Config_Manager
     */
    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        
        return self::$instance;
    }
    
    /**
     * Load dependencies
     *
     * @return void
     */
    private function load_dependencies() {
        $base_path = plugin_dir_path(__FILE__);
        
        require_once $base_path . 'class-security.php';
        require_once $base_path . 'class-settings-registry.php';
        require_once $base_path . 'class-ajax-handler.php';
        require_once $base_path . 'class-features-manager.php';
    }
    
    /**
     * Initialize WordPress hooks
     *
     * @return void
     */
    private function init_hooks() {
        // Admin hooks
        add_action('admin_init', array($this, 'register_settings'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
        
        // AJAX hooks
        $this->ajax_handler->register_handlers();
        
        // Active/Inactive toggle (requires authentication - options modification)
        add_action('wp_ajax_update_active_option_canonical_' . $this->active_option_name, array($this, 'update_active_option_callback'));
    }
    
    /**
     * Initialize features
     *
     * @return void
     */
    private function init_features() {
        // Initialize features manager
        $features_manager = new Aiautotool_Extra_Config_Features_Manager($this->settings);
        $features_manager->init();
    }
    
    /**
     * Register WordPress settings
     *
     * @return void
     */
    public function register_settings() {
        register_setting(
            'aiautotool_extra_config_group',
            'aiautotool_config_settings',
            array(
                'type' => 'array',
                'sanitize_callback' => array($this, 'sanitize_settings_callback'),
                'default' => $this->settings->get_defaults()
            )
        );
    }
    
    /**
     * Sanitize settings callback for WordPress Settings API
     *
     * @param array $input Input settings
     * @return array Sanitized settings
     */
    public function sanitize_settings_callback($input) {
        // Verify nonce
        if (!isset($_POST[$this->security::NONCE_FIELD]) || 
            !$this->security->verify_nonce($_POST[$this->security::NONCE_FIELD])) {
            add_settings_error(
                'aiautotool_config_settings',
                'nonce_failed',
                __('Security verification failed', 'ai-auto-tool'),
                'error'
            );
            return $this->settings->get_all();
        }
        
        // Verify permissions
        if (!$this->security->can_manage_settings()) {
            add_settings_error(
                'aiautotool_config_settings',
                'permission_denied',
                __('You do not have permission to update these settings', 'ai-auto-tool'),
                'error'
            );
            return $this->settings->get_all();
        }
        
        // Sanitize settings
        $sanitized = $this->security->sanitize_settings($input);
        
        // Add success message
        add_settings_error(
            'aiautotool_config_settings',
            'settings_updated',
            __('Settings saved successfully', 'ai-auto-tool'),
            'success'
        );
        
        // Clear cache
        $this->settings->clear_cache();
        
        return $sanitized;
    }
    
    /**
     * Enqueue admin assets
     *
     * @param string $hook Current admin page hook
     * @return void
     */
    public function enqueue_admin_assets($hook) {
        // Only load on our settings page
        if ($hook !== 'toplevel_page_ai_auto_tool') {
            return;
        }
        
        // Ensure translations are loaded (WordPress 6.7.0+ requirement)
        if (!did_action('init')) {
            return;
        }
        
        // Enqueue scripts
        wp_enqueue_script(
            'aiautotool-extra-config',
            plugins_url('../../js/extra-config.js', __FILE__),
            array('jquery'),
            defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : AIAUTOTOOL_VS,
            true
        );
        
        // Localize script (only use translation functions after 'init' has fired)
        wp_localize_script('aiautotool-extra-config', 'aiautotoolExtraConfig', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce'   => $this->security->create_nonce(),
            'strings' => array(
                'confirm_delete_revisions' => __('Are you sure you want to delete all revisions? This cannot be undone.', 'ai-auto-tool'),
                'confirm_delete_drafts'    => __('Are you sure you want to delete all auto-drafts? This cannot be undone.', 'ai-auto-tool'),
                'confirm_delete_trash'     => __('Are you sure you want to empty the trash? This cannot be undone.', 'ai-auto-tool'),
                'confirm_reset_settings'   => __('Are you sure you want to reset all settings to defaults?', 'ai-auto-tool'),
                'deleting'                 => __('Deleting...', 'ai-auto-tool'),
                'success'                  => __('Success!', 'ai-auto-tool'),
                'error'                    => __('Error!', 'ai-auto-tool'),
            )
        ));
        
        // Enqueue styles if needed
        wp_enqueue_style(
            'aiautotool-extra-config',
            plugins_url('../../css/extra-config.css', __FILE__),
            array(),
            defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : AIAUTOTOOL_VS
        );
    }
    
    /**
     * Update active option callback for AJAX
     *
     * @return void
     */
    public function update_active_option_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!$this->security->can_manage_settings()) {
            wp_die(__('Permission denied', 'ai-auto-tool'), 403);
        }
        
        if (isset($_POST['active'])) {
            $active = sanitize_text_field($_POST['active']);
            update_option($this->active_option_name, $active, false);
            echo esc_html($active);
        }
        
        wp_die();
    }
    
    /**
     * Render settings tab
     *
     * @return void
     */
    public function render_tab_setting() {
        // Always render (mandatory module)
        echo '<button href="#tool-extra-config" class="nav-tab sotab">';
        echo '<i class="fa-solid fa-shield-halved"></i> ';
        echo esc_html__('Optimize WP', 'ai-auto-tool');
        echo '</button>';
    }
    
    /**
     * Render settings page
     *
     * @return void
     */
    public function render_setting() {
        // Always render (mandatory module)
        // Load admin renderer
        require_once plugin_dir_path(__FILE__) . 'class-admin-renderer.php';
        $renderer = new Aiautotool_Extra_Config_Admin_Renderer($this->settings, $this->security);
        $renderer->render();
    }
    
    /**
     * Render feature box
     *
     * @return void
     */
    public function render_feature() {
        // Load feature descriptions
        require_once plugin_dir_path(dirname(dirname(__FILE__))) . 'lib/feature-descriptions.php';
        
        $autoToolBox = new AutoToolBox(
            '<i class="fa-solid fa-shield-halved"></i> ' . esc_html__('Extra Config & Optimization', 'ai-auto-tool'),
            AiAutoTool_Feature_Descriptions::get('tool_extra_config'),
            'https://doc.aiautotool.com/features/extra-tools',
            $this->active_option_name,
            $this->active,
            plugins_url('../../images/logo.svg', __FILE__)
        );
        
        echo $autoToolBox->generateHTML();
    }
    
    /**
     * Get settings instance
     *
     * @return Aiautotool_Extra_Config_Settings_Registry
     */
    public function get_settings() {
        return $this->settings;
    }
    
    /**
     * Get security instance
     *
     * @return Aiautotool_Extra_Config_Security
     */
    public function get_security() {
        return $this->security;
    }
    
    /**
     * Check if a feature is enabled
     *
     * @param string $feature_key Feature key
     * @return bool True if enabled
     */
    public function is_feature_enabled($feature_key) {
        return $this->settings->is_enabled($feature_key);
    }
    
    /**
     * Get all enabled features
     *
     * @return array Array of enabled feature keys
     */
    public function get_enabled_features() {
        return $this->settings->get_enabled_features();
    }
    
    /**
     * Get settings statistics
     *
     * @return array Statistics array
     */
    public function get_stats() {
        return $this->settings->get_stats();
    }
}

/**
 * Initialize Extra Config Manager
 * 
 * Note: This function is kept for backward compatibility but is no longer
 * automatically called on plugins_loaded. The manager is now initialized
 * by the bootstrap.php file on the 'init' hook to ensure translations
 * are loaded first (WordPress 6.7.0+ requirement).
 *
 * @return Aiautotool_Extra_Config_Manager
 */
function aiautotool_extra_config_manager() {
    return Aiautotool_Extra_Config_Manager::instance();
}

// Removed: add_action('plugins_loaded', 'aiautotool_extra_config_manager');
// The manager is now initialized by bootstrap.php on 'init' hook (priority 20)
// to comply with WordPress 6.7.0+ translation loading requirements


