<?php

/**
 * Admin Menu Class
 *
 * @package Giraforms
 */
// Exit if accessed directly.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Class GiraForms_Admin_Menu
 */
class GiraForms_Admin_Menu {
    /**
     * Instance of this class.
     *
     * @var GiraForms_Admin_Menu
     */
    private static $instance = null;

    /**
     * Get instance.
     *
     * @return GiraForms_Admin_Menu
     */
    public static function instance() {
        if ( is_null( self::$instance ) ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor.
     */
    private function __construct() {
        add_action( 'admin_menu', array($this, 'add_admin_menu') );
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_admin_assets') );
        add_action( 'admin_init', array($this, 'handle_export') );
        add_action( 'admin_init', array($this, 'handle_actions') );
    }

    /**
     * Get SVG icon for menu.
     *
     * @return string Base64 encoded SVG data URI.
     */
    private function get_menu_icon() {
        // SVG optimized for WordPress admin menu (20x20px)
        $svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20" fill="#9ca1a7"><path d="m7.3 0h0.2 0.2 0.2 0.2l0.3 0.2 0.2 0.3 0.1 0.3v0.2 0.3 0.3 0.4 0.3 0.3 0.5h1.2v-0.5-0.3l-0.1-0.4v-0.3-0.4-0.3l0.1-0.2 0.1-0.2 0.1-0.2 0.3-0.2 0.1-0.1h0.3 0.2 0.2l0.3 0.2 0.2 0.3 0.2 0.3v0.3 0.3 0.2 0.2 0.2 0.3 0.2 0.3 0.2 0.2 0.3 0.2 0.2 0.4l0.1 0.1 0.2 0.2 0.2 0.1 0.1-0.1 0.1-0.2 0.1-0.2 0.2-0.2 0.1-0.2 0.2-0.1 0.1-0.2 0.2-0.1 0.3-0.2 0.2-0.1h0.2l0.2-0.1h0.2 0.2 1.3c0 0.3 0 0.5 0 0.8v0.3l-0.1 0.2-0.1 0.2-0.1 0.2-0.1 0.2-0.1 0.2-0.1 0.2-0.3 0.3-0.1 0.1-0.2 0.1-0.2 0.1-0.2 0.1-0.2 0.1-0.1 0.1-0.2 0.1 0.1 0.1 0.2 0.2 0.2 0.2 0.3 0.2 0.2 0.3 0.3 0.2 0.2 0.2 0.3 0.3 0.2 0.2 0.3 0.3 0.3 0.2 0.2 0.2 0.2 0.3 0.2 0.2 0.2 0.3 0.2 0.2 0.1 0.3v0.3 0.3 0.3 0.3c-0.1 0.6-0.2 0.8-0.6 0.8h-0.2q-0.3 0-0.6 0.1h-0.2c-0.7-0.1-1.1-0.7-1.6-1.2h-4.4v8.9h-7.1c1-4.5 2-8.9 3-12.9 0.1-0.3 0.2-0.5 0.3-0.9l-0.4 0.1h-0.2-0.2-0.2-0.3-0.2l-0.2-0.1h-0.3l-0.2-0.2-0.3-0.1-0.2-0.2-0.1-0.1-0.3-0.2-0.2-0.2-0.1-0.2-0.1-0.3-0.1-0.2-0.1-0.2-0.1-0.2v-0.3c0-0.2 0-0.5 0-0.8 0.7 0.1 1.2 0 1.7 0l0.4 0.1 0.2 0.1 0.3 0.2 0.3 0.3 0.2 0.2 0.3 0.2 0.1 0.3 0.1 0.3 0.1 0.3v0.3l0.1 0.4v0.2l0.1-0.3 0.1-0.3v-0.4l0.1-0.3 0.1-0.1v-0.4-0.2-0.3-0.2-0.3-0.2-0.3-0.3-0.3-0.2-0.3-0.2-0.3-0.2-0.1l0.1-0.2 0.1-0.2 0.2-0.1z"/><path fill-rule="evenodd" d="m10.8 8.1c-0.6 0-1-0.5-1-1 0-0.5 0.4-0.9 1-0.9 0.5 0 0.9 0.4 0.9 0.9 0 0.5-0.4 1-0.9 1z"/></svg>';
        // Remove whitespace and encode to base64
        $svg = preg_replace( '/\\s+/', ' ', trim( $svg ) );
        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Required for SVG data URI.
        return 'data:image/svg+xml;base64,' . base64_encode( $svg );
    }

    /**
     * Add admin menu pages.
     */
    public function add_admin_menu() {
        // Main menu
        add_menu_page(
            __( 'Forms', 'giraforms' ),
            __( 'Forms', 'giraforms' ),
            'manage_options',
            'giraforms',
            array($this, 'render_submissions_page'),
            $this->get_menu_icon(),
            30
        );
        // Submissions submenu
        add_submenu_page(
            'giraforms',
            __( 'Submissions', 'giraforms' ),
            __( 'Submissions', 'giraforms' ),
            'manage_options',
            'giraforms-submissions',
            array($this, 'render_submissions_page')
        );
        // Remove duplicate main menu item
        remove_submenu_page( 'giraforms', 'giraforms' );
    }

    /**
     * Enqueue admin assets.
     *
     * @param string $hook Current admin page hook.
     */
    public function enqueue_admin_assets( $hook ) {
        // Only load on our admin pages
        if ( strpos( $hook, 'giraforms' ) === false ) {
            return;
        }
        wp_enqueue_style(
            'giraforms-admin',
            GIRAFORMS_PLUGIN_URL . 'assets/css/admin.css',
            array(),
            GIRAFORMS_VERSION
        );
        wp_enqueue_script(
            'giraforms-admin',
            GIRAFORMS_PLUGIN_URL . 'assets/js/admin.js',
            array('jquery'),
            GIRAFORMS_VERSION,
            true
        );
        $admin_data = array(
            'ajaxUrl'   => admin_url( 'admin-ajax.php' ),
            'nonce'     => wp_create_nonce( 'giraforms_admin' ),
            'isPremium' => giraforms__fs()->can_use_premium_code__premium_only(),
            'strings'   => array(
                'confirmDelete' => __( 'Are you sure you want to delete this submission?', 'giraforms' ),
            ),
        );
        wp_localize_script( 'giraforms-admin', 'giraFormsAdmin', $admin_data );
    }

    /**
     * Render submissions page.
     */
    public function render_submissions_page() {
        // Check if viewing single submission
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a simple URL parameter check for navigation, no data is being processed.
        if ( isset( $_GET['submission_id'] ) && !empty( $_GET['submission_id'] ) ) {
            $this->render_single_submission();
            return;
        }
        // Check if viewing submissions for a specific form
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a simple URL parameter check for navigation, no data is being processed.
        if ( isset( $_GET['form_id'] ) && !empty( $_GET['form_id'] ) ) {
            $this->render_form_submissions();
            return;
        }
        // Default: show forms list
        $this->render_forms_list();
    }

    /**
     * Render forms list page.
     */
    private function render_forms_list() {
        $forms = GiraForms_Submissions::get_forms_list();
        ?>
		<div class="wrap">
			<div class="giraforms-page-header-title">
				<h1 class="wp-heading-inline"><?php 
        esc_html_e( 'Forms', 'giraforms' );
        ?></h1>
			</div>
			<hr class="wp-header-end">

			<?php 
        if ( empty( $forms ) ) {
            ?>
				<!-- Empty State: Getting Started -->
				<div class="giraforms-empty-state" style="max-width: 800px; margin: 0px auto; text-align: center; padding: 40px 20px;">
					<div class="giraforms-empty-state-icon">
						<svg height="50" viewBox="0 0 849 150" xmlns="http://www.w3.org/2000/svg"><path d="m27.3 0h95.4c15.1 0 27.3 12.2 27.3 27.3v95.4c0 15.1-12.2 27.3-27.3 27.3h-95.4c-15.1 0-27.3-12.2-27.3-27.3v-95.4c0-15.1 12.2-27.3 27.3-27.3z" fill="#3859e9" fill-rule="evenodd"/><path d="m61 25.2 1-.1 1-.1h1.1l1 .2 1.4.9 1 1.2.7 1.7.1 1.2v1.5 1.5l-.1 1.7v1.6 1.6 2.5h5.8l-.1-2.6v-1.7l-.1-1.7v-1.7-1.7-1.5l.2-1.4.5-1 .6-.7 1.3-1 .7-.4 1.7-.1h1l1 .1 1.4.9 1 1.2.7 1.7v1.7 1.1 1.1 1.1 1.2 1.2 1.2 1.2 1.3 1.1 1.2 1.1 1l.3 1.9.6.7.6.7 1.2.9.4-.7.6-.9.7-1.1.7-1 .7-.9.8-.8.8-.7.8-.7 1.4-.8 1.3-.5 1-.2 1-.2h1 1 6.2c.1 1.4.1 2.4.1 3.7l-.1 1.4-.3 1.2-.5 1.1-.4 1-.5.8-.6 1.1-.8 1-1.2 1.4-.7.7-.8.6-1 .5-1 .5-.9.4-.8.3-1.1.7.7.6 1 .9 1.1 1 1.2 1.1 1.2 1.1 1.3 1.2 1.3 1.2 1.3 1.2 1.3 1.2 1.3 1.2 1.3 1.2 1.2 1.1 1.1 1.2 1.1 1.3 1 1.2.7 1.4.4 1.4.2 1.6.1 1.5-.1 1.5-.1 1.5c-.3 2.7-.9 3.8-2.8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-18.3-8.9-5.7-6.1-5.7-15.5 0-7.1 3.7-12.9 3.7-6 10.6-9.5 7.2-3.6 16.8-3.6 11.6 0 19.5 4.3 7.9 4.1 13.3 10.2l-14.8 13.3q-3.8-3.3-9-5.2-5-2.1-11-2.1-3.1 0-5.2 1-2 .9-2 2.8 0 1.8 2.6 3.2 2.9 1.2 11.4 3.3 14.5 3.4 20.8 9.6 6.5 5.9 6.5 16.1 0 7.5-4.1 13.4-4 5.7-11.2 8.9-7 3.2-16.4 3.2z" fill="#3859e9"/></svg>
					</div>

					<h2 style="font-size: 28px; margin-bottom: 16px; color: #1d2327;">
						<?php 
            esc_html_e( 'Welcome to Giraforms!', 'giraforms' );
            ?>
					</h2>

					<p style="font-size: 16px; color: #646970; margin-bottom: 40px; line-height: 1.6;">
						<?php 
            esc_html_e( 'No forms have been created yet. Let\'s get started by creating your first form!', 'giraforms' );
            ?>
					</p>

					<!-- Getting Started Steps -->
					<div class="giraforms-onboarding-steps" style="background: #f6f7f7; border-radius: 8px; padding: 40px; margin-bottom: 30px; text-align: left;">
						<h3 style="text-align: center; margin-bottom: 30px; font-size: 20px; color: #1d2327;">
							<?php 
            esc_html_e( 'How to Create Your First Form', 'giraforms' );
            ?>
						</h3>

						<div class="giraforms-step" style="display: flex; align-items: flex-start; margin-bottom: 24px; padding: 20px; background: white; border-left: 4px solid #3858e9;">
							<div class="giraforms-step-number" style="flex-shrink: 0; width: 40px; height: 40px; background: #3858e9; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 18px; margin-right: 20px;">
								1
							</div>
							<div class="giraforms-step-content">
								<h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1d2327;">
									<?php 
            esc_html_e( 'Create a New Page or Post', 'giraforms' );
            ?>
								</h4>
								<p style="margin: 0; color: #646970; font-size: 14px; line-height: 1.5;">
									<?php 
            esc_html_e( 'Go to Pages > Add New (or Posts > Add New) to create a new page where your form will live.', 'giraforms' );
            ?>
								</p>
							</div>
						</div>

						<div class="giraforms-step" style="display: flex; align-items: flex-start; margin-bottom: 24px; padding: 20px; background: white; border-left: 4px solid #3858e9;">
							<div class="giraforms-step-number" style="flex-shrink: 0; width: 40px; height: 40px; background: #3858e9; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 18px; margin-right: 20px;">
								2
							</div>
							<div class="giraforms-step-content">
								<h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1d2327;">
									<?php 
            esc_html_e( 'Add the Form Container Block', 'giraforms' );
            ?>
								</h4>
								<p style="margin: 0; color: #646970; font-size: 14px; line-height: 1.5;">
									<?php 
            esc_html_e( 'Click the (+) button in the editor, search for "Form Container" and add it to your page.', 'giraforms' );
            ?>
								</p>
							</div>
						</div>

						<div class="giraforms-step" style="display: flex; align-items: flex-start; margin-bottom: 24px; padding: 20px; background: white; border-left: 4px solid #3858e9;">
							<div class="giraforms-step-number" style="flex-shrink: 0; width: 40px; height: 40px; background: #3858e9; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 18px; margin-right: 20px;">
								3
							</div>
							<div class="giraforms-step-content">
								<h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1d2327;">
									<?php 
            esc_html_e( 'Add Form Fields', 'giraforms' );
            ?>
								</h4>
								<p style="margin: 0; color: #646970; font-size: 14px; line-height: 1.5;">
									<?php 
            esc_html_e( 'Inside the Form Container, add field blocks like Text Field, Email Field, Textarea, etc.', 'giraforms' );
            ?>
								</p>
							</div>
						</div>

						<div class="giraforms-step" style="display: flex; align-items: flex-start; padding: 20px; background: white; border-left: 4px solid #3858e9;">
							<div class="giraforms-step-number" style="flex-shrink: 0; width: 40px; height: 40px; background: #3858e9; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 18px; margin-right: 20px;">
								4
							</div>
							<div class="giraforms-step-content">
								<h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1d2327;">
									<?php 
            esc_html_e( 'Publish and Test', 'giraforms' );
            ?>
								</h4>
								<p style="margin: 0; color: #646970; font-size: 14px; line-height: 1.5;">
									<?php 
            esc_html_e( 'Publish your page and submit a test entry. Your submissions will appear here!', 'giraforms' );
            ?>
								</p>
							</div>
						</div>
					</div>

					<!-- Quick Actions -->
					<div class="giraforms-quick-actions" style="display: flex; gap: 16px; justify-content: center; flex-wrap: wrap;">
						<a href="<?php 
            echo esc_url( admin_url( 'post-new.php?post_type=page&giraforms_add_form=1' ) );
            ?>" class="button button-primary button-hero" style="display:flex;align-items:center;gap:8px;">
							<span class="dashicons dashicons-plus-alt"></span>
							<?php 
            esc_html_e( 'Create Your First Form', 'giraforms' );
            ?>
						</a>
					</div>

					<!-- Additional Resources -->
					<div class="giraforms-resources" style="margin-top: 40px; padding-top: 30px; border-top: 1px solid #dcdcde;">
						<p style="color: #646970; font-size: 14px; margin-bottom: 16px;">
							<?php 
            esc_html_e( 'Need help? Check out these resources:', 'giraforms' );
            ?>
						</p>
						<div style="display: flex; gap: 24px; justify-content: center; flex-wrap: wrap; font-size: 14px;">
							<a href="<?php 
            echo esc_url( admin_url( 'admin.php?page=giraforms-settings' ) );
            ?>" style="color: #2271b1; text-decoration: none;">
								<span class="dashicons dashicons-admin-settings" style="vertical-align: middle;"></span>
								<?php 
            esc_html_e( 'Plugin Settings', 'giraforms' );
            ?>
							</a>
							<a href="https://giraforms.com/docs" target="_blank" style="color: #2271b1; text-decoration: none;">
								<span class="dashicons dashicons-book" style="vertical-align: middle;"></span>
								<?php 
            esc_html_e( 'Documentation', 'giraforms' );
            ?>
							</a>
						</div>
					</div>
				</div>
			<?php 
        } else {
            ?>
				<div class="giraforms-forms-grid" style="margin-top: 20px;">
					<?php 
            foreach ( $forms as $form ) {
                ?>
						<?php 
                $has_booking = false;
                ?>
						<?php 
                // Get post info if available
                $post = null;
                $post_info = '';
                if ( !empty( $form['post_id'] ) ) {
                    $post = get_post( $form['post_id'] );
                    if ( $post ) {
                        $post_title = ( $post->post_title ? $post->post_title : __( '(no title)', 'giraforms' ) );
                        $edit_url = get_edit_post_link( $form['post_id'] );
                        if ( $edit_url ) {
                            $post_info = sprintf( '<a href="%s" target="_blank" style="color: #2271b1; text-decoration: none;">%s <span class="dashicons dashicons-external" style="vertical-align: middle;"></span></a>', esc_url( $edit_url ), esc_html( $post_title ) );
                        } else {
                            $post_info = esc_html( $post_title );
                        }
                    }
                }
                ?>
						<div class="giraforms-form-card">
							<div class="giraforms-form-card-header">
								<h2>
									<a href="<?php 
                echo esc_url( admin_url( 'admin.php?page=giraforms-submissions&form_id=' . urlencode( $form['form_id'] ) ) );
                ?>">
										<?php 
                echo esc_html( $form['form_name'] );
                ?>
									</a>
								</h2>
								<div class="giraforms-form-meta">
									<p class="giraforms-form-id">
										<code><?php 
                echo esc_html( $form['form_id'] );
                ?></code>
									</p>
									<?php 
                if ( $post_info ) {
                    ?>
										<p class="giraforms-form-location">
											<span class="dashicons dashicons-admin-page" style="vertical-align: middle; color: #646970;"></span>
											<?php 
                    echo wp_kses_post( $post_info );
                    ?>
										</p>
									<?php 
                }
                ?>
								</div>
							</div>

							<div class="giraforms-form-card-stats">
								<div class="giraforms-stat">
									<span class="giraforms-stat-icon"><span class="dashicons dashicons-chart-bar"></span></span>
									<div class="giraforms-stat-content">
										<span class="giraforms-stat-value"><?php 
                echo esc_html( $form['total'] );
                ?></span>
										<span class="giraforms-stat-label"><?php 
                esc_html_e( 'Total Submissions', 'giraforms' );
                ?></span>
									</div>
								</div>

								<?php 
                if ( $form['unread'] > 0 ) {
                    ?>
									<div class="giraforms-stat">
										<span class="giraforms-stat-icon"><span class="dashicons dashicons-bell"></span></span>
										<div class="giraforms-stat-content">
											<span class="giraforms-stat-value giraforms-stat-unread"><?php 
                    echo esc_html( $form['unread'] );
                    ?></span>
											<span class="giraforms-stat-label"><?php 
                    esc_html_e( 'Unread', 'giraforms' );
                    ?></span>
										</div>
									</div>
								<?php 
                }
                ?>

								<div class="giraforms-stat">
									<span class="giraforms-stat-icon"><span class="dashicons dashicons-calendar-alt"></span></span>
									<div class="giraforms-stat-content">
										<span class="giraforms-stat-value"><?php 
                echo esc_html( human_time_diff( strtotime( $form['latest_submission'] ), current_time( 'timestamp' ) ) );
                ?></span>
										<span class="giraforms-stat-label"><?php 
                esc_html_e( 'Latest submission', 'giraforms' );
                ?></span>
									</div>
								</div>
							</div>

							<div class="giraforms-form-card-actions">
								<a href="<?php 
                echo esc_url( admin_url( 'admin.php?page=giraforms-submissions&form_id=' . urlencode( $form['form_id'] ) ) );
                ?>" class="button button-primary">
									<?php 
                esc_html_e( 'View Submissions', 'giraforms' );
                ?>
									<span class="dashicons dashicons-arrow-right-alt2"></span>
								</a>
								<?php 
                ?>
								<a href="<?php 
                echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=giraforms-submissions&action=export&form_id=' . urlencode( $form['form_id'] ) ), 'giraforms_export_csv' ) );
                ?>" class="button">
									&#8595; <?php 
                esc_html_e( 'Export CSV', 'giraforms' );
                ?>
								</a>
							</div>
						</div>
					<?php 
            }
            ?>
				</div>
			<?php 
        }
        ?>
		</div>
		<?php 
    }

    /**
     * Render submissions for a specific form.
     */
    private function render_form_submissions() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- This is a navigation parameter, validated in render_submissions_page().
        $form_id = ( isset( $_GET['form_id'] ) ? sanitize_text_field( wp_unslash( $_GET['form_id'] ) ) : '' );
        require_once GIRAFORMS_PLUGIN_DIR . 'includes/admin/class-submissions-list.php';
        $list_table = new GiraForms_Submissions_List();
        $list_table->prepare_items();
        // Get form stats
        $stats = GiraForms_Submissions::get_form_stats( $form_id );
        // Get form name from latest submission
        $submissions = GiraForms_Submissions::get_submissions( array(
            'form_id' => $form_id,
            'limit'   => 1,
        ) );
        $form_name = ( !empty( $submissions ) ? $submissions[0]['form_name'] : $form_id );
        $post_id = ( !empty( $submissions ) ? $submissions[0]['post_id'] : 0 );
        $has_booking = false;
        ?>
		<div class="wrap">
			<h1 class="wp-heading-inline">
				<?php 
        echo esc_html( $form_name );
        ?>
				<span style="color: #666; font-size: 0.7em; font-weight: normal;">
					(<?php 
        echo esc_html( $form_id );
        ?>)
				</span>
				<?php 
        ?>
			</h1>
			<div class="giraforms-submission-actions">
				<a href="<?php 
        echo esc_url( admin_url( 'admin.php?page=giraforms-submissions' ) );
        ?>" class="button">
					<span class="dashicons dashicons-arrow-left-alt2" style="margin-top: 3px;"></span>
					<?php 
        esc_html_e( 'Back to Forms', 'giraforms' );
        ?>
				</a>
				<?php 
        ?>
				<a href="<?php 
        echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=giraforms-submissions&action=export&form_id=' . urlencode( $form_id ) ), 'giraforms_export_csv' ) );
        ?>" class="button">
					&#8595; <?php 
        esc_html_e( 'Export CSV', 'giraforms' );
        ?>
				</a>
			</div>
			<hr class="wp-header-end">

			<?php 
        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        $notices = array(
            'archived'       => ( isset( $_GET['archived'] ) ? absint( $_GET['archived'] ) : 0 ),
            'unarchived'     => ( isset( $_GET['unarchived'] ) ? absint( $_GET['unarchived'] ) : 0 ),
            'marked_spam'    => ( isset( $_GET['marked_spam'] ) ? absint( $_GET['marked_spam'] ) : 0 ),
            'unmarked_spam'  => ( isset( $_GET['unmarked_spam'] ) ? absint( $_GET['unmarked_spam'] ) : 0 ),
            'deleted'        => isset( $_GET['deleted'] ),
            'status_updated' => ( isset( $_GET['status_updated'] ) ? sanitize_key( wp_unslash( $_GET['status_updated'] ) ) : '' ),
        );
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        if ( $notices['archived'] ) {
            printf( '<div class="notice notice-success is-dismissible"><p>%s</p></div>', esc_html( ( 1 === $notices['archived'] ? __( 'Submission archived successfully.', 'giraforms' ) : sprintf( 
                /* translators: %d: number of submissions archived */
                __( '%d submissions archived successfully.', 'giraforms' ),
                $notices['archived']
             ) ) ) );
        }
        if ( $notices['unarchived'] ) {
            printf( '<div class="notice notice-success is-dismissible"><p>%s</p></div>', esc_html( ( 1 === $notices['unarchived'] ? __( 'Submission unarchived successfully.', 'giraforms' ) : sprintf( 
                /* translators: %d: number of submissions unarchived */
                __( '%d submissions unarchived successfully.', 'giraforms' ),
                $notices['unarchived']
             ) ) ) );
        }
        if ( $notices['marked_spam'] ) {
            printf( '<div class="notice notice-success is-dismissible"><p>%s</p></div>', esc_html( ( 1 === $notices['marked_spam'] ? __( 'Submission marked as spam successfully.', 'giraforms' ) : sprintf( 
                /* translators: %d: number of submissions marked as spam */
                __( '%d submissions marked as spam successfully.', 'giraforms' ),
                $notices['marked_spam']
             ) ) ) );
        }
        if ( $notices['unmarked_spam'] ) {
            printf( '<div class="notice notice-success is-dismissible"><p>%s</p></div>', esc_html( ( 1 === $notices['unmarked_spam'] ? __( 'Submission unmarked as spam successfully.', 'giraforms' ) : sprintf( 
                /* translators: %d: number of submissions unmarked as spam */
                __( '%d submissions unmarked as spam successfully.', 'giraforms' ),
                $notices['unmarked_spam']
             ) ) ) );
        }
        if ( $notices['status_updated'] ) {
            $status_labels = array(
                'read'   => __( 'read', 'giraforms' ),
                'unread' => __( 'unread', 'giraforms' ),
            );
            $label = ( isset( $status_labels[$notices['status_updated']] ) ? $status_labels[$notices['status_updated']] : $notices['status_updated'] );
            printf( '<div class="notice notice-success is-dismissible"><p>%s</p></div>', sprintf( 
                /* translators: %s: status label */
                esc_html__( 'Status updated to %s successfully.', 'giraforms' ),
                '<strong>' . esc_html( $label ) . '</strong>'
             ) );
        }
        if ( $notices['deleted'] ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Submission deleted successfully.', 'giraforms' ) . '</p></div>';
        }
        ?>

			<!-- Stats Cards -->
			<div class="giraforms-info-cards" style="margin: 20px 0;">
				<div class="giraforms-info-card">
					<span class="giraforms-info-card-label">
						<span class="giraforms-info-card-icon dashicons dashicons-chart-bar"></span>
						<?php 
        esc_html_e( 'Total Submissions', 'giraforms' );
        ?>
					</span>
					<span class="giraforms-info-card-value"><?php 
        echo esc_html( $stats['total'] );
        ?></span>
				</div>

				<div class="giraforms-info-card">
					<span class="giraforms-info-card-label">
						<span class="giraforms-info-card-icon dashicons dashicons-bell"></span>
						<?php 
        esc_html_e( 'Unread', 'giraforms' );
        ?>
					</span>
					<span class="giraforms-info-card-value"><?php 
        echo esc_html( $stats['unread'] );
        ?></span>
				</div>

				<div class="giraforms-info-card">
					<span class="giraforms-info-card-label">
						<span class="giraforms-info-card-icon dashicons dashicons-yes-alt"></span>
						<?php 
        esc_html_e( 'Read', 'giraforms' );
        ?>
					</span>
					<span class="giraforms-info-card-value"><?php 
        echo esc_html( $stats['read'] );
        ?></span>
				</div>

				<?php 
        ?>
			</div>

			<form method="get">
				<input type="hidden" name="page" value="giraforms-submissions" />
				<?php 
        if ( !empty( $form_id ) ) {
            ?>
					<input type="hidden" name="form_id" value="<?php 
            echo esc_attr( $form_id );
            ?>" />
				<?php 
        }
        ?>
				<?php 
        $list_table->display();
        ?>
			</form>
		</div>
		<?php 
    }

    /**
     * Render single submission.
     */
    private function render_single_submission() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- This is a navigation parameter, validated in render_submissions_page().
        $submission_id = ( isset( $_GET['submission_id'] ) ? intval( $_GET['submission_id'] ) : 0 );
        $submission = GiraForms_Submissions::get_submission( $submission_id );
        if ( !$submission ) {
            echo '<div class="wrap"><p>' . esc_html__( 'Submission not found.', 'giraforms' ) . '</p></div>';
            return;
        }
        // Handle status update
        if ( isset( $_POST['update_status'] ) && isset( $_POST['status'] ) && check_admin_referer( 'giraforms_update_status_' . $submission_id ) ) {
            $new_status = sanitize_text_field( wp_unslash( $_POST['status'] ) );
            $allowed_statuses = array('unread', 'read');
            if ( in_array( $new_status, $allowed_statuses, true ) ) {
                GiraForms_Submissions::update_status( $submission_id, $new_status );
                $submission['status'] = $new_status;
                echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Status updated successfully.', 'giraforms' ) . '</p></div>';
            }
        }
        // Mark as read (only if not manually updating status)
        if ( !isset( $_POST['update_status'] ) && $submission['status'] === 'unread' ) {
            GiraForms_Submissions::update_status( $submission_id, 'read' );
            $submission['status'] = 'read';
        }
        ?>
		<div class="wrap giraforms-submission-detail">
			<div class="giraforms-submission-header">
				<h1 class="giraforms-page-header-title"><?php 
        esc_html_e( 'Submission Details', 'giraforms' );
        ?></h1>
				<div class="giraforms-submission-actions">
					<a href="<?php 
        echo esc_url( admin_url( 'admin.php?page=giraforms-submissions' ) );
        ?>" class="button" style="display: flex;align-items: center;gap: 3px;">
						<span class="dashicons dashicons-arrow-left-alt2"></span>
						<?php 
        esc_html_e( 'Back', 'giraforms' );
        ?>
					</a>
				</div>
			</div>

			<!-- Info Cards -->
			<div class="giraforms-info-cards">
				<div class="giraforms-info-card">
					<span class="giraforms-info-card-label">
						<span class="giraforms-info-card-icon dashicons dashicons-id"></span>
						<?php 
        esc_html_e( 'Submission ID', 'giraforms' );
        ?>
					</span>
					<span class="giraforms-info-card-value">#<?php 
        echo esc_html( $submission['id'] );
        ?></span>
				</div>

				<div class="giraforms-info-card">
					<span class="giraforms-info-card-label">
						<span class="giraforms-info-card-icon dashicons dashicons-feedback"></span>
						<?php 
        esc_html_e( 'Form', 'giraforms' );
        ?>
					</span>
					<span class="giraforms-info-card-value">
						<?php 
        echo esc_html( $submission['form_name'] );
        ?>
						<?php 
        if ( $submission['post_id'] ) {
            ?>
							<?php 
            $post = get_post( $submission['post_id'] );
            if ( $post ) {
                ?>
								<br>
								<a href="<?php 
                echo esc_url( get_permalink( $post->ID ) );
                ?>" target="_blank" style="font-size: 13px; color: #646970; text-decoration: none; display: flex; align-items: center;">
									<span class="dashicons dashicons-admin-page" style="font-size: 14px;display: flex;align-items: center;"></span>
									<?php 
                echo esc_html( $post->post_title );
                ?>
								</a>
							<?php 
            }
            ?>
						<?php 
        }
        ?>
					</span>
				</div>

				<div class="giraforms-info-card">
					<span class="giraforms-info-card-label">
						<span class="giraforms-info-card-icon dashicons dashicons-calendar-alt"></span>
						<?php 
        esc_html_e( 'Submission Date', 'giraforms' );
        ?>
					</span>
					<span class="giraforms-info-card-value"><?php 
        echo esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $submission['created_at'] ) ) );
        ?></span>
				</div>

				<div class="giraforms-info-card">
					<span class="giraforms-info-card-label">
						<span class="giraforms-info-card-icon dashicons dashicons-lock"></span>
						<?php 
        esc_html_e( 'Status', 'giraforms' );
        ?>
					</span>
					<span class="giraforms-info-card-value">
						<form method="post" class="giraforms-status-update-form">
							<?php 
        wp_nonce_field( 'giraforms_update_status_' . $submission_id );
        ?>
							<select name="status" class="giraforms-status-select" style="padding: 4px 32px 4px 8px; border-radius: 4px; border: 1px solid #ddd;">
								<option value="unread" <?php 
        selected( $submission['status'], 'unread' );
        ?>><?php 
        esc_html_e( 'Unread', 'giraforms' );
        ?></option>
								<option value="read" <?php 
        selected( $submission['status'], 'read' );
        ?>><?php 
        esc_html_e( 'Read', 'giraforms' );
        ?></option>
								<?php 
        ?>
							</select>
							<button type="submit" name="update_status" class="button button-small" style="padding: 4px 12px; height: auto;">
								<?php 
        esc_html_e( 'Update', 'giraforms' );
        ?>
							</button>
						</form>
					</span>
				</div>
			</div>

			<!-- Form Data -->
			<div class="giraforms-form-data-header">
				<h2><?php 
        esc_html_e( 'Form Data', 'giraforms' );
        ?></h2>
			</div>
			<div class="giraforms-form-data">
				<table>
					<?php 
        // Get field labels from submission meta first (stored at submission time)
        $stored_labels = ( isset( $submission['data']['_field_labels'] ) ? $this->normalize_submission_field_labels( $submission['data']['_field_labels'] ) : array() );
        // Fallback: get field labels from the form post (for older submissions)
        $field_labels = $this->get_field_labels( $submission['post_id'] );
        // Merge: stored labels take priority, then post labels
        $all_labels = array_merge( $field_labels, $stored_labels );
        // Get email fields info (including sendConfirmation setting)
        $email_fields = $this->get_email_fields_info( $submission['post_id'] );
        foreach ( $submission['data'] as $key => $value ) {
            if ( strpos( $key, 'giraforms_' ) === 0 || strpos( $key, '_' ) === 0 || strpos( $key, 'booking-slot-' ) === 0 ) {
                continue;
            }
            // Remove [] suffix for checkbox/radio fields when looking up label
            $label_key = str_replace( '[]', '', $key );
            // Use field label if available, otherwise use field ID
            $label = ( isset( $all_labels[$label_key] ) ? $all_labels[$label_key] : '' );
            if ( '' === $label || $label === $label_key ) {
                $label = $this->get_default_label_from_field_key( $label_key );
            }
            if ( '' === $label ) {
                $label = $key;
            }
            // Check if this is an email field
            $is_email_field = isset( $email_fields[$key] );
            $send_confirmation = ( $is_email_field && isset( $email_fields[$key]['sendConfirmation'] ) ? $email_fields[$key]['sendConfirmation'] : false );
            ?>
						<tr>
							<th>
								<?php 
            echo esc_html( $label );
            ?>
								<br><small style="color: #666; font-weight: normal; font-size: 11px;"><?php 
            echo esc_html( $key );
            ?></small>
							</th>
							<td>
								<?php 
            if ( is_array( $value ) ) {
                echo esc_html( implode( ', ', $value ) );
            } else {
                echo nl2br( esc_html( $value ) );
            }
            // Display confirmation email status for email fields
            if ( $is_email_field && filter_var( $value, FILTER_VALIDATE_EMAIL ) ) {
                if ( $send_confirmation ) {
                    echo '<div style="margin-top: 8px; padding: 6px 10px; background: #d5f4e6; border-left: 3px solid #00a32a; font-size: 12px; color: #00502a;">';
                    echo '<span class="dashicons dashicons-yes-alt" style="display: inline; font-size: 14px; vertical-align: middle; margin-right: 4px;"></span>';
                    echo esc_html__( 'Confirmation email sent', 'giraforms' );
                    echo '</div>';
                } else {
                    echo '<div style="margin-top: 8px; padding: 6px 10px; background: #f0f0f1; border-left: 3px solid #8c8f94; font-size: 12px; color: #50575e;">';
                    echo '<span class="dashicons dashicons-info" style="display: inline; font-size: 14px; vertical-align: middle; margin-right: 4px;"></span>';
                    echo esc_html__( 'No confirmation email sent', 'giraforms' );
                    echo '</div>';
                }
            }
            ?>
							</td>
						</tr>
					<?php 
        }
        ?>
				</table>
			</div>

		<!-- Payment Information -->
		<?php 
        ?>

		<!-- Uploaded Files -->
		<?php 
        ?>

		<!-- Technical Information -->
		<div class="giraforms-technical-info" style="background: #f9f9f9; border: 1px solid #e0e0e0; border-radius: 8px; padding: 16px; margin: 20px 0;">
			<h3 style="margin: 0 0 12px 0; font-size: 13px; font-weight: 600; color: #646970; text-transform: uppercase; letter-spacing: 0.5px;">
				<?php 
        esc_html_e( 'Technical Information', 'giraforms' );
        ?>
			</h3>
			<div style="display: grid; gap: 8px; font-size: 13px;">
				<div style="display: flex; gap: 8px;">
					<span style="color: #646970; min-width: 80px; font-weight: 500;">
						<?php 
        esc_html_e( 'IP Address:', 'giraforms' );
        ?>
					</span>
					<span style="color: #2c3338; font-family: monospace;">
						<?php 
        echo esc_html( ( !empty( $submission['user_ip'] ) ? $submission['user_ip'] : '-' ) );
        ?>
					</span>
				</div>
				<div style="display: flex; gap: 8px;">
					<span style="color: #646970; min-width: 80px; font-weight: 500;">
						<?php 
        esc_html_e( 'User Agent:', 'giraforms' );
        ?>
					</span>
					<span style="color: #2c3338; font-size: 12px; word-break: break-all; font-family: monospace;">
						<?php 
        echo esc_html( ( !empty( $submission['user_agent'] ) ? $submission['user_agent'] : '-' ) );
        ?>
					</span>
				</div>
			</div>
		</div>

		<!-- Danger Zone -->
			<div class="giraforms-danger-zone">
				<h3><?php 
        esc_html_e( 'Danger Zone', 'giraforms' );
        ?></h3>
				<p><?php 
        esc_html_e( 'Deleting this submission is permanent and cannot be undone.', 'giraforms' );
        ?></p>
				<a href="<?php 
        echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=giraforms-submissions&action=delete&submission_id=' . $submission_id ), 'delete_submission_' . $submission_id ) );
        ?>"
				   class="button button-small giraforms-danger-btn"
				   style="background: rgba(209,62,62,0.06); color: #a00; border: 1px solid rgba(209,62,62,0.12); box-shadow: none; padding: 4px 8px;"
				   onclick="return confirm('<?php 
        echo esc_js( __( 'Are you sure you want to permanently delete this submission? This action is irreversible.', 'giraforms' ) );
        ?>')">
					<span class="dashicons dashicons-trash" style="margin-top: 2px; color: #a00;"></span>
					<?php 
        esc_html_e( 'Delete this submission', 'giraforms' );
        ?>
				</a>
			</div>
		</div>
		<?php 
    }

    /**
     * Handle export requests.
     */
    public function handle_export() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification is done in export_to_csv method.
        if ( !isset( $_GET['page'] ) || $_GET['page'] !== 'giraforms-submissions' ) {
            return;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification is done in export_to_csv method.
        if ( !isset( $_GET['action'] ) || $_GET['action'] !== 'export' ) {
            return;
        }
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification is done in export_to_csv method.
        $form_id = ( isset( $_GET['form_id'] ) ? sanitize_text_field( wp_unslash( $_GET['form_id'] ) ) : '' );
        GiraForms_Export::export_to_csv( $form_id );
    }

    /**
     * Process bulk actions.
     *
     * @param string $action The bulk action to process.
     */
    private function process_bulk_action( $action ) {
        if ( !isset( $_REQUEST['submission'] ) || !is_array( $_REQUEST['submission'] ) ) {
            return;
        }
        // Verify nonce for bulk actions
        if ( !isset( $_REQUEST['_wpnonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) ), 'bulk-submissions' ) ) {
            wp_die( esc_html__( 'Security check failed.', 'giraforms' ) );
        }
        // Check user permissions
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have permission to perform this action.', 'giraforms' ) );
        }
        $submission_ids = array_map( 'intval', $_REQUEST['submission'] );
        $form_id = ( isset( $_GET['form_id'] ) ? sanitize_text_field( wp_unslash( $_GET['form_id'] ) ) : '' );
        switch ( $action ) {
            case 'delete':
                foreach ( $submission_ids as $submission_id ) {
                    GiraForms_Submissions::delete_submission( $submission_id );
                }
                $redirect_url = admin_url( 'admin.php?page=giraforms-submissions&deleted=' . count( $submission_ids ) );
                if ( $form_id ) {
                    $redirect_url = add_query_arg( 'form_id', $form_id, $redirect_url );
                }
                wp_safe_redirect( $redirect_url );
                exit;
            case 'read':
                foreach ( $submission_ids as $submission_id ) {
                    GiraForms_Submissions::update_status( $submission_id, 'read' );
                }
                $redirect_url = admin_url( 'admin.php?page=giraforms-submissions&status_updated=read' );
                if ( $form_id ) {
                    $redirect_url = add_query_arg( 'form_id', $form_id, $redirect_url );
                }
                wp_safe_redirect( $redirect_url );
                exit;
            case 'unread':
                foreach ( $submission_ids as $submission_id ) {
                    GiraForms_Submissions::update_status( $submission_id, 'unread' );
                }
                $redirect_url = admin_url( 'admin.php?page=giraforms-submissions&status_updated=unread' );
                if ( $form_id ) {
                    $redirect_url = add_query_arg( 'form_id', $form_id, $redirect_url );
                }
                wp_safe_redirect( $redirect_url );
                exit;
            case 'archive':
                break;
            case 'unarchive':
                break;
            case 'mark_spam':
                break;
            case 'unmark_spam':
                break;
        }
    }

    /**
     * Handle admin actions.
     */
    public function handle_actions() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Initial check only, nonce verified below for each action.
        if ( !isset( $_GET['page'] ) || strpos( $_GET['page'], 'giraforms' ) === false ) {
            return;
        }
        // Handle bulk actions from WP_List_Table
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verified in process_bulk_action.
        if ( isset( $_REQUEST['action'] ) && $_REQUEST['action'] !== '-1' ) {
            $this->process_bulk_action( sanitize_text_field( wp_unslash( $_REQUEST['action'] ) ) );
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verified in process_bulk_action.
        if ( isset( $_REQUEST['action2'] ) && $_REQUEST['action2'] !== '-1' ) {
            $this->process_bulk_action( sanitize_text_field( wp_unslash( $_REQUEST['action2'] ) ) );
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verified below for each specific action.
        if ( !isset( $_GET['action'] ) ) {
            return;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verified below for each specific action.
        $action = sanitize_text_field( wp_unslash( $_GET['action'] ) );
        // Delete submission
        if ( $action === 'delete' && isset( $_GET['submission_id'] ) ) {
            $submission_id = intval( $_GET['submission_id'] );
            if ( !wp_verify_nonce( ( isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '' ), 'delete_submission_' . $submission_id ) ) {
                wp_die( esc_html__( 'Security error.', 'giraforms' ) );
            }
            if ( GiraForms_Submissions::delete_submission( $submission_id ) ) {
                wp_safe_redirect( admin_url( 'admin.php?page=giraforms-submissions&deleted=1' ) );
                exit;
            }
        }
    }

    /**
     * Get field labels from post content.
     *
     * @param int $post_id Post ID.
     * @return array Field labels keyed by field ID.
     */
    private function get_field_labels( $post_id ) {
        $labels = array();
        if ( !$post_id ) {
            return $labels;
        }
        $post = get_post( $post_id );
        if ( !$post || !has_blocks( $post->post_content ) ) {
            return $labels;
        }
        $blocks = parse_blocks( $post->post_content );
        $this->extract_field_labels( $blocks, $labels );
        return $labels;
    }

    /**
     * Remove invalid stored labels so admin views can fall back to human-readable names.
     *
     * @param mixed $labels Stored labels array.
     * @return array
     */
    private function normalize_submission_field_labels( $labels ) {
        if ( !is_array( $labels ) ) {
            return array();
        }
        $normalized = array();
        foreach ( $labels as $field_key => $label ) {
            if ( !is_string( $field_key ) || !is_scalar( $label ) ) {
                continue;
            }
            $clean_label = trim( wp_strip_all_tags( (string) $label ) );
            if ( '' === $clean_label || $clean_label === $field_key ) {
                continue;
            }
            $normalized[$field_key] = $clean_label;
        }
        return $normalized;
    }

    /**
     * Infer a readable label from a field key when no saved label is available.
     *
     * @param string $field_key Field name/ID.
     * @return string
     */
    private function get_default_label_from_field_key( $field_key ) {
        $field_key = str_replace( '[]', '', (string) $field_key );
        if ( !preg_match( '/^([a-z]+)_/', $field_key, $matches ) ) {
            return '';
        }
        $prefix = $matches[1];
        $labels = array(
            'text'        => __( 'Text', 'giraforms' ),
            'textarea'    => __( 'Message', 'giraforms' ),
            'email'       => __( 'Email', 'giraforms' ),
            'phone'       => __( 'Phone', 'giraforms' ),
            'select'      => __( 'Select', 'giraforms' ),
            'checkbox'    => __( 'Select your choices', 'giraforms' ),
            'radio'       => __( 'Choose an option', 'giraforms' ),
            'date'        => __( 'Date', 'giraforms' ),
            'time'        => __( 'Time', 'giraforms' ),
            'number'      => __( 'Number', 'giraforms' ),
            'url'         => __( 'URL', 'giraforms' ),
            'password'    => __( 'Password', 'giraforms' ),
            'range'       => __( 'Range', 'giraforms' ),
            'color'       => __( 'Color', 'giraforms' ),
            'consent'     => __( 'Consent', 'giraforms' ),
            'hidden'      => __( 'Hidden Field', 'giraforms' ),
            'booking'     => __( 'Booking', 'giraforms' ),
            'file'        => __( 'File Upload', 'giraforms' ),
            'rating'      => __( 'Rating', 'giraforms' ),
            'captcha'     => __( 'Captcha', 'giraforms' ),
            'calendar'    => __( 'Calendar', 'giraforms' ),
            'currency'    => __( 'Amount', 'giraforms' ),
            'signature'   => __( 'Signature', 'giraforms' ),
            'geolocation' => __( 'Location', 'giraforms' ),
        );
        return ( isset( $labels[$prefix] ) ? $labels[$prefix] : '' );
    }

    /**
     * Recursively extract field labels from blocks.
     *
     * @param array $blocks Blocks array.
     * @param array &$labels Labels array (by reference).
     */
    private function extract_field_labels( $blocks, &$labels ) {
        // Default labels for free block types
        $default_labels = array(
            'giraforms/text-field'         => __( 'Text', 'giraforms' ),
            'giraforms/textarea-field'     => __( 'Message', 'giraforms' ),
            'giraforms/email-field'        => __( 'Email', 'giraforms' ),
            'giraforms/phone-field'        => __( 'Phone', 'giraforms' ),
            'giraforms/select-field'       => __( 'Select', 'giraforms' ),
            'giraforms/checkbox-field'     => __( 'Select your choices', 'giraforms' ),
            'giraforms/radio-field'        => __( 'Choose an option', 'giraforms' ),
            'giraforms/date-field'         => __( 'Date', 'giraforms' ),
            'giraforms/time-field'         => __( 'Time', 'giraforms' ),
            'giraforms/number-field'       => __( 'Number', 'giraforms' ),
            'giraforms/url-field'          => __( 'URL', 'giraforms' ),
            'giraforms/password-field'     => __( 'Password', 'giraforms' ),
            'giraforms/range-slider-field' => __( 'Range', 'giraforms' ),
            'giraforms/color-picker-field' => __( 'Color', 'giraforms' ),
            'giraforms/consent-field'      => __( 'Consent', 'giraforms' ),
            'giraforms/hidden-field'       => __( 'Hidden Field', 'giraforms' ),
        );
        foreach ( $blocks as $block ) {
            // Check if this is a form field block (giraforms namespace)
            if ( isset( $block['blockName'] ) && strpos( $block['blockName'], 'giraforms/' ) === 0 ) {
                // Check if block has fieldId
                if ( !empty( $block['attrs']['fieldId'] ) ) {
                    $field_id = $block['attrs']['fieldId'];
                    $label = '';
                    // Get label from block attributes
                    if ( !empty( $block['attrs']['label'] ) ) {
                        $label = $block['attrs']['label'];
                    }
                    // If label is empty or equals the field ID, use default label
                    if ( empty( $label ) || $label === $field_id ) {
                        $block_type = $block['blockName'];
                        if ( isset( $default_labels[$block_type] ) ) {
                            $label = $default_labels[$block_type];
                        } else {
                            // Fallback: use block name without namespace
                            $label = str_replace( array('giraforms/', '-field', '-'), array('', '', ' '), $block_type );
                            $label = ucwords( $label );
                        }
                    }
                    if ( !empty( $label ) ) {
                        $labels[$field_id] = $label;
                    }
                }
            }
            // Recursively check inner blocks
            if ( !empty( $block['innerBlocks'] ) ) {
                $this->extract_field_labels( $block['innerBlocks'], $labels );
            }
        }
    }

    /**
     * Get email fields info from post content.
     *
     * @param int $post_id Post ID.
     * @return array Email fields info keyed by field ID.
     */
    private function get_email_fields_info( $post_id ) {
        $email_fields = array();
        if ( !$post_id ) {
            return $email_fields;
        }
        $post = get_post( $post_id );
        if ( !$post || !has_blocks( $post->post_content ) ) {
            return $email_fields;
        }
        $blocks = parse_blocks( $post->post_content );
        $this->extract_email_fields_info( $blocks, $email_fields );
        return $email_fields;
    }

    /**
     * Recursively extract email fields info from blocks.
     *
     * @param array $blocks Blocks array.
     * @param array &$email_fields Email fields array (by reference).
     */
    private function extract_email_fields_info( $blocks, &$email_fields ) {
        foreach ( $blocks as $block ) {
            // Check if this is an email field block
            if ( isset( $block['blockName'] ) && $block['blockName'] === 'giraforms/email-field' ) {
                // Get fieldId and sendConfirmation attribute
                if ( !empty( $block['attrs']['fieldId'] ) ) {
                    $email_fields[$block['attrs']['fieldId']] = array(
                        'sendConfirmation' => ( isset( $block['attrs']['sendConfirmation'] ) ? (bool) $block['attrs']['sendConfirmation'] : true ),
                    );
                }
            }
            // Recursively check inner blocks
            if ( !empty( $block['innerBlocks'] ) ) {
                $this->extract_email_fields_info( $block['innerBlocks'], $email_fields );
            }
        }
    }

}
