<?php
defined('ABSPATH') or die('Direct access not allowed');

class CodeEditor_SettingsController {
    private $hidden_menu_items = [];
    private $hidden_admin_bar_items = [];
    private $disable_frontend = false;

    public function __construct() {
        add_action('admin_menu', [$this, 'add_settings_page']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_init', [$this, 'apply_settings']);
    }

    public function add_settings_page() {
        add_submenu_page(
            'code-editor',
            __('系统设置', 'my-first-plugin'),
            __('系统设置', 'my-first-plugin'),
            'manage_options',
            'code-editor-settings',
            [$this, 'render_settings_page']
        );
    }

    public function register_settings() {
        register_setting('code_editor_settings', 'code_editor_hidden_menus');
        register_setting('code_editor_settings', 'code_editor_hidden_admin_bar');
        register_setting('code_editor_settings', 'code_editor_disable_frontend');
        register_setting('code_editor_settings', 'code_editor_discuz_path');
    }

    public function apply_settings() {
        $this->hidden_menu_items = get_option('code_editor_hidden_menus', []);
        $this->hidden_admin_bar_items = get_option('code_editor_hidden_admin_bar', []);
        $this->disable_frontend = get_option('code_editor_disable_frontend', false);

        if (!empty($this->hidden_menu_items)) {
            add_action('admin_menu', [$this, 'hide_menu_items'], 999);
        }

        if (!empty($this->hidden_admin_bar_items)) {
            add_action('admin_bar_menu', [$this, 'hide_admin_bar_items'], 999);
        }

        if ($this->disable_frontend) {
            add_action('template_redirect', [$this, 'disable_frontend']);
        }
    }

    public function hide_menu_items() {
        global $menu, $submenu;

        foreach ($this->hidden_menu_items as $item) {
            if (strpos($item, 'submenu-') === 0) {
                $parts = explode('-', $item);
                if (isset($parts[1]) && isset($parts[2])) {
                    remove_submenu_page($parts[1], $parts[2]);
                }
            } else {
                remove_menu_page($item);
            }
        }
    }

    public function hide_admin_bar_items($wp_admin_bar) {
        foreach ($this->hidden_admin_bar_items as $item) {
            $wp_admin_bar->remove_node($item);
        }
    }

    public function disable_frontend() {
        if (!is_admin()) {
            wp_die(__('前台功能已禁用', 'my-first-plugin'));
        }
    }

    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1><?php _e('系统设置', 'my-first-plugin'); ?></h1>
            <form method="post" action="options.php">
                <?php
                settings_fields('code_editor_settings');
                do_settings_sections('code_editor_settings');
                ?>
                
                <h2><?php _e('隐藏后台菜单', 'my-first-plugin'); ?></h2>
                <p><?php _e('选择要隐藏的后台菜单项:', 'my-first-plugin'); ?></p>
                <?php $this->render_menu_items_list(); ?>
                
                <h2><?php _e('隐藏顶部工具栏', 'my-first-plugin'); ?></h2>
                <p><?php _e('选择要隐藏的顶部工具栏项:', 'my-first-plugin'); ?></p>
                <?php $this->render_admin_bar_items_list(); ?>
                
                <h2><?php _e('前台功能', 'my-first-plugin'); ?></h2>
                <label>
                    <input type="checkbox" name="code_editor_disable_frontend" value="1" <?php checked($this->disable_frontend, true); ?>>
                    <?php _e('禁用前台功能(仅保留后台)', 'my-first-plugin'); ?>
                </label>
                
                <h2><?php _e('Discuz设置', 'my-first-plugin'); ?></h2>
                <div class="form-group">
                    <label for="discuz-path">Discuz安装路径</label>
                    <input type="text" id="discuz-path" name="code_editor_discuz_path" 
                           value="<?php echo esc_attr(get_option('code_editor_discuz_path')); ?>" 
                           style="width: 100%; max-width: 600px;">
                    <p class="description">请输入Discuz! 3.5的完整安装路径，例如：/var/www/discuz</p>
                    <button type="button" id="test-discuz-path" class="button">测试路径</button>
                    <span id="discuz-path-test-result"></span>
                </div>
                
                <?php submit_button(); ?>
            </form>
            
            <script>
            jQuery(document).ready(function($) {
                $('#test-discuz-path').on('click', function() {
                    const path = $('#discuz-path').val();
                    if (!path) {
                        $('#discuz-path-test-result').text('请输入路径').css('color', 'red');
                        return;
                    }
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'code_editor_set_discuz_path',
                            path: path,
                            security: codeEditorVars.nonce
                        },
                        success: function(response) {
                            if (response.success) {
                                $('#discuz-path-test-result').text('路径有效: ' + response.data.message).css('color', 'green');
                            } else {
                                $('#discuz-path-test-result').text('错误: ' + response.data).css('color', 'red');
                            }
                        }
                    });
                });
            });
            </script>
        </div>
        <?php
    }

    private function render_menu_items_list() {
        global $menu, $submenu;
        
        echo '<div style="column-count: 3;">';
        echo '<h3>'.__('主菜单', 'my-first-plugin').'</h3>';
        foreach ($menu as $item) {
            if (!empty($item[0]) && !empty($item[2])) {
                $checked = in_array($item[2], $this->hidden_menu_items) ? 'checked' : '';
                echo '<label style="display: block; margin-bottom: 5px;">';
                echo '<input type="checkbox" name="code_editor_hidden_menus[]" value="'.$item[2].'" '.$checked.'> ';
                echo strip_tags($item[0]);
                echo '</label>';
            }
        }
        
        echo '<h3>'.__('子菜单', 'my-first-plugin').'</h3>';
        foreach ($submenu as $parent => $items) {
            foreach ($items as $item) {
                $value = 'submenu-'.$parent.'-'.$item[2];
                $checked = in_array($value, $this->hidden_menu_items) ? 'checked' : '';
                echo '<label style="display: block; margin-bottom: 5px;">';
                echo '<input type="checkbox" name="code_editor_hidden_menus[]" value="'.$value.'" '.$checked.'> ';
                echo strip_tags($item[0]);
                echo '</label>';
            }
        }
        echo '</div>';
    }

    private function render_admin_bar_items_list() {
        global $wp_admin_bar;
        $nodes = $wp_admin_bar->get_nodes();
        
        echo '<div style="column-count: 3;">';
        foreach ($nodes as $node) {
            $checked = in_array($node->id, $this->hidden_admin_bar_items) ? 'checked' : '';
            echo '<label style="display: block; margin-bottom: 5px;">';
            echo '<input type="checkbox" name="code_editor_hidden_admin_bar[]" value="'.$node->id.'" '.$checked.'> ';
            echo strip_tags($node->title);
            echo '</label>';
        }
        echo '</div>';
    }
}

new CodeEditor_SettingsController();