<?php
/**
 * Name: Remove Unused Themes and Plugins
 * Description: Remove all inactive themes and plugins with single click after confirmation to clean up WordPress installation and free disk space from unused files
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Add Useful Functionality",
 *     "description": "Extend WordPress with helpful tools that make site management easier."
 *   },
 *   {
 *     "title": "Save Time",
 *     "description": "Automate or simplify tasks that would otherwise require manual work or additional tools."
 *   }
 * ]
 * Tags: cleanup, plugins, themes, optimization, maintenance
 * Added: 2025-10-20
 * WhereToFind: {
 *   "location": "Switchboard Settings",
 *   "url": "",
 *   "instructions": "Click button in module settings to see list of all inactive themes and plugins, then remove them with one click after confirmation.",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardRemoveUnusedThemesPlugins {

    public function __construct() {
        // Add AJAX handler for getting inactive items
        add_action('wp_ajax_switchboard_get_inactive_items', [$this, 'get_inactive_items']);

        // Add AJAX handler for removing inactive items
        add_action('wp_ajax_switchboard_remove_inactive_items', [$this, 'remove_inactive_items']);
    }

    /**
     * Get all inactive plugins and themes
     */
    public function get_inactive_items() {
        check_ajax_referer('switchboard-settings', 'nonce');

        if (!current_user_can('delete_plugins') && !current_user_can('delete_themes')) {
            wp_send_json_error(['message' => esc_html__('Insufficient permissions', 'wpswitchboard')]);
            return;
        }

        $inactive_plugins = $this->get_inactive_plugins();
        $inactive_themes = $this->get_inactive_themes();

        wp_send_json_success([
            'plugins' => $inactive_plugins,
            'themes' => $inactive_themes,
            'total' => count($inactive_plugins) + count($inactive_themes)
        ]);
    }

    /**
     * Get list of inactive plugins
     */
    private function get_inactive_plugins() {
        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $all_plugins = get_plugins();
        $active_plugins = get_option('active_plugins', []);

        // Check for network active plugins if multisite
        if (is_multisite()) {
            $network_active = get_site_option('active_sitewide_plugins', []);
            $network_active = array_keys($network_active);
            $active_plugins = array_merge($active_plugins, $network_active);
        }

        $inactive_plugins = [];

        foreach ($all_plugins as $plugin_file => $plugin_data) {
            if (!in_array($plugin_file, $active_plugins)) {
                $inactive_plugins[] = [
                    'file' => $plugin_file,
                    'name' => $plugin_data['Name'],
                    'version' => $plugin_data['Version'],
                    'author' => $plugin_data['Author']
                ];
            }
        }

        return $inactive_plugins;
    }

    /**
     * Get list of inactive themes
     */
    private function get_inactive_themes() {
        $all_themes = wp_get_themes();
        $current_theme = get_stylesheet();

        // Get parent theme if current theme is a child theme
        $parent_theme = get_template();

        $inactive_themes = [];

        foreach ($all_themes as $theme_slug => $theme) {
            // Skip active theme and its parent
            if ($theme_slug === $current_theme || $theme_slug === $parent_theme) {
                continue;
            }

            $inactive_themes[] = [
                'slug' => $theme_slug,
                'name' => $theme->get('Name'),
                'version' => $theme->get('Version'),
                'author' => $theme->get('Author')
            ];
        }

        return $inactive_themes;
    }

    /**
     * Remove inactive plugins and themes
     */
    public function remove_inactive_items() {
        check_ajax_referer('switchboard-settings', 'nonce');

        if (!current_user_can('delete_plugins') && !current_user_can('delete_themes')) {
            wp_send_json_error(['message' => esc_html__('Insufficient permissions', 'wpswitchboard')]);
            return;
        }

        $type = isset($_POST['type']) ? sanitize_text_field($_POST['type']) : 'all';

        $results = [
            'plugins_deleted' => 0,
            'themes_deleted' => 0,
            'plugins_failed' => 0,
            'themes_failed' => 0,
            'errors' => []
        ];

        // Remove plugins
        if ($type === 'all' || $type === 'plugins') {
            if (current_user_can('delete_plugins')) {
                $results = array_merge($results, $this->delete_inactive_plugins());
            }
        }

        // Remove themes
        if ($type === 'all' || $type === 'themes') {
            if (current_user_can('delete_themes')) {
                $results = array_merge($results, $this->delete_inactive_themes());
            }
        }

        $total_deleted = $results['plugins_deleted'] + $results['themes_deleted'];
        $total_failed = $results['plugins_failed'] + $results['themes_failed'];

        if ($total_deleted > 0) {
            wp_send_json_success([
                'message' => sprintf(
                    esc_html__('Successfully removed %d item(s). %s', 'wpswitchboard'),
                    $total_deleted,
                    $total_failed > 0 ? sprintf(esc_html__('%d item(s) failed to remove.', 'wpswitchboard'), $total_failed) : ''
                ),
                'results' => $results
            ]);
        } else {
            wp_send_json_error([
                'message' => esc_html__('No items were removed.', 'wpswitchboard') . ' ' . ($total_failed > 0 ? sprintf(esc_html__('%d item(s) failed to remove.', 'wpswitchboard'), $total_failed) : ''),
                'results' => $results
            ]);
        }
    }

    /**
     * Delete inactive plugins
     */
    private function delete_inactive_plugins() {
        if (!function_exists('delete_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $inactive_plugins = $this->get_inactive_plugins();
        $deleted = 0;
        $failed = 0;
        $errors = [];

        foreach ($inactive_plugins as $plugin) {
            $result = delete_plugins([$plugin['file']]);

            if (is_wp_error($result)) {
                $failed++;
                $errors[] = sprintf(esc_html__('Plugin "%s": %s', 'wpswitchboard'), $plugin['name'], $result->get_error_message());
            } elseif ($result === true) {
                $deleted++;
            } else {
                $failed++;
                $errors[] = sprintf(esc_html__('Plugin "%s": Unknown error', 'wpswitchboard'), $plugin['name']);
            }
        }

        return [
            'plugins_deleted' => $deleted,
            'plugins_failed' => $failed,
            'errors' => $errors
        ];
    }

    /**
     * Delete inactive themes
     */
    private function delete_inactive_themes() {
        if (!function_exists('delete_theme')) {
            require_once ABSPATH . 'wp-admin/includes/theme.php';
        }

        $inactive_themes = $this->get_inactive_themes();
        $deleted = 0;
        $failed = 0;
        $errors = [];

        foreach ($inactive_themes as $theme) {
            $result = delete_theme($theme['slug']);

            if (is_wp_error($result)) {
                $failed++;
                $errors[] = sprintf(esc_html__('Theme "%s": %s', 'wpswitchboard'), $theme['name'], $result->get_error_message());
            } elseif ($result === true) {
                $deleted++;
            } else {
                $failed++;
                $errors[] = sprintf(esc_html__('Theme "%s": Unknown error', 'wpswitchboard'), $theme['name']);
            }
        }

        return [
            'themes_deleted' => $deleted,
            'themes_failed' => $failed,
            'errors' => $errors
        ];
    }

    /**
     * Render settings panel
     *
     * @param array $settings Current module settings
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        ?>
        <input type="hidden" name="module" value="remove-unused-themes-plugins">

        <div class="sb-sp-info-box sb-sp-info-box-tip" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm">Warning</h4>
            <p class="sb-sp-description" style="margin: 0;">
                <?php esc_html_e('This action will permanently delete inactive themes and plugins. Make sure you have a backup before proceeding!', 'wpswitchboard'); ?>
            </p>
        </div>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin-bottom: 24px;">
            <div>
                <h3 style="font-size: 16px; font-weight: 600; color: #111827; margin: 0 0 12px 0; display: flex; align-items: center; gap: 8px;">
                    <?php esc_html_e('Inactive Plugins', 'wpswitchboard'); ?>
                    <span id="plugins-count" class="sb-sp-badge" style="background: #dbeafe; color: #1e40af; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 500;">0</span>
                </h3>
                <div id="inactive-plugins-list" style="max-height: 400px; overflow-y: auto; border: 1px solid #e5e7eb; border-radius: 8px; padding: 16px; background: #f9fafb; margin-bottom: 12px;">
                    <div style="text-align: center; padding: 32px 16px;">
                        <p class="sb-sp-description" style="margin: 0;"><?php esc_html_e('Click "Scan for Inactive Items" to load plugins', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <button type="button" class="sb-sp-card-action-btn sb-sp-card-action-btn-delete" id="remove-plugins-btn" style="width: 100%; min-height: 32px; font-size: 13px;">
                    <?php esc_html_e('Remove All Inactive Plugins', 'wpswitchboard'); ?>
                </button>
            </div>

            <div>
                <h3 style="font-size: 16px; font-weight: 600; color: #111827; margin: 0 0 12px 0; display: flex; align-items: center; gap: 8px;">
                    <?php esc_html_e('Inactive Themes', 'wpswitchboard'); ?>
                    <span id="themes-count" class="sb-sp-badge" style="background: #dbeafe; color: #1e40af; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 500;">0</span>
                </h3>
                <div id="inactive-themes-list" style="max-height: 400px; overflow-y: auto; border: 1px solid #e5e7eb; border-radius: 8px; padding: 16px; background: #f9fafb; margin-bottom: 12px;">
                    <div style="text-align: center; padding: 32px 16px;">
                        <p class="sb-sp-description" style="margin: 0;"><?php esc_html_e('Click "Scan for Inactive Items" to load themes', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <button type="button" class="sb-sp-card-action-btn sb-sp-card-action-btn-delete" id="remove-themes-btn" style="width: 100%; min-height: 32px; font-size: 13px;">
                    <?php esc_html_e('Remove All Inactive Themes', 'wpswitchboard'); ?>
                </button>
            </div>
        </div>

        <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;">
            <button type="button" class="sb-sp-card-action-btn sb-sp-card-action-btn-edit" id="scan-inactive-btn" style="min-height: 32px; padding: 0 16px; font-size: 13px;">
                <?php esc_html_e('Scan for Inactive Items', 'wpswitchboard'); ?>
            </button>
            <button type="button" class="sb-sp-card-action-btn sb-sp-card-action-btn-delete" id="remove-all-btn" style="display: none; min-height: 32px; padding: 0 16px; font-size: 13px;">
                <?php esc_html_e('Remove All Inactive Items', 'wpswitchboard'); ?>
            </button>
            <div id="scan-status" style="flex: 1;"></div>
        </div>

        <div id="removal-results" style="display: none;"></div>


        <script>
        jQuery(document).ready(function($) {
            let inactiveData = null;

            // Scan for inactive items
            $('#scan-inactive-btn').on('click', function() {
                const button = $(this);
                button.prop('disabled', true).html('Scanning...');
                $('#scan-status').text('Loading inactive plugins and themes...');

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_get_inactive_items',
                        nonce: '<?php echo wp_create_nonce('switchboard-settings'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            inactiveData = response.data;
                            displayInactiveItems(response.data);
                            $('#scan-status').html('<span style="color: var(--primary-600); font-weight: 500;">Scan complete!</span>');

                            if (response.data.total > 0) {
                                $('#remove-all-btn').show();
                            }
                        } else {
                            $('#scan-status').html('<span style="color: #dc2626; font-weight: 500;">Error: ' + response.data.message + '</span>');
                        }
                    },
                    error: function() {
                        $('#scan-status').html('<span style="color: #dc2626; font-weight: 500;">Failed to scan. Please try again.</span>');
                    },
                    complete: function() {
                        button.prop('disabled', false).html('Scan for Inactive Items');
                    }
                });
            });

            // Display inactive items
            function displayInactiveItems(data) {
                // Display plugins
                if (data.plugins.length === 0) {
                    $('#inactive-plugins-list').html('<div style="text-align: center; padding: 32px 16px;"><p class="sb-sp-description" style="margin: 0;">All plugins are active!</p></div>');
                    $('#remove-plugins-btn').hide();
                } else {
                    let pluginsHtml = '';
                    data.plugins.forEach(function(plugin) {
                        pluginsHtml += '<div class="sb-sp-card" style="margin-bottom: 8px;">';
                        pluginsHtml += '<div class="sb-sp-card-body">';
                        pluginsHtml += '<div class="sb-sp-text-semibold" style="margin-bottom: 4px;">' + escapeHtml(plugin.name) + '</div>';
                        pluginsHtml += '<div class="sb-sp-text-sm" style="color: #64748b;">Version: ' + escapeHtml(plugin.version);
                        if (plugin.author) {
                            pluginsHtml += ' | Author: ' + escapeHtml(plugin.author);
                        }
                        pluginsHtml += '</div>';
                        pluginsHtml += '</div>';
                        pluginsHtml += '</div>';
                    });
                    $('#inactive-plugins-list').html(pluginsHtml);
                    $('#remove-plugins-btn').show();
                }
                $('#plugins-count').text(data.plugins.length);

                // Display themes
                if (data.themes.length === 0) {
                    $('#inactive-themes-list').html('<div style="text-align: center; padding: 32px 16px;"><p class="sb-sp-description" style="margin: 0;">All themes are active!</p></div>');
                    $('#remove-themes-btn').hide();
                } else {
                    let themesHtml = '';
                    data.themes.forEach(function(theme) {
                        themesHtml += '<div class="sb-sp-card" style="margin-bottom: 8px;">';
                        themesHtml += '<div class="sb-sp-card-body">';
                        themesHtml += '<div class="sb-sp-text-semibold" style="margin-bottom: 4px;">' + escapeHtml(theme.name) + '</div>';
                        themesHtml += '<div class="sb-sp-text-sm" style="color: #64748b;">Version: ' + escapeHtml(theme.version);
                        if (theme.author) {
                            themesHtml += ' | Author: ' + escapeHtml(theme.author);
                        }
                        themesHtml += '</div>';
                        themesHtml += '</div>';
                        themesHtml += '</div>';
                    });
                    $('#inactive-themes-list').html(themesHtml);
                    $('#remove-themes-btn').show();
                }
                $('#themes-count').text(data.themes.length);
            }

            // Remove all inactive items
            $('#remove-all-btn').on('click', function() {
                removeItems('all');
            });

            // Remove only plugins
            $('#remove-plugins-btn').on('click', function() {
                removeItems('plugins');
            });

            // Remove only themes
            $('#remove-themes-btn').on('click', function() {
                removeItems('themes');
            });

            function removeItems(type) {
                let itemCount = 0;
                let itemText = '';

                if (type === 'all') {
                    itemCount = (inactiveData.plugins.length + inactiveData.themes.length);
                    itemText = itemCount + ' item(s) (' + inactiveData.plugins.length + ' plugins, ' + inactiveData.themes.length + ' themes)';
                } else if (type === 'plugins') {
                    itemCount = inactiveData.plugins.length;
                    itemText = itemCount + ' plugin(s)';
                } else if (type === 'themes') {
                    itemCount = inactiveData.themes.length;
                    itemText = itemCount + ' theme(s)';
                }

                if (itemCount === 0) {
                    alert('No items to remove!');
                    return;
                }

                const confirmed = confirm('WARNING: You are about to permanently delete ' + itemText + '.\n\nThis action CANNOT be undone!\n\nAre you sure you want to continue?');

                if (!confirmed) {
                    return;
                }

                const button = type === 'all' ? $('#remove-all-btn') : (type === 'plugins' ? $('#remove-plugins-btn') : $('#remove-themes-btn'));
                const originalText = button.html();
                button.prop('disabled', true).html('Removing...');
                $('#scan-status').text('Deleting inactive items... This may take a moment.');

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_remove_inactive_items',
                        type: type,
                        nonce: '<?php echo wp_create_nonce('switchboard-settings'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            showResults(response.data, true);
                            // Refresh the list
                            $('#scan-inactive-btn').trigger('click');
                        } else {
                            showResults(response.data, false);
                        }
                    },
                    error: function() {
                        alert('Failed to remove items. Please try again.');
                        $('#scan-status').html('<span style="color: #dc2626; font-weight: 500;">Failed to remove items.</span>');
                    },
                    complete: function() {
                        button.prop('disabled', false).html(originalText);
                    }
                });
            }

            function showResults(data, success) {
                let html = '<div class="sb-sp-info-box ' + (success ? 'sb-sp-info-box-success' : 'sb-sp-info-box-tip') + '">';
                html += '<h4 class="sb-sp-heading-sm">Removal Results</h4>';
                html += '<p class="sb-sp-description">' + escapeHtml(data.message) + '</p>';

                if (data.results) {
                    html += '<div style="margin-top: 12px;">';
                    html += '<p class="sb-sp-description" style="margin: 0 0 8px 0;"><strong>Details:</strong></p>';
                    html += '<ul class="sb-sp-list">';
                    html += '<li class="sb-sp-list-item">Plugins deleted: ' + data.results.plugins_deleted + '</li>';
                    html += '<li class="sb-sp-list-item">Themes deleted: ' + data.results.themes_deleted + '</li>';
                    if (data.results.plugins_failed > 0) {
                        html += '<li class="sb-sp-list-item" style="color: #dc2626;">Plugins failed: ' + data.results.plugins_failed + '</li>';
                    }
                    if (data.results.themes_failed > 0) {
                        html += '<li class="sb-sp-list-item" style="color: #dc2626;">Themes failed: ' + data.results.themes_failed + '</li>';
                    }
                    html += '</ul>';

                    if (data.results.errors && data.results.errors.length > 0) {
                        html += '<div style="margin-top: 12px;">';
                        html += '<p class="sb-sp-description" style="margin: 0 0 8px 0;"><strong>Errors:</strong></p>';
                        html += '<ul class="sb-sp-list">';
                        data.results.errors.forEach(function(error) {
                            html += '<li class="sb-sp-list-item">' + escapeHtml(error) + '</li>';
                        });
                        html += '</ul>';
                        html += '</div>';
                    }

                    html += '</div>';
                }

                html += '</div>';

                $('#removal-results').html(html).slideDown();

                // Auto-hide after 10 seconds if successful
                if (success) {
                    setTimeout(function() {
                        $('#removal-results').slideUp();
                    }, 10000);
                }
            }

            function escapeHtml(text) {
                if (!text) return '';
                const map = {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#039;'
                };
                return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
            }
        });
        </script>
        <?php

    }

    /**
     * Register data locations for cleanup system
     *
     * @return array Data storage locations
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_remove-unused-themes-plugins_settings',
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardRemoveUnusedThemesPlugins();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
