<?php
/**
 * Submission List Table
 *
 * @since 6.2.7
 * @package the-plus-addons-for-elementor-page-builder
 */

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

if ( ! class_exists( 'WP_List_Table' ) ) {
    include ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

if ( ! class_exists( 'Tpaep_Submission_List_Table' ) ) {

    class Tpaep_Submission_List_Table extends WP_List_Table {

        public function __construct() {
            parent::__construct( [
                'singular' => 'submission',
                'plural'   => 'submissions',
                'ajax'     => false,
            ] );
        }

        /**
         * Check whether the tpaep_formsmeta table exists in the database.
         *
         * @return bool
         */
        private function table_exists() {
            global $wpdb;
            $table = $wpdb->prefix . 'tpaep_formsmeta';
            return (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
        }

        /* ------------------------------------------------------------------ */
        /*  VIEWS (All / Unread / Read tabs)
        /* ------------------------------------------------------------------ */
        public function get_views() {
            global $wpdb;

            $table   = $wpdb->prefix . 'tpaep_formsmeta';
            $current = isset( $_REQUEST['status'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['status'] ) ) : 'all';

            if ( ! $this->table_exists() ) {
                $total  = 0;
                $unread = 0;
                $read   = 0;
            } else {
                $total  = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" );
                $unread = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table WHERE is_read = 0" );
                $read   = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table WHERE is_read = 1" );
            }

            $base = admin_url( 'admin.php?page=tpae-form-submissions' );

            return [
                'all' => sprintf(
                    '<a href="%s" %s>All <span class="count">(%d)</span></a>',
                    esc_url( $base ),
                    $current === 'all' ? 'class="current"' : '',
                    $total
                ),
                'unread' => sprintf(
                    '<a href="%s" %s>Unread <span class="count">(%d)</span></a>',
                    esc_url( add_query_arg( 'status', 'unread', $base ) ),
                    $current === 'unread' ? 'class="current"' : '',
                    $unread
                ),
                'read' => sprintf(
                    '<a href="%s" %s>Read <span class="count">(%d)</span></a>',
                    esc_url( add_query_arg( 'status', 'read', $base ) ),
                    $current === 'read' ? 'class="current"' : '',
                    $read
                ),
            ];
        }

        /* ------------------------------------------------------------------ */
        /*  BULK ACTIONS
        /* ------------------------------------------------------------------ */
        public function get_bulk_actions() {
            return [
                'delete'      => __( 'Delete', 'theplus' ),
                'export_csv'  => __( 'Export', 'theplus' ),
                'mark_read'   => __( 'Mark as Read', 'theplus' ),
                'mark_unread' => __( 'Mark as Unread', 'theplus' ),
            ];
        }

        public function process_bulk_action() {
            global $wpdb;

            // If the Filter button was clicked, never treat it as a bulk action.
            if ( isset( $_REQUEST['filter_action'] ) ) {
                return;
            }

            // Bail early — no bulk action selected.
            if ( ! $this->current_action() ) {
                return;
            }

            // Capability gate: only admins may perform bulk operations.
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_die( esc_html__( 'You do not have permission to perform this action.', 'theplus' ) );
            }

            // Nonce MUST always be verified — the check must never be conditional.
            check_admin_referer( 'bulk-submissions' );

            $table = $wpdb->prefix . 'tpaep_formsmeta';

            if ( empty( $_REQUEST['submission_id'] ) || ! is_array( $_REQUEST['submission_id'] ) ) {
                return;
            }

            $ids = array_map( 'absint', wp_unslash( $_REQUEST['submission_id'] ) );

            $placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) );

            switch ( $this->current_action() ) {

                case 'mark_read':
                    $wpdb->query( $wpdb->prepare(
                        "UPDATE {$wpdb->prefix}tpaep_formsmeta SET is_read = 1 WHERE id IN ($placeholders)",
                        ...$ids
                    ) );
                    break;

                case 'mark_unread':
                    $wpdb->query( $wpdb->prepare(
                        "UPDATE {$wpdb->prefix}tpaep_formsmeta SET is_read = 0 WHERE id IN ($placeholders)",
                        ...$ids
                    ) );
                    break;

                case 'delete':
                    $wpdb->query( $wpdb->prepare(
                        "DELETE FROM {$wpdb->prefix}tpaep_formsmeta WHERE id IN ($placeholders)",
                        ...$ids
                    ) );
                    $wpdb->query( $wpdb->prepare(
                        "DELETE FROM {$wpdb->prefix}tpaep_forms WHERE form_id IN ($placeholders)",
                        ...$ids
                    ) );
                    break;

                case 'export_csv':
                    // Cannot send CSV headers here — page HTML has already started.
                    // Hand off to admin-post.php which fires before any output.
                    $redirect = add_query_arg(
                        [
                            'action'         => 'tpae_export_selected_submissions',
                            'submission_ids' => implode( ',', $ids ),
                            '_wpnonce'       => wp_create_nonce( 'tpae_export_selected' ),
                        ],
                        admin_url( 'admin-post.php' )
                    );
                    wp_safe_redirect( $redirect );
                    exit;
            }
        }

        /* ------------------------------------------------------------------ */
        /*  COLUMNS
        /* ------------------------------------------------------------------ */
        public function get_columns() {
            return [
                'cb'           => '<input type="checkbox" />',
                'id'           => __( 'ID', 'theplus' ),
                'form_name'    => __( 'Form Name', 'theplus' ),
                'page'         => __( 'Page', 'theplus' ),
                'email'        => __( 'Email', 'theplus' ),
                'status'       => __( 'Status', 'theplus' ),
                'submitted_at' => __( 'Submitted At', 'theplus' ),
                'tpae_actions' => __( 'Actions', 'theplus' ),
            ];
        }

        public function get_sortable_columns() {
            return [
                'id'           => [ 'id', false ],
                'submitted_at' => [ 'submitted_at', true ],
            ];
        }

        /* ------------------------------------------------------------------ */
        /*  PAGINATION — hide prev on page 1, hide next on last page
        /* ------------------------------------------------------------------ */
        protected function pagination( $which ) {
            $total_items = (int) $this->get_pagination_arg( 'total_items' );
            $total_pages = (int) $this->get_pagination_arg( 'total_pages' );
            $current     = $this->get_pagenum();

            if ( $total_pages <= 0 ) {
                return;
            }

            $current_url = set_url_scheme( 'http://' . sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) . sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
            $current_url = remove_query_arg( wp_removable_query_args(), $current_url );

            $links = [];

            // First + Prev — only when NOT on page 1
            if ( $current > 1 ) {
                $links[] = sprintf(
                    '<a class="first-page button" href="%s"><span class="screen-reader-text">%s</span><span aria-hidden="true">%s</span></a>',
                    esc_url( remove_query_arg( 'paged', $current_url ) ),
                    esc_html__( 'First page', 'theplus' ),
                    '&laquo;'
                );
                $links[] = sprintf(
                    '<a class="prev-page button" href="%s"><span class="screen-reader-text">%s</span><span aria-hidden="true">%s</span></a>',
                    esc_url( add_query_arg( 'paged', max( 1, $current - 1 ), $current_url ) ),
                    esc_html__( 'Previous page', 'theplus' ),
                    '&lsaquo;'
                );
            }

            // Current page plain text — e.g. "1 of 2"
            $links[] = sprintf(
                '<span class="tpae-paging-text">%d %s %d</span>',
                $current,
                esc_html__( 'of', 'theplus' ),
                $total_pages
            );

            // Next + Last — only when NOT on the last page
            if ( $current < $total_pages ) {
                $links[] = sprintf(
                    '<a class="next-page button" href="%s"><span class="screen-reader-text">%s</span><span aria-hidden="true">%s</span></a>',
                    esc_url( add_query_arg( 'paged', min( $total_pages, $current + 1 ), $current_url ) ),
                    esc_html__( 'Next page', 'theplus' ),
                    '&rsaquo;'
                );
                $links[] = sprintf(
                    '<a class="last-page button" href="%s"><span class="screen-reader-text">%s</span><span aria-hidden="true">%s</span></a>',
                    esc_url( add_query_arg( 'paged', $total_pages, $current_url ) ),
                    esc_html__( 'Last page', 'theplus' ),
                    '&raquo;'
                );
            }

            $page_class = $total_pages < 2 ? ' one-page' : '';
            $items_label = sprintf(
                /* translators: %s: number of items */
                _n( '%s item', '%s items', $total_items, 'theplus' ),
                number_format_i18n( $total_items )
            );

            printf(
                '<div class="tablenav-pages%s"><span class="displaying-num">%s</span><span class="pagination-links">%s</span></div>',
                esc_attr( $page_class ),
                esc_html( $items_label ),
                implode( "\n", $links ) // phpcs:ignore WordPress.Security.EscapeOutput
            );
        }

        /* ------------------------------------------------------------------ */
        /*  COLUMN RENDERERS
        /* ------------------------------------------------------------------ */
        protected function column_cb( $item ) {
            return sprintf(
                '<input type="checkbox" name="submission_id[]" value="%d" />',
                absint( $item->id )
            );
        }

        public function column_id( $item ) {
            return absint( $item->id );
        }

        public function column_form_name( $item ) {
            $label = esc_html( $item->form_name ?: '-' );
            if ( empty( $item->post_id ) ) {
                return $label;
            }
            // Only link if the post still exists in the database
            $post = get_post( absint( $item->post_id ) );
            if ( ! $post || 'trash' === $post->post_status ) {
                return $label;
            }
            return sprintf(
                '<a href="%s" target="_blank">%s</a>',
                esc_url( admin_url( 'post.php?post=' . absint( $item->post_id ) . '&action=elementor' ) ),
                $label
            );
        }

        public function column_page( $item ) {
            if ( empty( $item->post_id ) ) {
                return '-';
            }
            $post = get_post( absint( $item->post_id ) );
            if ( ! $post || 'trash' === $post->post_status ) {
                return '-';
            }
            $title = get_the_title( $post );
            if ( ! $title ) {
                return '-';
            }
            return sprintf(
                '<a href="%s" target="_blank">%s</a>',
                esc_url( get_permalink( $post ) ),
                esc_html( $title )
            );
        }

        public function column_email( $item ) {
            $email = trim( $item->form_fields['email'] ?? '' );

            // Only show what is actually stored in the form submission.
            // No fallback to WP user email — if it wasn't submitted, leave blank.
            return $email !== '' ? esc_html( $email ) : '-';
        }

        public function column_status( $item ) {
            if ( (int) $item->is_read === 1 ) {
                return '<span class="tpae-status-badge tpae-status-read">'
                    . esc_html__( 'Read', 'theplus' ) . '</span>';
            }
            return '<span class="tpae-status-badge tpae-status-unread">'
                . esc_html__( 'Unread', 'theplus' ) . '</span>';
        }

        public function column_submitted_at( $item ) {
            return esc_html(
                date_i18n( 'Y-m-d H:i:s', strtotime( $item->submitted_at ) )
            );
        }

        public function column_tpae_actions( $item ) {
            $view_url = admin_url(
                'admin.php?page=tpae-form-submissions&view=' . absint( $item->id )
            );

            $mark_read_url = wp_nonce_url(
                admin_url(
                    'admin.php?page=tpae-form-submissions&mark_read=' . absint( $item->id )
                ),
                'tpae_mark_read'
            );

            $mark_unread_url = wp_nonce_url(
                admin_url(
                    'admin.php?page=tpae-form-submissions&mark_unread=' . absint( $item->id )
                ),
                'tpae_mark_unread'
            );

            $trash_url = wp_nonce_url(
                admin_url(
                    'admin.php?page=tpae-form-submissions&delete=' . absint( $item->id )
                ),
                'tpae_delete_submission'
            );

            $html = '<a href="' . esc_url( $view_url ) . '" class="tpae-action-btn tpae-btn-view">'
                . esc_html__( 'View', 'theplus' ) . '</a>';

            if ( (int) $item->is_read === 0 ) {
                $html .= '<a href="' . esc_url( $mark_read_url ) . '" class="tpae-action-btn tpae-btn-mark">'
                    . esc_html__( 'Mark as Read', 'theplus' ) . '</a>';
            } else {
                $html .= '<a href="' . esc_url( $mark_unread_url ) . '" class="tpae-action-btn tpae-btn-mark">'
                    . esc_html__( 'Mark as Unread', 'theplus' ) . '</a>';
            }

            $html .= '<a href="' . esc_url( $trash_url ) . '" class="tpae-action-btn tpae-btn-delete"'
                . ' onclick="return confirm(\'' . esc_js( __( 'Are you sure you want to delete this submission? This action cannot be undone.', 'theplus' ) ) . '\')">'
                . esc_html__( 'Delete', 'theplus' ) . '</a>';

            return $html;
        }

        public function column_default( $item, $column_name ) {
            return isset( $item->$column_name )
                ? esc_html( $item->$column_name )
                : '-';
        }

        /* ------------------------------------------------------------------ */
        /*  ROW DISPLAY
        /* ------------------------------------------------------------------ */
        public function no_items() {
            echo '
            <div class="tpae-no-items-wrap">
                <div class="tpae-no-items-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#c4c4d4" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                        <polyline points="14 2 14 8 20 8"/>
                        <line x1="16" y1="13" x2="8" y2="13"/>
                        <line x1="16" y1="17" x2="8" y2="17"/>
                        <polyline points="10 9 9 9 8 9"/>
                    </svg>
                </div>
                <p class="tpae-no-items-title">' . esc_html__( 'No submissions found', 'theplus' ) . '</p>
            </div>';
        }

        public function display_rows_or_placeholder() {
            if ( empty( $this->items ) ) {
                $colspan = count( $this->get_columns() );
                echo '<tr class="tpae-no-items-row"><td colspan="' . esc_attr( $colspan ) . '">';
                $this->no_items();
                echo '</td></tr>';
                return;
            }

            foreach ( $this->items as $item ) {
                $class = ( isset( $item->is_read ) && (int) $item->is_read === 0 )
                    ? 'tpae-unread-row'
                    : '';

                echo '<tr class="' . esc_attr( $class ) . '">';
                $this->single_row_columns( $item );
                echo '</tr>';
            }
        }

        /* ------------------------------------------------------------------ */
        /*  PREPARE ITEMS
        /* ------------------------------------------------------------------ */
        public function prepare_items() {

            // Handle mark_read
            if ( isset( $_GET['page'], $_GET['mark_read'] ) && $_GET['page'] === 'tpae-form-submissions' ) {
                check_admin_referer( 'tpae_mark_read' );
                global $wpdb;
                $wpdb->update(
                    $wpdb->prefix . 'tpaep_formsmeta',
                    [ 'is_read' => 1 ],
                    [ 'id' => absint( $_GET['mark_read'] ) ],
                    [ '%d' ],
                    [ '%d' ]
                );
                wp_safe_redirect( admin_url( 'admin.php?page=tpae-form-submissions' ) );
                exit;
            }

            // Handle mark_unread
            if ( isset( $_GET['page'], $_GET['mark_unread'] ) && $_GET['page'] === 'tpae-form-submissions' ) {
                check_admin_referer( 'tpae_mark_unread' );
                global $wpdb;
                $wpdb->update(
                    $wpdb->prefix . 'tpaep_formsmeta',
                    [ 'is_read' => 0 ],
                    [ 'id' => absint( $_GET['mark_unread'] ) ],
                    [ '%d' ],
                    [ '%d' ]
                );
                wp_safe_redirect( admin_url( 'admin.php?page=tpae-form-submissions' ) );
                exit;
            }

            // Handle delete
            if ( isset( $_GET['page'], $_GET['delete'] ) && $_GET['page'] === 'tpae-form-submissions' ) {
                check_admin_referer( 'tpae_delete_submission' );
                global $wpdb;
                $wpdb->delete(
                    $wpdb->prefix . 'tpaep_formsmeta',
                    [ 'id' => absint( $_GET['delete'] ) ],
                    [ '%d' ]
                );
                $wpdb->delete(
                    $wpdb->prefix . 'tpaep_forms',
                    [ 'form_id' => absint( $_GET['delete'] ) ],
                    [ '%d' ]
                );
                wp_safe_redirect( admin_url( 'admin.php?page=tpae-form-submissions' ) );
                exit;
            }

            $this->process_bulk_action();

            global $wpdb;

            $table_name = $wpdb->prefix . 'tpaep_formsmeta';

            $columns  = $this->get_columns();
            $hidden   = [];
            $sortable = $this->get_sortable_columns();
            $this->_column_headers = [ $columns, $hidden, $sortable ];

            // Bail early if the table does not yet exist — no error, just an empty list.
            if ( ! $this->table_exists() ) {
                $this->items = [];
                $this->set_pagination_args( [
                    'total_items' => 0,
                    'per_page'    => 20,
                    'total_pages' => 0,
                ] );
                return;
            }

            // Migrate: is_read column
            $col_exists = $wpdb->get_var(
                $wpdb->prepare( "SHOW COLUMNS FROM $table_name LIKE %s", 'is_read' )
            );
            if ( ! $col_exists ) {
                $wpdb->query( "ALTER TABLE $table_name ADD is_read TINYINT(1) NOT NULL DEFAULT 0" );
                $wpdb->query( "UPDATE $table_name SET is_read = 0" );
            }

            // Migrate: updated_at column
            $updated_at_exists = $wpdb->get_var(
                $wpdb->prepare( "SHOW COLUMNS FROM $table_name LIKE %s", 'updated_at' )
            );
            if ( ! $updated_at_exists ) {
                $wpdb->query(
                    "ALTER TABLE $table_name ADD updated_at DATETIME NULL DEFAULT NULL AFTER submitted_at"
                );
            }

            $per_page = 20;
            $paged    = $this->get_pagenum();
            $offset   = ( $paged - 1 ) * $per_page;

            $where = [];

            // Status filter
            $status = isset( $_REQUEST['status'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['status'] ) ) : 'all';
            if ( $status === 'read' ) {
                $where[] = 'is_read = 1';
            } elseif ( $status === 'unread' ) {
                $where[] = 'is_read = 0';
            }

            // Search — covers form_name, id, email (subquery), page title (subquery)
            if ( ! empty( $_REQUEST['s'] ) ) {
                $search  = '%' . $wpdb->esc_like( sanitize_text_field( $_REQUEST['s'] ) ) . '%';
                $where[] = $wpdb->prepare(
                    "(form_name LIKE %s
                      OR CAST(id AS CHAR) LIKE %s
                      OR id IN (SELECT form_id FROM {$wpdb->prefix}tpaep_forms WHERE `key`='email' AND `value` LIKE %s)
                      OR post_id IN (SELECT ID FROM {$wpdb->posts} WHERE post_title LIKE %s)
                    )",
                    $search,
                    $search,
                    $search,
                    $search
                );
            }

            // Form filter
            if ( ! empty( $_REQUEST['filter_form'] ) ) {
                $where[] = $wpdb->prepare(
                    'form_name = %s',
                    sanitize_text_field( $_REQUEST['filter_form'] )
                );
            }

            // Page filter
            if ( ! empty( $_REQUEST['filter_page'] ) ) {
                $where[] = $wpdb->prepare(
                    'post_id = %d',
                    absint( $_REQUEST['filter_page'] )
                );
            }

            // Date filter
            $date_filter = sanitize_text_field( $_REQUEST['date_filter'] ?? '' );
            switch ( $date_filter ) {
                case 'today':
                    $where[] = "DATE(submitted_at) = CURDATE()";
                    break;
                case 'yesterday':
                    $where[] = "DATE(submitted_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
                    break;
                case 'last_7':
                    $where[] = "DATE(submitted_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
                    break;
                case 'last_30':
                    $where[] = "DATE(submitted_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
                    break;
                case 'custom':
                    if ( ! empty( $_REQUEST['date_from'] ) ) {
                        $where[] = $wpdb->prepare(
                            'DATE(submitted_at) >= %s',
                            sanitize_text_field( $_REQUEST['date_from'] )
                        );
                    }
                    if ( ! empty( $_REQUEST['date_to'] ) ) {
                        $where[] = $wpdb->prepare(
                            'DATE(submitted_at) <= %s',
                            sanitize_text_field( $_REQUEST['date_to'] )
                        );
                    }
                    break;
            }

            $where_sql = $where ? 'WHERE ' . implode( ' AND ', $where ) : '';

            // Sorting
            $allowed_orderby = [ 'id', 'submitted_at' ];
            $allowed_order   = [ 'asc', 'desc' ];

            $req_orderby = isset( $_REQUEST['orderby'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['orderby'] ) ) : '';
            $req_order   = isset( $_REQUEST['order'] )   ? sanitize_text_field( wp_unslash( $_REQUEST['order'] ) )   : '';

            $orderby = in_array( $req_orderby, $allowed_orderby, true ) ? $req_orderby : 'submitted_at';
            $order   = in_array( strtolower( $req_order ), $allowed_order, true ) ? strtoupper( $req_order ) : 'DESC';

            $this->items = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT id, user_id, form_id, form_name, post_id, submitted_at, is_read
                    FROM $table_name
                    $where_sql
                    ORDER BY {$orderby} {$order}
                    LIMIT %d OFFSET %d",
                    $per_page,
                    $offset
                )
            );

            // Fetch email from form fields for all displayed items in one query
            if ( ! empty( $this->items ) ) {
                $item_ids = array_map( function ( $item ) {
                    return absint( $item->id );
                }, $this->items );

                $ids_in      = implode( ',', $item_ids );
                $email_rows  = $wpdb->get_results(
                    "SELECT form_id, `value`
                     FROM {$wpdb->prefix}tpaep_forms
                     WHERE form_id IN ($ids_in) AND `key` = 'email'"
                );

                $email_map = [];
                foreach ( $email_rows as $row ) {
                    $email_map[ $row->form_id ] = $row->value;
                }

                foreach ( $this->items as $item ) {
                    $item->form_fields = [ 'email' => $email_map[ $item->id ] ?? '' ];
                }
            }

            $total_items = (int) $wpdb->get_var(
                "SELECT COUNT(id) FROM $table_name $where_sql"
            );

            $this->set_pagination_args( [
                'total_items' => $total_items,
                'per_page'    => $per_page,
                'total_pages' => ceil( $total_items / $per_page ),
            ] );
        }

        /* ------------------------------------------------------------------ */
        /*  EXTRA TABLENAV  (filters + search + export)
        /* ------------------------------------------------------------------ */
        protected function extra_tablenav( $which ) {

            if ( $which !== 'top' ) {
                return;
            }

            global $wpdb;

            if ( ! $this->table_exists() ) {
                $forms = [];
                $pages = [];
            } else {
                $forms = $wpdb->get_col(
                    "SELECT DISTINCT form_name FROM {$wpdb->prefix}tpaep_formsmeta ORDER BY form_name ASC"
                );

                // Build pages list for the Page dropdown
                $pages_raw = $wpdb->get_results(
                    "SELECT DISTINCT post_id FROM {$wpdb->prefix}tpaep_formsmeta WHERE post_id > 0 ORDER BY post_id ASC"
                );
                $pages = [];
                foreach ( $pages_raw as $pr ) {
                    $title = get_the_title( absint( $pr->post_id ) );
                    if ( $title ) {
                        $pages[ $pr->post_id ] = $title;
                    }
                }
            }

            // Preserve sort params so they survive the filter form submit
            $orderby     = isset( $_REQUEST['orderby'] )     ? esc_attr( $_REQUEST['orderby'] )     : '';
            $order       = isset( $_REQUEST['order'] )       ? esc_attr( $_REQUEST['order'] )       : '';
            $date_filter = isset( $_REQUEST['date_filter'] ) ? sanitize_text_field( $_REQUEST['date_filter'] ) : '';
            ?>

            <!-- Form dropdown (inline with bulk actions) -->
            <select name="filter_form" class="tpae-select">
                <option value=""><?php esc_html_e( 'All Forms', 'theplus' ); ?></option>
                <?php foreach ( $forms as $form ) :
                    printf(
                        '<option value="%s" %s>%s</option>',
                        esc_attr( $form ),
                        selected( $_REQUEST['filter_form'] ?? '', $form, false ),
                        esc_html( $form )
                    );
                endforeach; ?>
            </select>

            <!-- Page dropdown -->
            <select name="filter_page" class="tpae-select">
                <option value=""><?php esc_html_e( 'All Pages', 'theplus' ); ?></option>
                <?php foreach ( $pages as $pid => $ptitle ) :
                    printf(
                        '<option value="%d" %s>%s</option>',
                        absint( $pid ),
                        selected( (int) ( $_REQUEST['filter_page'] ?? 0 ), (int) $pid, false ),
                        esc_html( $ptitle )
                    );
                endforeach; ?>
            </select>

            <!-- Time dropdown -->
            <select name="date_filter" id="tpae-date-filter-select" class="tpae-select">
                <option value="" <?php selected( $date_filter, '' ); ?>><?php esc_html_e( 'All Time', 'theplus' ); ?></option>
                <option value="today" <?php selected( $date_filter, 'today' ); ?>><?php esc_html_e( 'Today', 'theplus' ); ?></option>
                <option value="yesterday" <?php selected( $date_filter, 'yesterday' ); ?>><?php esc_html_e( 'Yesterday', 'theplus' ); ?></option>
                <option value="last_7" <?php selected( $date_filter, 'last_7' ); ?>><?php esc_html_e( 'Last 7 Days', 'theplus' ); ?></option>
                <option value="last_30" <?php selected( $date_filter, 'last_30' ); ?>><?php esc_html_e( 'Last 30 Days', 'theplus' ); ?></option>
                <option value="custom" <?php selected( $date_filter, 'custom' ); ?>><?php esc_html_e( 'Custom', 'theplus' ); ?></option>
            </select>

            <!-- Custom date pickers — visible only when "Custom" is selected -->
            <div id="tpae-custom-dates" style="display:<?php echo ( $date_filter === 'custom' ) ? 'inline-flex' : 'none'; ?>;align-items:center;gap:6px;">
                <input
                    type="date"
                    name="date_from"
                    value="<?php echo esc_attr( $_REQUEST['date_from'] ?? '' ); ?>"
                    class="tpae-date-field"
                >
                <span style="color:#9ca3af;font-size:12px;">—</span>
                <input
                    type="date"
                    name="date_to"
                    value="<?php echo esc_attr( $_REQUEST['date_to'] ?? '' ); ?>"
                    class="tpae-date-field"
                >
            </div>

            <!-- Filter button (blue) — resets bulk-action select so it never triggers export -->
            <button
                type="submit"
                name="filter_action"
                class="tpae-filter-apply-btn"
                onclick="(function(btn){var sel=btn.closest('form').querySelector('select[name=action]');if(sel)sel.value='-1';var sel2=btn.closest('form').querySelector('select[name=action2]');if(sel2)sel2.value='-1';})(this);"
            >
                <?php esc_html_e( 'Filter', 'theplus' ); ?>
            </button>

            <!-- Right side: search + export — pushed to far right via margin-left:auto -->
            <div class="tpae-filter-right">
                <div class="tpae-search-wrap">
                    <svg class="tpae-search-icon" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                    <input
                        type="search"
                        name="s"
                        value="<?php echo esc_attr( $_REQUEST['s'] ?? '' ); ?>"
                        placeholder="<?php esc_attr_e( 'Search submissions...', 'theplus' ); ?>"
                        class="tpae-search-field"
                    >
                </div>
                <?php
                // Detect active filters
                $ef_form        = isset( $_REQUEST['filter_form'] )   ? sanitize_text_field( $_REQUEST['filter_form'] )   : '';
                $ef_page        = isset( $_REQUEST['filter_page'] )   ? absint( $_REQUEST['filter_page'] )                : 0;
                $ef_date        = isset( $_REQUEST['date_filter'] )   ? sanitize_text_field( $_REQUEST['date_filter'] )   : '';
                $ef_date_from   = isset( $_REQUEST['date_from'] )     ? sanitize_text_field( $_REQUEST['date_from'] )     : '';
                $ef_date_to     = isset( $_REQUEST['date_to'] )       ? sanitize_text_field( $_REQUEST['date_to'] )       : '';
                $ef_s           = isset( $_REQUEST['s'] )             ? sanitize_text_field( $_REQUEST['s'] )             : '';
                $has_filter     = ( $ef_form || $ef_page || ( $ef_date && $ef_date !== 'all' ) || $ef_s );

                $export_base_url = admin_url( 'admin-post.php?action=tpae_export_all_submissions' );
                if ( $ef_form )      $export_base_url = add_query_arg( 'filter_form',  rawurlencode( $ef_form ),      $export_base_url );
                if ( $ef_page )      $export_base_url = add_query_arg( 'filter_page',  $ef_page,                      $export_base_url );
                if ( $ef_date )      $export_base_url = add_query_arg( 'date_filter',  rawurlencode( $ef_date ),      $export_base_url );
                if ( $ef_date_from ) $export_base_url = add_query_arg( 'date_from',    rawurlencode( $ef_date_from ), $export_base_url );
                if ( $ef_date_to )   $export_base_url = add_query_arg( 'date_to',      rawurlencode( $ef_date_to ),   $export_base_url );
                if ( $ef_s )         $export_base_url = add_query_arg( 's',            rawurlencode( $ef_s ),         $export_base_url );

                $export_url   = wp_nonce_url( $export_base_url, 'tpae_export_all' );
                $export_label = $has_filter ? __( 'Export Filtered', 'theplus' ) : __( 'Export All', 'theplus' );

                // Disable the export button when there are no rows to export.
                $total_items  = (int) $this->get_pagination_arg( 'total_items' );
                $export_disabled = ( $total_items === 0 );
                ?>
                <a
                    href="<?php echo $export_disabled ? '#' : esc_url( $export_url ); ?>"
                    class="tpae-export-btn<?php echo $has_filter ? ' tpae-export-filtered' : ''; ?><?php echo $export_disabled ? ' tpae-export-disabled' : ''; ?>"
                    id="tpae-export-btn"
                    data-base-action="<?php echo esc_attr( admin_url( 'admin-post.php?action=tpae_export_all_submissions' ) ); ?>"
                    data-nonce="<?php echo esc_attr( wp_create_nonce( 'tpae_export_all' ) ); ?>"
                    <?php echo $export_disabled ? 'aria-disabled="true" tabindex="-1"' : ''; ?>
                >
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                    <span id="tpae-export-btn-label"><?php echo esc_html( $export_label ); ?></span>
                </a>
            </div>

            <script>
            (function() {
                /* --- Strip ALL query params from visible URL — keep only ?page=tpae-form-submissions --- */
                if ( window.history && window.history.replaceState ) {
                    var cleanUrl = new URL( window.location.href );
                    var pageVal  = cleanUrl.searchParams.get( 'page' );
                    // Remove every param then restore only "page"
                    cleanUrl.search = '';
                    if ( pageVal ) {
                        cleanUrl.searchParams.set( 'page', pageVal );
                    }
                    window.history.replaceState( {}, '', cleanUrl.toString() );
                }

                /* --- Disable pagination buttons (prev on page 1, next on last page) --- */
                (function() {
                    function disableBtn( btn ) {
                        btn.style.cursor         = 'not-allowed';
                        btn.style.opacity        = '0.35';
                        btn.style.pointerEvents  = 'none';
                        btn.style.color          = '#9ca3af';
                        btn.style.borderColor    = '#e5e7eb';
                        btn.style.background     = '#f9fafb';
                        // If it's an <a> tag, also prevent navigation
                        if ( btn.tagName === 'A' ) {
                            btn.removeAttribute( 'href' );
                            btn.setAttribute( 'tabindex', '-1' );
                            btn.setAttribute( 'aria-disabled', 'true' );
                        }
                    }

                    document.querySelectorAll( '.tpae-table-card .tablenav-pages' ).forEach( function( nav ) {
                        var pageInput = nav.querySelector( '.current-page' );
                        var totalEl   = nav.querySelector( '.total-pages' );
                        if ( ! pageInput || ! totalEl ) return;

                        var current = parseInt( pageInput.value, 10 );
                        var total   = parseInt( totalEl.textContent, 10 );

                        if ( current <= 1 ) {
                            nav.querySelectorAll( '.first-page, .prev-page' ).forEach( disableBtn );
                        }
                        if ( current >= total ) {
                            nav.querySelectorAll( '.next-page, .last-page' ).forEach( disableBtn );
                        }

                        // Also catch any span WordPress already marked as disabled
                        nav.querySelectorAll( 'span.disabled, .tablenav-pages-navspan.disabled' ).forEach( disableBtn );
                    });
                })();

                /* --- Custom date picker toggle --- */
                var sel    = document.getElementById( 'tpae-date-filter-select' );
                var custom = document.getElementById( 'tpae-custom-dates' );
                if ( sel && custom ) {
                    sel.addEventListener( 'change', function() {
                        custom.style.display = ( this.value === 'custom' ) ? 'flex' : 'none';
                    } );
                }

                /* --- Bulk Delete confirm --- */
                var bulkForm = document.querySelector( '#tpae-submissions-page form' );
                if ( bulkForm ) {
                    bulkForm.addEventListener( 'submit', function( e ) {
                        var action = document.querySelector( '.tablenav.top .bulkactions select' );
                        if ( action && action.value === 'delete' ) {
                            var checked = document.querySelectorAll( '#the-list input[type="checkbox"]:checked' );
                            if ( checked.length > 0 ) {
                                if ( ! confirm( '<?php echo esc_js( __( 'Are you sure you want to delete the selected submissions? This action cannot be undone.', 'theplus' ) ); ?>' ) ) {
                                    e.preventDefault();
                                }
                            }
                        }
                    } );
                }

                /* --- Dropdown arrow up/down toggle for all selects --- */
                document.querySelectorAll( '.tpae-select, .tpae-table-card .tablenav.top .bulkactions select' ).forEach( function( s ) {
                    // Open: mousedown when closed
                    s.addEventListener( 'mousedown', function() {
                        var isOpen = this.classList.contains( 'tpae-select-open' );
                        // Toggle: if already open, next action closes it
                        if ( isOpen ) {
                            this.classList.remove( 'tpae-select-open' );
                        } else {
                            this.classList.add( 'tpae-select-open' );
                        }
                    } );
                    // Close on blur (clicked away / item selected)
                    s.addEventListener( 'blur', function() {
                        this.classList.remove( 'tpae-select-open' );
                    } );
                    // Close after a value is chosen
                    s.addEventListener( 'change', function() {
                        this.classList.remove( 'tpae-select-open' );
                    } );
                } );

                /* --- Dynamic Export button: "Export All" ↔ "Export Filtered" --- */
                (function() {
                    var btn       = document.getElementById( 'tpae-export-btn' );
                    var lbl       = document.getElementById( 'tpae-export-btn-label' );
                    if ( ! btn || ! lbl ) return;

                    // If the button was rendered as disabled (no items), keep it that way.
                    if ( btn.classList.contains( 'tpae-export-disabled' ) ) {
                        return;
                    }

                    var baseAction = btn.dataset.baseAction;
                    var nonce      = btn.dataset.nonce;

                    function updateExportBtn() {
                        var filterForm = document.querySelector( 'select[name="filter_form"]' );
                        var filterPage = document.querySelector( 'select[name="filter_page"]' );
                        var filterDate = document.getElementById( 'tpae-date-filter-select' );
                        var dateFrom   = document.querySelector( 'input[name="date_from"]' );
                        var dateTo     = document.querySelector( 'input[name="date_to"]' );
                        var search     = document.querySelector( '.tpae-search-field' );

                        var params = new URLSearchParams();
                        params.set( 'action', 'tpae_export_all_submissions' );
                        params.set( '_wpnonce', nonce );

                        var hasFilter = false;

                        if ( filterForm && filterForm.value ) {
                            params.set( 'filter_form', filterForm.value );
                            hasFilter = true;
                        }
                        if ( filterPage && filterPage.value ) {
                            params.set( 'filter_page', filterPage.value );
                            hasFilter = true;
                        }
                        if ( filterDate && filterDate.value && filterDate.value !== 'all' && filterDate.value !== '' ) {
                            params.set( 'date_filter', filterDate.value );
                            hasFilter = true;
                            if ( filterDate.value === 'custom' ) {
                                if ( dateFrom && dateFrom.value ) params.set( 'date_from', dateFrom.value );
                                if ( dateTo   && dateTo.value   ) params.set( 'date_to',   dateTo.value   );
                            }
                        }
                        if ( search && search.value.trim() ) {
                            params.set( 's', search.value.trim() );
                            hasFilter = true;
                        }

                        // Rebuild URL
                        var url = baseAction.split( '?' )[0] + '?' + params.toString();
                        btn.href = url;
                        lbl.textContent = hasFilter ? '<?php echo esc_js( __( 'Export Filtered', 'theplus' ) ); ?>' : '<?php echo esc_js( __( 'Export All', 'theplus' ) ); ?>';
                        btn.classList.toggle( 'tpae-export-filtered', hasFilter );
                    }

                    // Watch all filter controls
                    [ 'select[name="filter_form"]', 'select[name="filter_page"]', '#tpae-date-filter-select',
                      'input[name="date_from"]', 'input[name="date_to"]', '.tpae-search-field' ].forEach( function( sel ) {
                        var el = document.querySelector( sel );
                        if ( el ) el.addEventListener( 'change', updateExportBtn );
                        if ( el && el.tagName === 'INPUT' ) el.addEventListener( 'input', updateExportBtn );
                    } );
                })();

                /* --- Real-time search — server-side, debounced 500 ms --- */
                /* Typing triggers a full form submit so ALL pages are searched */
                var searchInput = document.querySelector( '.tpae-search-field' );
                if ( searchInput ) {
                    var searchForm = searchInput.closest( 'form' );

                    // Prevent instant submit on Enter (let debounce handle it)
                    searchInput.addEventListener( 'keydown', function( e ) {
                        if ( e.key === 'Enter' ) { e.preventDefault(); }
                    } );

                    var searchDebounce;
                    searchInput.addEventListener( 'input', function() {
                        clearTimeout( searchDebounce );
                        searchDebounce = setTimeout( function() {
                            // Reset to page 1 so results start from the beginning
                            var pagedInput = searchForm ? searchForm.querySelector( 'input[name="paged"]' ) : null;
                            if ( pagedInput ) {
                                pagedInput.value = '1';
                            } else if ( searchForm ) {
                                var pi = document.createElement( 'input' );
                                pi.type  = 'hidden';
                                pi.name  = 'paged';
                                pi.value = '1';
                                searchForm.appendChild( pi );
                            }
                            if ( searchForm ) {
                                searchForm.submit();
                            }
                        }, 500 );
                    } );
                }
            })();
            </script>

            <style>#tpae-submissions-page{max-width:100%}.tpae-table-card{position:relative;background:#fff;border:1px solid #d1d5db;border-radius:10px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,.09),0 0 0 1px rgba(0,0,0,.04);margin-top:12px}.tpae-table-card .tablenav.top{padding:16px 20px;margin:0;background:#fff;border-bottom:1px solid #f1f5f9;display:flex;align-items:center;flex-wrap:wrap;gap:8px;height:auto!important}.tpae-table-card .tablenav.top .bulkactions{display:flex;align-items:center;gap:6px;float:none;margin:0}.tpae-table-card .tablenav.top .bulkactions select{height:34px;border:1px solid #d1d5db;border-radius:5px;font-size:13px;padding:0 28px 0 8px;color:#374151;background:#fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E") no-repeat right 8px center;-webkit-appearance:none;-moz-appearance:none;appearance:none;cursor:pointer;margin:0}.tpae-table-card .tablenav.top .bulkactions select.tpae-select-open{background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='18 15 12 9 6 15'/%3E%3C/svg%3E")}.tpae-table-card .tablenav.top .bulkactions .button{height:34px;line-height:32px;padding:0 14px;border-radius:5px;font-size:13px;font-weight:600;border:none!important;background:#6660ef!important;color:#fff!important;cursor:pointer}.tpae-table-card .tablenav.top .bulkactions .button:hover{background:#5753d4!important;color:#fff!important}.tpae-select{height:34px!important;border:1px solid #d1d5db!important;border-radius:5px!important;font-size:13px!important;padding:0 28px 0 8px!important;color:#374151!important;background:#fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E") no-repeat right 8px center!important;-webkit-appearance:none!important;-moz-appearance:none!important;appearance:none!important;cursor:pointer}.tpae-select.tpae-select-open{background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='18 15 12 9 6 15'/%3E%3C/svg%3E")!important}.tpae-table-card .tablenav.top .tablenav-pages{display:none}.tpae-filter-right{margin-left:auto;display:flex;align-items:center;gap:10px}.tpae-date-field{height:34px!important;border:1px solid #d1d5db!important;border-radius:5px!important;padding:0 10px!important;font-size:13px!important;color:#374151!important;background:#fff!important;box-sizing:border-box;width:auto}.tpae-date-field:focus{border-color:#6660ef!important;outline:none!important;box-shadow:0 0 0 3px rgba(102,96,239,.12)!important}.tpae-search-wrap{position:relative;display:inline-flex;align-items:center}.tpae-search-icon{position:absolute;left:10px;color:#9ca3af;pointer-events:none;flex-shrink:0}.tpae-search-field{height:34px!important;border:1px solid #d1d5db!important;border-radius:5px!important;padding:0 10px 0 32px!important;font-size:13px!important;color:#374151!important;background:#fff!important;width:220px;box-sizing:border-box;margin:0!important}.tpae-search-field:focus{border-color:#6660ef!important;outline:none!important;box-shadow:0 0 0 3px rgba(102,96,239,.12)!important}#the-list tr[style*="display: none"],#the-list tr[style*="display:none"]{display:none!important}.tpae-filter-apply-btn{height:34px;line-height:34px;padding:0 18px;border-radius:5px;font-size:13px;font-weight:600;background:#6660ef;border:none;color:#fff;cursor:pointer;display:inline-flex;align-items:center;gap:4px;text-decoration:none;transition:background .15s}.tpae-filter-apply-btn:hover{background:#5753d4;color:#fff}.tpae-export-btn{height:34px;line-height:34px;padding:0 16px;border-radius:5px;font-size:13px;font-weight:600;background:#6660ef;border:none;color:#fff!important;cursor:pointer;display:inline-flex;align-items:center;gap:6px;text-decoration:none!important;transition:background .15s}.tpae-export-btn:hover{background:#5753d4;color:#fff!important}.tpae-export-btn.tpae-export-filtered{background:#4f46e5;border-color:#4f46e5}.tpae-export-btn.tpae-export-filtered:hover{background:#4338ca}.tpae-export-btn.tpae-export-disabled,.tpae-export-btn.tpae-export-disabled:hover{background:#e5e7eb!important;border-color:#e5e7eb!important;color:#9ca3af!important;cursor:not-allowed!important;pointer-events:none;opacity:.7}.tpae-no-items-row td{padding:0!important;border:none!important;background:#fff!important}.tpae-no-items-wrap{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:56px 24px;text-align:center}.tpae-no-items-icon{width:80px;height:80px;background:#f5f5fb;border-radius:50%;display:flex;align-items:center;justify-content:center;margin-bottom:18px}.tpae-no-items-title{font-size:16px;font-weight:600;color:#374151;margin:0 0 8px}.tpae-no-items-desc{font-size:13px;color:#9ca3af;margin:0;max-width:340px;line-height:1.6}.tpae-table-card .wp-list-table{width:100%;border:none!important;border-radius:0;margin:0;background:#fff}.tpae-table-card .wp-list-table.striped>tbody>tr:nth-child(odd),.tpae-table-card .wp-list-table.striped>tbody>tr:nth-child(even){background:#fff!important}.tpae-table-card .wp-list-table thead th,.tpae-table-card .wp-list-table thead td,.tpae-table-card .wp-list-table tfoot th,.tpae-table-card .wp-list-table tfoot td{background:#f8fafc!important;color:#64748b;font-size:13px;font-weight:600;text-transform:none;letter-spacing:0;padding:10px 14px;white-space:nowrap}.tpae-table-card .wp-list-table thead th,.tpae-table-card .wp-list-table thead td{border-bottom:1px solid #e2e8f0!important;border-top:none!important}.tpae-table-card .wp-list-table tfoot th,.tpae-table-card .wp-list-table tfoot td{border-top:1px solid #e2e8f0!important;border-bottom:none!important}.tpae-table-card .wp-list-table .column-id .sorting-indicator,.tpae-table-card .wp-list-table .column-submitted_at .sorting-indicator{display:inline-block}.tpae-table-card .wp-list-table thead th a,.tpae-table-card .wp-list-table thead th a:visited,.tpae-table-card .wp-list-table thead th a:hover,.tpae-table-card .wp-list-table thead th.sorted a,.tpae-table-card .wp-list-table thead th.sortable a,.tpae-table-card .wp-list-table tfoot th a,.tpae-table-card .wp-list-table tfoot th a:visited,.tpae-table-card .wp-list-table tfoot th a:hover,.tpae-table-card .wp-list-table tfoot th.sorted a,.tpae-table-card .wp-list-table tfoot th.sortable a{color:#6660ef!important}.tpae-table-card .wp-list-table tbody td{padding:14px 16px;border-bottom:1px solid #f1f5f9!important;background:#fff!important;vertical-align:middle;font-size:13px;color:#374151;border-top:none!important}.tpae-table-card .wp-list-table tbody tr:last-child td{border-bottom:none!important}.tpae-table-card .wp-list-table tbody tr:has(.tpae-status-unread) td{font-weight:600}.tpae-table-card .wp-list-table tbody tr:hover td{background:#f8fafc!important}.tpae-status-badge{display:inline-flex;align-items:center;padding:3px 11px;border-radius:20px;font-size:11px;font-weight:600;line-height:1.6;letter-spacing:.02em;white-space:nowrap}.tpae-status-unread{color:#6660ef;border:1.5px solid #6660ef;background:transparent}.tpae-status-read{color:#6b7280;border:1.5px solid #d1d5db;background:transparent}.tpae-action-btn{display:inline-flex;align-items:center;padding:4px 13px;border-radius:5px;font-size:12px;font-weight:500;text-decoration:none!important;margin-right:4px;cursor:pointer;line-height:1.5;border:1px solid transparent;vertical-align:middle;transition:background .12s,color .12s}.tpae-btn-view{background:#6660ef;color:#fff!important;border-color:#6660ef}.tpae-btn-view:hover{background:#5753d4;border-color:#5753d4;color:#fff!important}.tpae-btn-mark{background:#fff;color:#374151!important;border:1px solid #9ca3af!important}.tpae-btn-mark:hover{background:#f3f4f6;color:#374151!important}.tpae-btn-delete{background:transparent;color:#dc2626!important;border-color:transparent}.tpae-btn-delete:hover{color:#b91c1c!important;text-decoration:underline!important}.tpae-table-card .row-actions{display:none!important}.tpae-table-card .column-tpae_actions{white-space:nowrap;width:290px;min-width:290px}.tpae-table-card .tablenav.bottom{padding:10px 16px;margin:0;background:#fff;border-top:1px solid #f1f5f9;display:flex;align-items:center;justify-content:space-between;height:auto!important}.tpae-table-card .tablenav.bottom .bulkactions,.tpae-table-card .tablenav.bottom .actions{display:none!important}.tpae-table-card .tablenav.bottom .displaying-num{color:#6b7280;font-size:13px;float:none}.tpae-table-card .tablenav.bottom .tablenav-pages{float:none}.tpae-table-card .tablenav-pages .pagination-links a,.tpae-table-card .tablenav-pages .pagination-links span.current{border-radius:5px;border:1px solid #d1d5db;padding:4px 10px;font-size:13px;color:#374151;text-decoration:none;display:inline-flex;align-items:center}.tpae-table-card .tablenav-pages .pagination-links span.current{background:#f1f5f9;font-weight:600}.tpae-table-card .tablenav-pages .tpae-paging-text{display:inline-flex;align-items:center;font-size:13px;color:#374151;padding:0 6px}.tpae-table-card .tablenav-pages .tablenav-pages-navspan.disabled,.tpae-table-card .tablenav-pages span.button.disabled,.tpae-table-card .tablenav-pages a.button.disabled,.tpae-table-card .pagination-links span.disabled,.tpae-table-card .pagination-links .button.disabled{cursor:not-allowed!important;opacity:.35!important;pointer-events:none!important;color:#9ca3af!important;border-color:#e5e7eb!important;background:#f9fafb!important}#tpae-submissions-page .subsubsub{display:none!important;margin-bottom:10px;font-size:13px}.tpae-table-card .column-cb,.tpae-table-card th.check-column,.tpae-table-card td.check-column{width:26px!important;min-width:26px!important;padding-left:12px!important;padding-right:4px!important}.tpae-table-card .column-id,.tpae-table-card th.column-id,.tpae-table-card td.column-id{width:52px!important;min-width:52px!important;white-space:nowrap;text-align:center!important}.tpae-table-card .column-form_name,.tpae-table-card .column-page{max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tpae-table-card .column-form_name a,.tpae-table-card .column-page a{color:#6660ef;text-decoration:none}.tpae-table-card .column-form_name a:hover,.tpae-table-card .column-page a:hover{text-decoration:underline}</style>

            <?php
        }

    }
}
