<?php
/**
 * AI Auto Tool - Feature Management Admin Interface
 * 
 * Admin interface để quản lý các features và loading options
 * 
 * @package AI Auto Tool
 * @version 2.3.0
 */

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

class AIAutoTool_FeatureManager {
    
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        // Note: AJAX handler moved to AI_Auto_Tool::register_all_ajax_handlers()
        // to avoid conflicts. This handler is kept for backward compatibility but
        // should not be used for new code.
        // add_action('wp_ajax_aiautotool_toggle_feature', array($this, 'toggle_feature'));
    }
    
    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        
    }
    
    /**
     * Register settings
     */
    public function register_settings() {
        if (!class_exists('AIAutoTool_FeatureOptions')) {
            return;
        }
        
        // Get all features
        $allFeatures = AIAutoTool_FeatureOptions::get_all_features();
        
        foreach ($allFeatures as $feature) {
            $option = $feature . '_active';
            register_setting('aiautotool_features', $option, array(
                'type' => 'string',
                'sanitize_callback' => 'sanitize_text_field',
            ));
        }
    }
    
    /**
     * Render admin page
     */
    public function render_admin_page() {
        if (!class_exists('AIAutoTool_FeatureOptions')) {
            echo '<div class="wrap"><h1>Feature Manager</h1><p>Feature Options class not available.</p></div>';
            return;
        }
        
        $allFeatures = AIAutoTool_FeatureOptions::get_all_features();
        $activeFeatures = AIAutoTool_FeatureOptions::get_active_features();
        
        ?>
        <div class="wrap">
            <h1><?php _e('AI Auto Tool - Feature Manager', 'ai-auto-tool'); ?></h1>
            
            <!-- Feature Overview -->
            <div class="card" style="margin-bottom: 20px;">
                <h2><?php _e('Feature Overview', 'ai-auto-tool'); ?></h2>
                <p><?php printf(__('Total features: %d | Active features: %d | Inactive features: %d', 'ai-auto-tool'), 
                    count($allFeatures), 
                    count($activeFeatures), 
                    count($allFeatures) - count($activeFeatures)); ?></p>
            </div>
            
            <!-- Feature Management -->
            <form method="post" action="options.php">
                <?php settings_fields('aiautotool_features'); ?>
                
                <div class="card">
                    <h2><?php _e('Feature Management', 'ai-auto-tool'); ?></h2>
                    <p><?php _e('Enable/disable features to optimize loading performance. Only enabled features will be loaded.', 'ai-auto-tool'); ?></p>
                    
                    <table class="widefat">
                        <thead>
                            <tr>
                                <th><?php _e('Feature', 'ai-auto-tool'); ?></th>
                                <th><?php _e('Status', 'ai-auto-tool'); ?></th>
                                <th><?php _e('Action', 'ai-auto-tool'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($allFeatures as $feature): ?>
                                <?php 
                                $is_active = AIAutoTool_FeatureOptions::is_feature_active($feature);
                                $feature_name = str_replace('_', ' ', $feature);
                                $feature_name = ucwords($feature_name);
                                ?>
                                <tr>
                                    <td><strong><?php echo esc_html($feature_name); ?></strong></td>
                                    <td>
                                        <span class="status-<?php echo $is_active ? 'active' : 'inactive'; ?>">
                                            <?php echo $is_active ? __('Active', 'ai-auto-tool') : __('Inactive', 'ai-auto-tool'); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <button type="button" 
                                                class="button toggle-feature" 
                                                data-option="<?php echo esc_attr($feature . '_active'); ?>"
                                                data-current="<?php echo $is_active ? 'true' : 'false'; ?>">
                                            <?php echo $is_active ? __('Disable', 'ai-auto-tool') : __('Enable', 'ai-auto-tool'); ?>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <?php submit_button(__('Save Changes', 'ai-auto-tool')); ?>
            </form>
            
            <!-- Migration Tools -->
            <div class="card">
                <h2><?php _e('Migration Tools', 'ai-auto-tool'); ?></h2>
                <p><?php _e('Migrate to optimized loading system for better performance.', 'ai-auto-tool'); ?></p>
                
                <?php 
                $migration_needed = false;
                $optimized_loader_exists = false;
                
                if (class_exists('AIAutoTool_Migration')) {
                    $migration_needed = AIAutoTool_Migration::is_migration_needed();
                    $optimized_loader_exists = class_exists('AIAutoTool_Autoloader');
                }
                ?>
                
                <table class="widefat">
                    <tr>
                        <td><strong><?php _e('Migration Status', 'ai-auto-tool'); ?></strong></td>
                        <td>
                            <?php if ($migration_needed): ?>
                                <span style="color: orange;"><?php _e('Migration Available', 'ai-auto-tool'); ?></span>
                            <?php else: ?>
                                <span style="color: green;"><?php _e('Optimized Loading Active', 'ai-auto-tool'); ?></span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td><strong><?php _e('Optimized Loader', 'ai-auto-tool'); ?></strong></td>
                        <td>
                            <?php if ($optimized_loader_exists): ?>
                                <span style="color: green;">✓ <?php _e('Installed', 'ai-auto-tool'); ?></span>
                            <?php else: ?>
                                <span style="color: red;">✗ <?php _e('Not Installed', 'ai-auto-tool'); ?></span>
                            <?php endif; ?>
                        </td>
                    </tr>
                </table>
                
                <p>
                    <?php if ($migration_needed): ?>
                        <button type="button" class="button button-primary" onclick="migrateToOptimized()">
                            <?php _e('Migrate to Optimized Loading', 'ai-auto-tool'); ?>
                        </button>
                    <?php else: ?>
                        <button type="button" class="button" onclick="rollbackMigration()">
                            <?php _e('Rollback to Old Loading', 'ai-auto-tool'); ?>
                        </button>
                    <?php endif; ?>
                </p>
            </div>
        </div>
        
        <style>
        .status-active { color: green; font-weight: bold; }
        .status-inactive { color: red; font-weight: bold; }
        .card { background: white; padding: 20px; margin-bottom: 20px; border: 1px solid #ccd0d4; }
        </style>
        
        <script>
        jQuery(document).ready(function($) {
            $('.toggle-feature').on('click', function() {
                var button = $(this);
                var option = button.data('option');
                var current = button.data('current');
                var newValue = current === 'true' ? 'false' : 'true';
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'aiautotool_toggle_feature',
                        option: option,
                        value: newValue,
                        nonce: '<?php echo wp_create_nonce('aiautotool_features'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            alert('Error: ' + response.data);
                        }
                    }
                });
            });
        });
        
        function migrateToOptimized() {
            if (confirm('<?php _e('Are you sure you want to migrate to optimized loading? This will create a backup of your current settings.', 'ai-auto-tool'); ?>')) {
                // Implementation for migration
                alert('<?php _e('Migration feature will be implemented in the next update.', 'ai-auto-tool'); ?>');
            }
        }
        
        function rollbackMigration() {
            if (confirm('<?php _e('Are you sure you want to rollback to old loading method?', 'ai-auto-tool'); ?>')) {
                // Implementation for rollback
                alert('<?php _e('Rollback feature will be implemented in the next update.', 'ai-auto-tool'); ?>');
            }
        }
        </script>
        <?php
    }
    
    /**
     * Toggle feature via AJAX
     */
    public function toggle_feature() {
        check_ajax_referer('aiautotool_features', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $option = sanitize_text_field($_POST['option']);
        $value = sanitize_text_field($_POST['value']);
        
        update_option($option, $value);
        
        wp_send_json_success('Feature toggled successfully');
    }
}

// Initialize feature manager
new AIAutoTool_FeatureManager();
?>
