<?php

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

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

    /**
     * Constructor.
     */
    private function __construct() {
        // Email notifications are triggered from form handler
        add_action( 'wp_ajax_giraforms_send_test_email', array($this, 'ajax_send_test_email') );
    }

    /**
     * Handle AJAX request to send a test email.
     */
    public function ajax_send_test_email() {
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( __( 'Permission denied.', 'giraforms' ) );
        }
        check_ajax_referer( 'giraforms_test_email', 'nonce' );
        $settings = get_option( 'giraforms_settings', array() );
        $site_name = get_bloginfo( 'name' );
        // Build test data
        $test_data = array(
            'full_name_demo' => 'Jane Doe',
            'email_demo'     => 'jane.doe@example.com',
            'phone_demo'     => '+1 (555) 123-4567',
            'message_demo'   => 'This is a test submission to preview how your email notifications look.',
        );
        $test_fields = array(
            array(
                'name'  => 'full_name_demo',
                'type'  => 'text',
                'label' => __( 'Full Name', 'giraforms' ),
            ),
            array(
                'name'  => 'email_demo',
                'type'  => 'email',
                'label' => __( 'Email', 'giraforms' ),
            ),
            array(
                'name'  => 'phone_demo',
                'type'  => 'phone',
                'label' => __( 'Phone', 'giraforms' ),
            ),
            array(
                'name'  => 'message_demo',
                'type'  => 'textarea',
                'label' => __( 'Message', 'giraforms' ),
            )
        );
        $form_name = __( 'Contact Form (Test)', 'giraforms' );
        $page_title = __( 'My Page', 'giraforms' );
        $page_url = home_url();
        $message = $this->build_email_message(
            42,
            $test_data,
            $test_fields,
            $form_name,
            $page_title,
            $page_url
        );
        // Subject
        $subject = ( !empty( $settings['email_subject'] ) ? $settings['email_subject'] : __( 'New form submission', 'giraforms' ) );
        $subject = str_replace( '{form_name}', $form_name, $subject );
        $subject = str_replace( '{site_name}', $site_name, $subject );
        $subject = str_replace( '{submission_id}', '42', $subject );
        $subject = '[TEST] ' . $subject;
        // From
        $from_name = ( !empty( $settings['email_from_name'] ) ? $settings['email_from_name'] : $site_name );
        $from_address = ( !empty( $settings['email_from_address'] ) ? $settings['email_from_address'] : get_option( 'admin_email' ) );
        $headers = array('Content-Type: text/html; charset=UTF-8', 'From: ' . $from_name . ' <' . $from_address . '>');
        // Use configured notification emails, fallback to admin_email
        $notification_emails = ( !empty( $settings['notification_emails'] ) ? $settings['notification_emails'] : get_option( 'admin_email' ) );
        $email_addresses = array_map( 'trim', explode( "\n", $notification_emails ) );
        $email_addresses = array_filter( $email_addresses, 'is_email' );
        if ( empty( $email_addresses ) ) {
            $email_addresses = array(get_option( 'admin_email' ));
        }
        $sent = false;
        foreach ( $email_addresses as $to ) {
            if ( wp_mail(
                $to,
                $subject,
                $message,
                $headers
            ) ) {
                $sent = true;
            }
        }
        if ( $sent ) {
            $recipients = implode( ', ', $email_addresses );
            /* translators: %s: email address(es) */
            wp_send_json_success( sprintf( __( 'Test email sent to %s', 'giraforms' ), $recipients ) );
        } else {
            wp_send_json_error( __( 'Failed to send email. Check your server mail configuration.', 'giraforms' ) );
        }
    }

    /**
     * Send notifications.
     *
     * @param int    $submission_id Submission ID.
     * @param string $form_id Form ID.
     * @param array  $data Form data.
     * @param array  $fields Form fields configuration.
     */
    public function send_notifications(
        $submission_id,
        $form_id,
        $data,
        $fields,
        $form_attrs = array()
    ) {
        // Check if email notifications are enabled for this form
        $enable_notifications = ( isset( $data['giraforms_email_notifications'] ) ? $data['giraforms_email_notifications'] === 'true' : true );
        // Allow override via filter
        $enable_notifications = apply_filters(
            'giraforms_enable_notifications',
            $enable_notifications,
            $form_id,
            $data
        );
        if ( !$enable_notifications ) {
            return;
        }
        try {
            // Send admin notification
            $this->send_admin_notification(
                $submission_id,
                $form_id,
                $data,
                $fields,
                $form_attrs
            );
            // Send user confirmation (if email field exists)
            $this->send_user_confirmation(
                $submission_id,
                $form_id,
                $data,
                $fields
            );
        } catch ( Exception $e ) {
            // Log the error but don't block the submission
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Intentional error logging for email failures.
            error_log( 'Giraforms email error: ' . $e->getMessage() );
        }
    }

    /**
     * Send admin notification.
     *
     * @param int    $submission_id Submission ID.
     * @param string $form_id Form ID.
     * @param array  $data Form data.
     * @param array  $fields Form fields configuration.
     */
    private function send_admin_notification(
        $submission_id,
        $form_id,
        $data,
        $fields,
        $form_attrs = array()
    ) {
        // Per-form override (from trusted block attributes)
        $per_form_emails = ( isset( $form_attrs['notificationEmails'] ) ? trim( $form_attrs['notificationEmails'] ) : '' );
        if ( !empty( $per_form_emails ) ) {
            $notification_emails = $per_form_emails;
        } else {
            // Fallback to global settings
            $settings = get_option( 'giraforms_settings', array() );
            $notification_emails = ( isset( $settings['notification_emails'] ) ? $settings['notification_emails'] : '' );
            if ( empty( $notification_emails ) ) {
                $notification_emails = get_option( 'admin_email' );
            }
        }
        // Convert to array if multiple emails (one per line)
        $email_addresses = array_map( 'trim', explode( "\n", $notification_emails ) );
        $email_addresses = array_filter( $email_addresses, 'is_email' );
        if ( empty( $email_addresses ) ) {
            return;
            // No valid email addresses
        }
        // Allow custom admin email override via filter
        $email_addresses = apply_filters( 'giraforms_admin_email', $email_addresses, $form_id );
        $site_name = get_bloginfo( 'name' );
        $form_name = ( isset( $data['giraforms_name'] ) ? $data['giraforms_name'] : $form_id );
        // Get the post ID and page info
        $db = GiraForms_Database::instance();
        $submission = $db->get_submission( $submission_id );
        $post_id = ( $submission && isset( $submission->post_id ) ? intval( $submission->post_id ) : 0 );
        $page_title = '';
        $page_url = '';
        if ( $post_id > 0 ) {
            $page_title = get_the_title( $post_id );
            $page_url = get_permalink( $post_id );
        }
        // Check if a custom email template is selected
        $template_id = ( isset( $data['giraforms_email_template_id'] ) ? $data['giraforms_email_template_id'] : '' );
        $use_custom_template = false;
        $subject = '';
        $message = '';
        // Use default template if no custom template is used
        if ( !$use_custom_template ) {
            // Get subject from settings
            $subject = ( !empty( $settings['email_subject'] ) ? $settings['email_subject'] : __( 'New form submission', 'giraforms' ) );
            // Replace variables in subject
            $subject = str_replace( '{form_name}', $form_name, $subject );
            $subject = str_replace( '{site_name}', $site_name, $subject );
            $subject = str_replace( '{submission_id}', $submission_id, $subject );
            $message = $this->build_email_message(
                $submission_id,
                $data,
                $fields,
                $form_name,
                $page_title,
                $page_url
            );
        }
        // Set from name and email
        $from_name = ( !empty( $settings['email_from_name'] ) ? $settings['email_from_name'] : $site_name );
        $from_address = ( !empty( $settings['email_from_address'] ) ? $settings['email_from_address'] : get_option( 'admin_email' ) );
        $headers = array('Content-Type: text/html; charset=UTF-8', 'From: ' . $from_name . ' <' . $from_address . '>');
        // Send email to each recipient
        foreach ( $email_addresses as $email ) {
            wp_mail(
                $email,
                $subject,
                $message,
                $headers
            );
        }
    }

    /**
     * Send user confirmation email.
     *
     * @param int    $submission_id Submission ID.
     * @param string $form_id Form ID.
     * @param array  $data Form data.
     * @param array  $fields Form fields configuration.
     */
    private function send_user_confirmation(
        $submission_id,
        $form_id,
        $data,
        $fields
    ) {
        // Find email field
        $user_email = null;
        $email_field_id = null;
        foreach ( $fields as $field ) {
            if ( isset( $field['type'] ) && $field['type'] === 'email' && isset( $field['name'] ) ) {
                $field_name = $field['name'];
                if ( isset( $data[$field_name] ) && is_email( $data[$field_name] ) ) {
                    $user_email = $data[$field_name];
                    $email_field_id = $field_name;
                    break;
                }
            }
        }
        if ( !$user_email || !$email_field_id ) {
            return;
        }
        // Get the post ID to retrieve the actual block configuration from database (security)
        $db = GiraForms_Database::instance();
        $submission = $db->get_submission( $submission_id );
        $post_id = ( $submission && isset( $submission->post_id ) ? intval( $submission->post_id ) : 0 );
        // Retrieve sendConfirmation setting and template ID from the actual saved block (server-side, secure)
        $email_field_config = $this->get_email_field_config( $post_id, $form_id, $email_field_id );
        $send_confirmation_enabled = ( isset( $email_field_config['sendConfirmation'] ) ? $email_field_config['sendConfirmation'] : true );
        $confirmation_template_id = ( isset( $email_field_config['confirmationTemplateId'] ) ? $email_field_config['confirmationTemplateId'] : '' );
        // Check if confirmation is disabled for this specific email field
        if ( !$send_confirmation_enabled ) {
            return;
        }
        // Check if user confirmation is enabled (filter for backward compatibility)
        $send_confirmation = apply_filters( 'giraforms_send_user_confirmation', true, $form_id );
        if ( !$send_confirmation ) {
            return;
        }
        $site_name = get_bloginfo( 'name' );
        $form_name = ( isset( $data['giraforms_name'] ) ? $data['giraforms_name'] : $form_id );
        // Get page title for template variables
        $page_title = '';
        if ( $post_id > 0 ) {
            $page_title = get_the_title( $post_id );
        }
        // Check if a custom email template is selected
        $use_custom_template = false;
        $subject = '';
        $message = '';
        // Use default template if no custom template is used
        if ( !$use_custom_template ) {
            $subject = sprintf( 
                /* translators: %s: site name */
                __( 'Form submission confirmation - %s', 'giraforms' ),
                $site_name
             );
            $message = $this->build_confirmation_message( $submission_id, $data, $fields );
        }
        // Set HTML content type
        add_filter( 'wp_mail_content_type', array($this, 'set_html_content_type') );
        // Send email
        wp_mail( $user_email, $subject, $message );
        // Reset content type
        remove_filter( 'wp_mail_content_type', array($this, 'set_html_content_type') );
    }

    /**
     * Build email message for admin.
     *
     * @param int    $submission_id Submission ID.
     * @param array  $data Form data.
     * @param array  $fields Form fields configuration.
     * @param string $form_name Form name.
     * @param string $page_title Page title.
     * @param string $page_url Page URL.
     * @return string
     */
    private function build_email_message(
        $submission_id,
        $data,
        $fields,
        $form_name = '',
        $page_title = '',
        $page_url = ''
    ) {
        $styles = $this->get_email_styles();
        $message = '<html><head><style>' . $styles . '</style></head><body>';
        $message .= '<div class="email-container">';
        $message .= '<h2>' . __( 'New form submission', 'giraforms' ) . '</h2>';
        $message .= '<div class="meta-info">';
        if ( !empty( $form_name ) ) {
            $message .= '<p><strong>' . __( 'Form name:', 'giraforms' ) . '</strong> ' . esc_html( $form_name ) . '</p>';
        }
        if ( !empty( $page_title ) ) {
            if ( !empty( $page_url ) ) {
                $message .= '<p><strong>' . __( 'Page:', 'giraforms' ) . '</strong> <a href="' . esc_url( $page_url ) . '">' . esc_html( $page_title ) . '</a></p>';
            } else {
                $message .= '<p><strong>' . __( 'Page:', 'giraforms' ) . '</strong> ' . esc_html( $page_title ) . '</p>';
            }
        }
        $message .= '<p><strong>' . __( 'Submission ID:', 'giraforms' ) . '</strong> ' . $submission_id . '</p>';
        $message .= '<p><strong>' . __( 'Date:', 'giraforms' ) . '</strong> ' . date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), current_time( 'timestamp' ) ) . '</p>';
        $message .= '</div>';
        // Create field labels map with default fallback
        $field_labels = $this->build_field_labels_map( $fields );
        // Add form data
        $message .= '<div class="form-data">';
        foreach ( $data as $key => $value ) {
            if ( $this->should_skip_email_field( $key ) ) {
                continue;
            }
            $label = ( isset( $field_labels[$key] ) ? $field_labels[$key] : $key );
            // Check if value is JSON string
            if ( is_string( $value ) ) {
                $decoded = json_decode( $value, true );
                if ( json_last_error() === JSON_ERROR_NONE && isset( $decoded['date'] ) && isset( $decoded['slot'] ) ) {
                    $message .= '<div class="field-item">';
                    $message .= '<strong class="field-label">' . esc_html( $label ) . ':</strong>';
                    $message .= '<div>' . esc_html( wp_json_encode( $decoded ) ) . '</div>';
                    $message .= '</div>';
                    continue;
                }
            }
            // Handle arrays and regular values
            if ( is_array( $value ) ) {
                $value = implode( ', ', $value );
            }
            $message .= '<div class="field-item">';
            $message .= '<strong class="field-label">' . esc_html( $label ) . ':</strong>';
            // Check if value is a signature (base64 image)
            if ( is_string( $value ) && preg_match( '/^data:image\\/(png|jpg|jpeg|gif|webp);base64,/', $value ) ) {
                $message .= '<div class="field-value"><img src="' . esc_attr( $value ) . '" style="max-width: 400px; border: 1px solid #ddd; border-radius: 4px; display: block; margin-top: 8px;" alt="' . esc_attr( $label ) . '"></div>';
            } else {
                $message .= '<div class="field-value">' . nl2br( esc_html( $value ) ) . '</div>';
            }
            $message .= '</div>';
        }
        $message .= '</div>';
        $message .= '<div class="email-footer">';
        $message .= '<p><a href="' . admin_url( 'admin.php?page=giraforms-submissions&submission_id=' . $submission_id ) . '" class="view-link">' . __( 'View submission in admin', 'giraforms' ) . '</a></p>';
        $message .= '</div>';
        // Add attribution footer
        $message .= $this->get_email_attribution();
        $message .= '</div>';
        $message .= '</body></html>';
        return $message;
    }

    /**
     * Build confirmation message for user.
     *
     * @param int   $submission_id Submission ID.
     * @param array $data Form data.
     * @param array $fields Form fields configuration.
     * @return string
     */
    private function build_confirmation_message( $submission_id, $data, $fields ) {
        $styles = $this->get_email_styles();
        $message = '<html><head><style>' . $styles . '</style></head><body>';
        $message .= '<div class="email-container">';
        $message .= '<h2>' . __( 'Thank you for your submission!', 'giraforms' ) . '</h2>';
        $message .= '<p style="padding:0 20px">' . __( 'We have received your form and will contact you shortly if necessary.', 'giraforms' ) . '</p>';
        $message .= '<p style="padding:0 20px"><strong>' . __( 'Summary of your submission:', 'giraforms' ) . '</strong></p>';
        // Create field labels map with default fallback
        $field_labels = $this->build_field_labels_map( $fields );
        // Add form data
        $message .= '<div class="form-data">';
        foreach ( $data as $key => $value ) {
            if ( $this->should_skip_email_field( $key ) ) {
                continue;
            }
            $label = ( isset( $field_labels[$key] ) ? $field_labels[$key] : $key );
            // Check if value is JSON string
            if ( is_string( $value ) ) {
                $decoded = json_decode( $value, true );
                if ( json_last_error() === JSON_ERROR_NONE && isset( $decoded['date'] ) && isset( $decoded['slot'] ) ) {
                    $message .= '<div class="field-item">';
                    $message .= '<strong class="field-label">' . esc_html( $label ) . ':</strong>';
                    $message .= '<div>' . esc_html( wp_json_encode( $decoded ) ) . '</div>';
                    $message .= '</div>';
                    continue;
                }
            }
            // Handle arrays and regular values
            if ( is_array( $value ) ) {
                $value = implode( ', ', $value );
            }
            $message .= '<div class="field-item">';
            $message .= '<strong class="field-label">' . esc_html( $label ) . ':</strong>';
            // Check if value is a signature (base64 image)
            if ( is_string( $value ) && preg_match( '/^data:image\\/(png|jpg|jpeg|gif|webp);base64,/', $value ) ) {
                $message .= '<div class="field-value"><img src="' . esc_attr( $value ) . '" style="max-width: 400px; border: 1px solid #ddd; border-radius: 4px; display: block; margin-top: 8px;" alt="' . esc_attr( $label ) . '"></div>';
            } else {
                $message .= '<div class="field-value">' . nl2br( esc_html( $value ) ) . '</div>';
            }
            $message .= '</div>';
        }
        $message .= '</div>';
        // Add attribution footer
        $message .= $this->get_email_attribution();
        $message .= '</div>';
        $message .= '</body></html>';
        return $message;
    }

    /**
     * Determine whether a submission field should be omitted from email output.
     *
     * @param string $key Submission field key.
     * @return bool
     */
    private function should_skip_email_field( $key ) {
        // Skip meta fields and technical fields.
        if ( strpos( $key, 'giraforms_' ) === 0 || strpos( $key, '_' ) === 0 || strpos( $key, 'booking-slot-' ) === 0 ) {
            return true;
        }
        return false;
    }

    /**
     * Replace shortcodes in message.
     *
     * @param string $content Content with shortcodes.
     * @param array  $data Form data.
     * @return string
     */
    private function replace_shortcodes( $content, $data ) {
        // Replace field shortcodes {field_name}
        foreach ( $data as $key => $value ) {
            if ( is_array( $value ) ) {
                $value = implode( ', ', $value );
            }
            $content = str_replace( '{' . $key . '}', $value, $content );
        }
        // Replace system shortcodes
        $content = str_replace( '{site_name}', get_bloginfo( 'name' ), $content );
        $content = str_replace( '{site_url}', get_bloginfo( 'url' ), $content );
        $content = str_replace( '{date}', current_time( 'mysql' ), $content );
        return $content;
    }

    /**
     * Check notification conditions.
     *
     * @param array $conditions Conditions to check.
     * @param array $data Form data.
     * @return bool
     */
    private function check_conditions( $conditions, $data ) {
        foreach ( $conditions as $condition ) {
            $field = ( isset( $condition['field'] ) ? $condition['field'] : '' );
            $operator = ( isset( $condition['operator'] ) ? $condition['operator'] : '=' );
            $value = ( isset( $condition['value'] ) ? $condition['value'] : '' );
            if ( !isset( $data[$field] ) ) {
                return false;
            }
            $field_value = $data[$field];
            switch ( $operator ) {
                case '=':
                    if ( $field_value !== $value ) {
                        return false;
                    }
                    break;
                case '!=':
                    if ( $field_value === $value ) {
                        return false;
                    }
                    break;
                case 'contains':
                    if ( strpos( $field_value, $value ) === false ) {
                        return false;
                    }
                    break;
            }
        }
        return true;
    }

    /**
     * Get email field configuration (secure: reads from database).
     *
     * @param int    $post_id Post ID.
     * @param string $form_id Form ID.
     * @param string $email_field_id Email field ID.
     * @return array Configuration array with sendConfirmation and confirmationTemplateId.
     */
    private function get_email_field_config( $post_id, $form_id, $email_field_id ) {
        $default_config = array(
            'sendConfirmation'       => true,
            'confirmationTemplateId' => '',
        );
        if ( !$post_id ) {
            return $default_config;
        }
        $post = get_post( $post_id );
        if ( !$post || empty( $post->post_content ) ) {
            return $default_config;
        }
        // Parse blocks from post content (server-side, secure)
        $blocks = parse_blocks( $post->post_content );
        // Find the form container
        $form_container = $this->find_form_container( $blocks, $form_id );
        if ( !$form_container ) {
            return $default_config;
        }
        // Find the email field within the form
        $email_field = $this->find_email_field_in_blocks( $form_container, $email_field_id );
        if ( !$email_field ) {
            return $default_config;
        }
        // Return email field configuration
        return array(
            'sendConfirmation'       => ( isset( $email_field['attrs']['sendConfirmation'] ) ? (bool) $email_field['attrs']['sendConfirmation'] : true ),
            'confirmationTemplateId' => ( isset( $email_field['attrs']['confirmationTemplateId'] ) ? $email_field['attrs']['confirmationTemplateId'] : '' ),
        );
    }

    /**
     * Get sendConfirmation setting for an email field (secure: reads from database).
     * Deprecated: Use get_email_field_config() instead.
     *
     * @param int    $post_id Post ID.
     * @param string $form_id Form ID.
     * @param string $email_field_id Email field ID.
     * @return bool
     */
    private function get_email_field_send_confirmation( $post_id, $form_id, $email_field_id ) {
        $config = $this->get_email_field_config( $post_id, $form_id, $email_field_id );
        return $config['sendConfirmation'];
    }

    /**
     * Find form container by ID.
     *
     * @param array  $blocks Blocks array.
     * @param string $form_id Form ID.
     * @return array|null
     */
    private function find_form_container( $blocks, $form_id ) {
        foreach ( $blocks as $block ) {
            if ( $block['blockName'] === 'giraforms/form-container' ) {
                $block_form_id = ( isset( $block['attrs']['formId'] ) ? $block['attrs']['formId'] : '' );
                if ( $block_form_id === $form_id ) {
                    return $block;
                }
            }
            // Search in inner blocks recursively
            if ( !empty( $block['innerBlocks'] ) ) {
                $found = $this->find_form_container( $block['innerBlocks'], $form_id );
                if ( $found ) {
                    return $found;
                }
            }
        }
        return null;
    }

    /**
     * Find email field in blocks recursively.
     *
     * @param array  $form_block Form container block.
     * @param string $email_field_id Email field ID.
     * @return array|null
     */
    private function find_email_field_in_blocks( $form_block, $email_field_id ) {
        if ( !isset( $form_block['innerBlocks'] ) || empty( $form_block['innerBlocks'] ) ) {
            return null;
        }
        foreach ( $form_block['innerBlocks'] as $block ) {
            // Check if this is the email field we're looking for
            if ( $block['blockName'] === 'giraforms/email-field' ) {
                $field_id = ( isset( $block['attrs']['fieldId'] ) ? $block['attrs']['fieldId'] : '' );
                if ( $field_id === $email_field_id ) {
                    return $block;
                }
            }
            // Search in inner blocks recursively (for columns, etc.)
            if ( !empty( $block['innerBlocks'] ) ) {
                $found = $this->find_email_field_in_blocks( $block, $email_field_id );
                if ( $found ) {
                    return $found;
                }
            }
        }
        return null;
    }

    /**
     * Set HTML content type for emails.
     *
     * @return string
     */
    public function set_html_content_type() {
        return 'text/html';
    }

    /**
     * Get email styles (public accessor for template preview).
     *
     * @return string
     */
    public function get_email_styles_public( $overrides = array() ) {
        return $this->get_email_styles( $overrides );
    }

    /**
     * Get email styles.
     *
     * @param array $overrides Optional color overrides (accent_color, header_text_color).
     * @return string
     */
    private function get_email_styles( $overrides = array() ) {
        $accent_color = '#385aea';
        $header_text_color = '#ffffff';
        // Per-template overrides take priority
        if ( !empty( $overrides['accent_color'] ) ) {
            $accent_color = $overrides['accent_color'];
        }
        if ( !empty( $overrides['header_text_color'] ) ) {
            $header_text_color = $overrides['header_text_color'];
        }
        return '
			body {
				font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
				line-height: 1.6;
				color: #333;
				background-color: #f5f5f5;
				margin: 0;
				padding: 0;
			}
			.email-container {
				max-width: 600px;
				margin: 20px auto;
				background-color: #ffffff;
				border-radius: 8px;
				box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
				overflow: hidden;
			}
			h2 {
				background-color: ' . esc_attr( $accent_color ) . ';
				color: ' . esc_attr( $header_text_color ) . ';
				margin: 0;
				padding: 20px;
				font-size: 24px;
			}
			.meta-info {
				background-color: #f8f9fa;
				padding: 15px 20px;
				border-bottom: 1px solid #e0e0e0;
			}
			.meta-info p {
				margin: 5px 0;
			}
			.form-data {
				padding: 20px;
			}
			.field-item {
				margin-bottom: 20px;
				padding-bottom: 15px;
				border-bottom: 1px solid #e9ecef;
			}
			.field-item:last-child {
				border-bottom: none;
				margin-bottom: 0;
			}
			.field-label {
				display: block;
				color: ' . esc_attr( $accent_color ) . ';
				font-size: 14px;
				margin-bottom: 5px;
			}
			.field-value {
				color: #333;
				font-size: 15px;
			}
			.booking-summary {
				background-color: #f8f9fa;
				border: 1px solid #e0e0e0;
				border-radius: 6px;
				padding: 15px;
				margin-top: 10px;
			}
			.booking-item {
				margin-bottom: 10px;
				padding-bottom: 10px;
				border-bottom: 1px solid #e0e0e0;
			}
			.booking-item:last-child {
				border-bottom: none;
				margin-bottom: 0;
			}
			.booking-label {
				color: #666;
				font-size: 14px;
			}
			.booking-options {
				margin: 8px 0 0 0;
				padding-left: 20px;
			}
			.booking-options li {
				margin: 4px 0;
				color: #333;
			}
			.booking-total {
				padding-top: 10px;
				margin-top: 10px;
				border-bottom: none;
			}
			.booking-total .booking-price {
				color: ' . esc_attr( $accent_color ) . ';
				font-size: 18px;
				font-weight: 700;
			}
			.email-footer {
				background-color: #f8f9fa;
				padding: 15px 20px;
				border-top: 1px solid #e0e0e0;
				text-align: center;
			}
			.view-link {
				display: inline-block;
				padding: 10px 20px;
				background-color: ' . esc_attr( $accent_color ) . ';
				color: ' . esc_attr( $header_text_color ) . ' !important;
				text-decoration: none;
				border-radius: 4px;
				font-weight: 500;
			}
			.view-link:hover {
				opacity: 0.9;
			}
		';
    }

    /**
     * Get email attribution footer.
     *
     * @return string
     */
    private function get_email_attribution() {
        // Allow disabling attribution via filter (for developers)
        $show_attribution = apply_filters( 'giraforms_show_email_attribution', true );
        if ( !$show_attribution ) {
            return '';
        }
        $attribution = '<div class="giraforms-attribution" style="text-align: center; padding: 15px 20px; border-top: 1px solid #e0e0e0; font-size: 12px; color: #999;">';
        $attribution .= '<p style="margin: 0;">';
        $attribution .= sprintf( 
            /* translators: %s: Giraforms link */
            __( 'Powered by %s', 'giraforms' ),
            '<a href="https://giraforms.com/?utm_source=email&utm_medium=attribution" style="color: #385aea; text-decoration: none;">Giraforms</a>'
         );
        $attribution .= '</p>';
        $attribution .= '</div>';
        return $attribution;
    }

    /**
     * Build field labels map with default fallback values.
     *
     * @param array $fields Form fields configuration.
     * @return array Field labels keyed by field name/ID.
     */
    private function build_field_labels_map( $fields ) {
        // Default labels for free block types
        $default_labels = array(
            'text-field'         => __( 'Text Field', 'giraforms' ),
            'textarea-field'     => __( 'Textarea', 'giraforms' ),
            'email-field'        => __( 'Email', 'giraforms' ),
            'phone-field'        => __( 'Phone', 'giraforms' ),
            'select-field'       => __( 'Select', 'giraforms' ),
            'checkbox-field'     => __( 'Checkboxes', 'giraforms' ),
            'radio-field'        => __( 'Radio', 'giraforms' ),
            'date-field'         => __( 'Date', 'giraforms' ),
            'time-field'         => __( 'Time', 'giraforms' ),
            'number-field'       => __( 'Number', 'giraforms' ),
            'url-field'          => __( 'URL', 'giraforms' ),
            'hidden-field'       => __( 'Hidden Field', 'giraforms' ),
            'password-field'     => __( 'Password', 'giraforms' ),
            'range-slider-field' => __( 'Range Slider', 'giraforms' ),
            'color-picker-field' => __( 'Color Picker', 'giraforms' ),
            'consent-field'      => __( 'Consent', 'giraforms' ),
        );
        $field_labels = array();
        foreach ( $fields as $field ) {
            // Determine field name (support both 'name' and 'fieldId')
            $field_name = null;
            if ( isset( $field['name'] ) ) {
                $field_name = $field['name'];
            } elseif ( isset( $field['fieldId'] ) ) {
                $field_name = $field['fieldId'];
            }
            if ( !$field_name ) {
                continue;
            }
            // Determine field label (support 'label', 'fieldName' for hidden fields)
            $field_label = null;
            if ( isset( $field['label'] ) && !empty( $field['label'] ) && $field['label'] !== $field_name ) {
                $field_label = $field['label'];
            } elseif ( isset( $field['fieldName'] ) && !empty( $field['fieldName'] ) ) {
                $field_label = $field['fieldName'];
            }
            // If no label found, try to get default label based on block type
            if ( empty( $field_label ) ) {
                $block_type = null;
                // Try to get type from field array
                if ( isset( $field['type'] ) ) {
                    $block_type = $field['type'];
                } elseif ( preg_match( '/^([a-z]+)_/', $field_name, $matches ) ) {
                    $prefix = $matches[1];
                    // Map common prefixes to block types
                    $prefix_map = array(
                        'range'       => 'range-slider-field',
                        'color'       => 'color-picker-field',
                        'signature'   => 'signature-field',
                        'consent'     => 'consent-field',
                        'password'    => 'password-field',
                        'hidden'      => 'hidden-field',
                        'geolocation' => 'geolocation-field',
                        'currency'    => 'currency-field',
                        'booking'     => 'booking-field',
                        'calendar'    => 'calendar-field',
                        'rating'      => 'rating-field',
                    );
                    if ( isset( $prefix_map[$prefix] ) ) {
                        $block_type = $prefix_map[$prefix];
                    }
                }
                if ( $block_type && isset( $default_labels[$block_type] ) ) {
                    $field_label = $default_labels[$block_type];
                } elseif ( $block_type ) {
                    // Fallback: create label from block type
                    $field_label = str_replace( array('-field', '-'), array('', ' '), $block_type );
                    $field_label = ucwords( $field_label );
                }
            }
            // Final fallback: use field name if still no label
            if ( empty( $field_label ) ) {
                $field_label = $field_name;
            }
            // Clean the label: remove asterisk and everything after colon
            $clean_label = $field_label;
            // Remove asterisk if present
            $clean_label = str_replace( '*', '', $clean_label );
            // Remove options (text after colon like ":Morning,Afternoon")
            $colon_pos = strpos( $clean_label, ':' );
            if ( $colon_pos !== false ) {
                $clean_label = substr( $clean_label, 0, $colon_pos );
            }
            // Trim whitespace
            $clean_label = trim( $clean_label );
            // Store with both formats (with and without []) for checkbox/array fields
            $field_labels[$field_name] = $clean_label;
            // Also store with [] suffix if not already present
            if ( strpos( $field_name, '[]' ) === false ) {
                $field_labels[$field_name . '[]'] = $clean_label;
            } else {
                // Also store without [] suffix
                $field_labels[str_replace( '[]', '', $field_name )] = $clean_label;
            }
        }
        return $field_labels;
    }

}
