<?php
/**
 * Name: Simple Forms
 * Description: Create custom contact and lead forms with file uploads, email notifications, entry management, and spam protection without external form builder services or plugins
 * 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."
 *   }
 * ]
 * Added: 2025-10-05
 * Tags: forms, contact, entries, email, uploads
 * WhereToFind: {
 *   "location": "Switchboard → Forms",
 *   "url": "admin.php?page=switchboard-forms",
 *   "instructions": "Create and manage forms with drag-and-drop builder. Copy generated shortcode to display forms anywhere on your site.",
 *   "newTab": false
 * }
 */

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

// Load WP_List_Table if not already loaded
if (!class_exists('WP_List_Table')) {
    require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}

/**
 * Forms List Table
 */
class Switchboard_Forms_List_Table extends WP_List_Table {
    
    public function __construct() {
        parent::__construct(array(
            'singular' => 'form',
            'plural'   => 'forms',
            'ajax'     => false
        ));
    }
    
    public function get_columns() {
        return array(
            'id'        => 'ID',
            'title'     => 'Form Name',
            'entries'   => 'Entries',
            'date'      => 'Date Created',
            'shortcode' => 'Shortcode'
        );
    }
    
    public function get_sortable_columns() {
        return array(
            'id'    => array('ID', false),
            'title' => array('post_title', false),
            'date'  => array('post_date', true) // true means it's already sorted by this
        );
    }
    
    public function column_default($item, $column_name) {
        switch ($column_name) {
            case 'id':
                return $item->ID;
            case 'entries':
                global $wpdb;
                $table_name = $wpdb->prefix . 'switchboard_form_entries';
                $count = $wpdb->get_var($wpdb->prepare(
                    "SELECT COUNT(*) FROM {$table_name} WHERE form_id = %d",
                    $item->ID
                ));
                if ($count > 0) {
                    return '<a href="' . admin_url('admin.php?page=switchboard-forms&view=all-entries&form_filter=' . $item->ID) . '">' . $count . ' entries</a>';
                }
                return '<span class="color: #94a3b8;">0 entries</span>';
            case 'date':
                return date('M j, Y', strtotime($item->post_date));
            case 'shortcode':
                return '<input type="text" readonly value=\'[simple_form id="' . $item->ID . '"]\' 
                        class="sb-module-shortcode-input" 
                        onclick="copyShortcode(this)"
                        title="Click to copy">
                        <span class="sb-module-shortcode-copied">Copied!</span>';
            default:
                return '';
        }
    }
    
    public function column_title($item) {
        $actions = array(
            'edit'    => '<a href="' . admin_url('post.php?post=' . $item->ID . '&action=edit') . '">Edit</a>',
            'entries' => '<a href="' . admin_url('admin.php?page=switchboard-forms&view=all-entries&form_filter=' . $item->ID) . '">Entries</a>',
            'delete'  => '<a href="' . wp_nonce_url(admin_url('admin.php?page=switchboard-forms&action=delete&form_id=' . $item->ID), 'delete_form_' . $item->ID) . '" onclick="return confirm(\'Delete this form and all its entries?\')">Delete</a>',
        );
        
        return sprintf('<strong><a href="%s">%s</a></strong>%s',
            admin_url('post.php?post=' . $item->ID . '&action=edit'),
            esc_html($item->post_title),
            $this->row_actions($actions)
        );
    }
    
    public function prepare_items() {
        global $wpdb;
        
        // Set column headers
        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = array($columns, $hidden, $sortable);
        
        $per_page = 20;
        $current_page = $this->get_pagenum();
        
        // Handle sorting
        $orderby = (!empty($_GET['orderby'])) ? sanitize_text_field($_GET['orderby']) : 'post_date';
        $order = (!empty($_GET['order'])) ? sanitize_text_field($_GET['order']) : 'DESC';
        
        // Get forms
        $args = array(
            'post_type'      => 'switchboard_form',
            'posts_per_page' => $per_page,
            'paged'          => $current_page,
            'orderby'        => $orderby,
            'order'          => $order,
            'post_status'    => 'any'
        );
        
        $query = new WP_Query($args);
        $this->items = $query->posts;
        
        // Set pagination
        $this->set_pagination_args(array(
            'total_items' => $query->found_posts,
            'per_page'    => $per_page,
            'total_pages' => $query->max_num_pages
        ));
    }
}

/**
 * Entries List Table
 */
class Switchboard_Entries_List_Table extends WP_List_Table {
    
    private $table_name;
    
    public function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'switchboard_form_entries';
        
        parent::__construct(array(
            'singular' => 'entry',
            'plural'   => 'entries',
            'ajax'     => false
        ));
    }
    
    public function get_columns() {
        return array(
            'id'       => 'ID',
            'form'     => 'Form',
            'name'     => 'Name',
            'email'    => 'Email',
            'date'     => 'Date',
            'status'   => 'Status'
        );
    }
    
    public function get_sortable_columns() {
        return array(
            'id'     => array('id', false),
            'form'   => array('form_id', false),
            'name'   => array('user_name', false),
            'email'  => array('user_email', false),
            'date'   => array('date_created', true),
            'status' => array('status', false)
        );
    }
    
    public function column_default($item, $column_name) {
        switch ($column_name) {
            case 'id':
                return '<strong>' . $item->id . '</strong>';
            case 'form':
                $form = get_post($item->form_id);
                return $form ? esc_html($form->post_title) : 'Unknown';
            case 'name':
                return esc_html($item->user_name);
            case 'email':
                return esc_html($item->user_email);
            case 'date':
                return date('M j, Y g:i a', strtotime($item->date_created));
            case 'status':
                $class = 'status-' . $item->status;
                $text = $item->status === 'unread' ? 'Unread' : 'Read';
                return '<span class="status-badge ' . $class . '">' . $text . '</span>';
            default:
                return '';
        }
    }
    
    public function column_id($item) {
        $filter_form = isset($_GET['form_filter']) ? intval($_GET['form_filter']) : 0;
        $filter_status = isset($_GET['status_filter']) ? sanitize_text_field($_GET['status_filter']) : '';
        
        $base_url = admin_url('admin.php?page=switchboard-forms&view=all-entries');
        if ($filter_form) $base_url = add_query_arg('form_filter', $filter_form, $base_url);
        if ($filter_status) $base_url = add_query_arg('status_filter', $filter_status, $base_url);
        
        $actions = array(
            'view'   => '<button type="button" class="view-entry" data-entry-id="' . $item->id . '">View</button>',
        );
        
        // Add mark as read/unread based on current status
        if ($item->status === 'unread') {
            $actions['mark_read'] = '<a href="' . wp_nonce_url($base_url . '&mark_read_entry=' . $item->id, 'mark_read_entry_' . $item->id) . '">Mark as Read</a>';
        } else {
            $actions['mark_unread'] = '<a href="' . wp_nonce_url($base_url . '&mark_unread_entry=' . $item->id, 'mark_unread_entry_' . $item->id) . '">Mark as Unread</a>';
        }
        
        $actions['delete'] = '<a href="' . wp_nonce_url($base_url . '&delete_entry=' . $item->id, 'delete_entry_' . $item->id) . '" onclick="return confirm(\'Delete this entry?\')">Delete</a>';
        
        return sprintf('<strong><button type="button" class="view-entry" data-entry-id="%s">%s</button></strong>%s',
            $item->id,
            $item->id,
            $this->row_actions($actions)
        );
    }
    
    protected function extra_tablenav($which) {
        if ($which === 'top') {
            $forms = get_posts(array('post_type' => 'switchboard_form', 'posts_per_page' => -1));
            $filter_form = isset($_GET['form_filter']) ? intval($_GET['form_filter']) : 0;
            $filter_status = isset($_GET['status_filter']) ? sanitize_text_field($_GET['status_filter']) : '';
            ?>
            <div class="alignleft actions">
                <select name="form_filter" id="form-filter">
                    <option value="0">All Forms</option>
                    <?php foreach ($forms as $form): ?>
                        <option value="<?php echo $form->ID; ?>" <?php selected($filter_form, $form->ID); ?>>
                            <?php echo esc_html($form->post_title); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                
                <select name="status_filter" id="status-filter">
                    <option value="">All Statuses</option>
                    <option value="unread" <?php selected($filter_status, 'unread'); ?>>Unread</option>
                    <option value="read" <?php selected($filter_status, 'read'); ?>>Read</option>
                </select>
                
                <input type="submit" class="button" value="Filter">
            </div>
            
            <div class="alignleft actions">
                <a href="<?php echo wp_nonce_url(admin_url('admin.php?page=switchboard-forms&view=all-entries&action=export_csv&form_filter=' . $filter_form . '&status_filter=' . $filter_status), 'export_entries_csv'); ?>" class="button">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                        <polyline points="7 10 12 15 17 10"></polyline>
                        <line x1="12" y1="15" x2="12" y2="3"></line>
                    </svg>
                    Export CSV
                </a>
            </div>
            <?php
        }
    }
    
    public function prepare_items() {
        global $wpdb;
        
        // Set column headers
        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = array($columns, $hidden, $sortable);
        
        $per_page = 20;
        $current_page = $this->get_pagenum();
        
        // Handle sorting - SECURITY FIX: Whitelist to prevent SQL injection
        $orderby_input = (!empty($_GET['orderby'])) ? sanitize_text_field($_GET['orderby']) : 'date_created';
        $order_input = (!empty($_GET['order'])) ? sanitize_text_field($_GET['order']) : 'DESC';

        // SECURITY FIX: Whitelist allowed columns
        $allowed_orderby = array('id', 'form_id', 'user_name', 'user_email', 'date_created', 'status');
        $orderby = in_array($orderby_input, $allowed_orderby, true) ? $orderby_input : 'date_created';

        // SECURITY FIX: Validate order direction
        $order = strtoupper($order_input) === 'ASC' ? 'ASC' : 'DESC';

        // Handle filters
        $filter_form = isset($_GET['form_filter']) ? intval($_GET['form_filter']) : 0;
        $filter_status = isset($_GET['status_filter']) ? sanitize_text_field($_GET['status_filter']) : '';

        // SECURITY FIX: Validate status value
        if (!empty($filter_status) && !in_array($filter_status, array('read', 'unread'), true)) {
            $filter_status = '';
        }

        // Build WHERE clause
        $where_conditions = array();
        if ($filter_form) {
            $where_conditions[] = $wpdb->prepare("form_id = %d", $filter_form);
        }
        if ($filter_status) {
            $where_conditions[] = $wpdb->prepare("status = %s", $filter_status);
        }
        $where = !empty($where_conditions) ? ' WHERE ' . implode(' AND ', $where_conditions) : '';

        // Get total count
        $total_items = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name}{$where}");

        // Get entries - SECURITY FIX: Safe because $orderby and $order are whitelisted
        $offset = ($current_page - 1) * $per_page;
        $this->items = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$this->table_name}{$where} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d",
            $per_page,
            $offset
        ));
        
        // Set pagination
        $this->set_pagination_args(array(
            'total_items' => $total_items,
            'per_page'    => $per_page,
            'total_pages' => ceil($total_items / $per_page)
        ));
    }
}

class Switchboard_Simple_Forms {
    
    private static $switchboard_instance = null;
    private $table_name;
    
    public static function get_instance() {
        if (null === self::$switchboard_instance) {
            self::$switchboard_instance = new self();
        }
        return self::$switchboard_instance;
    }
    
    private function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'switchboard_form_entries';
        
        // Create table if it doesn't exist
        $this->maybe_create_table();
        
        // Handle CSV export early before any output
        add_action('admin_init', array($this, 'handle_csv_export'));
        
        // Register CPT immediately since we're already in init hook when Switchboard loads us
        $this->register_cpt();
        
        // Setup other hooks
        add_action('admin_init', array($this, 'redirect_form_editor'));
        add_action('admin_menu', array($this, 'add_entries_menu'));
        add_action('admin_menu', array($this, 'remove_forms_menu'), 999);
        add_action('parent_file', array($this, 'fix_parent_menu'));
        add_action('submenu_file', array($this, 'fix_submenu_file'));
        add_action('add_meta_boxes', array($this, 'add_form_builder_meta_box'));
        add_action('save_post_switchboard_form', array($this, 'save_form_fields'), 10, 2);
        add_action('admin_head', array($this, 'add_form_editor_header'));
        add_action('admin_footer', array($this, 'add_form_editor_wrapper'));
        add_shortcode('simple_form', array($this, 'render_form_shortcode'));
        add_action('wp_ajax_submit_simple_form', array($this, 'handle_form_submission'));
        add_action('wp_ajax_nopriv_submit_simple_form', array($this, 'handle_form_submission'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_assets'));
    }
    
    /**
     * Handle CSV export early
     */
    public function handle_csv_export() {
        if (isset($_GET['page']) && $_GET['page'] === 'switchboard-forms' && 
            isset($_GET['action']) && $_GET['action'] === 'export_csv' && 
            isset($_GET['_wpnonce'])) {
            if (check_admin_referer('export_entries_csv')) {
                $this->export_entries_csv();
                exit;
            }
        }
    }
    
    /**
     * Check and create table if it doesn't exist
     */
    private function maybe_create_table() {
        global $wpdb;
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$this->table_name}'");
        
        if ($table_exists != $this->table_name) {
            $this->create_entries_table();
        }
        
        // Flush rewrite rules once
        if (!get_option('switchboard_forms_rewrite_flushed')) {
            add_action('init', function() {
                flush_rewrite_rules();
            }, 999);
            update_option('switchboard_forms_rewrite_flushed', 1);
        }
    }
    
    /**
     * Create custom table for form entries
     */
    public function create_entries_table() {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            form_id bigint(20) NOT NULL,
            date_created datetime DEFAULT CURRENT_TIMESTAMP,
            status varchar(20) DEFAULT 'unread',
            user_ip varchar(100),
            user_agent text,
            payload longtext,
            user_email varchar(255),
            user_name varchar(255),
            PRIMARY KEY (id),
            KEY form_id (form_id),
            KEY date_created (date_created),
            KEY status (status),
            KEY user_email (user_email)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    /**
     * Register Forms CPT
     */
    public function register_cpt() {
        $labels = array(
            'name' => 'Forms',
            'singular_name' => 'Form',
            'add_new' => 'Add New Form',
            'add_new_item' => 'Add New Form',
            'edit_item' => 'Edit Form',
            'new_item' => 'New Form',
            'view_item' => 'View Form',
            'search_items' => 'Search Forms',
            'not_found' => 'No forms found',
            'not_found_in_trash' => 'No forms found in Trash',
            'all_items' => 'All Forms',
        );
        
        $args = array(
            'labels' => $labels,
            'public' => true,
            'publicly_queryable' => false,
            'show_ui' => true,
            'show_in_menu' => true,
            'query_var' => true,
            'rewrite' => array('slug' => 'switchboard-form'),
            'menu_icon' => 'dashicons-feedback',
            'menu_position' => 100,
            'supports' => array('title'),
            'capability_type' => 'post',
            'capabilities' => array(
                'edit_post' => 'manage_options',
                'edit_posts' => 'manage_options',
                'edit_others_posts' => 'manage_options',
                'publish_posts' => 'manage_options',
                'read_post' => 'manage_options',
                'read_private_posts' => 'manage_options',
                'delete_post' => 'manage_options',
            ),
        );
        
        register_post_type('switchboard_form', $args);
    }
    
    /**
     * Remove the standalone Forms menu (we'll add it under Switchboard)
     */
    public function remove_forms_menu() {
        remove_menu_page('edit.php?post_type=switchboard_form');
    }
    
    /**
     * Fix parent menu highlighting for Forms pages
     */
    public function fix_parent_menu($parent_file) {
        global $current_screen;
        
        if ($current_screen && $current_screen->post_type === 'switchboard_form') {
            return 'switchboard';
        }
        
        return $parent_file;
    }
    
    /**
     * Fix submenu highlighting for Forms pages
     */
    public function fix_submenu_file($submenu_file) {
        global $current_screen;
        
        if ($current_screen && $current_screen->post_type === 'switchboard_form') {
            if ($current_screen->base === 'post') {
                return 'post-new.php?post_type=switchboard_form';
            }
            return 'edit.php?post_type=switchboard_form';
        }
        
        return $submenu_file;
    }
    
    /**
     * Redirect form editor requests to WordPress post editor
     */
    public function redirect_form_editor() {
        // Only on our forms page
        if (!isset($_GET['page']) || $_GET['page'] !== 'switchboard-forms') {
            return;
        }
        
        // Handle add action - redirect immediately
        if (isset($_GET['action']) && $_GET['action'] === 'add') {
            wp_safe_redirect(admin_url('post-new.php?post_type=switchboard_form'));
            exit;
        }
        
        // Handle edit action - redirect immediately
        if (isset($_GET['action']) && $_GET['action'] === 'edit' && isset($_GET['form_id'])) {
            $form_id = intval($_GET['form_id']);
            if ($form_id > 0) {
                wp_safe_redirect(admin_url('post.php?post=' . $form_id . '&action=edit'));
                exit;
            }
        }
    }
    
    /**
     * Add Forms menu under Switchboard
     */
    public function add_entries_menu() {
        // Add single Forms submenu
        add_submenu_page(
            'switchboard',
            'Forms',
            'Forms',
            'manage_options',
            'switchboard-forms',
            array($this, 'render_forms_page')
        );
    }
    
    /**
     * Render Forms management page (list & add new)
     */
    public function render_forms_page() {
        // Check which view to show
        $current_view = isset($_GET['view']) ? $_GET['view'] : 'forms';
        
        // Redirect old entries view to new all-entries view with filter
        if ($current_view === 'entries' && isset($_GET['form_id'])) {
            wp_safe_redirect(admin_url('admin.php?page=switchboard-forms&view=all-entries&form_filter=' . intval($_GET['form_id'])));
            exit;
        }
        
        // Check if viewing all entries
        if ($current_view === 'all-entries') {
            $this->render_all_entries_view();
            return;
        }
        
        // Handle bulk actions for forms
        if (isset($_POST['action']) && $_POST['action'] === 'delete' && !empty($_POST['form_ids'])) {
            check_admin_referer('bulk-forms');
            foreach ($_POST['form_ids'] as $form_id) {
                wp_delete_post(intval($form_id), true);
            }
            echo '<div class="notice notice-success"><p>' . count($_POST['form_ids']) . ' form(s) deleted.</p></div>';
        }
        
        // Handle single delete action
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['form_id'])) {
            if (check_admin_referer('delete_form_' . intval($_GET['form_id']))) {
                wp_delete_post(intval($_GET['form_id']), true);
                echo '<div class="notice notice-success"><p>Form deleted successfully.</p></div>';
            }
        }
        
        // Get stats
        global $wpdb;
        $table_name = $wpdb->prefix . 'switchboard_form_entries';
        $total_forms = wp_count_posts('switchboard_form')->publish;
        $total_entries = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name}");
        $entries_today = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table_name} WHERE DATE(date_created) = %s",
            current_time('Y-m-d')
        ));
        $entries_this_week = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table_name} WHERE date_created >= %s",
            date('Y-m-d H:i:s', strtotime('-7 days'))
        ));

        // Get recent entries (last 5)
        $recent_entries = $wpdb->get_results($wpdb->prepare(
            "SELECT e.*, p.post_title as form_name 
             FROM {$table_name} e 
             LEFT JOIN {$wpdb->posts} p ON e.form_id = p.ID 
             ORDER BY e.date_created DESC 
             LIMIT %d",
            5
        ));

        // Get top forms by entry count
        $top_forms = $wpdb->get_results(
            "SELECT p.ID, p.post_title, COUNT(e.id) as entry_count
             FROM {$wpdb->posts} p
             LEFT JOIN {$table_name} e ON p.ID = e.form_id
             WHERE p.post_type = 'switchboard_form' AND p.post_status = 'publish'
             GROUP BY p.ID
             ORDER BY entry_count DESC
             LIMIT 5"
        );
        
        ?>
        <div class="wrap sb-module-wrap">
            <!-- Header -->
            <div class="sb-module-header">
                <div class="sb-module-header-left">
                    <svg class="sb-module-title-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                    <div>
                        <h1 class="sb-module-title">
                            <?php esc_html_e('Forms', 'wpswitchboard'); ?>
                            <span class="switchboard-badge">SWITCHBOARD</span>
                        </h1>
                        <p class="sb-module-subtitle"><?php esc_html_e('Create and manage custom contact and lead forms with file uploads, email notifications, and entry management', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-header-right">
                    <a href="https://docs.wpswitchboard.com/modules/utilities/simple-forms" target="_blank" class="sb-module-help-link">
                        <span class="sb-module-help-link-icon dashicons dashicons-editor-help"></span>
                        Help
                    </a>
                    <?php
                    $action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : '';
                    $form_id = isset($_GET['form_id']) ? intval($_GET['form_id']) : (isset($_GET['post']) ? intval($_GET['post']) : 0);
                    if ($action === 'add' || $action === 'edit' || ($form_id > 0 && get_post_type($form_id) === 'switchboard_form')):
                    ?>
                        <a href="<?php echo admin_url('admin.php?page=switchboard-forms'); ?>" class="sb-module-button sb-module-button-secondary">
                            <?php esc_html_e('Go Back', 'wpswitchboard'); ?>
                        </a>
                    <?php else: ?>
                        <a href="<?php echo admin_url('admin.php?page=switchboard-forms&view=all-entries'); ?>" class="sb-module-button sb-module-button-secondary">
                            <?php esc_html_e('All Entries', 'wpswitchboard'); ?>
                        </a>
                        <a href="<?php echo admin_url('admin.php?page=switchboard-forms&action=add'); ?>" class="sb-module-button sb-module-button-primary">
                            <?php esc_html_e('Add New Form', 'wpswitchboard'); ?>
                        </a>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Main Content -->
            <div class="sb-module-container">
            <!-- Stats Cards -->
            <div class="sb-module-stats">
                <div class="sb-module-stat-card">
                    <div class="sb-module-stat-label"><?php esc_html_e('Total Forms', 'wpswitchboard'); ?></div>
                    <div class="sb-module-stat-content">
                        <div class="sb-module-stat-value"><?php echo number_format($total_forms ?: 0); ?></div>
                    </div>
                </div>

                <div class="sb-module-stat-card">
                    <div class="sb-module-stat-label"><?php esc_html_e('Total Entries', 'wpswitchboard'); ?></div>
                    <div class="sb-module-stat-content">
                        <div class="sb-module-stat-value"><?php echo number_format($total_entries ?: 0); ?></div>
                    </div>
                </div>

                <div class="sb-module-stat-card">
                    <div class="sb-module-stat-label"><?php esc_html_e('Entries Today', 'wpswitchboard'); ?></div>
                    <div class="sb-module-stat-content">
                        <div class="sb-module-stat-value"><?php echo number_format($entries_today ?: 0); ?></div>
                    </div>
                </div>

                <div class="sb-module-stat-card">
                    <div class="sb-module-stat-label"><?php esc_html_e('This Week', 'wpswitchboard'); ?></div>
                    <div class="sb-module-stat-content">
                        <div class="sb-module-stat-value"><?php echo number_format($entries_this_week ?: 0); ?></div>
                    </div>
                </div>
            </div>

            <!-- Two Column Layout: Recent Entries & Top Forms -->
            <div class="sb-module-layout-2col" style="grid-template-columns: 1fr 1fr !important; align-items: start;">
                <!-- Recent Entries -->
                <div class="sb-module-card" style="height: fit-content;">
                    <div class="sb-module-card-header">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Recent Entries', 'wpswitchboard'); ?></h2>
                    </div>
                    <div class="sb-module-card-body">
                        <?php if (!empty($recent_entries)): ?>
                            <div class="sb-module-table-wrapper">
                                <table class="sb-module-table">
                                    <thead>
                                        <tr>
                                            <th><?php esc_html_e('Form', 'wpswitchboard'); ?></th>
                                            <th><?php esc_html_e('Submitted', 'wpswitchboard'); ?></th>
                                            <th><?php esc_html_e('Status', 'wpswitchboard'); ?></th>
                                            <th><?php esc_html_e('Action', 'wpswitchboard'); ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recent_entries as $entry): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo esc_html($entry->form_name ?: 'Unknown Form'); ?></strong>
                                                </td>
                                                <td><?php echo human_time_diff(strtotime($entry->date_created), current_time('timestamp')) . ' ago'; ?></td>
                                                <td>
                                                    <span class="sb-module-badge <?php echo $entry->status === 'unread' ? 'sb-module-badge-warning' : 'sb-module-badge-primary'; ?>">
                                                        <?php echo $entry->status === 'unread' ? 'Unread' : 'Read'; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <a href="<?php echo admin_url('admin.php?page=switchboard-forms&view=all-entries&form_filter=' . intval($entry->form_id)); ?>" class="sb-module-button sb-module-button-secondary sb-module-button-sm">
                                                        <?php esc_html_e('View', 'wpswitchboard'); ?>
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="sb-module-empty">
                                <p class="sb-module-empty-desc"><?php esc_html_e('Form entries will appear here once users start submitting forms.', 'wpswitchboard'); ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Top Forms -->
                <div class="sb-module-card" style="height: fit-content;">
                    <div class="sb-module-card-header">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Top Forms', 'wpswitchboard'); ?></h2>
                    </div>
                    <div class="sb-module-card-body">
                        <?php if (!empty($top_forms)): ?>
                            <div class="sb-module-table-wrapper">
                                <table class="sb-module-table">
                                    <thead>
                                        <tr>
                                            <th><?php esc_html_e('Form Name', 'wpswitchboard'); ?></th>
                                            <th><?php esc_html_e('Entries', 'wpswitchboard'); ?></th>
                                            <th><?php esc_html_e('Action', 'wpswitchboard'); ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($top_forms as $form): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo esc_html($form->post_title); ?></strong>
                                                </td>
                                                <td style="font-weight: 600;"><?php echo number_format($form->entry_count); ?></td>
                                                <td>
                                                    <a href="<?php echo admin_url('admin.php?page=switchboard-forms&view=all-entries&form_filter=' . intval($form->ID)); ?>" class="sb-module-button sb-module-button-secondary sb-module-button-sm">
                                                        <?php esc_html_e('View Entries', 'wpswitchboard'); ?>
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="sb-module-empty">
                                <p class="sb-module-empty-desc"><?php esc_html_e('Create your first form to start collecting entries!', 'wpswitchboard'); ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- All Forms Table -->
            <div class="sb-module-card" id="all-forms" style="margin-top: 24px;">
                <div class="sb-module-card-header">
                    <h2 class="sb-module-card-title"><?php esc_html_e('All Forms', 'wpswitchboard'); ?></h2>
                </div>
                <div class="sb-module-card-body">
                    <div class="sb-module-table-wrapper">
                <?php
                $list_table = new Switchboard_Forms_List_Table();
                $list_table->prepare_items();
                    $items = $list_table->items;
                    ?>
                        <table class="sb-module-table" id="forms-table">
                            <thead>
                                <tr>
                                    <th style="width: 40px;">
                                        <input type="checkbox" id="cb-select-all">
                                    </th>
                                    <th style="width: 10%;">ID</th>
                                    <th style="width: 25%;"><?php esc_html_e('Form Name', 'wpswitchboard'); ?></th>
                                    <th style="width: 15%;"><?php esc_html_e('Entries', 'wpswitchboard'); ?></th>
                                    <th style="width: 15%;"><?php esc_html_e('Date Created', 'wpswitchboard'); ?></th>
                                    <th style="width: 25%;"><?php esc_html_e('Shortcode', 'wpswitchboard'); ?></th>
                                    <th style="width: 10%;"><?php esc_html_e('Actions', 'wpswitchboard'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($items)): ?>
                                    <?php foreach ($items as $item):
                                        global $wpdb;
                                        $table_name = $wpdb->prefix . 'switchboard_form_entries';
                                        $entry_count = $wpdb->get_var($wpdb->prepare(
                                            "SELECT COUNT(*) FROM {$table_name} WHERE form_id = %d",
                                            $item->ID
                                        ));
                                        $unread_count = $wpdb->get_var($wpdb->prepare(
                                            "SELECT COUNT(*) FROM {$table_name} WHERE form_id = %d AND is_read = 0",
                                            $item->ID
                                        ));
                                    ?>
                                        <tr>
                                            <td>
                                                <input type="checkbox" name="form_ids[]" value="<?php echo esc_attr($item->ID); ?>">
                                            </td>
                                            <td><?php echo esc_html($item->ID); ?></td>
                                            <td>
                                                <strong><a href="<?php echo admin_url('admin.php?page=switchboard-forms&action=edit&form_id=' . $item->ID); ?>"><?php echo esc_html($item->post_title); ?></a></strong>
                                            </td>
                                            <td>
                                                <?php if ($entry_count > 0): ?>
                                                    <?php
                                                    $link_color = $unread_count > 0 ? '#ea580c' : 'var(--primary-500)';
                                                    $link_style = 'color: ' . $link_color . '; font-weight: ' . ($unread_count > 0 ? '600' : '500') . ';';
                                                    ?>
                                                    <a href="<?php echo admin_url('admin.php?page=switchboard-forms&view=all-entries&form_filter=' . $item->ID); ?>" style="<?php echo $link_style; ?>">
                                                        <?php echo number_format($entry_count); ?> <?php esc_html_e('entries', 'wpswitchboard'); ?>
                                                    </a>
                                                <?php else: ?>
                                                    <span style="color: #94a3b8;">0 <?php esc_html_e('entries', 'wpswitchboard'); ?></span>
                                                <?php endif; ?>
                                            </td>
                                            <td style="color: #94a3b8;"><?php echo date('M j, Y', strtotime($item->post_date)); ?></td>
                                            <td>
                                                <input type="text" readonly value='[simple_form id="<?php echo esc_attr($item->ID); ?>"]'
                                                       class="sb-module-shortcode-input"
                                                       onclick="copyShortcode(this)"
                                                       title="Click to copy">
                                                <span class="sb-module-shortcode-copied">Copied!</span>
                                            </td>
                                            <td>
                                                <div style="display: flex; gap: 8px; align-items: center;">
                                                    <a href="<?php echo admin_url('admin.php?page=switchboard-forms&action=edit&form_id=' . $item->ID); ?>" class="sb-module-button sb-module-button-secondary sb-module-button-sm">
                                                        <?php esc_html_e('Edit', 'wpswitchboard'); ?>
                                                    </a>
                                                    <a href="<?php echo wp_nonce_url(admin_url('admin.php?page=switchboard-forms&action=delete&form_id=' . $item->ID), 'delete_form_' . $item->ID); ?>"
                                                       class="sb-module-button sb-module-button-danger sb-module-button-sm"
                                                       onclick="return confirm('<?php esc_attr_e('Delete this form and all its entries?', 'wpswitchboard'); ?>');">
                                                        <?php esc_html_e('Delete', 'wpswitchboard'); ?>
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="7">
                                            <div class="sb-module-empty">
                                                <p class="sb-module-empty-desc"><?php esc_html_e('Create your first form to start collecting entries!', 'wpswitchboard'); ?></p>
                                                <a href="<?php echo admin_url('admin.php?page=switchboard-forms&action=add'); ?>" class="sb-module-button sb-module-button-primary sb-module-button-icon-text" style="margin-top: 16px;">
                                                    <span class="dashicons dashicons-plus-alt"></span>
                                                    <?php esc_html_e('Create Your First Form', 'wpswitchboard'); ?>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            </div>
        </div>
        
        <script>
        function copyShortcode(input) {
            input.select();
            input.setSelectionRange(0, 99999); // For mobile devices
            
            try {
                // Modern clipboard API
                navigator.clipboard.writeText(input.value).then(function() {
                    showCopiedMessage(input);
                }).catch(function() {
                    // Fallback for older browsers
                    document.execCommand('copy');
                    showCopiedMessage(input);
                });
            } catch (err) {
                // Final fallback
                document.execCommand('copy');
                showCopiedMessage(input);
            }
        }
        
        function showCopiedMessage(input) {
            var message = input.parentElement.querySelector('.sb-module-shortcode-copied');
            if (message) {
                message.classList.add('show');
                setTimeout(function() {
                    message.classList.remove('show');
                }, 2000);
            }
        }

        // Select all checkbox
        jQuery(document).ready(function($) {
            $('#cb-select-all').on('change', function() {
                $('input[name="form_ids[]"]').prop('checked', $(this).prop('checked'));
            });
        });
        </script>
        <?php
        }

    /**
     * Render form editor page (add/edit) below stats cards
     * This redirects to the actual WordPress post editor but with our wrapper
     */

    /**
     * Add custom header for form editor (Legacy mode - disabled)
     */
    public function add_form_editor_header() {
        // Legacy mode: Modern editor header disabled
        return;
    }

    /**
     * Add wrapper and reorganize form editor (Legacy mode - disabled)
     */
    public function add_form_editor_wrapper() {
        // Legacy mode: Modern editor wrapper and reorganization disabled
        return;
    }
    
    /**
     * Render all entries view (all forms combined)
     */
    public function render_all_entries_view() {
        global $wpdb;
        
        // Handle single entry mark as read
        if (isset($_GET['mark_read_entry']) && check_admin_referer('mark_read_entry_' . intval($_GET['mark_read_entry']))) {
            $entry_id = intval($_GET['mark_read_entry']);
            $wpdb->update($this->table_name, array('status' => 'read'), array('id' => $entry_id), array('%s'), array('%d'));
            echo '<div class="notice notice-success is-dismissible"><p>Entry marked as read.</p></div>';
        }
        
        // Handle single entry mark as unread
        if (isset($_GET['mark_unread_entry']) && check_admin_referer('mark_unread_entry_' . intval($_GET['mark_unread_entry']))) {
            $entry_id = intval($_GET['mark_unread_entry']);
            $wpdb->update($this->table_name, array('status' => 'unread'), array('id' => $entry_id), array('%s'), array('%d'));
            echo '<div class="notice notice-success is-dismissible"><p>Entry marked as unread.</p></div>';
        }
        
        // Handle single entry deletion
        if (isset($_GET['delete_entry']) && check_admin_referer('delete_entry_' . intval($_GET['delete_entry']))) {
            $wpdb->delete($this->table_name, array('id' => intval($_GET['delete_entry'])), array('%d'));
            echo '<div class="notice notice-success"><p>Entry deleted.</p></div>';
        }
        
        ?>
        <div class="wrap sb-module-wrap">
            <!-- Header -->
            <div class="sb-module-header">
                <div class="sb-module-header-left">
                    <h1 class="sb-module-title">
                        <svg class="sb-module-title-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                        <?php esc_html_e('Form Entries', 'wpswitchboard'); ?>
                        <span class="switchboard-badge">SWITCHBOARD</span>
            </h1>
                    <p class="sb-module-subtitle"><?php esc_html_e('View and manage all form submissions and entries', 'wpswitchboard'); ?></p>
                </div>
                <div class="sb-module-header-right">
                    <a href="https://docs.wpswitchboard.com/modules/utilities/simple-forms" target="_blank" class="sb-module-help-link">
                        <span class="sb-module-help-link-icon dashicons dashicons-editor-help"></span>
                        Help
                </a>
                    <a href="<?php echo admin_url('admin.php?page=switchboard-forms'); ?>" class="sb-module-button sb-module-button-secondary sb-module-button-icon-text">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                        </svg>
                        <?php esc_html_e('Back to Forms', 'wpswitchboard'); ?>
                    </a>
                </div>
            </div>

            <!-- Main Content -->
            <div class="sb-module-container">
                <?php
                    // Get entries using the same logic as WP_List_Table
                $list_table = new Switchboard_Entries_List_Table();
                $list_table->prepare_items();
                    $items = $list_table->items;
                    $filter_form = isset($_GET['form_filter']) ? intval($_GET['form_filter']) : 0;
                    $filter_status = isset($_GET['status_filter']) ? sanitize_text_field($_GET['status_filter']) : '';
                    $forms = get_posts(array('post_type' => 'switchboard_form', 'posts_per_page' => -1));
                    ?>

                <!-- Filters Card -->
                <div class="sb-module-card" style="margin-bottom: 16px;">
                    <div class="sb-module-card-body" style="padding: 16px;">
                        <form method="get">
                            <input type="hidden" name="page" value="switchboard-forms">
                            <input type="hidden" name="view" value="all-entries">
                            <div style="display: flex; gap: 12px; align-items: center; justify-content: flex-end;">
                                <svg style="width: 18px; height: 18px; color: #64748b; flex-shrink: 0;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"></path>
                                </svg>
                                <select name="form_filter" id="form-filter" class="sb-module-select" style="width: 200px;">
                                    <option value="0"><?php esc_html_e('All Forms', 'wpswitchboard'); ?></option>
                                    <?php foreach ($forms as $form): ?>
                                        <option value="<?php echo $form->ID; ?>" <?php selected($filter_form, $form->ID); ?>>
                                            <?php echo esc_html($form->post_title); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>

                                <select name="status_filter" id="status-filter" class="sb-module-select" style="width: 120px;">
                                    <option value=""><?php esc_html_e('All Statuses', 'wpswitchboard'); ?></option>
                                    <option value="unread" <?php selected($filter_status, 'unread'); ?>><?php esc_html_e('Unread', 'wpswitchboard'); ?></option>
                                    <option value="read" <?php selected($filter_status, 'read'); ?>><?php esc_html_e('Read', 'wpswitchboard'); ?></option>
                                </select>

                                <button type="submit" class="sb-module-button sb-module-button-primary sb-module-button-sm sb-module-button-icon-text">
                                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" style="width: 16px; height: 16px;">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                    </svg>
                                    <?php esc_html_e('Apply Filters', 'wpswitchboard'); ?>
                                </button>

                                <a href="<?php echo wp_nonce_url(admin_url('admin.php?page=switchboard-forms&view=all-entries&action=export_csv&form_filter=' . $filter_form . '&status_filter=' . $filter_status), 'export_entries_csv'); ?>" class="sb-module-button sb-module-button-secondary sb-module-button-sm sb-module-button-icon-text">
                                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" style="width: 16px; height: 16px;">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path>
                                    </svg>
                                    <?php esc_html_e('Export CSV', 'wpswitchboard'); ?>
                                </a>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Entries Table Card -->
                <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('All Entries', 'wpswitchboard'); ?></h2>
                            <?php if (!empty($items)): ?>
                                <p class="sb-module-card-subtitle"><?php echo count($items); ?> <?php echo count($items) === 1 ? 'entry' : 'entries'; ?></p>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="sb-module-card-body">
                        <div class="sb-module-table-wrapper">
                    
                    <table class="sb-module-table" id="entries-table">
                        <thead>
                            <tr>
                                <th style="width: 8%;"><?php esc_html_e('ID', 'wpswitchboard'); ?></th>
                                <th style="width: 20%;"><?php esc_html_e('Form', 'wpswitchboard'); ?></th>
                                <th style="width: 20%;"><?php esc_html_e('Name', 'wpswitchboard'); ?></th>
                                <th style="width: 20%;"><?php esc_html_e('Email', 'wpswitchboard'); ?></th>
                                <th style="width: 15%;"><?php esc_html_e('Date', 'wpswitchboard'); ?></th>
                                <th style="width: 10%;"><?php esc_html_e('Status', 'wpswitchboard'); ?></th>
                                <th style="width: 7%;"><?php esc_html_e('Actions', 'wpswitchboard'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($items)): ?>
                                <?php foreach ($items as $item): 
                                    $form = get_post($item->form_id);
                                    $base_url = admin_url('admin.php?page=switchboard-forms&view=all-entries');
                                    if ($filter_form) $base_url = add_query_arg('form_filter', $filter_form, $base_url);
                                    if ($filter_status) $base_url = add_query_arg('status_filter', $filter_status, $base_url);
                                ?>
                                    <tr class="<?php echo $item->status === 'unread' ? 'entry-unread' : ''; ?>">
                                        <td>
                                            <button type="button" class="view-entry sb-module-button sb-module-button-secondary sb-module-button-sm" data-entry-id="<?php echo esc_attr($item->id); ?>">
                                                <?php echo esc_html($item->id); ?>
                                            </button>
                                        </td>
                                        <td><?php echo $form ? esc_html($form->post_title) : 'Unknown'; ?></td>
                                        <td><?php echo esc_html($item->user_name); ?></td>
                                        <td><?php echo esc_html($item->user_email); ?></td>
                                        <td style="color: #94a3b8;"><?php echo date('M j, Y g:i a', strtotime($item->date_created)); ?></td>
                                        <td>
                                            <span class="sb-module-badge <?php echo $item->status === 'unread' ? 'sb-module-badge-warning' : 'sb-module-badge-primary'; ?>">
                                                <?php echo $item->status === 'unread' ? 'Unread' : 'Read'; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div style="display: flex; gap: 6px; align-items: center;">
                                                <?php if ($item->status === 'unread'): ?>
                                                    <a href="<?php echo wp_nonce_url($base_url . '&mark_read_entry=' . $item->id, 'mark_read_entry_' . $item->id); ?>"
                                                       class="sb-module-button sb-module-button-secondary sb-module-button-sm"
                                                       title="<?php esc_attr_e('Mark as Read', 'wpswitchboard'); ?>"
                                                       style="padding: 6px;">
                                                        <svg style="width: 16px; height: 16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                                                        </svg>
                                                    </a>
                                                <?php else: ?>
                                                    <a href="<?php echo wp_nonce_url($base_url . '&mark_unread_entry=' . $item->id, 'mark_unread_entry_' . $item->id); ?>"
                                                       class="sb-module-button sb-module-button-secondary sb-module-button-sm"
                                                       title="<?php esc_attr_e('Mark as Unread', 'wpswitchboard'); ?>"
                                                       style="padding: 6px;">
                                                        <svg style="width: 16px; height: 16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                                        </svg>
                                                    </a>
                                                <?php endif; ?>
                                                <a href="<?php echo wp_nonce_url($base_url . '&delete_entry=' . $item->id, 'delete_entry_' . $item->id); ?>"
                                                   class="sb-module-button sb-module-button-danger sb-module-button-sm"
                                                   onclick="return confirm('<?php esc_attr_e('Delete this entry?', 'wpswitchboard'); ?>');"
                                                   title="<?php esc_attr_e('Delete', 'wpswitchboard'); ?>"
                                                   style="padding: 6px;">
                                                    <svg style="width: 16px; height: 16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                                    </svg>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7" class="sb-module-empty">
                                        <div class="sb-module-empty-icon"></div>
                                        <h2 class="sb-module-empty-title"><?php esc_html_e('No Entries Yet', 'wpswitchboard'); ?></h2>
                                        <p class="sb-module-empty-desc"><?php esc_html_e('Form entries will appear here once users start submitting forms.', 'wpswitchboard'); ?></p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Entry View Modal -->
        <div id="entry-modal" class="entry-modal-overlay">
            <div class="entry-modal-container">
                <div class="entry-modal-header">
                    <h2 id="entry-modal-title"><?php esc_html_e('Entry Details', 'wpswitchboard'); ?></h2>
                    <button type="button" class="entry-modal-close" onclick="closeEntryModal()">&times;</button>
                </div>
                <div class="entry-modal-content" id="entry-modal-content">
                    <div class="entry-modal-loading"><?php esc_html_e('Loading...', 'wpswitchboard'); ?></div>
                </div>
            </div>
        </div>
        
        <script>
        function closeEntryModal() {
            document.getElementById('entry-modal').classList.remove('show');
        }
        
        function openEntryModal() {
            document.getElementById('entry-modal').classList.add('show');
        }
        
        jQuery(document).ready(function($) {
            // View entry
            $(document).on('click', '.view-entry', function(e) {
                e.preventDefault();
                var entryId = $(this).data('entry-id');
                var $row = $(this).closest('tr');

                console.log('Opening entry modal for ID:', entryId);
                openEntryModal();
                $('#entry-modal-content').html('<div class="entry-modal-loading">Loading entry details...</div>');

                // Check if required data exists
                if (typeof switchboardFormsData === 'undefined') {
                    console.error('switchboardFormsData is not defined');
                    $('#entry-modal-content').html('<div style="padding: 20px; color: #dc2626; text-align: center;">Error: Required data not loaded. Please refresh the page.</div>');
                    return;
                }

                $.post(ajaxurl, {
                    action: 'view_form_entry',
                    entry_id: entryId,
                    nonce: switchboardFormsData.nonce
                }, function(response) {
                    console.log('AJAX Response:', response);
                    if (response.success) {
                        $('#entry-modal-content').html(response.data.html);
                        // Update row to mark as read
                        $row.removeClass('entry-unread');
                        $row.find('.sb-module-badge').removeClass('sb-module-badge-warning').addClass('sb-module-badge-primary').text('Read');
                    } else {
                        var errorMsg = response.data && response.data.message ? response.data.message : 'Unknown error occurred';
                        $('#entry-modal-content').html('<div style="padding: 20px; color: #dc2626; text-align: center;">Error: ' + errorMsg + '</div>');
                    }
                }).fail(function(xhr, status, error) {
                    console.error('AJAX Error:', status, error, xhr);
                    $('#entry-modal-content').html('<div style="padding: 20px; color: #dc2626; text-align: center;">Network error: ' + error + '</div>');
                });
            });

            // Close modal on background click
            $('#entry-modal').on('click', function(e) {
                if (e.target.classList.contains('entry-modal-overlay')) {
                    closeEntryModal();
                }
            });

            // Close modal on Escape key
            $(document).on('keydown', function(e) {
                if (e.key === 'Escape') {
                    closeEntryModal();
                }
            });
        });
        </script>
        <?php
    }
    
    /**
     * Render entries page for a specific form
     */
    public function render_form_entries_page($form_id) {
        global $wpdb;
        $form = get_post($form_id);
        
        if (!$form) {
            echo '<div class="wrap"><p>Form not found.</p></div>';
            return;
        }
        
        // Handle entry deletion
        if (isset($_GET['delete_entry']) && check_admin_referer('delete_entry_' . intval($_GET['delete_entry']))) {
            $wpdb->delete($this->table_name, array('id' => intval($_GET['delete_entry'])), array('%d'));
            echo '<div class="notice notice-success"><p>Entry deleted.</p></div>';
        }
        
        // Get entries for this form
        $entries = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$this->table_name} WHERE form_id = %d ORDER BY date_created DESC LIMIT 100",
            $form_id
        ));
        
        ?>
        <div class="wrap">
            <h1>
                Entries for: <?php echo esc_html($form->post_title); ?>
                <a href="<?php echo admin_url('admin.php?page=switchboard-forms'); ?>" class="page-title-action">← Back to Forms</a>
            </h1>
            
            <?php if (empty($entries)): ?>
                <p style="margin-top: 20px;">No entries yet for this form.</p>
            <?php else: ?>
                <table class="wp-list-table widefat fixed striped" style="margin-top: 20px;">
                    <thead>
                        <tr>
                            <th width="40">ID</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($entries as $entry): 
                            $data = json_decode($entry->payload, true);
                        ?>
                            <tr class="<?php echo $entry->status === 'unread' ? 'status-unread' : ''; ?>">
                                <td><?php echo $entry->id; ?></td>
                                <td><?php echo esc_html($entry->user_name); ?></td>
                                <td><?php echo esc_html($entry->user_email); ?></td>
                                <td><?php echo date('M j, Y g:i a', strtotime($entry->date_created)); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo esc_attr($entry->status); ?>">
                                        <?php echo esc_html($entry->status); ?>
                                    </span>
                                </td>
                                <td>
                                    <button type="button" class="button button-small view-entry" data-entry-id="<?php echo $entry->id; ?>">View</button>
                                    <a href="<?php echo wp_nonce_url(admin_url('admin.php?page=switchboard-forms&view=entries&form_id=' . $form_id . '&delete_entry=' . $entry->id), 'delete_entry_' . $entry->id); ?>" 
                                       class="button button-small" 
                                       onclick="return confirm('Are you sure?')">Delete</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        
        <!-- Entry View Modal -->
        <div id="entry-modal" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.7); z-index:100000;">
            <div style="background:#fff; max-width:800px; margin:50px auto; padding:30px; border-radius:5px; max-height:80vh; overflow-y:auto;">
                <button onclick="document.getElementById('entry-modal').style.display='none'" style="float:right; font-size:24px; border:none; background:none; cursor:pointer;">&times;</button>
                <div id="entry-modal-content"></div>
            </div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            $('.view-entry').on('click', function(e) {
                e.preventDefault();
                var entryId = $(this).data('entry-id');
                
                $.post(ajaxurl, {
                    action: 'view_form_entry',
                    entry_id: entryId,
                    nonce: switchboardFormsData.nonce
                }, function(response) {
                    if (response.success) {
                        $('#entry-modal-content').html(response.data.html);
                        $('#entry-modal').show();
                    }
                });
            });
        });
        </script>
        
        <style>
        .status-unread { background-color: #f0f8ff; }
        .status-badge { 
            padding: 3px 8px; 
            border-radius: 3px; 
            font-size: 11px; 
            text-transform: uppercase;
        }
        .status-unread { background: #fff3cd; color: #856404; }
        .status-read { background: #d4edda; color: #155724; }
        </style>
        <?php
    }
    
    /**
     * Add meta box for form builder
     */
    public function add_form_builder_meta_box() {
        add_meta_box(
            'switchboard_form_builder',
            'Form Fields',
            array($this, 'render_form_builder'),
            'switchboard_form',
            'normal',
            'high'
        );

        add_meta_box(
            'switchboard_form_shortcode',
            'Form Shortcode',
            array($this, 'render_form_shortcode_box'),
            'switchboard_form',
            'side',
            'high'
        );

        add_meta_box(
            'switchboard_form_settings',
            'Form Settings',
            array($this, 'render_form_settings'),
            'switchboard_form',
            'side',
            'default'
        );

        // Remove the post type selector from the publish box
        remove_meta_box('submitdiv', 'switchboard_form', 'side');
        add_meta_box('submitdiv', __('Publish'), array($this, 'render_custom_publish_box'), 'switchboard_form', 'side', 'high');
    }
    
    /**
     * Render form builder meta box
     */
    public function render_form_builder($post) {
        wp_nonce_field('switchboard_form_builder', 'switchboard_form_nonce');
        $fields = get_post_meta($post->ID, '_form_fields', true);
        if (empty($fields)) {
            $fields = array();
        }
        ?>
        <div id="form-builder-app">
            <div class="field-palette" style="margin-bottom: 24px;">
                <h4 class="sb-module-heading-sm" style="margin-bottom: 16px; color: #1e293b; font-size: 13px; font-weight: 600;">Add Fields</h4>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px;">
                    <button type="button" class="add-field-btn sb-module-quick-add-btn" data-type="text">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
                        <span><?php esc_html_e('Text', 'wpswitchboard'); ?></span>
                    </button>
                    <button type="button" class="add-field-btn sb-module-quick-add-btn" data-type="email">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg>
                        <span><?php esc_html_e('Email', 'wpswitchboard'); ?></span>
                    </button>
                    <button type="button" class="add-field-btn sb-module-quick-add-btn" data-type="textarea">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h7"></path></svg>
                        <span><?php esc_html_e('Textarea', 'wpswitchboard'); ?></span>
                    </button>
                    <button type="button" class="add-field-btn sb-module-quick-add-btn" data-type="number">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"></path></svg>
                        <span><?php esc_html_e('Number', 'wpswitchboard'); ?></span>
                    </button>
                    <button type="button" class="add-field-btn sb-module-quick-add-btn" data-type="select">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg>
                        <span><?php esc_html_e('Select Dropdown', 'wpswitchboard'); ?></span>
                    </button>
                    <button type="button" class="add-field-btn sb-module-quick-add-btn" data-type="radio">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                        <span><?php esc_html_e('Radio Buttons', 'wpswitchboard'); ?></span>
                    </button>
                    <button type="button" class="add-field-btn sb-module-quick-add-btn" data-type="checkbox">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path></svg>
                        <span><?php esc_html_e('Checkbox', 'wpswitchboard'); ?></span>
                    </button>
                    <button type="button" class="add-field-btn sb-module-quick-add-btn" data-type="date">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                        <span><?php esc_html_e('Date Picker', 'wpswitchboard'); ?></span>
                    </button>
                    <button type="button" class="add-field-btn sb-module-quick-add-btn" data-type="url">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path></svg>
                        <span><?php esc_html_e('URL', 'wpswitchboard'); ?></span>
                    </button>
                    <button type="button" class="add-field-btn sb-module-quick-add-btn" data-type="phone">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"></path></svg>
                        <span><?php esc_html_e('Phone', 'wpswitchboard'); ?></span>
                    </button>
                    <button type="button" class="add-field-btn sb-module-quick-add-btn" data-type="file">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"></path></svg>
                        <span><?php esc_html_e('File Upload', 'wpswitchboard'); ?></span>
                    </button>
                    <button type="button" class="add-field-btn sb-module-quick-add-btn" data-type="hidden">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"></path></svg>
                        <span><?php esc_html_e('Hidden Field', 'wpswitchboard'); ?></span>
                    </button>
                </div>

                <!-- Layout Fields -->
                <h4 class="sb-module-heading-sm" style="margin: 16px 0 12px; color: #64748b; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em;">Layout</h4>
                <div style="display: grid; grid-template-columns: 1fr; gap: 8px;">
                    <button type="button" class="add-field-btn sb-module-quick-add-btn sf-quick-add-group" data-type="group" style="flex-direction: row; justify-content: center; gap: 10px; padding: 12px 16px; background: var(--primary-50); border: 2px dashed var(--primary-200);">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" style="width: 18px; height: 18px;"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path></svg>
                        <span style="font-weight: 600; color: var(--primary-700);"><?php esc_html_e('Section/Group', 'wpswitchboard'); ?></span>
                    </button>
                    <button type="button" class="add-field-btn sb-module-quick-add-btn sf-quick-add-separator" data-type="separator" style="flex-direction: row; justify-content: center; gap: 10px; padding: 12px 16px;">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" style="width: 18px; height: 18px;"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4"></path></svg>
                        <span><?php esc_html_e('Separator/Divider', 'wpswitchboard'); ?></span>
                    </button>
                </div>
            </div>

            <div class="fields-container" id="fields-container">
                <!-- Fields will be rendered here -->
            </div>

            <input type="hidden" name="form_fields" id="form-fields-data" value="<?php echo esc_attr(json_encode($fields)); ?>">
        </div>
        <?php
    }

    /**
     * Render form shortcode meta box
     */
    public function render_form_shortcode_box($post) {
        if ($post->post_status === 'auto-draft') {
            ?>
            <p style="color: #64748b; font-size: 13px; line-height: 1.5;">
                <?php esc_html_e('Publish the form to get the shortcode.', 'wpswitchboard'); ?>
            </p>
            <?php
        } else {
            ?>
            <div style="margin-bottom: 12px;">
                <label style="display: block; margin-bottom: 6px; color: #475569; font-size: 12px; font-weight: 500;">
                    <?php esc_html_e('Copy and paste this shortcode:', 'wpswitchboard'); ?>
                </label>
                <input type="text"
                       readonly
                       value='[simple_form id="<?php echo esc_attr($post->ID); ?>"]'
                       class="sb-module-shortcode-input"
                       onclick="copyShortcode(this)"
                       style="width: 100%; max-width: 100%;"
                       title="Click to copy">
                <span class="sb-module-shortcode-copied">Copied!</span>
            </div>
            <p style="color: #64748b; font-size: 12px; line-height: 1.5; margin: 0;">
                <?php esc_html_e('Use this shortcode in posts, pages, or widgets to display the form.', 'wpswitchboard'); ?>
            </p>
            <?php
        }
    }

    /**
     * Render custom publish box without post type selector
     */
    public function render_custom_publish_box($post) {
        ?>
        <div class="submitbox" id="submitpost">
            <div id="minor-publishing">
                <div id="misc-publishing-actions">
                    <div class="misc-pub-section misc-pub-post-status">
                        <label for="post_status"><?php esc_html_e('Status:'); ?></label>
                        <span id="post-status-display">
                            <?php
                            switch ($post->post_status) {
                                case 'publish':
                                    esc_html_e('Published');
                                    break;
                                case 'draft':
                                    esc_html_e('Draft');
                                    break;
                                case 'pending':
                                    esc_html_e('Pending Review');
                                    break;
                                case 'future':
                                    esc_html_e('Scheduled');
                                    break;
                                default:
                                    esc_html_e('Draft');
                            }
                            ?>
                        </span>
                        <a href="#post_status" class="edit-post-status hide-if-no-js" role="button">
                            <span aria-hidden="true"><?php esc_html_e('Edit'); ?></span>
                        </a>
                        <div id="post-status-select" class="hide-if-js">
                            <input type="hidden" name="hidden_post_status" id="hidden_post_status" value="<?php echo esc_attr($post->post_status); ?>" />
                            <select name="post_status" id="post_status">
                                <option value="publish"<?php selected($post->post_status, 'publish'); ?>><?php esc_html_e('Published'); ?></option>
                                <option value="draft"<?php selected($post->post_status, 'draft'); ?>><?php esc_html_e('Draft'); ?></option>
                            </select>
                            <a href="#post_status" class="save-post-status hide-if-no-js button"><?php esc_html_e('OK'); ?></a>
                            <a href="#post_status" class="cancel-post-status hide-if-no-js button-cancel"><?php esc_html_e('Cancel'); ?></a>
                        </div>
                    </div>

                    <div class="misc-pub-section curtime misc-pub-curtime">
                        <span id="timestamp">
                            <?php
                            if ($post->post_status === 'publish') {
                                printf(
                                    esc_html__('Published on: %s'),
                                    '<b>' . date_i18n(get_option('date_format'), strtotime($post->post_date)) . '</b>'
                                );
                            } else {
                                esc_html_e('Publish immediately');
                            }
                            ?>
                        </span>
                    </div>
                </div>
                <div class="clear"></div>
            </div>

            <div id="major-publishing-actions">
                <div id="delete-action">
                    <?php
                    if (current_user_can('delete_post', $post->ID)) {
                        if (!EMPTY_TRASH_DAYS) {
                            $delete_text = __('Delete Permanently');
                        } else {
                            $delete_text = __('Move to Trash');
                        }
                        ?>
                        <a class="submitdelete deletion" href="<?php echo get_delete_post_link($post->ID); ?>">
                            <?php echo esc_html($delete_text); ?>
                        </a>
                        <?php
                    }
                    ?>
                </div>

                <div id="publishing-action">
                    <span class="spinner"></span>
                    <?php
                    if (!in_array($post->post_status, array('publish', 'future', 'private'), true) || $post->post_status === 'auto-draft') {
                        ?>
                        <input name="original_publish" type="hidden" id="original_publish" value="<?php esc_attr_e('Publish'); ?>" />
                        <?php submit_button(__('Publish'), 'primary large', 'publish', false); ?>
                        <?php
                    } else {
                        ?>
                        <input name="original_publish" type="hidden" id="original_publish" value="<?php esc_attr_e('Update'); ?>" />
                        <input name="save" type="submit" class="button button-primary button-large" id="publish" value="<?php esc_attr_e('Update'); ?>" />
                        <?php
                    }
                    ?>
                </div>
                <div class="clear"></div>
            </div>
        </div>
        <?php
    }

    /**
     * Render form settings meta box
     */
    public function render_form_settings($post) {
        $settings = get_post_meta($post->ID, '_form_settings', true);
        $defaults = array(
            'recipient' => get_option('admin_email'),
            'subject' => 'New form submission from ' . get_bloginfo('name'),
            'success_message' => 'Thank you! Your submission has been received.',
            'redirect_url' => '',
            'submit_button_text' => 'Submit',
            'enable_spam_protection' => true,
            'enable_autoreply' => false,
            'autoreply_subject' => 'Thank you for your submission',
            'autoreply_message' => 'We have received your submission and will get back to you soon.',
        );
        $settings = wp_parse_args($settings, $defaults);
        ?>
        <p>
            <label><strong>Email Recipient:</strong></label><br>
            <input type="email" name="form_settings[recipient]" value="<?php echo esc_attr($settings['recipient']); ?>" class="widefat">
        </p>
        <p>
            <label><strong>Email Subject:</strong></label><br>
            <input type="text" name="form_settings[subject]" value="<?php echo esc_attr($settings['subject']); ?>" class="widefat">
        </p>
        <p>
            <label><strong>Success Message:</strong></label><br>
            <textarea name="form_settings[success_message]" class="widefat" rows="3"><?php echo esc_textarea($settings['success_message']); ?></textarea>
            <small>Shown after successful submission (if no redirect URL)</small>
        </p>
        <p>
            <label><strong>Redirect URL (Optional):</strong></label><br>
            <input type="url" name="form_settings[redirect_url]" value="<?php echo esc_attr($settings['redirect_url']); ?>" class="widefat" placeholder="https://example.com/thank-you">
            <small>Leave blank to show success message instead</small>
        </p>
        <p>
            <label><strong>Submit Button Text:</strong></label><br>
            <input type="text" name="form_settings[submit_button_text]" value="<?php echo esc_attr($settings['submit_button_text']); ?>" class="widefat">
        </p>
        <p>
            <label>
                <input type="checkbox" name="form_settings[enable_spam_protection]" value="1" <?php checked($settings['enable_spam_protection']); ?>>
                Enable spam protection (honeypot + timing)
            </label>
        </p>

        <?php $this->render_captcha_status_box(); ?>

        <p>
            <label>
                <input type="checkbox" name="form_settings[enable_autoreply]" value="1" <?php checked($settings['enable_autoreply']); ?>>
                Send auto-reply email
            </label>
        </p>
        <div id="autoreply-settings" style="<?php echo $settings['enable_autoreply'] ? '' : 'display:none;'; ?>">
            <p>
                <label><strong>Auto-reply Subject:</strong></label><br>
                <input type="text" name="form_settings[autoreply_subject]" value="<?php echo esc_attr($settings['autoreply_subject']); ?>" class="widefat">
            </p>
            <p>
                <label><strong>Auto-reply Message:</strong></label><br>
                <textarea name="form_settings[autoreply_message]" class="widefat" rows="4"><?php echo esc_textarea($settings['autoreply_message']); ?></textarea>
            </p>
        </div>
        <?php
    }

    /**
     * Render CAPTCHA status box in form settings
     */
    private function render_captcha_status_box() {
        // Check which CAPTCHA modules are active
        $simple_captcha_active = class_exists('SwitchboardSimpleCaptcha');
        $recaptcha_active = class_exists('SwitchboardGoogleReCaptcha');
        $turnstile_active = class_exists('SwitchboardCloudflareTurnstile');

        // Get their settings if active
        $simple_captcha_settings = $simple_captcha_active ? get_option('switchboard_simple_captcha', []) : [];
        $recaptcha_settings = $recaptcha_active ? get_option('switchboard_google_recaptcha', []) : [];
        $turnstile_settings = $turnstile_active ? get_option('switchboard_cloudflare_turnstile', []) : [];

        // Check if keys are configured (Simple CAPTCHA doesn't need keys)
        $simple_captcha_ready = $simple_captcha_active;
        $recaptcha_configured = !empty($recaptcha_settings['site_key']) && !empty($recaptcha_settings['secret_key']);
        $turnstile_configured = !empty($turnstile_settings['site_key']) && !empty($turnstile_settings['secret_key']);

        // Check if any CAPTCHA is protecting forms
        $any_active = $simple_captcha_ready || $recaptcha_configured || $turnstile_configured;
        ?>
        <div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; padding: 12px; margin: 12px 0;">
            <strong style="font-size: 12px; color: #475569; display: block; margin-bottom: 8px;"><?php _e('CAPTCHA Protection', 'wpswitchboard'); ?></strong>

            <?php if (!$simple_captcha_active && !$recaptcha_active && !$turnstile_active): ?>
                <p style="font-size: 12px; color: #64748b; margin: 0;">
                    <?php _e('No CAPTCHA module enabled.', 'wpswitchboard'); ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=switchboard&category=security')); ?>"><?php _e('Enable one', 'wpswitchboard'); ?></a>
                </p>
            <?php else: ?>
                <div style="display: flex; flex-direction: column; gap: 6px;">
                    <?php if ($simple_captcha_active): ?>
                        <div style="display: flex; align-items: center; gap: 8px; font-size: 12px;">
                            <span class="dashicons dashicons-yes" style="color: #16a34a; font-size: 14px; width: 14px; height: 14px;"></span>
                            <span style="color: #16a34a;"><?php _e('Simple CAPTCHA active', 'wpswitchboard'); ?></span>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=switchboard&module=simple-captcha')); ?>" style="font-size: 11px;"><?php _e('Configure', 'wpswitchboard'); ?></a>
                        </div>
                    <?php endif; ?>

                    <?php if ($recaptcha_active): ?>
                        <div style="display: flex; align-items: center; gap: 8px; font-size: 12px;">
                            <?php if ($recaptcha_configured): ?>
                                <span class="dashicons dashicons-yes" style="color: #16a34a; font-size: 14px; width: 14px; height: 14px;"></span>
                                <span style="color: #16a34a;"><?php _e('Google reCAPTCHA active', 'wpswitchboard'); ?></span>
                            <?php else: ?>
                                <span class="dashicons dashicons-marker" style="color: #f59e0b; font-size: 14px; width: 14px; height: 14px;"></span>
                                <span style="color: #64748b;"><?php _e('reCAPTCHA - keys not configured', 'wpswitchboard'); ?></span>
                            <?php endif; ?>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=switchboard&module=google-recaptcha')); ?>" style="font-size: 11px;"><?php _e('Configure', 'wpswitchboard'); ?></a>
                        </div>
                    <?php endif; ?>

                    <?php if ($turnstile_active): ?>
                        <div style="display: flex; align-items: center; gap: 8px; font-size: 12px;">
                            <?php if ($turnstile_configured): ?>
                                <span class="dashicons dashicons-yes" style="color: #16a34a; font-size: 14px; width: 14px; height: 14px;"></span>
                                <span style="color: #16a34a;"><?php _e('Cloudflare Turnstile active', 'wpswitchboard'); ?></span>
                            <?php else: ?>
                                <span class="dashicons dashicons-marker" style="color: #f59e0b; font-size: 14px; width: 14px; height: 14px;"></span>
                                <span style="color: #64748b;"><?php _e('Turnstile - keys not configured', 'wpswitchboard'); ?></span>
                            <?php endif; ?>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=switchboard&module=cloudflare-turnstile')); ?>" style="font-size: 11px;"><?php _e('Configure', 'wpswitchboard'); ?></a>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Save form fields and settings
     */
    public function save_form_fields($post_id, $post) {
        // Security checks
        if (!isset($_POST['switchboard_form_nonce']) || !wp_verify_nonce($_POST['switchboard_form_nonce'], 'switchboard_form_builder')) {
            return;
        }
        
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // Save fields
        if (isset($_POST['form_fields'])) {
            $fields = json_decode(stripslashes($_POST['form_fields']), true);
            update_post_meta($post_id, '_form_fields', $fields);
        }
        
        // Save settings
        if (isset($_POST['form_settings'])) {
            $settings = array_map('sanitize_text_field', $_POST['form_settings']);
            update_post_meta($post_id, '_form_settings', $settings);
        }
    }
    
    /**
     * Enqueue admin assets
     */
    public function enqueue_admin_assets($hook) {
        global $post_type;

        // Check if we're on the forms list page or entries page
        $is_forms_page = (
            (isset($_GET['page']) && $_GET['page'] === 'switchboard-forms') ||
            strpos($hook, 'switchboard-forms') !== false
        );

        // Check if we're on the form editor page
        $is_form_editor = ($post_type === 'switchboard_form' && ($hook === 'post.php' || $hook === 'post-new.php'));

        if (!$is_forms_page && !$is_form_editor) {
            return;
        }

        // Enqueue the main Switchboard admin CSS (contains all sb-module-* classes)
        if (defined('SWITCHBOARD_URL') && defined('SWITCHBOARD_VERSION')) {
            wp_enqueue_style(
                'switchboard-admin',
                SWITCHBOARD_URL . 'switchboard-admin.css',
                [],
                SWITCHBOARD_VERSION
            );
        }

        // Add inline styles/scripts for form editor
        if ($is_form_editor) {
            wp_add_inline_style('wp-admin', $this->get_admin_css());
            wp_add_inline_script('jquery', $this->get_admin_js());
        }

        // Add inline styles for forms page (needed for modal)
        if ($is_forms_page) {
            wp_add_inline_style('wp-admin', $this->get_admin_css());
        }

        // Localize nonce for AJAX security (needed for both form editor and entries page)
        if ($is_form_editor || $is_forms_page) {
            wp_localize_script('jquery', 'switchboardFormsData', [
                'nonce' => wp_create_nonce('view_form_entry')
            ]);
        }
    }
    
    /**
     * Enqueue frontend assets
     */
    public function enqueue_frontend_assets() {
        // Enqueue jQuery
        wp_enqueue_script('jquery');
        wp_add_inline_style('wp-block-library', $this->get_frontend_css());
    }
    
    /**
     * Render form via shortcode
     */
    public function render_form_shortcode($atts) {
        // Make sure jQuery is loaded
        wp_enqueue_script('jquery');

        $atts = shortcode_atts(array('id' => 0), $atts);

        $form_id = intval($atts['id']);

        if (!$form_id) {
            return '<p>Invalid form ID.</p>';
        }

        $form = get_post($form_id);

        if (!$form || $form->post_type !== 'switchboard_form' || $form->post_status !== 'publish') {
            return '<p>Form not found.</p>';
        }
        
        $fields = get_post_meta($form_id, '_form_fields', true);
        $settings = get_post_meta($form_id, '_form_settings', true);
        
        if (empty($fields)) {
            return '<p>This form has no fields yet.</p>';
        }
        
        $defaults = array(
            'submit_button_text' => 'Submit',
            'enable_spam_protection' => true,
        );
        $settings = wp_parse_args($settings, $defaults);
        
        // Generate unique form slug for styling
        $form_slug = sanitize_title($form->post_title);

        ob_start();
        ?>
        <div class="simple-form-wrapper simple-form-<?php echo $form_id; ?> simple-form-<?php echo esc_attr($form_slug); ?>" id="simple-form-<?php echo $form_id; ?>" data-form-id="<?php echo $form_id; ?>">
            <form class="simple-form" data-form-id="<?php echo $form_id; ?>" method="post" enctype="multipart/form-data">
                <?php wp_nonce_field('submit_simple_form_' . $form_id, 'simple_form_nonce'); ?>
                
                <?php if ($settings['enable_spam_protection']): ?>
                    <input type="text" name="website" style="display:none !important;" tabindex="-1" autocomplete="off">
                    <input type="hidden" name="form_start_time" value="<?php echo time(); ?>">
                <?php endif; ?>
                
                <?php foreach ($fields as $field): ?>
                    <?php echo $this->render_field($field); ?>
                <?php endforeach; ?>

                <?php
                // Hook for CAPTCHA integration (reCAPTCHA, Turnstile, etc.)
                do_action('switchboard_simple_form_after_fields', $form_id);
                ?>

                <div class="form-message" style="display:none;"></div>

                <div class="form-field">
                    <button type="submit" class="simple-form-submit"><?php echo esc_html($settings['submit_button_text']); ?></button>
                </div>
            </form>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            console.log('=== Simple Form <?php echo $form_id; ?> Ready ===');
            
            $('#simple-form-<?php echo $form_id; ?> .simple-form').on('submit', function(e) {
                e.preventDefault();
                console.log('Form submitted!');
                
                var $form = $(this);
                var $message = $form.find('.form-message');
                var $submit = $form.find('.simple-form-submit');
                var formData = new FormData(this);
                
                console.log('Message element found:', $message.length);
                console.log('Message element:', $message);
                
                formData.append('action', 'submit_simple_form');
                formData.append('form_id', <?php echo $form_id; ?>);
                
                $submit.prop('disabled', true).text('Sending...');
                $message.hide().removeClass('error success');
                
                console.log('Sending AJAX request to:', '<?php echo admin_url('admin-ajax.php'); ?>');
                
                $.ajax({
                    url: '<?php echo admin_url('admin-ajax.php'); ?>',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        console.log('AJAX Success - Full response:', response);
                        console.log('Response success:', response.success);
                        console.log('Response data:', response.data);
                        
                        if (response.success) {
                            console.log('Response is successful');
                            console.log('Redirect URL:', response.data.redirect_url);
                            console.log('Success Message:', response.data.message);
                            
                            // Check if there's a redirect URL
                            if (response.data.redirect_url) {
                                console.log('Redirecting to:', response.data.redirect_url);
                                $message.addClass('success').html('Redirecting...').fadeIn();
                                setTimeout(function() {
                                    window.location.href = response.data.redirect_url;
                                }, 500);
                            } else {
                                console.log('Showing success message');
                                // Show success message and reset form
                                $message.removeClass('error').addClass('success').html(response.data.message);
                                console.log('Message HTML set to:', response.data.message);
                                console.log('Message classes:', $message.attr('class'));
                                
                                $message.fadeIn(400, function() {
                                    console.log('Message faded in, display:', $message.css('display'));
                                });
                                
                                $form[0].reset();
                                console.log('Form reset');
                                
                                // Scroll to top of form to see message
                                $('html, body').animate({
                                    scrollTop: $form.offset().top - 50
                                }, 300);
                                
                                $submit.prop('disabled', false).text('<?php echo esc_js($settings['submit_button_text']); ?>');
                            }
                        } else {
                            console.log('Response has error');
                            console.log('Error message:', response.data.message);
                            
                            $message.removeClass('success').addClass('error').html(response.data.message).fadeIn();
                            $submit.prop('disabled', false).text('<?php echo esc_js($settings['submit_button_text']); ?>');
                            
                            // Scroll to message
                            $('html, body').animate({
                                scrollTop: $message.offset().top - 50
                            }, 300);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.log('AJAX Error!');
                        console.log('Status:', status);
                        console.log('Error:', error);
                        console.log('XHR:', xhr);
                        
                        $message.addClass('error').html('An error occurred. Please try again.').show();
                        $submit.prop('disabled', false).text('<?php echo esc_js($settings['submit_button_text']); ?>');
                    }
                });
            });
        });
        </script>
        <?php
        return ob_get_clean();
    }
    
    /**
     * Render individual field
     */
    private function render_field($field) {
        $type = $field['type'];
        $id = 'field_' . $field['id'];
        $required = !empty($field['required']) ? 'required' : '';
        $label = esc_html($field['label']);
        $placeholder = !empty($field['placeholder']) ? esc_attr($field['placeholder']) : '';
        $help = !empty($field['help']) ? '<small>' . esc_html($field['help']) . '</small>' : '';

        ob_start();

        // Handle separator field
        if ($type === 'separator') {
            ?>
            <div class="form-field field-type-separator">
                <hr class="simple-form-separator">
            </div>
            <?php
            return ob_get_clean();
        }

        // Handle group/section field
        if ($type === 'group') {
            ?>
            <div class="form-field field-type-group">
                <?php if (!empty($field['label'])): ?>
                    <h3 class="simple-form-group-title"><?php echo esc_html($field['label']); ?></h3>
                <?php endif; ?>
                <?php if (!empty($field['description'])): ?>
                    <p class="simple-form-group-description"><?php echo esc_html($field['description']); ?></p>
                <?php endif; ?>
            </div>
            <?php
            return ob_get_clean();
        }
        ?>
        <div class="form-field field-type-<?php echo esc_attr($type); ?>">
            <?php if ($type !== 'hidden'): ?>
                <label for="<?php echo $id; ?>">
                    <?php echo $label; ?>
                    <?php if ($required): ?><span class="required">*</span><?php endif; ?>
                </label>
            <?php endif; ?>
            
            <?php
            switch ($type) {
                case 'text':
                case 'email':
                case 'url':
                case 'phone':
                case 'number':
                case 'date':
                case 'hidden':
                    ?>
                    <input 
                        type="<?php echo esc_attr($type); ?>" 
                        id="<?php echo $id; ?>" 
                        name="<?php echo $id; ?>" 
                        placeholder="<?php echo $placeholder; ?>"
                        <?php echo $required; ?>
                        <?php if ($type === 'number' && !empty($field['min'])) echo 'min="' . esc_attr($field['min']) . '"'; ?>
                        <?php if ($type === 'number' && !empty($field['max'])) echo 'max="' . esc_attr($field['max']) . '"'; ?>
                    >
                    <?php
                    break;
                    
                case 'textarea':
                    ?>
                    <textarea 
                        id="<?php echo $id; ?>" 
                        name="<?php echo $id; ?>" 
                        placeholder="<?php echo $placeholder; ?>"
                        rows="5"
                        <?php echo $required; ?>
                    ></textarea>
                    <?php
                    break;
                    
                case 'select':
                    $options = !empty($field['options']) ? explode("\n", $field['options']) : array();
                    ?>
                    <select id="<?php echo $id; ?>" name="<?php echo $id; ?>" <?php echo $required; ?>>
                        <option value="">-- Select --</option>
                        <?php foreach ($options as $option): 
                            $option = trim($option);
                            if (empty($option)) continue;
                        ?>
                            <option value="<?php echo esc_attr($option); ?>"><?php echo esc_html($option); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php
                    break;
                    
                case 'radio':
                    $options = !empty($field['options']) ? explode("\n", $field['options']) : array();
                    ?>
                    <div class="radio-group">
                        <?php foreach ($options as $index => $option): 
                            $option = trim($option);
                            if (empty($option)) continue;
                            $option_id = $id . '_' . $index;
                        ?>
                            <label class="radio-label">
                                <input 
                                    type="radio" 
                                    id="<?php echo $option_id; ?>" 
                                    name="<?php echo $id; ?>" 
                                    value="<?php echo esc_attr($option); ?>"
                                    <?php echo $required; ?>
                                >
                                <?php echo esc_html($option); ?>
                            </label>
                        <?php endforeach; ?>
                    </div>
                    <?php
                    break;
                    
                case 'checkbox':
                    $options = !empty($field['options']) ? explode("\n", $field['options']) : array();
                    if (count($options) > 1) {
                        // Multiple checkboxes
                        ?>
                        <div class="checkbox-group">
                            <?php foreach ($options as $index => $option): 
                                $option = trim($option);
                                if (empty($option)) continue;
                                $option_id = $id . '_' . $index;
                            ?>
                                <label class="checkbox-label">
                                    <input 
                                        type="checkbox" 
                                        id="<?php echo $option_id; ?>" 
                                        name="<?php echo $id; ?>[]" 
                                        value="<?php echo esc_attr($option); ?>"
                                    >
                                    <?php echo esc_html($option); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                        <?php
                    } else {
                        // Single checkbox
                        ?>
                        <label class="checkbox-label">
                            <input 
                                type="checkbox" 
                                id="<?php echo $id; ?>" 
                                name="<?php echo $id; ?>" 
                                value="1"
                                <?php echo $required; ?>
                            >
                            <?php echo !empty($field['checkbox_label']) ? esc_html($field['checkbox_label']) : 'I agree'; ?>
                        </label>
                        <?php
                    }
                    break;
                    
                case 'file':
                    $accept = !empty($field['file_types']) ? esc_attr($field['file_types']) : 'image/*,.pdf';
                    $max_size = !empty($field['max_size']) ? intval($field['max_size']) : 5;
                    $multiple = !empty($field['multiple']) ? 'multiple' : '';
                    ?>
                    <input 
                        type="file" 
                        id="<?php echo $id; ?>" 
                        name="<?php echo $id; ?><?php echo $multiple ? '[]' : ''; ?>" 
                        accept="<?php echo $accept; ?>"
                        <?php echo $multiple; ?>
                        <?php echo $required; ?>
                    >
                    <small>Max size: <?php echo $max_size; ?>MB per file</small>
                    <?php
                    break;
            }
            ?>
            
            <?php echo $help; ?>
        </div>
        <?php
        return ob_get_clean();
    }
    
    /**
     * Handle form submission via AJAX
     */
    public function handle_form_submission() {
        $form_id = intval($_POST['form_id']);
        
        // Verify nonce
        if (!isset($_POST['simple_form_nonce']) || !wp_verify_nonce($_POST['simple_form_nonce'], 'submit_simple_form_' . $form_id)) {
            wp_send_json_error(array('message' => esc_html__('Security check failed.', 'wpswitchboard')));
        }

        // Get form settings
        $settings = get_post_meta($form_id, '_form_settings', true);
        $fields = get_post_meta($form_id, '_form_fields', true);

        // Spam protection
        if (!empty($settings['enable_spam_protection'])) {
            // Honeypot check
            if (!empty($_POST['website'])) {
                wp_send_json_error(array('message' => esc_html__('Spam detected.', 'wpswitchboard')));
            }

            // Timing check (minimum 2 seconds)
            if (isset($_POST['form_start_time']) && (time() - intval($_POST['form_start_time'])) < 2) {
                wp_send_json_error(array('message' => esc_html__('Form submitted too quickly.', 'wpswitchboard')));
            }
        }

        // CAPTCHA validation filter (reCAPTCHA, Turnstile, etc.)
        $captcha_valid = apply_filters('switchboard_simple_form_validate', true, $form_id);
        if (is_wp_error($captcha_valid)) {
            wp_send_json_error(array('message' => $captcha_valid->get_error_message()));
        }
        if ($captcha_valid === false) {
            wp_send_json_error(array('message' => esc_html__('CAPTCHA verification failed. Please try again.', 'wpswitchboard')));
        }

        // Validate and collect data
        $data = array();
        $user_email = '';
        $user_name = '';
        $errors = array();

        foreach ($fields as $field) {
            // Skip layout fields (separator and group) - they don't have input values
            if ($field['type'] === 'separator' || $field['type'] === 'group') {
                continue;
            }

            $field_id = 'field_' . $field['id'];
            // SECURITY FIX: Sanitize POST data before processing
            $value = isset($_POST[$field_id]) ? wp_unslash($_POST[$field_id]) : '';

            // Handle file uploads
            if ($field['type'] === 'file' && !empty($_FILES[$field_id]['name'])) {
                $uploaded_files = $this->handle_file_upload($field_id, $field);
                if (is_wp_error($uploaded_files)) {
                    $errors[] = $field['label'] . ': ' . $uploaded_files->get_error_message();
                } else {
                    $value = $uploaded_files;
                }
            }

            // Required field validation
            if (!empty($field['required']) && empty($value)) {
                $errors[] = sprintf(esc_html__('%s is required.', 'wpswitchboard'), $field['label']);
            }

            // Email validation
            if ($field['type'] === 'email' && !empty($value) && !is_email($value)) {
                $errors[] = sprintf(esc_html__('%s must be a valid email address.', 'wpswitchboard'), $field['label']);
            }

            // Store email and name for indexing
            if ($field['type'] === 'email' && empty($user_email)) {
                $user_email = sanitize_email($value);
            }
            if (strtolower($field['label']) === 'name' && empty($user_name)) {
                $user_name = sanitize_text_field($value);
            }

            $data[$field['label']] = $value;
        }
        
        if (!empty($errors)) {
            wp_send_json_error(array('message' => implode('<br>', $errors)));
        }
        
        // Save to database
        global $wpdb;

        // SECURITY FIX: Sanitize user agent
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '';

        $wpdb->insert(
            $this->table_name,
            array(
                'form_id' => $form_id,
                'date_created' => current_time('mysql'),
                'status' => 'unread',
                'user_ip' => $this->get_user_ip(),
                'user_agent' => $user_agent,
                'payload' => json_encode($data),
                'user_email' => $user_email,
                'user_name' => $user_name,
            ),
            array('%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
        );
        
        // Send email notification
        $this->send_admin_notification($form_id, $data, $settings);
        
        // Send auto-reply if enabled
        if (!empty($settings['enable_autoreply']) && !empty($user_email)) {
            $this->send_autoreply($user_email, $settings);
        }
        
        $success_message = !empty($settings['success_message']) ? $settings['success_message'] : __('Thank you! Your submission has been received.', 'wpswitchboard');
        $redirect_url = !empty($settings['redirect_url']) ? $settings['redirect_url'] : '';
        
        wp_send_json_success(array(
            'message' => $success_message,
            'redirect_url' => $redirect_url
        ));
    }
    
    /**
     * Handle file upload
     */
    private function handle_file_upload($field_id, $field) {
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        
        $max_size = !empty($field['max_size']) ? intval($field['max_size']) * 1048576 : 5242880; // Default 5MB
        $uploaded_files = array();
        
        // Handle multiple files
        if (is_array($_FILES[$field_id]['name'])) {
            $files = $_FILES[$field_id];
            foreach ($files['name'] as $key => $value) {
                if (empty($files['name'][$key])) continue;
                
                // Size check
                if ($files['size'][$key] > $max_size) {
                    return new WP_Error('file_too_large', 'File size exceeds limit.');
                }
                
                $file = array(
                    'name' => $files['name'][$key],
                    'type' => $files['type'][$key],
                    'tmp_name' => $files['tmp_name'][$key],
                    'error' => $files['error'][$key],
                    'size' => $files['size'][$key]
                );
                
                $upload = wp_handle_upload($file, array('test_form' => false));
                if (isset($upload['error'])) {
                    return new WP_Error('upload_failed', $upload['error']);
                }
                
                $uploaded_files[] = $upload['url'];
            }
        } else {
            // Single file
            if ($_FILES[$field_id]['size'] > $max_size) {
                return new WP_Error('file_too_large', 'File size exceeds limit.');
            }
            
            $upload = wp_handle_upload($_FILES[$field_id], array('test_form' => false));
            if (isset($upload['error'])) {
                return new WP_Error('upload_failed', $upload['error']);
            }
            
            $uploaded_files[] = $upload['url'];
        }
        
        return $uploaded_files;
    }
    
    /**
     * Send admin email notification
     */
    private function send_admin_notification($form_id, $data, $settings) {
        $form = get_post($form_id);
        $recipient = !empty($settings['recipient']) ? $settings['recipient'] : get_option('admin_email');
        $subject = !empty($settings['subject']) ? $settings['subject'] : 'New form submission';

        // Clean, minimal, modern email template
        $message = '
        <div style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif; max-width: 600px; margin: 0 auto; background-color: #ffffff;">
            <!-- Header -->
            <div style="background-color: #ffffff; padding: 32px 32px 24px; border-bottom: 2px solid #000000;">
                <h1 style="color: #000000; margin: 0; font-size: 22px; font-weight: 700; letter-spacing: -0.5px;">New Form Submission</h1>
                <p style="color: #6b7280; margin: 6px 0 0 0; font-size: 14px; font-weight: 500;">' . esc_html($form->post_title) . '</p>
            </div>

            <!-- Content -->
            <div style="padding: 0;">';

        foreach ($data as $label => $value) {
            if (is_array($value)) {
                $value = implode(', ', $value);
            }

            $message .= '
                <div style="padding: 24px 32px; border-bottom: 1px solid #e5e7eb;">
                    <div style="color: #6b7280; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 8px;">' . esc_html($label) . '</div>
                    <div style="color: #000000; font-size: 15px; line-height: 1.6; font-weight: 400;">' . nl2br(esc_html($value)) . '</div>
                </div>';
        }

        $message .= '
            </div>

            <!-- Footer -->
            <div style="padding: 24px 32px; background-color: #fafafa; border-top: 1px solid #e5e7eb;">
                <div style="text-align: center; margin-bottom: 16px;">
                    <p style="margin: 0; color: #6b7280; font-size: 12px;">
                        Submitted on ' . current_time('F j, Y') . ' at ' . current_time('g:i a') . '
                    </p>
                </div>
                <div style="text-align: center; padding-top: 16px; border-top: 1px solid #e5e7eb;">
                    <a href="https://wpswitchboard.com" style="display: inline-flex; align-items: center; gap: 6px; text-decoration: none; color: #9ca3af; font-size: 11px; font-weight: 500;">
                                                <span>Powered by WP Switchboard</span>
                    </a>
                </div>
            </div>
        </div>';

        // Let WordPress handle From address (allows SMTP plugins to override via wp_mail_from filter)
        $headers = array(
            'Content-Type: text/html; charset=UTF-8'
        );

        // Set reply-to if user email exists
        foreach ($data as $label => $value) {
            if (is_email($value)) {
                $headers[] = 'Reply-To: ' . $value;
                break;
            }
        }

        // Send email and log if it fails
        $sent = wp_mail($recipient, $subject, $message, $headers);

        if (!$sent) {
            error_log('Simple Forms: Failed to send admin notification for form ID ' . $form_id);
        }

        return $sent;
    }
    
    /**
     * Send auto-reply email
     */
    private function send_autoreply($user_email, $settings) {
        $subject = !empty($settings['autoreply_subject']) ? $settings['autoreply_subject'] : 'Thank you for your submission';
        $message = !empty($settings['autoreply_message']) ? $settings['autoreply_message'] : 'We have received your submission and will get back to you soon.';

        // Let WordPress handle From address (allows SMTP plugins to override via wp_mail_from filter)
        $headers = array();

        // Send email and log if it fails
        $sent = wp_mail($user_email, $subject, $message, $headers);

        if (!$sent) {
            error_log('Simple Forms: Failed to send auto-reply to ' . $user_email);
        }

        return $sent;
    }
    
    /**
     * Get user IP address
     */
    private function get_user_ip() {
        // SECURITY NOTE: HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR can be spoofed
        // Only use them if you trust your proxy/CDN setup
        // For maximum security, use REMOTE_ADDR only

        // SECURITY FIX: Add wp_unslash() and validate IP format
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = sanitize_text_field(wp_unslash($_SERVER['HTTP_CLIENT_IP']));
            // Validate IP format
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                return $ip;
            }
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            // Take only the first IP from the list (original client IP)
            $ip_list = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR']));
            $ips = explode(',', $ip_list);
            $ip = trim($ips[0]);
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                return $ip;
            }
        }

        // Fallback to REMOTE_ADDR (most reliable)
        if (!empty($_SERVER['REMOTE_ADDR'])) {
            $ip = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                return $ip;
            }
        }

        return '0.0.0.0'; // Unknown IP
    }
    
    /**
     * Export entries to CSV
     */
    private function export_entries_csv() {
        global $wpdb;
        
        // Get filters
        $filter_form = isset($_GET['form_filter']) ? intval($_GET['form_filter']) : 0;
        $filter_status = isset($_GET['status_filter']) ? sanitize_text_field($_GET['status_filter']) : '';
        
        // Build WHERE clause
        $where_conditions = array();
        if ($filter_form) {
            $where_conditions[] = $wpdb->prepare("form_id = %d", $filter_form);
        }
        if ($filter_status) {
            $where_conditions[] = $wpdb->prepare("status = %s", $filter_status);
        }
        $where = !empty($where_conditions) ? ' WHERE ' . implode(' AND ', $where_conditions) : '';
        
        // Get all entries (no limit for export)
        $entries = $wpdb->get_results("SELECT * FROM {$this->table_name}{$where} ORDER BY date_created DESC");
        
        if (empty($entries)) {
            wp_die(esc_html__('No entries to export.', 'wpswitchboard'));
        }
        
        // Prepare filename
        $filename = 'form-entries-' . date('Y-m-d-His') . '.csv';
        
        // Set headers for download
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=' . $filename);
        header('Pragma: no-cache');
        header('Expires: 0');
        
        // Open output stream
        $output = fopen('php://output', 'w');
        
        // Collect all unique field names from all entries
        $all_fields = array();
        foreach ($entries as $entry) {
            // Use 'payload' column, not 'data'
            $data = !empty($entry->payload) ? json_decode($entry->payload, true) : array();
            if (is_array($data)) {
                $all_fields = array_merge($all_fields, array_keys($data));
            }
        }
        $all_fields = array_unique($all_fields);
        
        // Write CSV header
        $header = array_merge(
            array('Entry ID', 'Form', 'Status', 'Date', 'IP Address', 'User Name', 'User Email'),
            $all_fields
        );
        fputcsv($output, $header);
        
        // Write data rows
        foreach ($entries as $entry) {
            $form = get_post($entry->form_id);
            $form_title = $form ? $form->post_title : 'Form #' . $entry->form_id;
            $data = !empty($entry->payload) ? json_decode($entry->payload, true) : array();
            
            $row = array(
                $entry->id,
                $form_title,
                ucfirst($entry->status),
                $entry->date_created,
                !empty($entry->user_ip) ? $entry->user_ip : '',
                !empty($entry->user_name) ? $entry->user_name : '',
                !empty($entry->user_email) ? $entry->user_email : ''
            );
            
            // Add field data in the same order as headers
            foreach ($all_fields as $field) {
                if (isset($data[$field])) {
                    $value = $data[$field];
                    // Handle arrays (checkboxes, etc.)
                    if (is_array($value)) {
                        $value = implode(', ', $value);
                    }
                    $row[] = $value;
                } else {
                    $row[] = '';
                }
            }
            
            fputcsv($output, $row);
        }
        
        fclose($output);
    }
    
    /**
     * Render entries page
     */
    public function render_entries_page() {
        global $wpdb;
        
        // Handle entry deletion
        if (isset($_GET['delete']) && check_admin_referer('delete_entry_' . intval($_GET['delete']))) {
            $wpdb->delete($this->table_name, array('id' => intval($_GET['delete'])), array('%d'));
            echo '<div class="notice notice-success"><p>Entry deleted.</p></div>';
        }
        
        // Handle mark as read
        if (isset($_GET['mark_read']) && check_admin_referer('mark_read_' . intval($_GET['mark_read']))) {
            $wpdb->update($this->table_name, array('status' => 'read'), array('id' => intval($_GET['mark_read'])), array('%s'), array('%d'));
            echo '<div class="notice notice-success"><p>Entry marked as read.</p></div>';
        }
        
        // Get filter
        $filter_form = isset($_GET['form_filter']) ? intval($_GET['form_filter']) : 0;
        
        // Get entries
        $where = $filter_form ? $wpdb->prepare(" WHERE form_id = %d", $filter_form) : '';
        $entries = $wpdb->get_results("SELECT * FROM {$this->table_name}{$where} ORDER BY date_created DESC LIMIT 100");
        
        // Get all forms for filter
        $forms = get_posts(array('post_type' => 'switchboard_form', 'posts_per_page' => -1));
        
        ?>
        <div class="wrap">
            <h1>Form Entries</h1>
            
            <div style="margin: 20px 0;">
                <label>Filter by form: </label>
                <select onchange="window.location.href='?page=switchboard-form-entries&form_filter=' + this.value">
                    <option value="0">All Forms</option>
                    <?php foreach ($forms as $form): ?>
                        <option value="<?php echo $form->ID; ?>" <?php selected($filter_form, $form->ID); ?>>
                            <?php echo esc_html($form->post_title); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <?php if (empty($entries)): ?>
                <p>No entries found.</p>
            <?php else: ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th width="40">ID</th>
                            <th>Form</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($entries as $entry): 
                            $form = get_post($entry->form_id);
                            $data = json_decode($entry->payload, true);
                        ?>
                            <tr class="<?php echo $entry->status === 'unread' ? 'status-unread' : ''; ?>">
                                <td><?php echo $entry->id; ?></td>
                                <td><?php echo $form ? esc_html($form->post_title) : 'Unknown'; ?></td>
                                <td><?php echo esc_html($entry->user_name); ?></td>
                                <td><?php echo esc_html($entry->user_email); ?></td>
                                <td><?php echo date('M j, Y g:i a', strtotime($entry->date_created)); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo esc_attr($entry->status); ?>">
                                        <?php echo esc_html($entry->status); ?>
                                    </span>
                                </td>
                                <td>
                                    <button type="button" class="button button-small view-entry" data-entry-id="<?php echo $entry->id; ?>">View</button>
                                    <?php if ($entry->status === 'unread'): ?>
                                        <a href="<?php echo wp_nonce_url('?page=switchboard-form-entries&mark_read=' . $entry->id, 'mark_read_' . $entry->id); ?>" class="button button-small">Mark Read</a>
                                    <?php endif; ?>
                                    <a href="<?php echo wp_nonce_url('?page=switchboard-form-entries&delete=' . $entry->id, 'delete_entry_' . $entry->id); ?>" class="button button-small" onclick="return confirm('Are you sure?')">Delete</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        
        <!-- Entry View Modal -->
        <div id="entry-modal" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.7); z-index:100000;">
            <div style="background:#fff; max-width:800px; margin:50px auto; padding:30px; border-radius:5px; max-height:80vh; overflow-y:auto;">
                <button onclick="document.getElementById('entry-modal').style.display='none'" style="float:right; font-size:24px; border:none; background:none; cursor:pointer;">&times;</button>
                <div id="entry-modal-content"></div>
            </div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            $('.view-entry').on('click', function(e) {
                e.preventDefault();
                var entryId = $(this).data('entry-id');
                
                $.post(ajaxurl, {
                    action: 'view_form_entry',
                    entry_id: entryId,
                    nonce: switchboardFormsData.nonce
                }, function(response) {
                    if (response.success) {
                        $('#entry-modal-content').html(response.data.html);
                        $('#entry-modal').show();
                    }
                });
            });
        });
        </script>
        
        <style>
        .status-unread { background-color: #f0f8ff; }
        .status-badge { 
            padding: 3px 8px; 
            border-radius: 3px; 
            font-size: 11px; 
            text-transform: uppercase;
        }
        .status-unread { background: #fff3cd; color: #856404; }
        .status-read { background: #d4edda; color: #155724; }
        </style>
        <?php
    }
    
    /**
     * Admin CSS
     */
    private function get_admin_css() {
        return "
        #form-builder-app {
            display: flex;
            gap: 24px;
            margin-top: 20px;
        }
        .field-palette {
            flex: 0 0 300px;
            background: #fafbfc;
            padding: 20px;
            border-radius: 8px;
            border: 2px dashed #e1e4e8;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        /* Remove background when inside custom layout */
        .sb-module-form-field-palette-wrapper .field-palette {
            background: transparent;
            border: none;
            box-shadow: none;
            padding: 0;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .field-palette h4 {
            margin: 0;
            font-size: 13px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #6b7280;
            width: 100%;
            margin-bottom: 12px;
        }
        /* Use sb-module-button styling for add-field-btn buttons */
        .field-palette .add-field-btn.sb-mp-quick-add-btn {
            margin: 0;
        }
        .fields-container {
            display: flex;
            flex-direction: column;
            flex: 1;
            min-height: 400px;
            background: #fafbfc;
            border: 2px dashed #e1e4e8;
            border-radius: 8px;
            padding: 12px;
            gap: 8px;
        }
        /* Remove background when inside custom layout */
        .sb-module-form-fields-wrapper .fields-container {
            background: transparent;
            border: none;
            box-shadow: none;
        }
        .fields-container:empty {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 400px;
            padding: 60px 20px;
            text-align: center;
            position: relative;
        }
        .fields-container:empty::before {
            content: '';
            font-size: 48px;
            opacity: 0.4;
            margin-bottom: 12px;
            display: block;
        }
        .fields-container:empty::after {
            content: 'No fields yet. Click a field type on the left to add it here.';
            display: block;
            color: #6b7280;
            font-size: 14px;
            line-height: 1.5;
            max-width: 300px;
        }
        .form-field-item {
            background: #fff;
            border: 1px solid #e5e7eb;
            padding: 8px 12px;
            margin-bottom: 6px;
            border-radius: 6px;
            transition: all 0.2s ease;
            box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            overflow: hidden;
        }
        .form-field-item:hover {
            border-color: var(--primary-300);
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1);
        }
        .field-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0;
            cursor: pointer;
            user-select: none;
            padding: 6px 12px;
            border-radius: 6px;
            transition: background-color 0.2s ease;
        }
        /* Highlighted header when field is opened */
        .form-field-item:not(.collapsed) .field-header {
            background: var(--primary-50);
            border: 1px solid var(--primary-200);
        }
        /* Regular header when field is collapsed */
        .form-field-item.collapsed .field-header {
            background: transparent;
        }
        .field-header strong {
            font-size: 14px;
            font-weight: 600;
            color: #1f2937;
            flex: 1;
        }
        .field-header strong:after {
            content: '▼';
            font-size: 10px;
            margin-left: 8px;
            color: #9ca3af;
            transition: transform 0.2s ease;
        }
        .form-field-item.collapsed .field-header strong:after {
            transform: rotate(-90deg);
        }
        .field-actions {
            display: flex;
            gap: 6px;
            position: relative;
            z-index: 10;
        }
        .field-actions button {
            padding: 6px 12px;
            border: 1px solid #e5e7eb;
            border-radius: 5px;
            background: #ffffff;
            color: #6b7280;
            font-size: 12px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.15s ease;
        }
        .field-actions button:hover {
            background: #f9fafb;
            border-color: #3b82f6;
            color: #3b82f6;
            z-index: 20;
        }
        .field-actions .move-up-field,
        .field-actions .move-down-field {
            padding: 4px 10px;
            font-size: 16px;
            line-height: 1;
            font-weight: bold;
        }
        .field-actions .move-up-field:hover,
        .field-actions .move-down-field:hover {
            background: #eff6ff;
            border-color: #3b82f6;
            color: #3b82f6;
        }
        .field-actions .delete-field:hover {
            background: #fef2f2;
            border-color: #ef4444;
            color: #ef4444;
        }
        .field-config {
            display: none;
            margin-top: 0;
            padding-top: 12px;
            padding-left: 8px;
            padding-right: 8px;
        }
        .field-config.active {
            display: block;
        }
        .field-config label {
            display: block;
            margin-bottom: 6px;
            font-weight: 600;
            font-size: 13px;
            color: #374151;
        }
        .field-config input[type='text'],
        .field-config input[type='number'],
        .field-config textarea,
        .field-config select {
            width: 100%;
            margin-bottom: 14px;
            padding: 8px 12px;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.15s ease;
            background: #ffffff;
        }
        .field-config input:focus,
        .field-config textarea:focus,
        .field-config select:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59,130,246,0.1);
        }
        .field-config textarea {
            height: 80px;
            resize: vertical;
        }
        .field-config input[type='checkbox'] {
            margin-right: 6px;
        }

        /* Entry Modal Styles */
        .entry-modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 100000;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .entry-modal-overlay.show {
            display: flex;
        }
        .entry-modal-container {
            background: #fff;
            max-width: 800px;
            width: 100%;
            max-height: 90vh;
            border-radius: 12px;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }
        .entry-modal-header {
            padding: 24px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #f9fafb;
        }
        .entry-modal-header h2 {
            margin: 0;
            font-size: 20px;
            font-weight: 600;
            color: #1e293b;
        }
        .entry-modal-close {
            background: none;
            border: none;
            font-size: 32px;
            line-height: 1;
            color: #94a3b8;
            cursor: pointer;
            padding: 0;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 6px;
            transition: all 0.15s ease;
        }
        .entry-modal-close:hover {
            background: #e5e7eb;
            color: #475569;
        }
        .entry-modal-content {
            padding: 24px;
            overflow-y: auto;
            flex: 1;
        }
        .entry-modal-loading {
            text-align: center;
            padding: 40px 20px;
            color: #94a3b8;
            font-size: 14px;
        }

        /* Unread Entry Row */
        tr.entry-unread {
            background: #fef3c7;
        }
        tr.entry-unread:hover {
            background: #fde68a;
        }

        /* Disable hover on empty state row but allow button clicks */
        tr:has(.sb-module-empty) {
            pointer-events: none;
        }
        tr:has(.sb-module-empty) .sb-module-empty {
            pointer-events: auto;
        }
        tr:has(.sb-module-empty):hover {
            background: transparent !important;
        }

        /* ===================================
           Field Config Grid Layout (2-3 columns)
           =================================== */
        .sf-field-config-grid {
            display: grid;
            gap: 16px;
            margin-bottom: 16px;
        }
        .sf-field-config-2col {
            grid-template-columns: 1fr 1fr;
        }
        .sf-field-config-3col {
            grid-template-columns: 1fr 1fr 1fr;
        }
        .sf-field-config-item {
            display: flex;
            flex-direction: column;
        }
        .sf-field-config-item label {
            margin-bottom: 6px;
            font-size: 13px;
            font-weight: 600;
            color: #374151;
        }
        .sf-field-config-item input,
        .sf-field-config-item textarea,
        .sf-field-config-item select {
            margin-bottom: 0 !important;
        }
        .sf-field-config-full {
            grid-column: 1 / -1;
        }
        .sf-field-config-checkbox .sb-module-checkbox-item {
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 500;
            cursor: pointer;
            margin-bottom: 0;
            padding: 10px 14px;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            width: 100%;
        }
        .sf-field-config-checkbox .sb-module-checkbox-item:hover {
            background: #f1f5f9;
            border-color: var(--primary-300);
        }
        .sf-field-config-checkbox .sb-module-checkbox-item input[type='checkbox'] {
            width: 18px;
            height: 18px;
            margin: 0;
            accent-color: var(--primary-500);
        }
        .sf-field-config-checkbox .sb-module-checkbox-item span {
            font-size: 14px;
            color: #374151;
        }

        /* Required field indicator (matching OPB) */
        .sf-required {
            color: #ef4444;
            font-weight: 700;
        }

        /* Field type badge */
        .field-type-badge {
            display: inline-flex;
            align-items: center;
            background: #f1f5f9;
            color: #64748b;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            margin-right: 10px;
        }
        .field-type-badge.field-type-group {
            background: var(--primary-500);
            color: white;
        }

        /* Field header content */
        .field-header-content {
            display: flex;
            align-items: center;
            flex: 1;
        }
        .field-header-content strong {
            margin-right: 0;
        }
        .field-header-content strong:after {
            display: none;
        }

        /* Required field indicator - matching OPB style */
        .field-required-indicator {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: #ef4444;
            font-weight: 700;
            font-size: 16px;
            line-height: 1;
            margin-left: 6px;
        }

        /* Updated field action buttons */
        .sf-field-action-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 32px;
            height: 32px;
            padding: 0 !important;
            background: transparent !important;
            border: 1px solid #e5e7eb !important;
            border-radius: 6px !important;
            cursor: pointer;
            transition: all 0.15s ease;
        }
        .sf-field-action-btn:hover {
            background: var(--primary-50) !important;
            border-color: var(--primary-300) !important;
            color: var(--primary-600);
        }
        .sf-field-action-btn svg {
            width: 16px;
            height: 16px;
            color: #64748b;
        }
        .sf-field-action-btn:hover svg {
            color: var(--primary-600);
        }
        .sf-field-action-btn-delete:hover {
            background: #fef2f2 !important;
            border-color: #fecaca !important;
        }
        .sf-field-action-btn-delete:hover svg {
            color: #ef4444;
        }

        /* Group/Section field styling */
        .form-field-group {
            background: linear-gradient(135deg, var(--primary-50) 0%, white 100%);
            border: 2px dashed var(--primary-300) !important;
            border-radius: 10px;
        }
        .form-field-group:hover {
            background: linear-gradient(135deg, var(--primary-100) 0%, var(--primary-50) 100%);
            border-color: var(--primary-500) !important;
            border-style: solid !important;
        }
        .form-field-group .field-header {
            padding: 10px 14px;
        }
        .form-field-group .field-header-content strong {
            color: var(--primary-700);
        }

        /* Separator field styling */
        .form-field-separator {
            background: #f8fafc;
            border: 1px dashed #cbd5e1 !important;
        }
        .form-field-separator .field-header-content strong {
            color: #94a3b8;
            font-weight: 500;
        }

        @media (max-width: 782px) {
            .sf-field-config-2col,
            .sf-field-config-3col {
                grid-template-columns: 1fr;
            }
        }
        ";
    }
    
    /**
     * Admin JS
     */
    private function get_admin_js() {
        return "
        // Shortcode copy function
        function copyShortcode(input) {
            input.select();
            input.setSelectionRange(0, 99999);

            try {
                navigator.clipboard.writeText(input.value).then(function() {
                    showCopiedMessage(input);
                }).catch(function() {
                    document.execCommand('copy');
                    showCopiedMessage(input);
                });
            } catch (err) {
                document.execCommand('copy');
                showCopiedMessage(input);
            }
        }

        function showCopiedMessage(input) {
            var message = input.parentElement.querySelector('.sb-module-shortcode-copied');
            if (message) {
                message.classList.add('show');
                setTimeout(function() {
                    message.classList.remove('show');
                }, 2000);
            }
        }

        jQuery(document).ready(function($) {
            var fieldCounter = 0;
            var formFields = [];

            // Load existing fields
            var existingFields = $('#form-fields-data').val();
            if (existingFields) {
                try {
                    formFields = JSON.parse(existingFields);
                    formFields.forEach(function(field) {
                        renderField(field);
                        if (field.id >= fieldCounter) fieldCounter = field.id + 1;
                    });
                } catch(e) {}
            }
            
            // Add field buttons
            $('.add-field-btn').on('click', function() {
                var type = $(this).data('type');

                var label = type.charAt(0).toUpperCase() + type.slice(1) + ' Field';
                if (type === 'separator') {
                    label = '';
                } else if (type === 'group') {
                    label = 'Section Title';
                }

                var field = {
                    id: fieldCounter++,
                    type: type,
                    label: label,
                    placeholder: '',
                    required: false,
                    help: '',
                    options: '',
                    description: ''
                };
                formFields.push(field);
                renderField(field);
                updateFieldsData();
            });
            
            // Render field
            function renderField(field) {
                // Check if it's a layout field (separator or group)
                var isLayoutField = (field.type === 'separator' || field.type === 'group');
                var fieldClass = isLayoutField ? 'form-field-item form-field-layout collapsed' : 'form-field-item collapsed';
                if (field.type === 'group') fieldClass += ' form-field-group';
                if (field.type === 'separator') fieldClass += ' form-field-separator';

                var html = '<div class=\"' + fieldClass + '\" data-id=\"' + field.id + '\">';
                html += '<div class=\"field-header\">';

                // Field title and type badge
                var typeLabel = field.type.charAt(0).toUpperCase() + field.type.slice(1);
                if (field.type === 'separator') {
                    html += '<div class=\"field-header-content\"><strong>— Separator —</strong></div>';
                } else if (field.type === 'group') {
                    html += '<div class=\"field-header-content\"><span class=\"field-type-badge field-type-group\">Section</span> <strong>' + field.label + '</strong>';
                    if (field.required) html += ' <span class=\"field-required-indicator\">*</span>';
                    html += '</div>';
                } else {
                    html += '<div class=\"field-header-content\"><strong>' + field.label + '</strong> <span class=\"field-type-badge\">' + typeLabel + '</span>';
                    if (field.required) html += ' <span class=\"field-required-indicator\">*</span>';
                    html += '</div>';
                }

                html += '<div class=\"field-actions\">';
                html += '<button type=\"button\" class=\"button sf-field-action-btn move-up-field\" title=\"Move Up\"><svg fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\" width=\"16\" height=\"16\"><path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M5 15l7-7 7 7\"/></svg></button>';
                html += '<button type=\"button\" class=\"button sf-field-action-btn move-down-field\" title=\"Move Down\"><svg fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\" width=\"16\" height=\"16\"><path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M19 9l-7 7-7-7\"/></svg></button>';
                html += '<button type=\"button\" class=\"button sf-field-action-btn sf-field-action-btn-delete delete-field\" title=\"Delete\"><svg fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\" width=\"16\" height=\"16\"><path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16\"/></svg></button>';
                html += '</div>';
                html += '</div>';
                html += '<div class=\"field-config\">';

                // Separator field - no config needed
                if (field.type === 'separator') {
                    html += '<p style=\"color: #64748b; font-size: 13px; margin: 0;\">This adds a horizontal line to visually separate form sections.</p>';
                }
                // Group/Section field
                else if (field.type === 'group') {
                    html += '<div class=\"sf-field-config-grid sf-field-config-2col\">';
                    html += '<div class=\"sf-field-config-item\"><label>Section Title</label>';
                    html += '<input type=\"text\" class=\"field-label\" value=\"' + field.label + '\" placeholder=\"e.g., Personal Information\"></div>';
                    html += '<div class=\"sf-field-config-item\"><label>Description</label>';
                    html += '<input type=\"text\" class=\"field-description\" value=\"' + (field.description || '') + '\" placeholder=\"Optional description\"></div>';
                    html += '</div>';
                }
                // Regular fields
                else {
                    // Row 1: Label + Placeholder (for most fields)
                    html += '<div class=\"sf-field-config-grid sf-field-config-2col\">';
                    html += '<div class=\"sf-field-config-item\"><label>Label <span class=\"sf-required\">*</span></label>';
                    html += '<input type=\"text\" class=\"field-label\" value=\"' + field.label + '\"></div>';

                    if (field.type !== 'hidden') {
                        html += '<div class=\"sf-field-config-item\"><label>Placeholder</label>';
                        html += '<input type=\"text\" class=\"field-placeholder\" value=\"' + (field.placeholder || '') + '\"></div>';
                    } else {
                        html += '<div class=\"sf-field-config-item\"><label>Default Value</label>';
                        html += '<input type=\"text\" class=\"field-default\" value=\"' + (field.default_value || '') + '\"></div>';
                    }
                    html += '</div>';

                    // Options for select/radio/checkbox
                    if (field.type === 'select' || field.type === 'radio' || field.type === 'checkbox') {
                        html += '<div class=\"sf-field-config-item sf-field-config-full\"><label>Options (one per line) <span class=\"sf-required\">*</span></label>';
                        html += '<textarea class=\"field-options\" rows=\"4\">' + (field.options || '') + '</textarea></div>';
                    }

                    // Number field: min/max
                    if (field.type === 'number') {
                        html += '<div class=\"sf-field-config-grid sf-field-config-2col\">';
                        html += '<div class=\"sf-field-config-item\"><label>Min Value</label>';
                        html += '<input type=\"number\" class=\"field-min\" value=\"' + (field.min || '') + '\"></div>';
                        html += '<div class=\"sf-field-config-item\"><label>Max Value</label>';
                        html += '<input type=\"number\" class=\"field-max\" value=\"' + (field.max || '') + '\"></div>';
                        html += '</div>';
                    }

                    // File field: types, size, multiple
                    if (field.type === 'file') {
                        html += '<div class=\"sf-field-config-grid sf-field-config-3col\">';
                        html += '<div class=\"sf-field-config-item\"><label>Allowed Types</label>';
                        html += '<input type=\"text\" class=\"field-file-types\" value=\"' + (field.file_types || 'image/*,.pdf') + '\"></div>';
                        html += '<div class=\"sf-field-config-item\"><label>Max Size (MB)</label>';
                        html += '<input type=\"number\" class=\"field-max-size\" value=\"' + (field.max_size || '5') + '\"></div>';
                        html += '<div class=\"sf-field-config-item sf-field-config-checkbox\"><label class=\"sb-module-checkbox-item\"><input type=\"checkbox\" class=\"field-multiple\" ' + (field.multiple ? 'checked' : '') + '><span>Allow Multiple</span></label></div>';
                        html += '</div>';
                    }

                    // Help text + Required (for non-hidden fields)
                    if (field.type !== 'hidden') {
                        html += '<div class=\"sf-field-config-grid sf-field-config-2col\">';
                        html += '<div class=\"sf-field-config-item\"><label>Help Text</label>';
                        html += '<input type=\"text\" class=\"field-help\" value=\"' + (field.help || '') + '\" placeholder=\"Appears below the field\"></div>';
                        html += '<div class=\"sf-field-config-item sf-field-config-checkbox\"><label>Validation</label>';
                        html += '<label class=\"sb-module-checkbox-item\"><input type=\"checkbox\" class=\"field-required\" ' + (field.required ? 'checked' : '') + '><span>Required Field</span></label></div>';
                        html += '</div>';
                    } else {
                        html += '<div class=\"sf-field-config-item sf-field-config-checkbox\"><label>Validation</label>';
                        html += '<label class=\"sb-module-checkbox-item\"><input type=\"checkbox\" class=\"field-required\" ' + (field.required ? 'checked' : '') + '><span>Required Field</span></label></div>';
                    }
                }

                html += '</div>';
                html += '</div>';

                $('#fields-container').append(html);
            }
            
            // Toggle field config on header click
            $(document).on('click', '.field-header', function(e) {
                // Don't toggle if clicking action buttons
                if ($(e.target).closest('.field-actions').length) {
                    return;
                }
                var \$item = $(this).closest('.form-field-item');
                \$item.toggleClass('collapsed');
                \$item.find('.field-config').toggleClass('active');
            });
            
            // Delete field
            $(document).on('click', '.delete-field', function(e) {
                e.stopPropagation();
                if (confirm('Delete this field?')) {
                    var id = $(this).closest('.form-field-item').data('id');
                    formFields = formFields.filter(function(f) { return f.id !== id; });
                    $(this).closest('.form-field-item').remove();
                    updateFieldsData();
                }
            });
            
            // Move field up
            $(document).on('click', '.move-up-field', function(e) {
                e.stopPropagation();
                var \$item = $(this).closest('.form-field-item');
                var \$prev = \$item.prev('.form-field-item');
                if (\$prev.length) {
                    \$item.insertBefore(\$prev);
                    reorderFieldsFromDOM();
                }
            });
            
            // Move field down
            $(document).on('click', '.move-down-field', function(e) {
                e.stopPropagation();
                var \$item = $(this).closest('.form-field-item');
                var \$next = \$item.next('.form-field-item');
                if (\$next.length) {
                    \$item.insertAfter(\$next);
                    reorderFieldsFromDOM();
                }
            });
            
            // Reorder fields array based on DOM order
            function reorderFieldsFromDOM() {
                var newOrder = [];
                $('#fields-container .form-field-item').each(function() {
                    var id = $(this).data('id');
                    var field = formFields.find(function(f) { return f.id === id; });
                    if (field) {
                        newOrder.push(field);
                    }
                });
                formFields = newOrder;
                updateFieldsData();
            }
            
            // Update field data on input change
            $(document).on('input change', '.field-config input, .field-config textarea', function() {
                var \$item = $(this).closest('.form-field-item');
                var id = \$item.data('id');
                var field = formFields.find(function(f) { return f.id === id; });

                if (field) {
                    field.label = \$item.find('.field-label').val();
                    field.placeholder = \$item.find('.field-placeholder').val();
                    field.help = \$item.find('.field-help').val();
                    field.required = \$item.find('.field-required').is(':checked');
                    field.options = \$item.find('.field-options').val();
                    field.min = \$item.find('.field-min').val();
                    field.max = \$item.find('.field-max').val();
                    field.file_types = \$item.find('.field-file-types').val();
                    field.max_size = \$item.find('.field-max-size').val();
                    field.multiple = \$item.find('.field-multiple').is(':checked');
                    field.description = \$item.find('.field-description').val();
                    field.default_value = \$item.find('.field-default').val();

                    // Update header display
                    var headerContent = \$item.find('.field-header-content');
                    if (field.type === 'separator') {
                        // No change for separator
                    } else if (field.type === 'group') {
                        headerContent.find('strong').text(field.label);
                    } else {
                        headerContent.find('strong').text(field.label);
                    }
                    updateFieldsData();
                }
            });
            
            // Update hidden field with JSON
            function updateFieldsData() {
                $('#form-fields-data').val(JSON.stringify(formFields));
            }
            
            // Auto-reply toggle
            $('input[name=\"form_settings[enable_autoreply]\"]').on('change', function() {
                $('#autoreply-settings').toggle(this.checked);
            });
        });
        ";
    }
    
    /**
     * Frontend CSS
     */
    private function get_frontend_css() {
        return "
        .simple-form-wrapper {
            max-width: 600px;
            margin: 0 auto;
        }
        .simple-form .form-field {
            margin-bottom: 20px;
        }
        .simple-form label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
        }
        .simple-form input[type='text'],
        .simple-form input[type='email'],
        .simple-form input[type='url'],
        .simple-form input[type='tel'],
        .simple-form input[type='number'],
        .simple-form input[type='date'],
        .simple-form select,
        .simple-form textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .simple-form textarea {
            resize: vertical;
        }
        .simple-form .required {
            color: #d00;
        }
        .simple-form .radio-group,
        .simple-form .checkbox-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .simple-form .radio-label,
        .simple-form .checkbox-label {
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: normal;
        }
        .simple-form .simple-form-submit {
            background: #0073aa;
            color: #fff;
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
        }
        .simple-form .simple-form-submit:hover {
            background: #005177;
        }
        .simple-form .form-message {
            padding: 15px 20px;
            border-radius: 6px;
            margin-bottom: 20px;
            font-size: 15px;
            line-height: 1.5;
            display: block;
        }
        .simple-form .form-message.success {
            background: #d1f2eb;
            color: #0d5e47;
            border: 2px solid #48c9a9;
            font-weight: 500;
        }
        .simple-form .form-message.success:before {
            content: \"\\2713 \";
            font-size: 18px;
            margin-right: 5px;
        }
        .simple-form .form-message.error {
            background: #ffe6e6;
            color: #c41e3a;
            border: 2px solid #ff6b6b;
            font-weight: 500;
        }
        .simple-form .form-message.error:before {
            content: \"\\2715 \";
            font-size: 18px;
            margin-right: 5px;
        }
        .simple-form small {
            display: block;
            margin-top: 5px;
            color: #666;
            font-size: 12px;
        }
        /* Separator/Divider */
        .simple-form .field-type-separator {
            margin: 30px 0;
        }
        .simple-form .simple-form-separator {
            border: none;
            border-top: 1px solid #e5e7eb;
            margin: 0;
        }
        /* Group/Section */
        .simple-form .field-type-group {
            margin-top: 30px;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e5e7eb;
        }
        .simple-form .field-type-group:first-child {
            margin-top: 0;
        }
        .simple-form .simple-form-group-title {
            font-size: 20px;
            font-weight: 700;
            color: #1e293b;
            margin: 0 0 8px 0;
        }
        .simple-form .simple-form-group-description {
            font-size: 14px;
            color: #64748b;
            margin: 0;
            line-height: 1.5;
        }
        ";
    }

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

// AJAX handler for viewing entry
add_action('wp_ajax_view_form_entry', function() {
    check_ajax_referer('view_form_entry', 'nonce');

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

    global $wpdb;
    $table_name = $wpdb->prefix . 'switchboard_form_entries';

    $entry_id = intval($_POST['entry_id']);
    $entry = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table_name} WHERE id = %d", $entry_id));
    
    if (!$entry) {
        wp_send_json_error();
    }
    
    // Mark as read
    $wpdb->update(
        $table_name,
        array('status' => 'read'),
        array('id' => $entry_id),
        array('%s'),
        array('%d')
    );
    
    $form = get_post($entry->form_id);
    $data = json_decode($entry->payload, true);
    
    // Build styled HTML
    $html = '<div class="entry-details-container">';
    
    // Meta information
    $html .= '<div class="entry-meta-grid">';
    $html .= '<div class="entry-meta-item">';
    $html .= '<div class="entry-meta-label">Entry ID</div>';
    $html .= '<div class="entry-meta-value">#' . $entry->id . '</div>';
    $html .= '</div>';
    
    $html .= '<div class="entry-meta-item">';
    $html .= '<div class="entry-meta-label">Form</div>';
    $html .= '<div class="entry-meta-value">' . esc_html($form->post_title) . '</div>';
    $html .= '</div>';
    
    $html .= '<div class="entry-meta-item">';
    $html .= '<div class="entry-meta-label">Date</div>';
    $html .= '<div class="entry-meta-value">' . date('F j, Y \a\t g:i A', strtotime($entry->date_created)) . '</div>';
    $html .= '</div>';
    
    $html .= '<div class="entry-meta-item">';
    $html .= '<div class="entry-meta-label">IP Address</div>';
    $html .= '<div class="entry-meta-value">' . esc_html($entry->user_ip) . '</div>';
    $html .= '</div>';
    $html .= '</div>';
    
    // Form data
    $html .= '<div class="entry-data-section">';
    $html .= '<h3 style="margin: 30px 0 16px; font-size: 16px; font-weight: 600; color: #1f2937;">Form Data</h3>';
    $html .= '<div class="entry-data-table">';
    
    foreach ($data as $label => $value) {
        if (is_array($value)) {
            $value = implode(', ', $value);
        }
        $html .= '<div class="entry-data-row">';
        $html .= '<div class="entry-data-label">' . esc_html($label) . '</div>';
        $html .= '<div class="entry-data-value">' . nl2br(esc_html($value)) . '</div>';
        $html .= '</div>';
    }
    
    $html .= '</div>'; // entry-data-table
    $html .= '</div>'; // entry-data-section
    $html .= '</div>'; // entry-details-container
    
    // Add inline styles for the modal content
    $html .= '<style>
        .entry-details-container {
            font-size: 14px;
            line-height: 1.6;
        }
        .entry-meta-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 20px;
            padding: 20px;
            background: #f9fafb;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
        }
        .entry-meta-item {
            min-width: 0;
        }
        .entry-meta-label {
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #6b7280;
            margin-bottom: 4px;
        }
        .entry-meta-value {
            font-size: 14px;
            font-weight: 500;
            color: #1f2937;
            word-break: break-word;
        }
        .entry-data-table {
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            overflow: hidden;
        }
        .entry-data-row {
            display: grid;
            grid-template-columns: 200px 1fr;
            border-bottom: 1px solid #e5e7eb;
        }
        .entry-data-row:last-child {
            border-bottom: none;
        }
        .entry-data-label {
            padding: 16px 20px;
            background: #f9fafb;
            font-weight: 600;
            color: #374151;
            border-right: 1px solid #e5e7eb;
        }
        .entry-data-value {
            padding: 16px 20px;
            background: #ffffff;
            color: #1f2937;
            word-break: break-word;
        }
        @media (max-width: 768px) {
            .entry-data-row {
                grid-template-columns: 1fr;
            }
            .entry-data-label {
                border-right: none;
                border-bottom: 1px solid #e5e7eb;
            }
        }
    </style>';
    
    wp_send_json_success(array('html' => $html));
});

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