<?php
/**
 * Name: Options Page Builder
 * Description: Create custom admin pages with settings panels to store site options, custom data points, and configuration using all available field types with database storage
 * Category: Admin
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Site Settings Hub",
 *     "description": "Create centralized options page for client to manage social media links, contact information, and opening hours without touching theme code."
 *   },
 *   {
 *     "title": "Plugin Settings Organization",
 *     "description": "Consolidate scattered plugin settings into single organized options page instead of having 10 different menu items."
 *   },
 *   {
 *     "title": "Theme Options Panel",
 *     "description": "Build custom theme settings page for colors, layouts, and features without requiring expensive page builder or theme framework."
 *   }
 * ]
 * Added: 2025-10-03
 * Tags: options, settings, admin-pages, custom-fields, data-storage
 * WhereToFind: {
 *   "location": "Switchboard → Options Page Builder",
 *   "url": "admin.php?page=switchboard-options-page-builder",
 *   "instructions": "Create and manage custom admin pages with fields",
 *   "newTab": false
 * }
 */

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

class SwitchboardOptionsPageBuilder {

    public function __construct() {
        add_action('admin_menu', [$this, 'register_admin_menu'], 20);
        add_action('admin_menu', [$this, 'register_options_pages'], 99);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('wp_ajax_switchboard_save_options_page', [$this, 'ajax_save_options_page']);
        add_action('wp_ajax_switchboard_delete_options_page', [$this, 'ajax_delete_options_page']);
        add_action('wp_ajax_save_options_page', [$this, 'save_options_page']);
        add_action('wp_ajax_delete_options_page', [$this, 'delete_options_page']);
        add_action('wp_ajax_get_options_page_data', [$this, 'get_options_page_data']);
        add_action('wp_ajax_get_options_pages_list', [$this, 'get_options_pages_list']);
        add_action('wp_ajax_save_options_page_fields', [$this, 'save_options_page_fields']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_media_uploader']);
    }

    /**
     * Register admin menu page for Options Page Builder
     */
    public function register_admin_menu() {
        add_submenu_page(
            'switchboard',
            __('Options Page Builder', 'wpswitchboard'),
            __('Options Page Builder', 'wpswitchboard'),
            'manage_options',
            'switchboard-options-page-builder',
            [$this, 'render_admin_page']
        );
    }

    /**
     * Enqueue admin assets for Options Page Builder
     */
    public function enqueue_admin_assets($hook) {
        // Check if we're on the options-page-builder page (check both hook and GET parameter)
        $is_opb_page = (
            (isset($_GET['page']) && $_GET['page'] === 'switchboard-options-page-builder') ||
            strpos($hook, 'switchboard-options-page-builder') !== false
        );

        if (!$is_opb_page) {
            return;
        }

        // Enqueue Switchboard admin CSS using constant
        if (defined('SWITCHBOARD_URL') && defined('SWITCHBOARD_VERSION')) {
            wp_enqueue_style(
                'switchboard-admin',
                SWITCHBOARD_URL . 'switchboard-admin.css',
                [],
                SWITCHBOARD_VERSION
            );
        }

        // Enqueue Options Page Builder CSS
        if (defined('SWITCHBOARD_URL') && defined('SWITCHBOARD_VERSION')) {
            wp_enqueue_style(
                'switchboard-opb-admin',
                SWITCHBOARD_URL . 'assets/options-page-builder/admin.css',
                ['switchboard-admin'],
                SWITCHBOARD_VERSION
            );
        }

        // Enqueue jQuery UI for sortable
        wp_enqueue_script('jquery-ui-sortable');

        // Enqueue Options Page Builder JS
        if (defined('SWITCHBOARD_URL') && defined('SWITCHBOARD_VERSION')) {
            wp_enqueue_script(
                'switchboard-opb-admin',
                SWITCHBOARD_URL . 'assets/options-page-builder/admin.js',
                ['jquery', 'jquery-ui-sortable'],
                SWITCHBOARD_VERSION,
                true
            );
        }

        // Localize script
        wp_localize_script('switchboard-opb-admin', 'switchboard_opb', [
            'nonce' => wp_create_nonce('switchboard_opb'),
            'ajax_url' => admin_url('admin-ajax.php')
        ]);
    }

    /**
     * Render Options Page Builder admin page
     */
    public function render_admin_page() {
        $action = isset($_GET['action']) ? sanitize_key($_GET['action']) : '';
        $page_id = isset($_GET['page_id']) ? sanitize_key($_GET['page_id']) : '';

        // Get all options pages
        $options_pages = get_option('switchboard_options_pages', []);
        if (!is_array($options_pages)) {
            $options_pages = [];
        }

        // Include admin template
        include dirname(dirname(dirname(__FILE__))) . '/assets/options-page-builder/admin.php';
    }

    /**
     * AJAX handler to save options page
     */
    public function ajax_save_options_page() {
        check_ajax_referer('switchboard_opb', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'wpswitchboard')]);
        }

        $page_id = isset($_POST['page_id']) ? sanitize_key($_POST['page_id']) : '';
        $page_title = isset($_POST['page_title']) ? sanitize_text_field($_POST['page_title']) : '';
        $page_description = isset($_POST['page_description']) ? sanitize_textarea_field($_POST['page_description']) : '';
        $menu_title = isset($_POST['menu_title']) ? sanitize_text_field($_POST['menu_title']) : '';
        $menu_slug = isset($_POST['menu_slug']) ? sanitize_key($_POST['menu_slug']) : '';
        $parent_menu = isset($_POST['parent_menu']) ? sanitize_text_field($_POST['parent_menu']) : '';
        $capability = isset($_POST['capability']) ? sanitize_text_field($_POST['capability']) : 'manage_options';
        $icon = isset($_POST['icon']) ? sanitize_text_field($_POST['icon']) : '';
        $position = isset($_POST['position']) ? intval($_POST['position']) : null;
        $fields = isset($_POST['fields']) ? $_POST['fields'] : [];

        // Validate required fields
        if (empty($page_title) || empty($menu_title) || empty($menu_slug)) {
            wp_send_json_error(['message' => __('Page title, menu title, and menu slug are required', 'wpswitchboard')]);
        }

        // Sanitize fields
        $sanitized_fields = [];
        if (is_array($fields)) {
            foreach ($fields as $field) {
                if (!is_array($field)) continue;

                $sanitized_fields[] = [
                    'id' => isset($field['id']) ? sanitize_key($field['id']) : '',
                    'type' => isset($field['type']) ? sanitize_key($field['type']) : 'text',
                    'label' => isset($field['label']) ? sanitize_text_field($field['label']) : '',
                    'field_id' => isset($field['field_id']) ? sanitize_key($field['field_id']) : '',
                    'description' => isset($field['description']) ? sanitize_textarea_field($field['description']) : '',
                    'default' => isset($field['default']) ? sanitize_text_field($field['default']) : '',
                    'options' => isset($field['options']) ? sanitize_textarea_field($field['options']) : '',
                    'required' => isset($field['required']) ? (bool)$field['required'] : false,
                    'width' => isset($field['width']) ? sanitize_key($field['width']) : 'full',
                    'order' => isset($field['order']) ? intval($field['order']) : 0
                ];
            }
        }

        // Get existing pages
        $pages = get_option('switchboard_options_pages', []);
        if (!is_array($pages)) {
            $pages = [];
        }

        // Generate page ID if new
        if (empty($page_id)) {
            $page_id = 'opb_' . time();
        }

        // Check for duplicate slug
        $slug_exists = false;
        foreach ($pages as $existing_page) {
            if (is_array($existing_page) &&
                isset($existing_page['slug']) &&
                $existing_page['slug'] === $menu_slug &&
                isset($existing_page['id']) &&
                $existing_page['id'] !== $page_id) {
                $slug_exists = true;
                break;
            }
        }

        if ($slug_exists) {
            wp_send_json_error(['message' => __('A page with this slug already exists', 'wpswitchboard')]);
        }

        // Build page data
        $page_data = [
            'id' => $page_id,
            'page_title' => $page_title,
            'page_description' => $page_description,
            'menu_title' => $menu_title,
            'slug' => $menu_slug,
            'parent_slug' => $parent_menu,
            'capability' => $capability,
            'icon' => $icon,
            'position' => $position,
            'fields' => $sanitized_fields
        ];

        // Update or add page
        $found = false;
        foreach ($pages as $key => $page) {
            if (is_array($page) && isset($page['id']) && $page['id'] === $page_id) {
                $pages[$key] = $page_data;
                $found = true;
                break;
            }
        }

        if (!$found) {
            $pages[] = $page_data;
        }

        // Save pages
        update_option('switchboard_options_pages', $pages);

        wp_send_json_success([
            'message' => __('Options page saved successfully', 'wpswitchboard'),
            'page_id' => $page_id
        ]);
    }

    /**
     * AJAX handler to delete options page
     */
    public function ajax_delete_options_page() {
        check_ajax_referer('switchboard_opb', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'wpswitchboard')]);
        }

        $page_id = isset($_POST['page_id']) ? sanitize_key($_POST['page_id']) : '';

        if (empty($page_id)) {
            wp_send_json_error(['message' => __('No page ID provided', 'wpswitchboard')]);
        }

        // Get existing pages
        $pages = get_option('switchboard_options_pages', []);
        if (!is_array($pages)) {
            wp_send_json_error(['message' => __('No pages found', 'wpswitchboard')]);
        }

        // Find and remove page
        $found = false;
        foreach ($pages as $key => $page) {
            if (is_array($page) && isset($page['id']) && $page['id'] === $page_id) {
                unset($pages[$key]);
                $found = true;
                break;
            }
        }

        if (!$found) {
            wp_send_json_error(['message' => __('Page not found', 'wpswitchboard')]);
        }

        // Re-index array
        $pages = array_values($pages);

        // Save pages
        update_option('switchboard_options_pages', $pages);

        wp_send_json_success(['message' => __('Options page deleted successfully', 'wpswitchboard')]);
    }
    
    public function enqueue_media_uploader($hook) {
        // Enqueue media uploader on our options pages
        $pages = get_option('switchboard_options_pages', []);

        // Validate pages is an array
        if (!is_array($pages)) {
            return;
        }

        $current_page = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';

        if (empty($current_page)) {
            return;
        }

        foreach ($pages as $page) {
            // Validate page structure
            if (!is_array($page) || !isset($page['slug'])) {
                continue;
            }

            if ($page['slug'] === $current_page) {
                wp_enqueue_media();
                add_action('admin_footer', [$this, 'add_media_uploader_script']);

                // Also enqueue OPB CSS for styled forms
                if (defined('SWITCHBOARD_URL') && defined('SWITCHBOARD_VERSION')) {
                    wp_enqueue_style(
                        'switchboard-opb-frontend',
                        SWITCHBOARD_URL . 'assets/options-page-builder/admin.css',
                        ['switchboard-admin'],
                        SWITCHBOARD_VERSION
                    );
                }
                break;
            }
        }
    }
    
    public function add_media_uploader_script() {
        ?>
        <script>
        jQuery(document).ready(function($) {
            var mediaUploader;

            $(document).on('click', '.upload-image-btn', function(e) {
                e.preventDefault();

                var button = $(this);
                var targetId = button.data('target');
                var targetInput = $('#' + targetId);
                var $container = button.closest('.sb-module-image-upload');
                var previewContainer = $container.find('.sb-module-image-preview');

                // If the uploader object has already been created, reopen the dialog
                if (mediaUploader) {
                    mediaUploader.open();
                    return;
                }

                // Create the media uploader
                mediaUploader = wp.media({
                    title: 'Choose Image',
                    button: {
                        text: 'Use this image'
                    },
                    multiple: false
                });

                // When an image is selected, run a callback
                mediaUploader.on('select', function() {
                    var attachment = mediaUploader.state().get('selection').first().toJSON();
                    targetInput.val(attachment.url);

                    // Show preview
                    if (previewContainer.length) {
                        previewContainer.html('<img src="' + attachment.url + '" style="max-width: 300px; border-radius: 8px;">');
                    } else {
                        $container.prepend('<div class="sb-module-image-preview"><img src="' + attachment.url + '" style="max-width: 300px; border-radius: 8px;"></div>');
                    }

                    // Show remove button
                    var $buttonsContainer = $container.find('.sb-module-image-buttons');
                    if (!$buttonsContainer.find('.remove-image-btn').length) {
                        button.after('<button type="button" class="sb-module-button sb-module-button-danger sb-module-button-sm remove-image-btn" data-target="' + targetId + '" style="margin-left: 8px;">Remove</button>');
                    } else {
                        $buttonsContainer.find('.remove-image-btn').show();
                    }
                });

                // Open the uploader dialog
                mediaUploader.open();
            });

            // Remove image
            $(document).on('click', '.remove-image-btn', function(e) {
                e.preventDefault();

                var button = $(this);
                var targetId = button.data('target');
                var targetInput = $('#' + targetId);
                var $container = button.closest('.sb-module-image-upload');
                var previewContainer = $container.find('.sb-module-image-preview');

                targetInput.val('');
                previewContainer.remove();
                button.remove();
            });

            // Color picker sync
            $(document).on('input change', '.sb-module-color-input', function() {
                $(this).siblings('.sb-module-color-text').val($(this).val());
            });
        });
        </script>
        <?php
    }
    
    public function register_options_pages() {
        $pages = get_option('switchboard_options_pages', []);

        // Validate pages is an array
        if (!is_array($pages)) {
            return;
        }

        foreach ($pages as $page) {
            // Validate page structure
            if (!is_array($page)) {
                continue;
            }

            // Validate required fields
            if (empty($page['slug']) || empty($page['page_title']) || empty($page['menu_title'])) {
                continue;
            }

            $capability = !empty($page['capability']) ? sanitize_text_field($page['capability']) : 'manage_options';
            $icon = !empty($page['icon']) ? sanitize_text_field($page['icon']) : 'dashicons-admin-generic';
            $position = !empty($page['position']) ? intval($page['position']) : null;
            $parent = !empty($page['parent_slug']) ? sanitize_text_field($page['parent_slug']) : '';

            if ($parent) {
                // Add as submenu
                add_submenu_page(
                    $parent,
                    sanitize_text_field($page['page_title']),
                    sanitize_text_field($page['menu_title']),
                    $capability,
                    sanitize_key($page['slug']),
                    [$this, 'render_options_page']
                );
            } else {
                // Add as top-level menu
                add_menu_page(
                    sanitize_text_field($page['page_title']),
                    sanitize_text_field($page['menu_title']),
                    $capability,
                    sanitize_key($page['slug']),
                    [$this, 'render_options_page'],
                    $icon,
                    $position
                );
            }
        }
    }
    
    public function register_settings() {
        $pages = get_option('switchboard_options_pages', []);

        // Validate pages is an array
        if (!is_array($pages)) {
            return;
        }

        foreach ($pages as $page) {
            // Validate page structure
            if (!is_array($page) || empty($page['slug'])) {
                continue;
            }

            $option_name = 'switchboard_options_' . sanitize_key($page['slug']);
            register_setting(sanitize_key($page['slug']) . '_group', $option_name);
        }
    }
    
    public function render_options_page() {
        $page_slug = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';

        if (empty($page_slug)) {
            echo '<div class="wrap"><h1>' . esc_html__('Invalid page', 'wpswitchboard') . '</h1></div>';
            return;
        }

        $pages = get_option('switchboard_options_pages', []);

        // Validate pages is an array
        if (!is_array($pages)) {
            echo '<div class="wrap"><h1>' . esc_html__('Configuration error', 'wpswitchboard') . '</h1></div>';
            return;
        }

        $current_page = null;
        foreach ($pages as $page) {
            // Validate page structure
            if (!is_array($page) || !isset($page['slug'])) {
                continue;
            }

            if ($page['slug'] === $page_slug) {
                $current_page = $page;
                break;
            }
        }

        if (!$current_page || !is_array($current_page)) {
            echo '<div class="wrap"><h1>' . esc_html__('Page not found', 'wpswitchboard') . '</h1></div>';
            return;
        }

        // Validate required page fields
        if (!isset($current_page['page_title'])) {
            echo '<div class="wrap"><h1>' . esc_html__('Invalid page configuration', 'wpswitchboard') . '</h1></div>';
            return;
        }

        $option_name = 'switchboard_options_' . $page_slug;
        $values = get_option($option_name, []);

        // Validate values is an array
        if (!is_array($values)) {
            $values = [];
        }

        $fields = [];
        if (isset($current_page['fields']) && is_array($current_page['fields'])) {
            $fields = $current_page['fields'];
        }

        // Enqueue Switchboard admin styles for the options page
        if (defined('SWITCHBOARD_URL') && defined('SWITCHBOARD_VERSION')) {
            wp_enqueue_style(
                'switchboard-admin',
                SWITCHBOARD_URL . 'switchboard-admin.css',
                [],
                SWITCHBOARD_VERSION
            );
        }
        ?>
        <div class="wrap sb-module-wrap">
            <!-- Page Header -->
            <div class="sb-module-header">
                <div class="sb-module-header-content">
                    <h1 class="sb-module-title"><?php echo esc_html($current_page['page_title']); ?></h1>
                    <?php if (!empty($current_page['page_description'])): ?>
                        <p class="sb-module-desc"><?php echo esc_html($current_page['page_description']); ?></p>
                    <?php endif; ?>
                </div>
                <div class="sb-module-header-right">
                    <button type="button" id="opb-how-to-use-btn" class="sb-module-button sb-module-button-secondary sb-module-button-sm">
                        <span class="dashicons dashicons-editor-code"></span>
                        <?php esc_html_e('How to Use', 'wpswitchboard'); ?>
                    </button>
                </div>
            </div>

            <!-- How to Use Modal -->
            <div id="opb-usage-modal" class="opb-usage-modal" style="display: none;">
                <div class="opb-usage-modal-backdrop"></div>
                <div class="opb-usage-modal-content">
                    <div class="opb-usage-modal-header">
                        <h2><?php esc_html_e('How to Use These Options', 'wpswitchboard'); ?></h2>
                        <button type="button" class="opb-usage-modal-close">&times;</button>
                    </div>
                    <div class="opb-usage-modal-body">
                        <!-- PHP Usage -->
                        <div class="opb-usage-section">
                            <h3>
                                <span class="dashicons dashicons-editor-code"></span>
                                <?php esc_html_e('PHP - Get All Options', 'wpswitchboard'); ?>
                            </h3>
                            <div class="opb-usage-code-block">
                                <button type="button" class="opb-copy-btn" data-copy="php-all"><?php esc_html_e('Copy', 'wpswitchboard'); ?></button>
                                <pre id="php-all">$options = get_option( 'switchboard_options_<?php echo esc_js($page_slug); ?>', [] );</pre>
                            </div>
                        </div>

                        <!-- PHP Get Single Field -->
                        <div class="opb-usage-section">
                            <h3>
                                <span class="dashicons dashicons-editor-code"></span>
                                <?php esc_html_e('PHP - Get Single Field', 'wpswitchboard'); ?>
                            </h3>
                            <div class="opb-usage-code-block">
                                <button type="button" class="opb-copy-btn" data-copy="php-single"><?php esc_html_e('Copy', 'wpswitchboard'); ?></button>
                                <pre id="php-single">$options = get_option( 'switchboard_options_<?php echo esc_js($page_slug); ?>', [] );
$value = isset( $options['field_id'] ) ? $options['field_id'] : '';</pre>
                            </div>
                        </div>

                        <!-- Helper Function -->
                        <div class="opb-usage-section">
                            <h3>
                                <span class="dashicons dashicons-lightbulb"></span>
                                <?php esc_html_e('Pro Tip: Create a Helper Function', 'wpswitchboard'); ?>
                            </h3>
                            <div class="opb-usage-code-block">
                                <button type="button" class="opb-copy-btn" data-copy="php-helper"><?php esc_html_e('Copy', 'wpswitchboard'); ?></button>
                                <pre id="php-helper">// Add to your theme's functions.php
function get_<?php echo esc_js(str_replace('-', '_', $page_slug)); ?>_option( $key, $default = '' ) {
    $options = get_option( 'switchboard_options_<?php echo esc_js($page_slug); ?>', [] );
    return isset( $options[$key] ) ? $options[$key] : $default;
}

// Usage:
$site_name = get_<?php echo esc_js(str_replace('-', '_', $page_slug)); ?>_option( 'site_name', 'Default Name' );</pre>
                            </div>
                        </div>

                        <?php if (!empty($fields)): ?>
                        <!-- Available Fields -->
                        <div class="opb-usage-section">
                            <h3>
                                <span class="dashicons dashicons-list-view"></span>
                                <?php esc_html_e('Available Field IDs', 'wpswitchboard'); ?>
                            </h3>
                            <div class="opb-usage-fields-list">
                                <?php foreach ($fields as $field):
                                    if (!is_array($field) || !isset($field['type']) || $field['type'] === 'group') continue;
                                    $field_key = !empty($field['field_id']) ? $field['field_id'] : (!empty($field['name']) ? $field['name'] : (!empty($field['id']) ? $field['id'] : ''));
                                    if (empty($field_key)) continue;
                                    $field_label = !empty($field['label']) ? $field['label'] : ucfirst(str_replace('_', ' ', $field_key));
                                ?>
                                    <div class="opb-usage-field-item">
                                        <code><?php echo esc_html($field_key); ?></code>
                                        <span class="opb-usage-field-label"><?php echo esc_html($field_label); ?></span>
                                        <span class="opb-usage-field-type"><?php echo esc_html($field['type']); ?></span>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Example Usage -->
                        <div class="opb-usage-section">
                            <h3>
                                <span class="dashicons dashicons-media-text"></span>
                                <?php esc_html_e('Example: Display in Template', 'wpswitchboard'); ?>
                            </h3>
                            <div class="opb-usage-code-block">
                                <button type="button" class="opb-copy-btn" data-copy="php-template"><?php esc_html_e('Copy', 'wpswitchboard'); ?></button>
                                <pre id="php-template">&lt;?php
$options = get_option( 'switchboard_options_<?php echo esc_js($page_slug); ?>', [] );
?&gt;

&lt;!-- Text field --&gt;
&lt;p&gt;&lt;?php echo esc_html( $options['company_name'] ?? '' ); ?&gt;&lt;/p&gt;

&lt;!-- Image field --&gt;
&lt;?php if ( ! empty( $options['logo'] ) ) : ?&gt;
    &lt;img src="&lt;?php echo esc_url( $options['logo'] ); ?&gt;" alt="Logo"&gt;
&lt;?php endif; ?&gt;

&lt;!-- Checkbox (toggle) field --&gt;
&lt;?php if ( ! empty( $options['show_banner'] ) ) : ?&gt;
    &lt;!-- Banner content here --&gt;
&lt;?php endif; ?&gt;</pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <?php
            // Show success message after save
            if (isset($_GET['settings-updated']) && $_GET['settings-updated'] === 'true') {
                echo '<div class="sb-module-notice sb-module-notice-success" style="margin-bottom: 20px;">';
                echo '<span class="dashicons dashicons-yes-alt"></span> ';
                esc_html_e('Settings saved successfully.', 'wpswitchboard');
                echo '</div>';
            }
            ?>

            <?php if (empty($fields)): ?>
                <div class="sb-module-card">
                    <div class="sb-module-card-body">
                        <div class="sb-module-empty">
                            <div class="sb-module-empty-icon"></div>
                            <p class="sb-module-empty-title"><?php esc_html_e('No fields configured', 'wpswitchboard'); ?></p>
                            <p class="sb-module-empty-desc"><?php esc_html_e('Go to Switchboard → Options Page Builder to add fields to this page.', 'wpswitchboard'); ?></p>
                        </div>
                    </div>
                </div>
            <?php else:
                // Check if there are any groups
                $has_groups = false;
                $groups = [];
                foreach ($fields as $field) {
                    if (is_array($field) && isset($field['type']) && $field['type'] === 'group') {
                        $has_groups = true;
                        break;
                    }
                }

                if ($has_groups):
                    // Organize fields into groups
                    $groups = $this->organize_fields_by_groups($fields);
                ?>
                <form method="post" action="options.php" class="sb-module-opb-frontend-form opb-form-with-groups">
                    <?php settings_fields($page_slug . '_group'); ?>

                    <div class="opb-grouped-layout">
                        <!-- Sidebar Navigation -->
                        <div class="opb-groups-sidebar">
                            <nav class="opb-groups-nav">
                                <?php
                                $first_group = true;
                                foreach ($groups as $group_id => $group_data):
                                ?>
                                    <a href="#<?php echo esc_attr($group_id); ?>"
                                       class="opb-group-nav-item<?php echo $first_group ? ' active' : ''; ?>"
                                       data-group="<?php echo esc_attr($group_id); ?>">
                                        <span class="opb-group-nav-title"><?php echo esc_html($group_data['label']); ?></span>
                                        <?php if (!empty($group_data['description'])): ?>
                                            <span class="opb-group-nav-desc"><?php echo esc_html($group_data['description']); ?></span>
                                        <?php endif; ?>
                                    </a>
                                <?php
                                    $first_group = false;
                                endforeach;
                                ?>
                            </nav>
                        </div>

                        <!-- Content Sections -->
                        <div class="opb-groups-content">
                            <?php
                            $first_section = true;
                            foreach ($groups as $group_id => $group_data):
                            ?>
                                <div class="opb-group-section<?php echo $first_section ? ' active' : ''; ?>"
                                     id="<?php echo esc_attr($group_id); ?>"
                                     data-group="<?php echo esc_attr($group_id); ?>">
                                    <div class="sb-module-card">
                                        <div class="sb-module-card-header">
                                            <div class="sb-module-card-header-left">
                                                <h2 class="sb-module-card-title"><?php echo esc_html($group_data['label']); ?></h2>
                                                <?php if (!empty($group_data['description'])): ?>
                                                    <p class="sb-module-card-desc"><?php echo esc_html($group_data['description']); ?></p>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="sb-module-card-body">
                                            <?php foreach ($group_data['fields'] as $field):
                                                // Get field identifier
                                                $field_key = '';
                                                if (!empty($field['field_id'])) {
                                                    $field_key = $field['field_id'];
                                                } elseif (!empty($field['name'])) {
                                                    $field_key = $field['name'];
                                                } elseif (!empty($field['id'])) {
                                                    $field_key = $field['id'];
                                                }

                                                if (empty($field_key)) {
                                                    continue;
                                                }

                                                $field_label = !empty($field['label']) ? $field['label'] : ucfirst(str_replace('_', ' ', $field_key));
                                                $field['name'] = $field_key;
                                                $field_name = $option_name . '[' . sanitize_key($field_key) . ']';
                                                $field_value = isset($values[$field_key]) ? $values[$field_key] : '';
                                                if ($field_value === '' && !empty($field['default'])) {
                                                    $field_value = $field['default'];
                                                }
                                                $width = !empty($field['width']) ? $field['width'] : 'full';
                                                $width_class = 'opb-field-width-' . sanitize_html_class($width);
                                                ?>
                                                <div class="sb-module-form-group <?php echo esc_attr($width_class); ?>">
                                                    <label for="<?php echo esc_attr($field_key); ?>" class="sb-module-form-label">
                                                        <?php echo esc_html($field_label); ?>
                                                        <?php if (!empty($field['required'])): ?>
                                                            <span class="sb-module-required">*</span>
                                                        <?php endif; ?>
                                                    </label>
                                                    <?php $this->render_field($field, $field_name, $field_value); ?>
                                                    <?php if (!empty($field['description'])): ?>
                                                        <p class="sb-module-form-help"><?php echo esc_html($field['description']); ?></p>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php
                                $first_section = false;
                            endforeach;
                            ?>
                        </div>
                    </div>

                    <!-- Bottom Action Bar -->
                    <div class="sb-module-card opb-form-actions-bar">
                        <div class="sb-module-card-footer">
                            <div class="sb-module-button-group" style="margin-left: auto;">
                                <button type="button" class="sb-module-button sb-module-button-secondary" onclick="window.location.reload();">
                                    <?php esc_html_e('Reset', 'wpswitchboard'); ?>
                                </button>
                                <button type="submit" class="sb-module-button sb-module-button-primary">
                                    <?php esc_html_e('Save Changes', 'wpswitchboard'); ?>
                                </button>
                            </div>
                        </div>
                    </div>
                </form>

                <script>
                jQuery(document).ready(function($) {
                    // Group navigation
                    $('.opb-group-nav-item').on('click', function(e) {
                        e.preventDefault();
                        var groupId = $(this).data('group');

                        // Update nav active state
                        $('.opb-group-nav-item').removeClass('active');
                        $(this).addClass('active');

                        // Update section visibility
                        $('.opb-group-section').removeClass('active');
                        $('.opb-group-section[data-group="' + groupId + '"]').addClass('active');

                        // Update URL hash
                        history.replaceState(null, null, '#' + groupId);
                    });

                    // Check for hash on load
                    if (window.location.hash) {
                        var hash = window.location.hash.substring(1);
                        var $navItem = $('.opb-group-nav-item[data-group="' + hash + '"]');
                        if ($navItem.length) {
                            $navItem.trigger('click');
                        }
                    }
                });
                </script>

                <?php else: ?>
                <form method="post" action="options.php" class="sb-module-opb-frontend-form">
                    <?php settings_fields($page_slug . '_group'); ?>

                    <div class="sb-module-card">
                        <div class="sb-module-card-header">
                            <div class="sb-module-card-header-left">
                                <h2 class="sb-module-card-title"><?php esc_html_e('Settings', 'wpswitchboard'); ?></h2>
                                <p class="sb-module-card-desc"><?php esc_html_e('Configure your settings below', 'wpswitchboard'); ?></p>
                            </div>
                        </div>
                        <div class="sb-module-card-body">
                            <?php foreach ($fields as $field):
                                // Validate field structure - support both 'name' and 'field_id' keys
                                if (!is_array($field) || !isset($field['type'])) {
                                    continue;
                                }

                                // Get field identifier - prefer field_id, fallback to name, then id
                                $field_key = '';
                                if (!empty($field['field_id'])) {
                                    $field_key = $field['field_id'];
                                } elseif (!empty($field['name'])) {
                                    $field_key = $field['name'];
                                } elseif (!empty($field['id'])) {
                                    $field_key = $field['id'];
                                }

                                if (empty($field_key)) {
                                    continue;
                                }

                                // Get label - fallback to field key if not set
                                $field_label = !empty($field['label']) ? $field['label'] : ucfirst(str_replace('_', ' ', $field_key));

                                // Normalize field data for render_field
                                $field['name'] = $field_key;

                                $field_name = $option_name . '[' . sanitize_key($field_key) . ']';

                                // Get field value - use saved value or default
                                $field_value = isset($values[$field_key]) ? $values[$field_key] : '';
                                if ($field_value === '' && !empty($field['default'])) {
                                    $field_value = $field['default'];
                                }

                                // Get field width class
                                $width = !empty($field['width']) ? $field['width'] : 'full';
                                $width_class = 'opb-field-width-' . sanitize_html_class($width);
                                ?>
                                <div class="sb-module-form-group <?php echo esc_attr($width_class); ?>">
                                    <label for="<?php echo esc_attr($field_key); ?>" class="sb-module-form-label">
                                        <?php echo esc_html($field_label); ?>
                                        <?php if (!empty($field['required'])): ?>
                                            <span class="sb-module-required">*</span>
                                        <?php endif; ?>
                                    </label>
                                    <?php $this->render_field($field, $field_name, $field_value); ?>
                                    <?php if (!empty($field['description'])): ?>
                                        <p class="sb-module-form-help"><?php echo esc_html($field['description']); ?></p>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <div class="sb-module-card-footer">
                            <div class="sb-module-button-group" style="margin-left: auto;">
                                <button type="button" class="sb-module-button sb-module-button-secondary" onclick="window.location.reload();">
                                    <?php esc_html_e('Reset', 'wpswitchboard'); ?>
                                </button>
                                <button type="submit" class="sb-module-button sb-module-button-primary">
                                    <?php esc_html_e('Save Changes', 'wpswitchboard'); ?>
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <!-- How to Use Modal JavaScript -->
        <script>
        jQuery(document).ready(function($) {
            // Open modal
            $('#opb-how-to-use-btn').on('click', function() {
                $('#opb-usage-modal').fadeIn(200);
                $('body').css('overflow', 'hidden');
            });

            // Close modal
            $('.opb-usage-modal-close, .opb-usage-modal-backdrop').on('click', function() {
                $('#opb-usage-modal').fadeOut(200);
                $('body').css('overflow', '');
            });

            // Close on escape key
            $(document).on('keydown', function(e) {
                if (e.key === 'Escape' && $('#opb-usage-modal').is(':visible')) {
                    $('#opb-usage-modal').fadeOut(200);
                    $('body').css('overflow', '');
                }
            });

            // Copy code functionality
            $('.opb-copy-btn').on('click', function() {
                var targetId = $(this).data('copy');
                var $pre = $('#' + targetId);
                var $btn = $(this);
                var originalText = $btn.text();

                // Create temporary textarea
                var $temp = $('<textarea>');
                $('body').append($temp);
                $temp.val($pre.text()).select();
                document.execCommand('copy');
                $temp.remove();

                // Show copied feedback
                $btn.text('<?php esc_html_e('Copied!', 'wpswitchboard'); ?>').addClass('copied');
                setTimeout(function() {
                    $btn.text(originalText).removeClass('copied');
                }, 2000);
            });
        });
        </script>
        <?php
    }

    /**
     * Organize fields into groups
     * Fields before the first group go into "General" group
     * Fields between groups go into that group
     *
     * @param array $fields Array of field configurations
     * @return array Grouped fields organized by group_id
     */
    private function organize_fields_by_groups($fields) {
        $groups = [];
        $current_group_id = 'general';
        $current_group_label = __('General', 'wpswitchboard');
        $current_group_desc = '';
        $has_initial_group = false;

        // Check if first field is a group
        foreach ($fields as $field) {
            if (!is_array($field) || !isset($field['type'])) {
                continue;
            }
            if ($field['type'] === 'group') {
                $has_initial_group = true;
            }
            break;
        }

        // If first field is not a group, create a "General" group for orphaned fields
        if (!$has_initial_group) {
            $groups[$current_group_id] = [
                'label' => $current_group_label,
                'description' => '',
                'fields' => []
            ];
        }

        foreach ($fields as $field) {
            if (!is_array($field) || !isset($field['type'])) {
                continue;
            }

            if ($field['type'] === 'group') {
                // Get group ID
                $group_id = '';
                if (!empty($field['field_id'])) {
                    $group_id = $field['field_id'];
                } elseif (!empty($field['name'])) {
                    $group_id = $field['name'];
                } elseif (!empty($field['id'])) {
                    $group_id = $field['id'];
                }

                if (empty($group_id)) {
                    $group_id = 'group_' . count($groups);
                }

                $current_group_id = sanitize_key($group_id);
                $current_group_label = !empty($field['label']) ? $field['label'] : ucfirst(str_replace('_', ' ', $group_id));
                $current_group_desc = !empty($field['description']) ? $field['description'] : '';

                // Initialize this group
                $groups[$current_group_id] = [
                    'label' => $current_group_label,
                    'description' => $current_group_desc,
                    'fields' => []
                ];
            } else {
                // Add field to current group
                if (!isset($groups[$current_group_id])) {
                    $groups[$current_group_id] = [
                        'label' => $current_group_label,
                        'description' => $current_group_desc,
                        'fields' => []
                    ];
                }
                $groups[$current_group_id]['fields'][] = $field;
            }
        }

        // Remove empty groups (groups with no fields)
        foreach ($groups as $group_id => $group_data) {
            if (empty($group_data['fields'])) {
                unset($groups[$group_id]);
            }
        }

        return $groups;
    }

    /**
     * Parse field options from string or array format
     * Supports: "value : label" per line OR array format
     *
     * @param array $field Field configuration
     * @return array Parsed options as value => label pairs
     */
    private function parse_field_options($field) {
        if (!isset($field['options'])) {
            return [];
        }

        // If already an array, return as-is
        if (is_array($field['options'])) {
            return $field['options'];
        }

        // Parse string format: "value : label" per line
        $options = [];
        $lines = explode("\n", $field['options']);

        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line)) {
                continue;
            }

            // Check for "value : label" format
            if (strpos($line, ':') !== false) {
                $parts = explode(':', $line, 2);
                $opt_value = trim($parts[0]);
                $opt_label = isset($parts[1]) ? trim($parts[1]) : $opt_value;
            } else {
                // Use line as both value and label
                $opt_value = $line;
                $opt_label = $line;
            }

            if (!empty($opt_value)) {
                $options[$opt_value] = $opt_label;
            }
        }

        return $options;
    }

    private function render_field($field, $field_name, $value) {
        // Validate field array
        if (!is_array($field) || !isset($field['type']) || !isset($field['name'])) {
            return;
        }

        $type = sanitize_key($field['type']);
        $required = !empty($field['required']) ? 'required' : '';

        switch ($type) {
            case 'text':
                echo '<input type="text" name="' . esc_attr($field_name) . '" id="' . esc_attr($field['name']) . '" value="' . esc_attr($value) . '" class="sb-module-input" ' . $required . '>';
                break;

            case 'textarea':
                $rows = !empty($field['rows']) ? intval($field['rows']) : 5;
                echo '<textarea name="' . esc_attr($field_name) . '" id="' . esc_attr($field['name']) . '" rows="' . $rows . '" class="sb-module-input" ' . $required . '>' . esc_textarea($value) . '</textarea>';
                break;

            case 'number':
                $min = isset($field['min']) ? 'min="' . esc_attr($field['min']) . '"' : '';
                $max = isset($field['max']) ? 'max="' . esc_attr($field['max']) . '"' : '';
                echo '<input type="number" name="' . esc_attr($field_name) . '" id="' . esc_attr($field['name']) . '" value="' . esc_attr($value) . '" class="sb-module-input" style="max-width: 150px;" ' . $min . ' ' . $max . ' ' . $required . '>';
                break;

            case 'email':
                echo '<input type="email" name="' . esc_attr($field_name) . '" id="' . esc_attr($field['name']) . '" value="' . esc_attr($value) . '" class="sb-module-input" ' . $required . '>';
                break;

            case 'url':
                echo '<input type="url" name="' . esc_attr($field_name) . '" id="' . esc_attr($field['name']) . '" value="' . esc_attr($value) . '" class="sb-module-input" ' . $required . '>';
                break;

            case 'color':
                echo '<div class="sb-module-color-picker">';
                echo '<input type="color" name="' . esc_attr($field_name) . '" id="' . esc_attr($field['name']) . '" value="' . esc_attr($value ?: '#000000') . '" class="sb-module-color-input" ' . $required . '>';
                echo '<input type="text" value="' . esc_attr($value) . '" class="sb-module-input sb-module-color-text" style="max-width: 120px;" placeholder="#000000" readonly>';
                echo '</div>';
                break;

            case 'checkbox':
                echo '<label class="sb-module-toggle">';
                echo '<input type="checkbox" name="' . esc_attr($field_name) . '" id="' . esc_attr($field['name']) . '" value="1" ' . checked($value, '1', false) . '>';
                echo '<span class="sb-module-toggle-slider"></span>';
                echo '</label>';
                break;

            case 'select':
                echo '<select name="' . esc_attr($field_name) . '" id="' . esc_attr($field['name']) . '" ' . $required . ' class="sb-module-select">';
                $options = $this->parse_field_options($field);
                foreach ($options as $option_value => $option_label) {
                    echo '<option value="' . esc_attr($option_value) . '" ' . selected($value, $option_value, false) . '>' . esc_html($option_label) . '</option>';
                }
                echo '</select>';
                break;

            case 'radio':
                $options = $this->parse_field_options($field);
                if (!empty($options)) {
                    echo '<div class="sb-module-radio-group">';
                    foreach ($options as $option_value => $option_label) {
                        $checked = checked($value, $option_value, false);
                        echo '<label class="sb-module-radio-item' . ($checked ? ' checked' : '') . '">';
                        echo '<input type="radio" name="' . esc_attr($field_name) . '" value="' . esc_attr($option_value) . '" ' . $checked . '>';
                        echo '<span class="sb-module-radio-label">' . esc_html($option_label) . '</span>';
                        echo '</label>';
                    }
                    echo '</div>';
                }
                break;

            case 'wysiwyg':
                $editor_id = preg_replace('/[^a-z0-9_-]/i', '_', $field['name']);
                $textarea_rows = 10;
                if (isset($field['rows'])) {
                    $textarea_rows = intval($field['rows']);
                    $textarea_rows = max(3, min($textarea_rows, 50)); // Constrain between 3-50
                }

                wp_editor($value, $editor_id, [
                    'textarea_name' => $field_name,
                    'textarea_rows' => $textarea_rows,
                    'media_buttons' => isset($field['media_buttons']) && $field['media_buttons'],
                ]);
                break;

            case 'image':
                echo '<div class="sb-module-image-upload">';
                echo '<input type="hidden" name="' . esc_attr($field_name) . '" id="' . esc_attr($field['name']) . '" value="' . esc_attr($value) . '">';
                if ($value) {
                    echo '<div class="sb-module-image-preview"><img src="' . esc_url($value) . '" style="max-width: 300px; border-radius: 8px;"></div>';
                }
                echo '<div class="sb-module-image-buttons" style="margin-top: 12px;">';
                echo '<button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm upload-image-btn" data-target="' . esc_attr($field['name']) . '">' . esc_html__('Choose Image', 'wpswitchboard') . '</button>';
                if ($value) {
                    echo '<button type="button" class="sb-module-button sb-module-button-danger sb-module-button-sm remove-image-btn" data-target="' . esc_attr($field['name']) . '" style="margin-left: 8px;">' . esc_html__('Remove', 'wpswitchboard') . '</button>';
                }
                echo '</div>';
                echo '</div>';
                break;

            case 'date':
                echo '<input type="date" name="' . esc_attr($field_name) . '" id="' . esc_attr($field['name']) . '" value="' . esc_attr($value) . '" class="sb-module-input" style="max-width: 200px;" ' . $required . '>';
                break;

            default:
                echo '<input type="text" name="' . esc_attr($field_name) . '" id="' . esc_attr($field['name']) . '" value="' . esc_attr($value) . '" class="sb-module-input" ' . $required . '>';
        }
    }
    
    public function save_options_page() {
        check_ajax_referer('switchboard_settings', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Permission denied', 'wpswitchboard')]);
            return;
        }

        // Validate and decode POST data
        if (!isset($_POST['page_data'])) {
            wp_send_json_error(['message' => esc_html__('No data provided', 'wpswitchboard')]);
            return;
        }

        $page_data = json_decode(stripslashes($_POST['page_data']), true);

        // Validate JSON decode success
        if (!is_array($page_data)) {
            wp_send_json_error(['message' => esc_html__('Invalid data format', 'wpswitchboard')]);
            return;
        }

        // Validate required fields
        if (empty($page_data['slug']) || empty($page_data['page_title'])) {
            wp_send_json_error(['message' => esc_html__('Slug and page title are required', 'wpswitchboard')]);
            return;
        }

        // Sanitize all fields
        $page_data['slug'] = sanitize_key($page_data['slug']);
        $page_data['page_title'] = sanitize_text_field($page_data['page_title']);
        $page_data['menu_title'] = isset($page_data['menu_title']) ? sanitize_text_field($page_data['menu_title']) : $page_data['page_title'];
        $page_data['capability'] = isset($page_data['capability']) ? sanitize_text_field($page_data['capability']) : 'manage_options';
        $page_data['icon'] = isset($page_data['icon']) ? sanitize_text_field($page_data['icon']) : 'dashicons-admin-generic';
        $page_data['position'] = isset($page_data['position']) ? intval($page_data['position']) : null;
        $page_data['parent_slug'] = isset($page_data['parent_slug']) ? sanitize_text_field($page_data['parent_slug']) : '';
        $page_data['description'] = isset($page_data['description']) ? sanitize_textarea_field($page_data['description']) : '';

        // Get existing pages
        $pages = get_option('switchboard_options_pages', []);

        // Validate pages is an array
        if (!is_array($pages)) {
            $pages = [];
        }

        // Check for duplicate slug
        $found = false;
        foreach ($pages as $key => $page) {
            if (is_array($page) && isset($page['slug']) && $page['slug'] === $page_data['slug']) {
                $pages[$key] = $page_data;
                $found = true;
                break;
            }
        }

        if (!$found) {
            $pages[] = $page_data;
        }

        update_option('switchboard_options_pages', $pages);

        wp_send_json_success(['message' => esc_html__('Options page saved successfully', 'wpswitchboard')]);
    }

    /**
     * Save field values for an options page
     */
    public function save_options_page_fields() {
        check_ajax_referer('switchboard_settings', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Permission denied', 'wpswitchboard')]);
            return;
        }

        $page_slug = isset($_POST['page_slug']) ? sanitize_key($_POST['page_slug']) : '';
        if (empty($page_slug)) {
            wp_send_json_error(['message' => esc_html__('Page slug is required', 'wpswitchboard')]);
            return;
        }

        $fields_data = isset($_POST['fields']) ? wp_unslash($_POST['fields']) : [];
        if (!is_array($fields_data)) {
            wp_send_json_error(['message' => esc_html__('Invalid fields data', 'wpswitchboard')]);
            return;
        }

        // Sanitize each field value
        $sanitized = [];
        foreach ($fields_data as $key => $value) {
            $key = sanitize_key($key);
            if (is_array($value)) {
                $sanitized[$key] = array_map('sanitize_text_field', $value);
            } else {
                $sanitized[$key] = sanitize_text_field($value);
            }
        }

        update_option('switchboard_opb_' . $page_slug, $sanitized);

        wp_send_json_success(['message' => esc_html__('Fields saved successfully', 'wpswitchboard')]);
    }

    public function delete_options_page() {
        check_ajax_referer('switchboard_settings', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Permission denied', 'wpswitchboard')]);
            return;
        }

        $slug = isset($_POST['slug']) ? sanitize_key($_POST['slug']) : '';

        if (empty($slug)) {
            wp_send_json_error(['message' => esc_html__('Slug is required', 'wpswitchboard')]);
            return;
        }

        $pages = get_option('switchboard_options_pages', []);

        // Validate pages is an array
        if (!is_array($pages)) {
            wp_send_json_error(['message' => esc_html__('Configuration error', 'wpswitchboard')]);
            return;
        }

        foreach ($pages as $key => $page) {
            if (is_array($page) && isset($page['slug']) && $page['slug'] === $slug) {
                unset($pages[$key]);
                break;
            }
        }

        update_option('switchboard_options_pages', array_values($pages));

        // Optionally delete the options data
        delete_option('switchboard_options_' . $slug);

        wp_send_json_success(['message' => esc_html__('Options page deleted successfully', 'wpswitchboard')]);
    }

    public function get_options_page_data() {
        check_ajax_referer('switchboard_settings', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Permission denied', 'wpswitchboard')]);
            return;
        }

        $slug = isset($_POST['slug']) ? sanitize_key($_POST['slug']) : '';

        if (empty($slug)) {
            wp_send_json_error(['message' => esc_html__('Slug is required', 'wpswitchboard')]);
            return;
        }

        $pages = get_option('switchboard_options_pages', []);

        // Validate pages is an array
        if (!is_array($pages)) {
            wp_send_json_error(['message' => esc_html__('Configuration error', 'wpswitchboard')]);
            return;
        }

        foreach ($pages as $page) {
            if (is_array($page) && isset($page['slug']) && $page['slug'] === $slug) {
                wp_send_json_success(['page' => $page]);
                return;
            }
        }

        wp_send_json_error(['message' => esc_html__('Options page not found', 'wpswitchboard')]);
    }

    public function get_options_pages_list() {
        check_ajax_referer('switchboard_settings', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Permission denied', 'wpswitchboard')]);
            return;
        }

        $pages = get_option('switchboard_options_pages', []);

        ob_start();
        if (empty($pages)):
        ?>
            <div class="sb-sp-text-center">
                <p class="sb-sp-m-0">No options pages created yet</p>
            </div>
        <?php else: ?>
            <div class="sb-sp-flex-col sb-sp-gap-3">
                <?php foreach ($pages as $page): ?>
                    <div class="options-page-item sb-sp-bg-white sb-sp-card" data-slug="<?php echo esc_attr($page['slug']); ?>">
                        <span class="dashicons <?php echo esc_attr($page['icon'] ?? 'dashicons-admin-generic'); ?> sb-sp-icon-lg"></span>
                        <div class="sb-sp-col">
                            <div class="sb-sp-label"><?php echo esc_html($page['page_title']); ?></div>
                            <div class="sb-sp-text-xs">
                                <code class="sb-sp-code"><?php echo esc_html($page['slug']); ?></code>
                                <?php if (!empty($page['fields'])): ?>
                                    <span class="sb-sp-ml-2"><?php echo count($page['fields']); ?> field<?php echo count($page['fields']) !== 1 ? 's' : ''; ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <a href="<?php echo admin_url('admin.php?page=' . $page['slug']); ?>" target="_blank" class="sb-sp-h-8">View</a>
                        <button type="button" class="edit-options-page-btn" data-slug="<?php echo esc_attr($page['slug']); ?>" class="sb-sp-button sb-sp-button-primary">Edit</button>
                        <button type="button" class="delete-options-page-btn" data-slug="<?php echo esc_attr($page['slug']); ?>" class="sb-sp-button sb-sp-button-danger">Delete</button>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif;

        $html = ob_get_clean();
        wp_send_json_success(['html' => $html]);
    }

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_options_pages',
            ],
            'option_patterns' => [
                'switchboard_options_%',
            ],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }
}

$switchboard_instance = new SwitchboardOptionsPageBuilder();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
