<?php
/**
 * Plugin Name: Database Optimizer Pro
 * Plugin URI: https://fedia.eu
 * Description: Професионален инструмент за оптимизация на WordPress база данни с модерен интерфейс
 * Version: 2.0.0
 * Author: Fedya Serafiev
 * Author URI: https://fedia.eu
 * License: GPL v2 or later
 * Text Domain: db-optimizer-pro
 */

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

class DB_Optimizer_Pro {
    
    private $plugin_slug = 'db-optimizer-pro';
    private $version = '2.0.0';
    
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
        add_action('admin_footer', array($this, 'output_admin_scripts'));
        add_action('wp_ajax_dbop_scan_database', array($this, 'ajax_scan_database'));
        add_action('wp_ajax_dbop_clean_items', array($this, 'ajax_clean_items'));
        add_action('wp_ajax_dbop_optimize_tables', array($this, 'ajax_optimize_tables'));
        add_action('wp_ajax_dbop_get_stats', array($this, 'ajax_get_stats'));
    }
    
    public function add_admin_menu() {
        add_menu_page(
            'Database Optimizer Pro',
            'DB Optimizer',
            'manage_options',
            $this->plugin_slug,
            array($this, 'render_admin_page'),
            'dashicons-database-view',
            80
        );
    }
    
    public function enqueue_admin_assets($hook) {
        if (strpos($hook, $this->plugin_slug) === false) {
            return;
        }
        
        // Enqueue jQuery (already included in WordPress)
        wp_enqueue_script('jquery');
        
        // Enqueue inline styles
        wp_register_style($this->plugin_slug . '-inline', false);
        wp_enqueue_style($this->plugin_slug . '-inline');
        wp_add_inline_style($this->plugin_slug . '-inline', $this->get_styles());
    }
    
    public function output_admin_scripts() {
        global $pagenow;
        
        if (isset($_GET['page']) && $_GET['page'] === $this->plugin_slug) {
            ?>
            <script type="text/javascript">
            jQuery(document).ready(function($) {
                // Define AJAX object
                var dbopAjax = {
                    ajax_url: '<?php echo admin_url('admin-ajax.php'); ?>',
                    nonce: '<?php echo wp_create_nonce('dbop_nonce'); ?>'
                };
                
                var scanData = {};
                
                // Tab switching
                $('.dbop-tab').on('click', function(e) {
                    e.preventDefault();
                    const tab = $(this).data('tab');
                    $('.dbop-tab').removeClass('active');
                    $(this).addClass('active');
                    $('.dbop-tab-content').removeClass('active');
                    $('#tab-' + tab).addClass('active');
                });
                
                // Scan database
                $('#dbop-scan-btn').on('click', function() {
                    const btn = $(this);
                    btn.prop('disabled', true).html('<span class="dbop-loading"></span> Сканиране...');
                    
                    console.log('Sending AJAX request...');
                    
                    $.ajax({
                        url: dbopAjax.ajax_url,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            action: 'dbop_scan_database',
                            nonce: dbopAjax.nonce
                        },
                        success: function(response) {
                            console.log('AJAX Response:', response);
                            if (response.success) {
                                scanData = response.data;
                                displayScanResults(response.data);
                                showAlert('success', 'Сканирането завърши успешно!');
                            } else {
                                showAlert('error', response.data?.message || 'Грешка при сканиране');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('AJAX Error:', error);
                            showAlert('error', 'AJAX грешка: ' + error);
                        },
                        complete: function() {
                            btn.prop('disabled', false).html('🔍 Сканирай база данни');
                        }
                    });
                });
                
                // Clean items
                $(document).on('click', '.dbop-clean-btn', function() {
                    const type = $(this).data('type');
                    const btn = $(this);
                    
                    if (!confirm('Сигурни ли сте, че искате да изтриете тези елементи?')) {
                        return;
                    }
                    
                    btn.prop('disabled', true).html('<span class="dbop-loading"></span>');
                    
                    $.ajax({
                        url: dbopAjax.ajax_url,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            action: 'dbop_clean_items',
                            nonce: dbopAjax.nonce,
                            type: type
                        },
                        success: function(response) {
                            if (response.success) {
                                showAlert('success', 'Почистването завърши успешно! Изтрити: ' + response.data.deleted);
                                $('#dbop-scan-btn').click();
                            } else {
                                showAlert('error', response.data?.message || 'Грешка при почистване');
                            }
                        },
                        error: function(xhr, status, error) {
                            showAlert('error', 'AJAX грешка: ' + error);
                        },
                        complete: function() {
                            btn.prop('disabled', false).html('🗑️ Изтрий');
                        }
                    });
                });
                
                // Optimize tables
                $('#dbop-optimize-btn').on('click', function() {
                    const btn = $(this);
                    
                    if (!confirm('Искате ли да оптимизирате всички таблици?')) {
                        return;
                    }
                    
                    btn.prop('disabled', true).html('<span class="dbop-loading"></span> Оптимизация...');
                    
                    $.ajax({
                        url: dbopAjax.ajax_url,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            action: 'dbop_optimize_tables',
                            nonce: dbopAjax.nonce
                        },
                        success: function(response) {
                            if (response.success) {
                                showAlert('success', 'Таблиците са оптимизирани успешно!');
                                updateStats(response.data.stats);
                            } else {
                                showAlert('error', response.data?.message || 'Грешка при оптимизация');
                            }
                        },
                        error: function(xhr, status, error) {
                            showAlert('error', 'AJAX грешка: ' + error);
                        },
                        complete: function() {
                            btn.prop('disabled', false).html('⚡ Оптимизирай таблици');
                        }
                    });
                });
                
                // Get initial stats
                function loadInitialStats() {
                    $.ajax({
                        url: dbopAjax.ajax_url,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            action: 'dbop_get_stats',
                            nonce: dbopAjax.nonce
                        },
                        success: function(response) {
                            if (response.success) {
                                updateStatsUI(response.data);
                            }
                        }
                    });
                }
                
                // Call on page load
                loadInitialStats();
                
                function displayScanResults(data) {
                    let html = '';
                    
                    const items = [
                        { key: 'orphaned_postmeta', icon: '🗂️', title: 'Orphaned Post Meta', desc: 'Мета данни без съответен пост' },
                        { key: 'orphaned_commentmeta', icon: '💬', title: 'Orphaned Comment Meta', desc: 'Мета данни без съответен коментар' },
                        { key: 'orphaned_usermeta', icon: '👤', title: 'Orphaned User Meta', desc: 'Мета данни без съответен потребител' },
                        { key: 'orphaned_termmeta', icon: '🏷️', title: 'Orphaned Term Meta', desc: 'Мета данни без съответен термин' },
                        { key: 'expired_transients', icon: '⏱️', title: 'Expired Transients', desc: 'Изтекли временни данни' },
                        { key: 'post_revisions', icon: '📝', title: 'Post Revisions', desc: 'Ревизии на публикации' },
                        { key: 'auto_drafts', icon: '📄', title: 'Auto Drafts', desc: 'Автоматични чернови' },
                        { key: 'trashed_posts', icon: '🗑️', title: 'Trashed Posts', desc: 'Изтрити публикации в кошчето' },
                        { key: 'spam_comments', icon: '⚠️', title: 'Spam Comments', desc: 'Спам коментари' },
                        { key: 'trashed_comments', icon: '💬', title: 'Trashed Comments', desc: 'Изтрити коментари' }
                    ];
                    
                    items.forEach(item => {
                        if (data[item.key] > 0) {
                            html += createResultItem(item.key, item.icon + ' ' + item.title, item.desc, data[item.key]);
                        }
                    });
                    
                    if (html === '') {
                        html = '<div class="dbop-alert dbop-alert-success">✅ Базата данни е чиста! Няма елементи за почистване.</div>';
                    }
                    
                    $('#dbop-results').html(html);
                }
                
                function createResultItem(type, title, description, count) {
                    return `
                        <div class="dbop-result-item">
                            <div class="dbop-result-info">
                                <div class="dbop-result-title">${title}</div>
                                <div class="dbop-result-description">${description}</div>
                            </div>
                            <div style="display: flex; align-items: center;">
                                <span class="dbop-result-count">${count}</span>
                                <button class="dbop-btn dbop-btn-danger dbop-clean-btn" data-type="${type}">🗑️ Изтрий</button>
                            </div>
                        </div>
                    `;
                }
                
                function updateStatsUI(stats) {
                    $('#stat-db-size').text(stats.db_size || '0 MB');
                    $('#stat-tables').text(stats.total_tables || '0');
                    $('#stat-overhead').text(stats.overhead || '0 MB');
                }
                
                function updateStats(stats) {
                    // Update stats after optimization
                    if (stats) {
                        $('#stat-db-size').text(stats.db_size || '0 MB');
                        $('#stat-tables').text(stats.total_tables || '0');
                        $('#stat-overhead').text(stats.overhead || '0 MB');
                    }
                }
                
                function showAlert(type, message) {
                    const alertClass = 'dbop-alert-' + type;
                    const icon = type === 'success' ? '✅' : (type === 'warning' ? '⚠️' : '❌');
                    const alert = `<div class="dbop-alert ${alertClass}">${icon} ${message}</div>`;
                    
                    $('.dbop-main-card').prepend(alert);
                    
                    setTimeout(function() {
                        $('.dbop-alert').first().fadeOut(function() {
                            $(this).remove();
                        });
                    }, 5000);
                }
                
                // Initialize tabs
                $('.dbop-tab[data-tab="cleaner"]').addClass('active');
                $('#tab-cleaner').addClass('active');
            });
            </script>
            <?php
        }
    }
    
    private function get_styles() {
        return "
            .dbop-container {
                max-width: 1400px;
                margin: 20px auto;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            }
            
            .dbop-header {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 40px;
                border-radius: 16px;
                margin-bottom: 30px;
                box-shadow: 0 10px 40px rgba(102, 126, 234, 0.3);
            }
            
            .dbop-header h1 {
                margin: 0 0 10px 0;
                font-size: 32px;
                font-weight: 700;
            }
            
            .dbop-header p {
                margin: 0;
                opacity: 0.9;
                font-size: 16px;
            }
            
            .dbop-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
                gap: 20px;
                margin-bottom: 30px;
            }
            
            .dbop-card {
                background: white;
                border-radius: 12px;
                padding: 25px;
                box-shadow: 0 2px 12px rgba(0,0,0,0.08);
                transition: all 0.3s ease;
                border: 1px solid #e5e7eb;
            }
            
            .dbop-card:hover {
                transform: translateY(-4px);
                box-shadow: 0 8px 24px rgba(0,0,0,0.12);
            }
            
            .dbop-card h3 {
                margin-top: 0;
                margin-bottom: 10px;
                color: #374151;
                font-size: 16px;
                font-weight: 600;
            }
            
            .dbop-stat-value {
                font-size: 32px;
                font-weight: 700;
                color: #111827;
                margin: 10px 0;
            }
            
            .dbop-card p {
                font-size: 13px;
                color: #9ca3af;
                margin: 0;
            }
            
            .dbop-main-card {
                background: white;
                border-radius: 12px;
                padding: 30px;
                box-shadow: 0 2px 12px rgba(0,0,0,0.08);
                border: 1px solid #e5e7eb;
                margin-bottom: 30px;
            }
            
            .dbop-actions {
                display: flex;
                gap: 15px;
                margin-bottom: 30px;
                flex-wrap: wrap;
            }
            
            .dbop-btn {
                padding: 12px 24px;
                border: none;
                border-radius: 8px;
                font-size: 14px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s ease;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                gap: 8px;
                min-height: 44px;
            }
            
            .dbop-btn-primary {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
            }
            
            .dbop-btn-primary:hover:not(:disabled) {
                transform: translateY(-2px);
                box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
            }
            
            .dbop-btn-secondary {
                background: #f3f4f6;
                color: #374151;
            }
            
            .dbop-btn-secondary:hover:not(:disabled) {
                background: #e5e7eb;
            }
            
            .dbop-btn-danger {
                background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
                color: white;
            }
            
            .dbop-btn-danger:hover:not(:disabled) {
                transform: translateY(-2px);
                box-shadow: 0 6px 20px rgba(239, 68, 68, 0.4);
            }
            
            .dbop-btn:disabled {
                opacity: 0.5;
                cursor: not-allowed;
                transform: none !important;
            }
            
            .dbop-results {
                margin-top: 30px;
            }
            
            .dbop-result-item {
                background: #f9fafb;
                border-left: 4px solid #667eea;
                padding: 15px 20px;
                margin-bottom: 12px;
                border-radius: 8px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                transition: all 0.2s ease;
            }
            
            .dbop-result-item:hover {
                background: #f3f4f6;
            }
            
            .dbop-result-info {
                flex: 1;
            }
            
            .dbop-result-title {
                font-weight: 600;
                color: #111827;
                margin-bottom: 4px;
            }
            
            .dbop-result-description {
                font-size: 13px;
                color: #6b7280;
            }
            
            .dbop-result-count {
                background: #667eea;
                color: white;
                padding: 6px 12px;
                border-radius: 20px;
                font-weight: 600;
                font-size: 14px;
                margin-right: 10px;
            }
            
            .dbop-loading {
                display: inline-block;
                width: 16px;
                height: 16px;
                border: 2px solid rgba(255,255,255,0.3);
                border-top-color: white;
                border-radius: 50%;
                animation: spin 0.8s linear infinite;
            }
            
            @keyframes spin {
                to { transform: rotate(360deg); }
            }
            
            .dbop-alert {
                padding: 15px 20px;
                border-radius: 8px;
                margin-bottom: 20px;
                display: flex;
                align-items: flex-start;
                gap: 12px;
            }
            
            .dbop-alert-success {
                background: #ecfdf5;
                color: #065f46;
                border: 1px solid #a7f3d0;
            }
            
            .dbop-alert-warning {
                background: #fef3c7;
                color: #92400e;
                border: 1px solid #fde68a;
            }
            
            .dbop-alert-error {
                background: #fee2e2;
                color: #991b1b;
                border: 1px solid #fecaca;
            }
            
            .dbop-alert-info {
                background: #eff6ff;
                color: #1e40af;
                border: 1px solid #bfdbfe;
            }
            
            .dbop-tabs {
                display: flex;
                gap: 10px;
                margin-bottom: 25px;
                border-bottom: 2px solid #e5e7eb;
                flex-wrap: wrap;
            }
            
            .dbop-tab {
                padding: 12px 20px;
                background: none;
                border: none;
                color: #6b7280;
                font-weight: 600;
                cursor: pointer;
                position: relative;
                transition: all 0.3s ease;
                border-radius: 6px 6px 0 0;
            }
            
            .dbop-tab:hover {
                color: #667eea;
                background: #f3f4f6;
            }
            
            .dbop-tab.active {
                color: #667eea;
            }
            
            .dbop-tab.active::after {
                content: '';
                position: absolute;
                bottom: -2px;
                left: 0;
                right: 0;
                height: 2px;
                background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            }
            
            .dbop-tab-content {
                display: none;
            }
            
            .dbop-tab-content.active {
                display: block;
            }
            
            @media (max-width: 768px) {
                .dbop-grid {
                    grid-template-columns: 1fr;
                }
                
                .dbop-actions {
                    flex-direction: column;
                }
                
                .dbop-btn {
                    width: 100%;
                }
                
                .dbop-header {
                    padding: 25px;
                }
                
                .dbop-header h1 {
                    font-size: 24px;
                }
            }
        ";
    }
    
    public function render_admin_page() {
        global $wpdb;
        
        // Get initial database stats
        $stats = $this->get_database_stats();
        ?>
        <div class="dbop-container">
            <div class="dbop-header">
                <h1>🚀 Database Optimizer Pro</h1>
                <p>Професионален инструмент за оптимизация и почистване на WordPress база данни</p>
            </div>
            
            <div class="dbop-grid">
                <div class="dbop-card">
                    <h3>Размер на БД</h3>
                    <div class="dbop-stat-value" id="stat-db-size"><?php echo esc_html($stats['db_size']); ?></div>
                    <p>Общ размер на базата данни</p>
                </div>
                
                <div class="dbop-card">
                    <h3>Таблици</h3>
                    <div class="dbop-stat-value" id="stat-tables"><?php echo (int)$stats['total_tables']; ?></div>
                    <p>Общо таблици в БД</p>
                </div>
                
                <div class="dbop-card">
                    <h3>Overhead</h3>
                    <div class="dbop-stat-value" id="stat-overhead"><?php echo esc_html($stats['overhead']); ?></div>
                    <p>Неизползвано място в таблици</p>
                </div>
                
                <div class="dbop-card">
                    <h3>Оптимизации</h3>
                    <div class="dbop-stat-value"><?php echo (int)get_option('dbop_optimization_count', 0); ?></div>
                    <p>Брой оптимизации</p>
                </div>
            </div>
            
            <div class="dbop-main-card">
                <nav class="dbop-tabs">
                    <button class="dbop-tab active" data-tab="cleaner">🧹 Почистване</button>
                    <button class="dbop-tab" data-tab="optimizer">⚡ Оптимизация</button>
                    <button class="dbop-tab" data-tab="info">ℹ️ Информация</button>
                </nav>
                
                <div id="tab-cleaner" class="dbop-tab-content active">
                    <div class="dbop-actions">
                        <button id="dbop-scan-btn" class="dbop-btn dbop-btn-primary">
                            🔍 Сканирай база данни
                        </button>
                    </div>
                    
                    <div id="dbop-results">
                        <div class="dbop-alert dbop-alert-warning">
                            ⚠️ Натиснете "Сканирай база данни" за да започнете анализ
                        </div>
                    </div>
                </div>
                
                <div id="tab-optimizer" class="dbop-tab-content">
                    <div class="dbop-actions">
                        <button id="dbop-optimize-btn" class="dbop-btn dbop-btn-primary">
                            ⚡ Оптимизирай таблици
                        </button>
                    </div>
                    
                    <div class="dbop-alert dbop-alert-info">
                        ℹ️ Оптимизацията ще подобри производителността на базата данни чрез реорганизация на таблиците
                    </div>
                </div>
                
                <div id="tab-info" class="dbop-tab-content">
                    <h3>За плъгина</h3>
                    <p>Database Optimizer Pro е професионален инструмент за поддръжка на WordPress база данни.</p>
                    
                    <h4>Функции:</h4>
                    <ul>
                        <li>✅ Почистване на orphaned metadata</li>
                        <li>✅ Изтриване на изтекли transients</li>
                        <li>✅ Премахване на ревизии и автосъхранения</li>
                        <li>✅ Изчистване на спам и изтрити коментари</li>
                        <li>✅ Оптимизация на всички таблици</li>
                        <li>✅ Подробна статистика и визуализация</li>
                    </ul>
                    
                    <div class="dbop-alert dbop-alert-warning">
                        ⚠️ Препоръчително: Направете backup на базата данни преди да извършвате операции!
                    </div>
                </div>
            </div>
            
            <div class="dbop-alert dbop-alert-info">
                💡 <strong>Pro Tip:</strong> Редовната поддръжка на базата данни подобрява производителността на сайта.
            </div>
        </div>
        <?php
    }
    
    private function get_database_stats() {
        global $wpdb;
        
        $db_size = $wpdb->get_var("
            SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 2)
            FROM information_schema.tables 
            WHERE table_schema = DATABASE()
        ") . ' MB';
        
        $total_tables = $wpdb->get_var("
            SELECT COUNT(*)
            FROM information_schema.tables 
            WHERE table_schema = DATABASE()
        ");
        
        $overhead = $wpdb->get_var("
            SELECT ROUND(SUM(data_free) / 1024 / 1024, 2)
            FROM information_schema.tables 
            WHERE table_schema = DATABASE() 
            AND ENGINE = 'InnoDB'
        ") . ' MB';
        
        return array(
            'db_size' => $db_size,
            'total_tables' => $total_tables,
            'overhead' => $overhead
        );
    }
    
    public function ajax_scan_database() {
        check_ajax_referer('dbop_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Недостатъчни права'));
        }
        
        global $wpdb;
        
        $data = array(
            'orphaned_postmeta' => $this->count_orphaned_postmeta(),
            'orphaned_commentmeta' => $this->count_orphaned_commentmeta(),
            'orphaned_usermeta' => $this->count_orphaned_usermeta(),
            'orphaned_termmeta' => $this->count_orphaned_termmeta(),
            'expired_transients' => $this->count_expired_transients(),
            'post_revisions' => $this->count_post_revisions(),
            'auto_drafts' => $this->count_auto_drafts(),
            'trashed_posts' => $this->count_trashed_posts(),
            'spam_comments' => $this->count_spam_comments(),
            'trashed_comments' => $this->count_trashed_comments()
        );
        
        wp_send_json_success($data);
    }
    
    public function ajax_clean_items() {
        check_ajax_referer('dbop_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Недостатъчни права'));
        }
        
        $type = sanitize_text_field($_POST['type']);
        $deleted = 0;
        
        switch ($type) {
            case 'orphaned_postmeta':
                $deleted = $this->clean_orphaned_postmeta();
                break;
            case 'orphaned_commentmeta':
                $deleted = $this->clean_orphaned_commentmeta();
                break;
            case 'orphaned_usermeta':
                $deleted = $this->clean_orphaned_usermeta();
                break;
            case 'orphaned_termmeta':
                $deleted = $this->clean_orphaned_termmeta();
                break;
            case 'expired_transients':
                $deleted = $this->clean_expired_transients();
                break;
            case 'post_revisions':
                $deleted = $this->clean_post_revisions();
                break;
            case 'auto_drafts':
                $deleted = $this->clean_auto_drafts();
                break;
            case 'trashed_posts':
                $deleted = $this->clean_trashed_posts();
                break;
            case 'spam_comments':
                $deleted = $this->clean_spam_comments();
                break;
            case 'trashed_comments':
                $deleted = $this->clean_trashed_comments();
                break;
        }
        
        wp_send_json_success(array('deleted' => $deleted));
    }
    
    public function ajax_optimize_tables() {
        check_ajax_referer('dbop_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Недостатъчни права'));
        }
        
        global $wpdb;
        $optimized = 0;
        
        $tables = $wpdb->get_results("SHOW TABLES", ARRAY_N);
        
        foreach ($tables as $table) {
            $table_name = $table[0];
            $result = $wpdb->query("OPTIMIZE TABLE `{$table_name}`");
            if ($result !== false) {
                $optimized++;
            }
        }
        
        // Update optimization count
        $count = get_option('dbop_optimization_count', 0);
        update_option('dbop_optimization_count', $count + 1);
        
        wp_send_json_success(array(
            'optimized' => $optimized,
            'stats' => $this->get_database_stats()
        ));
    }
    
    public function ajax_get_stats() {
        check_ajax_referer('dbop_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Недостатъчни права'));
        }
        
        wp_send_json_success($this->get_database_stats());
    }
    
    // Count methods
    private function count_orphaned_postmeta() {
        global $wpdb;
        return (int)$wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$wpdb->postmeta} pm 
            LEFT JOIN {$wpdb->posts} p ON pm.post_id = p.ID 
            WHERE p.ID IS NULL
        ");
    }
    
    private function count_orphaned_commentmeta() {
        global $wpdb;
        return (int)$wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$wpdb->commentmeta} cm 
            LEFT JOIN {$wpdb->comments} c ON cm.comment_id = c.comment_ID 
            WHERE c.comment_ID IS NULL
        ");
    }
    
    private function count_orphaned_usermeta() {
        global $wpdb;
        return (int)$wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$wpdb->usermeta} um 
            LEFT JOIN {$wpdb->users} u ON um.user_id = u.ID 
            WHERE u.ID IS NULL
        ");
    }
    
    private function count_orphaned_termmeta() {
        global $wpdb;
        return (int)$wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$wpdb->termmeta} tm 
            LEFT JOIN {$wpdb->terms} t ON tm.term_id = t.term_id 
            WHERE t.term_id IS NULL
        ");
    }
    
    private function count_expired_transients() {
        global $wpdb;
        return (int)$wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$wpdb->options} 
            WHERE option_name LIKE '_transient_timeout_%' 
            AND option_value < UNIX_TIMESTAMP()
        ");
    }
    
    private function count_post_revisions() {
        global $wpdb;
        return (int)$wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$wpdb->posts} 
            WHERE post_type = 'revision'
        ");
    }
    
    private function count_auto_drafts() {
        global $wpdb;
        return (int)$wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$wpdb->posts} 
            WHERE post_status = 'auto-draft'
        ");
    }
    
    private function count_trashed_posts() {
        global $wpdb;
        return (int)$wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$wpdb->posts} 
            WHERE post_status = 'trash'
        ");
    }
    
    private function count_spam_comments() {
        global $wpdb;
        return (int)$wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$wpdb->comments} 
            WHERE comment_approved = 'spam'
        ");
    }
    
    private function count_trashed_comments() {
        global $wpdb;
        return (int)$wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$wpdb->comments} 
            WHERE comment_approved = 'trash'
        ");
    }
    
    // Clean methods
    private function clean_orphaned_postmeta() {
        global $wpdb;
        return (int)$wpdb->query("
            DELETE pm FROM {$wpdb->postmeta} pm 
            LEFT JOIN {$wpdb->posts} p ON pm.post_id = p.ID 
            WHERE p.ID IS NULL
        ");
    }
    
    private function clean_orphaned_commentmeta() {
        global $wpdb;
        return (int)$wpdb->query("
            DELETE cm FROM {$wpdb->commentmeta} cm 
            LEFT JOIN {$wpdb->comments} c ON cm.comment_id = c.comment_ID 
            WHERE c.comment_ID IS NULL
        ");
    }
    
    private function clean_orphaned_usermeta() {
        global $wpdb;
        return (int)$wpdb->query("
            DELETE um FROM {$wpdb->usermeta} um 
            LEFT JOIN {$wpdb->users} u ON um.user_id = u.ID 
            WHERE u.ID IS NULL
        ");
    }
    
    private function clean_orphaned_termmeta() {
        global $wpdb;
        return (int)$wpdb->query("
            DELETE tm FROM {$wpdb->termmeta} tm 
            LEFT JOIN {$wpdb->terms} t ON tm.term_id = t.term_id 
            WHERE t.term_id IS NULL
        ");
    }
    
    private function clean_expired_transients() {
        global $wpdb;
        
        $time = time();
        $transients = $wpdb->get_col("
            SELECT option_name 
            FROM {$wpdb->options} 
            WHERE option_name LIKE '_transient_timeout_%' 
            AND option_value < {$time}
        ");
        
        $deleted = 0;
        
        foreach ($transients as $transient) {
            $key = str_replace('_transient_timeout_', '', $transient);
            delete_transient($key);
            $deleted++;
        }
        
        return $deleted;
    }
    
    private function clean_post_revisions() {
        global $wpdb;
        return (int)$wpdb->query("
            DELETE FROM {$wpdb->posts} 
            WHERE post_type = 'revision'
        ");
    }
    
    private function clean_auto_drafts() {
        global $wpdb;
        return (int)$wpdb->query("
            DELETE FROM {$wpdb->posts} 
            WHERE post_status = 'auto-draft'
        ");
    }
    
    private function clean_trashed_posts() {
        global $wpdb;
        return (int)$wpdb->query("
            DELETE FROM {$wpdb->posts} 
            WHERE post_status = 'trash'
        ");
    }
    
    private function clean_spam_comments() {
        global $wpdb;
        return (int)$wpdb->query("
            DELETE FROM {$wpdb->comments} 
            WHERE comment_approved = 'spam'
        ");
    }
    
    private function clean_trashed_comments() {
        global $wpdb;
        return (int)$wpdb->query("
            DELETE FROM {$wpdb->comments} 
            WHERE comment_approved = 'trash'
        ");
    }
}

// Initialize the plugin
function db_optimizer_pro_init() {
    new DB_Optimizer_Pro();
}
add_action('plugins_loaded', 'db_optimizer_pro_init');