<?php
/**
 * Name: Disable Gutenberg
 * Description: Disable the Gutenberg block editor site-wide or for specific post types and restore classic editor for users preferring traditional editing experience or working with legacy content workflows
 * Category: Optimization
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Use Classic Editor",
 *     "description": "Switch back to the familiar Classic Editor if you prefer its simplicity over the block-based Gutenberg editor."
 *   },
 *   {
 *     "title": "Better Performance",
 *     "description": "Reduce admin page load times by removing Gutenberg\'s JavaScript and CSS files when you don\'t need them."
 *   },
 *   {
 *     "title": "Per Post Type Control",
 *     "description": "Keep Gutenberg for pages while using Classic Editor for posts, or vice versa based on your content workflow."
 *   }
 * ]
 * Added: 2025-06-22
 * Tags: gutenberg, block-editor, classic, disable, editor, post-types
 * WhereToFind: {
 *   "location": "Post/Page Editor",
 *   "url": "post-new.php",
 *   "instructions": "Classic editor replaces block editor",
 *   "newTab": false
 * }
 */

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

class SwitchboardDisableGutenberg {

    private $settings;

    public function __construct() {
        $this->settings = get_option('switchboard_disable-gutenberg_settings', []);

        add_filter('use_block_editor_for_post', [$this, 'maybe_disable_gutenberg'], 10, 2);
        add_filter('use_block_editor_for_post_type', [$this, 'maybe_disable_for_post_type'], 10, 2);
        add_action('wp_enqueue_scripts', [$this, 'remove_block_css'], 100);
    }

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

    /**
     * Render settings panel
     *
     * @param array $settings Current module settings
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        $mode = isset($settings['mode']) ? $settings['mode'] : 'all';

        // Get all public post types that support the editor
        $all_post_types = get_post_types(['public' => true], 'objects');
        $exclude_types = ['attachment', 'wp_block', 'wp_template', 'wp_template_part', 'wp_navigation'];
        $editor_post_types = [];

        foreach ($all_post_types as $post_type) {
            if (post_type_supports($post_type->name, 'editor') && !in_array($post_type->name, $exclude_types)) {
                $editor_post_types[$post_type->name] = $post_type->label;
            }
        }
        ?>
        <input type="hidden" name="module" value="disable-gutenberg">

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <label class="sb-sp-label"><?php esc_html_e('Disable Mode', 'wpswitchboard'); ?></label>
            <p class="sb-sp-description" style="margin-bottom: 16px;"><?php esc_html_e('Choose whether to disable Gutenberg everywhere or only for specific post types.', 'wpswitchboard'); ?></p>

            <label class="sb-module-option-item sb-module-toggle-item mode-option <?php echo $mode === 'all' ? 'active' : ''; ?>" style="margin-bottom: 12px; cursor: pointer; display: flex; align-items: center; gap: 12px;">
                <input type="radio" name="setting_mode" value="all" <?php checked($mode, 'all'); ?> class="mode-radio">
                <div class="sb-module-option-content" style="flex: 1;">
                    <strong class="sb-module-option-title"><?php esc_html_e('Disable Everywhere', 'wpswitchboard'); ?></strong>
                    <p class="sb-module-option-text" style="margin: 0 0 0 8px;"><?php esc_html_e('Disable Gutenberg for all post types site-wide', 'wpswitchboard'); ?></p>
                </div>
            </label>

            <label class="sb-module-option-item sb-module-toggle-item mode-option <?php echo $mode === 'specific' ? 'active' : ''; ?>" style="cursor: pointer; display: flex; align-items: center; gap: 12px;">
                <input type="radio" name="setting_mode" value="specific" <?php checked($mode, 'specific'); ?> class="mode-radio">
                <div class="sb-module-option-content" style="flex: 1;">
                    <strong class="sb-module-option-title"><?php esc_html_e('Disable for Specific Post Types', 'wpswitchboard'); ?></strong>
                    <p class="sb-module-option-text" style="margin: 0 0 0 8px;"><?php esc_html_e('Choose which post types should use Classic Editor', 'wpswitchboard'); ?></p>
                </div>
            </label>
        </div>

        <div id="post-type-selection" class="sb-sp-group" style="margin-bottom: 24px; <?php echo $mode === 'all' ? 'display: none;' : ''; ?>">
            <div class="sb-sp-divider" style="margin-bottom: 24px;"></div>
            <div class="sb-sp-header-actions">
                <div class="sb-sp-header-content">
                    <label class="sb-sp-label"><?php esc_html_e('Select Post Types to Disable Gutenberg', 'wpswitchboard'); ?></label>
                    <p class="sb-sp-description"><?php esc_html_e('Enable the toggle for each post type that should use Classic Editor instead of Gutenberg.', 'wpswitchboard'); ?></p>
                </div>
                <div class="sb-sp-button-group sb-sp-header-buttons">
                    <button type="button" class="button button-small button-primary switchboard-toggle-all-pt" data-action="enable">
                        <?php esc_html_e('Enable All', 'wpswitchboard'); ?>
                    </button>
                    <button type="button" class="button button-small button-primary-outline switchboard-toggle-all-pt" data-action="disable">
                        <?php esc_html_e('Disable All', 'wpswitchboard'); ?>
                    </button>
                </div>
            </div>

            <?php foreach ($editor_post_types as $pt_slug => $pt_label):
                $is_enabled = !empty($settings['post_type_' . $pt_slug]);
            ?>
                <div class="sb-module-option-item sb-module-toggle-item">
                    <div class="sb-module-option-content">
                        <div class="sb-module-toggle-header">
                            <strong class="sb-module-option-title"><?php echo esc_html($pt_label); ?></strong>
                            <label class="sb-module-toggle">
                                <input type="checkbox"
                                       name="setting_post_type_<?php echo esc_attr($pt_slug); ?>"
                                       value="1"
                                       class="post-type-toggle"
                                       data-post-type="<?php echo esc_attr($pt_slug); ?>"
                                       <?php checked($is_enabled, true); ?>>
                                <span class="sb-module-toggle-slider"></span>
                            </label>
                        </div>
                        <?php // translators: %s is the post type name (e.g., "posts", "pages") ?>
                        <p class="sb-module-option-text"><?php printf(esc_html__('Use Classic Editor for %s', 'wpswitchboard'), esc_html(strtolower($pt_label))); ?></p>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-info">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('How It Works', 'wpswitchboard'); ?></h4>
            <ul class="sb-sp-list">
                <li class="sb-sp-list-item"><?php esc_html_e('When disabled, posts will open in the Classic Editor instead of Gutenberg.', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('Frontend block styles are also removed to improve page load performance (when disabled everywhere).', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('Existing block content will still render correctly on the frontend.', 'wpswitchboard'); ?></li>
            </ul>
        </div>

        <script>
        jQuery(document).ready(function($) {
            // Handle mode radio selection and highlighting
            function updateModeHighlight() {
                var selectedValue = $('input[name="setting_mode"]:checked').val();
                $('.mode-option').removeClass('active');
                $('input[name="setting_mode"]:checked').closest('.mode-option').addClass('active');

                // Show/hide post type selection
                $('#post-type-selection').toggle(selectedValue === 'specific');
            }

            // Handle radio change
            $('input[name="setting_mode"]').on('change', updateModeHighlight);

            // Handle Enable All / Disable All buttons
            $('.switchboard-toggle-all-pt').on('click', function(e) {
                e.preventDefault();
                var action = $(this).data('action');
                var checkboxes = $('.post-type-toggle');

                if (action === 'enable') {
                    checkboxes.prop('checked', true).trigger('change');
                } else if (action === 'disable') {
                    checkboxes.prop('checked', false).trigger('change');
                }
            });
        });
        </script>

        <style>
        .mode-option.active {
            background: var(--primary-50) !important;
            border-color: var(--primary-500) !important;
            box-shadow: 0 1px 3px 0 rgba(var(--primary-500-rgb), 0.1);
        }
        .mode-option.active:hover {
            background: var(--primary-100) !important;
            border-color: var(--primary-400) !important;
        }
        </style>
        <?php
    }

    /**
     * Get disabled post types from settings
     *
     * @return array List of post type slugs
     */
    private function get_disabled_post_types() {
        $disabled = [];

        // Check for individual post type settings (new format: post_type_{slug})
        foreach ($this->settings as $key => $value) {
            if (strpos($key, 'post_type_') === 0 && !empty($value)) {
                $post_type = str_replace('post_type_', '', $key);
                $disabled[] = $post_type;
            }
        }

        // Also support legacy format (comma-separated string or array)
        if (empty($disabled) && isset($this->settings['post_types'])) {
            $post_types_setting = $this->settings['post_types'];
            if (is_string($post_types_setting) && !empty($post_types_setting)) {
                return array_map('trim', explode(',', $post_types_setting));
            } elseif (is_array($post_types_setting)) {
                return $post_types_setting;
            }
        }

        return $disabled;
    }

    /**
     * Check if Gutenberg should be disabled for a specific post
     *
     * @param bool $use_block_editor Whether to use block editor
     * @param WP_Post $post The post object
     * @return bool Whether to use block editor
     */
    public function maybe_disable_gutenberg($use_block_editor, $post) {
        if (!$use_block_editor) {
            return false;
        }

        $mode = isset($this->settings['mode']) ? $this->settings['mode'] : 'all';

        if ($mode === 'all') {
            return false;
        }

        // Specific post types mode
        $disabled_post_types = $this->get_disabled_post_types();

        if (in_array($post->post_type, $disabled_post_types)) {
            return false;
        }

        return $use_block_editor;
    }

    /**
     * Check if Gutenberg should be disabled for a post type
     *
     * @param bool $use_block_editor Whether to use block editor
     * @param string $post_type The post type
     * @return bool Whether to use block editor
     */
    public function maybe_disable_for_post_type($use_block_editor, $post_type) {
        if (!$use_block_editor) {
            return false;
        }

        $mode = isset($this->settings['mode']) ? $this->settings['mode'] : 'all';

        if ($mode === 'all') {
            return false;
        }

        // Specific post types mode
        $disabled_post_types = $this->get_disabled_post_types();

        if (in_array($post_type, $disabled_post_types)) {
            return false;
        }

        return $use_block_editor;
    }

    /**
     * Remove block CSS from frontend
     */
    public function remove_block_css() {
        $mode = isset($this->settings['mode']) ? $this->settings['mode'] : 'all';

        // Only remove block CSS if disabled everywhere
        if ($mode === 'all') {
            wp_dequeue_style('wp-block-library');
            wp_dequeue_style('wp-block-library-theme');
            wp_dequeue_style('wc-blocks-style');
        }
    }
}

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