<?php
/**
 * Email Template Customizer
 *
 * Allows users to customize email templates through a visual interface.
 * Currently supports two-factor authentication code emails.
 *
 * @package GuardDog
 * @since 1.8.45
 */

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

class Guard_Dog_Email_Template_Customizer extends Guard_Dog_Customizer {

    /**
     * Available template types
     * @var array
     */
    protected $available_template_types = [];

    /**
     * Template type (two-factor-code, email-verification, etc.)
     * @var string
     */
    protected $template_type = 'two-factor-code';

    /**
     * Constructor
     *
     * @param array $args Optional. Supports 'template_type' for programmatic use.
     */
    public function __construct( $args = array() ) {
        // Initialize available template types
        $this->available_template_types = [
            'two-factor-code' => [
                'label' => __('Two-Factor Authentication Code', 'guard-dog'),
                'description' => __('Email sent when users request a 2FA login code.', 'guard-dog'),
            ],
            'email-verification' => [
                'label' => __('Email Verification', 'guard-dog'),
                'description' => __('Email sent to new users to verify their email address.', 'guard-dog'),
            ],
            'password-expiration' => [
                'label' => __('Password Expiration', 'guard-dog'),
                'description' => __('Email sent when a user\'s password is about to expire or has expired.', 'guard-dog'),
            ],
            'suspicious-activity-admin' => [
                'label' => __('Suspicious Session Activity (Admin)', 'guard-dog'),
                'description' => __('Email sent to the site admin when suspicious session activity is detected.', 'guard-dog'),
            ],
            'suspicious-activity-user' => [
                'label' => __('Suspicious Session Activity (User)', 'guard-dog'),
                'description' => __('Email sent to the affected user when unusual session activity is detected.', 'guard-dog'),
            ],
        ];

        // Determine template type: $args['template_type'] (programmatic) overrides $_GET
        $requested_type = '';
        if ( isset( $args['template_type'] ) && array_key_exists( $args['template_type'], $this->available_template_types ) ) {
            $requested_type = $args['template_type'];
        } else {
            // phpcs:disable WordPress.Security.NonceVerification.Recommended
            // Nonce verification is not required: GET is for display/navigation only, sanitized, whitelisted; access requires manage_options.
            $get_type = isset( $_GET['template_type'] ) ? sanitize_text_field( wp_unslash( $_GET['template_type'] ) ) : '';
            // phpcs:enable WordPress.Security.NonceVerification.Recommended
            if ( $get_type && array_key_exists( $get_type, $this->available_template_types ) ) {
                $requested_type = $get_type;
            }
        }
        if ( $requested_type ) {
            $this->template_type = $requested_type;
        }

        parent::__construct();
    }

    /**
     * Get current template type
     *
     * @return string
     */
    public function get_template_type() {
        return $this->template_type;
    }

    /**
     * Set template type
     *
     * @since 1.9.1
     * @param string $type The template type to set.
     * @return bool True if set successfully, false if invalid type.
     */
    public function set_template_type($type) {
        if (array_key_exists($type, $this->available_template_types)) {
            $this->template_type = $type;
            return true;
        }
        return false;
    }

    /**
     * Get the email subject with placeholders replaced.
     * Returns null if this template type has no subject control or the setting is empty.
     *
     * @param array $args Keys: site_name, type, username, name, is_expired (as needed per template type).
     * @return string|null Subject string or null.
     */
    public function get_email_subject( $args = array() ) {
        if ( $this->template_type === 'password-expiration' ) {
            $subject = ( ! empty( $args['is_expired'] ) )
                ? $this->get_setting( 'subject_expired', null )
                : $this->get_setting( 'subject_warning', null );
        } else {
            $subject = $this->get_setting( 'subject', null );
        }
        if ( $subject === null || $subject === '' ) {
            return null;
        }
        $subject  = (string) $subject;
        $site_name = isset( $args['site_name'] ) ? $args['site_name'] : get_bloginfo( 'name' );
        $subject  = str_replace( '{site_name}', $site_name, $subject );
        $subject  = str_replace( '{type}', isset( $args['type'] ) ? $args['type'] : '', $subject );
        $subject  = str_replace( '{username}', isset( $args['username'] ) ? $args['username'] : ( isset( $args['user'] ) && ! empty( $args['user']->user_login ) ? $args['user']->user_login : '' ), $subject );
        $subject  = str_replace( '{name}', isset( $args['name'] ) ? $args['name'] : ( isset( $args['user'] ) && ! empty( $args['user']->display_name ) ? $args['user']->display_name : '' ), $subject );
        return $subject;
    }

    /**
     * Get available template types
     *
     * @return array
     */
    public function get_available_template_types() {
        return $this->available_template_types;
    }

    /**
     * Get unique ID for this customizer
     *
     * @return string
     */
    public function get_customizer_id() {
        return 'email_template';
    }

    /**
     * Get option name for storing settings
     * Override to include template type
     *
     * @return string
     */
    protected function get_option_name() {
        return 'guard_dog_customizer_' . $this->get_customizer_id() . '_' . $this->template_type;
    }

    /**
     * Get title for this customizer
     *
     * @return string
     */
    public function get_customizer_title() {
        return __('Email Template Customizer', 'guard-dog');
    }

    /**
     * Get description for this customizer
     *
     * @return string
     */
    public function get_customizer_description() {
        return __('Customize the appearance of security emails sent by Guard Dog. Changes are saved to your database and can be exported to a theme file for advanced customization.', 'guard-dog');
    }

    /**
     * Register sections and controls
     */
    protected function register_controls() {
        // Register controls based on template type
        if ($this->template_type === 'email-verification') {
            $this->register_email_verification_controls();
        } elseif ($this->template_type === 'password-expiration') {
            $this->register_password_expiration_controls();
        } elseif ($this->template_type === 'suspicious-activity-admin') {
            $this->register_suspicious_activity_admin_controls();
        } elseif ($this->template_type === 'suspicious-activity-user') {
            $this->register_suspicious_activity_user_controls();
        } else {
            $this->register_two_factor_controls();
        }
    }

    /**
     * Register controls for two-factor authentication code template
     */
    protected function register_two_factor_controls() {
        // ===== BRANDING SECTION =====
        $this->add_section('branding', __('Branding', 'guard-dog'), [
            'description' => __('Upload your logo and set your brand colors.', 'guard-dog'),
            'priority' => 10,
        ]);

        $this->add_control('logo', 'image', 'branding', [
            'label' => __('Logo', 'guard-dog'),
            'description' => __('Upload your company logo. Recommended size: 200x50 pixels. Leave empty to use site name.', 'guard-dog'),
            'storage_type' => 'url',
            'default' => '',
        ]);

        $this->add_control('logo_width', 'number', 'branding', [
            'label' => __('Logo Width (px)', 'guard-dog'),
            'description' => __('Maximum width for the logo in pixels.', 'guard-dog'),
            'default' => 200,
            'input_attrs' => [
                'min' => 50,
                'max' => 600,
                'step' => 10,
            ],
        ]);

        $this->add_control('primary_color', 'color', 'branding', [
            'label' => __('Primary Color', 'guard-dog'),
            'description' => __('Main brand color used for header and accents.', 'guard-dog'),
            'default' => '#0073aa',
        ]);

        $this->add_control('accent_color', 'color', 'branding', [
            'label' => __('Accent Color', 'guard-dog'),
            'description' => __('Secondary color used for borders and highlights.', 'guard-dog'),
            'default' => '#00a0d2',
        ]);

        $this->add_control('text_color', 'color', 'branding', [
            'label' => __('Text Color', 'guard-dog'),
            'description' => __('Main text color for email content.', 'guard-dog'),
            'default' => '#333333',
        ]);

        // ===== CONTENT SECTION =====
        $this->add_section('content', __('Content', 'guard-dog'), [
            'description' => __('Customize the text content of your emails.', 'guard-dog'),
            'priority' => 20,
        ]);

        $this->add_control('subject', 'text', 'content', [
            'label' => __('Subject Line', 'guard-dog'),
            'description' => __('Use {site_name} and {name} as placeholders.', 'guard-dog'),
            'default' => __( '[{site_name}] Two-Factor Authentication Code', 'guard-dog' ),
        ]);

        $this->add_control('header_text', 'text', 'content', [
            'label' => __('Header Text', 'guard-dog'),
            'description' => __('Text displayed in the email header. Leave empty to use site name.', 'guard-dog'),
            'default' => get_bloginfo('name'),
            'placeholder' => get_bloginfo('name'),
        ]);

        $this->add_control('greeting_text', 'text', 'content', [
            'label' => __('Greeting Text', 'guard-dog'),
            'description' => __('Greeting message. Use {name} for user\'s display name.', 'guard-dog'),
            'default' => __('Hello {name},', 'guard-dog'),
            'placeholder' => __('Hello {name},', 'guard-dog'),
        ]);

        $this->add_control('intro_text', 'textarea', 'content', [
            'label' => __('Introduction Text', 'guard-dog'),
            'description' => __('Text displayed before the verification code.', 'guard-dog'),
            'default' => __('You have requested a two-factor authentication code to log in to your account.', 'guard-dog'),
            'rows' => 3,
        ]);

        $this->add_control('code_label', 'text', 'content', [
            'label' => __('Code Label', 'guard-dog'),
            'description' => __('Label displayed above the verification code.', 'guard-dog'),
            'default' => __('Your Verification Code', 'guard-dog'),
        ]);

        $this->add_control('footer_text', 'textarea', 'content', [
            'label' => __('Footer Text', 'guard-dog'),
            'description' => __('Text displayed in the email footer.', 'guard-dog'),
            // Translators: %s is the site name.
            'default' => sprintf(__('This email was sent from %s', 'guard-dog'), get_bloginfo('name')),
            'rows' => 3,
        ]);

        $this->add_control('security_notice', 'textarea', 'content', [
            'label' => __('Security Notice', 'guard-dog'),
            'description' => __('Security warning displayed at the bottom of the email.', 'guard-dog'),
            'default' => __('If you did not request this code, please ignore this email and consider changing your password.', 'guard-dog'),
            'rows' => 2,
        ]);

        // ===== LAYOUT SECTION =====
        $this->add_section('layout', __('Layout & Style', 'guard-dog'), [
            'description' => __('Configure the layout and visual style of your emails.', 'guard-dog'),
            'priority' => 30,
        ]);

        $this->add_control('background_color', 'color', 'layout', [
            'label' => __('Background Color', 'guard-dog'),
            'description' => __('Email background color (outside the main content area).', 'guard-dog'),
            'default' => '#f4f4f4',
        ]);

        $this->add_control('content_background', 'color', 'layout', [
            'label' => __('Content Background', 'guard-dog'),
            'description' => __('Background color for the main content area.', 'guard-dog'),
            'default' => '#ffffff',
        ]);

        $this->add_control('code_background', 'color', 'layout', [
            'label' => __('Code Box Background', 'guard-dog'),
            'description' => __('Background color for the verification code box.', 'guard-dog'),
            'default' => '#f8f9fa',
        ]);

        $this->add_control('border_radius', 'number', 'layout', [
            'label' => __('Border Radius (px)', 'guard-dog'),
            'description' => __('Rounded corners for boxes and buttons. Set to 0 for square corners.', 'guard-dog'),
            'default' => 4,
            'input_attrs' => [
                'min' => 0,
                'max' => 20,
                'step' => 1,
            ],
        ]);
    }

    /**
     * Register controls for email verification template
     */
    protected function register_email_verification_controls() {
        // ===== BRANDING SECTION =====
        $this->add_section('branding', __('Branding', 'guard-dog'), [
            'description' => __('Upload your logo and set your brand colors.', 'guard-dog'),
            'priority' => 10,
        ]);

        $this->add_control('logo', 'image', 'branding', [
            'label' => __('Logo', 'guard-dog'),
            'description' => __('Upload your company logo. Recommended size: 200x50 pixels. Leave empty to use site name.', 'guard-dog'),
            'storage_type' => 'url',
            'default' => '',
        ]);

        $this->add_control('logo_width', 'number', 'branding', [
            'label' => __('Logo Width (px)', 'guard-dog'),
            'description' => __('Maximum width for the logo in pixels.', 'guard-dog'),
            'default' => 200,
            'input_attrs' => [
                'min' => 50,
                'max' => 600,
                'step' => 10,
            ],
        ]);

        $this->add_control('primary_color', 'color', 'branding', [
            'label' => __('Primary Color', 'guard-dog'),
            'description' => __('Main brand color used for header and button.', 'guard-dog'),
            'default' => '#2271b1',
        ]);

        $this->add_control('accent_color', 'color', 'branding', [
            'label' => __('Accent Color', 'guard-dog'),
            'description' => __('Secondary color used for borders and highlights.', 'guard-dog'),
            'default' => '#135e96',
        ]);

        $this->add_control('text_color', 'color', 'branding', [
            'label' => __('Text Color', 'guard-dog'),
            'description' => __('Main text color for email content.', 'guard-dog'),
            'default' => '#333333',
        ]);

        // ===== CONTENT SECTION =====
        $this->add_section('content', __('Content', 'guard-dog'), [
            'description' => __('Customize the text content of your emails.', 'guard-dog'),
            'priority' => 20,
        ]);

        $this->add_control('subject', 'text', 'content', [
            'label' => __('Subject Line', 'guard-dog'),
            'description' => __('Use {site_name} and {name} as placeholders.', 'guard-dog'),
            'default' => __( '[{site_name}] Verify Your Email Address', 'guard-dog' ),
        ]);

        $this->add_control('header_text', 'text', 'content', [
            'label' => __('Header Text', 'guard-dog'),
            'description' => __('Text displayed in the email header. Leave empty to use site name.', 'guard-dog'),
            'default' => get_bloginfo('name'),
            'placeholder' => get_bloginfo('name'),
        ]);

        $this->add_control('greeting_text', 'text', 'content', [
            'label' => __('Greeting Text', 'guard-dog'),
            'description' => __('Greeting message. Use {name} for user\'s display name.', 'guard-dog'),
            'default' => __('Hello {name},', 'guard-dog'),
            'placeholder' => __('Hello {name},', 'guard-dog'),
        ]);

        $this->add_control('intro_text', 'textarea', 'content', [
            'label' => __('Introduction Text', 'guard-dog'),
            'description' => __('Text displayed before the verification button.', 'guard-dog'),
            'default' => __('Thank you for registering! Please verify your email address by clicking the button below:', 'guard-dog'),
            'rows' => 3,
        ]);

        $this->add_control('button_text', 'text', 'content', [
            'label' => __('Button Text', 'guard-dog'),
            'description' => __('Text displayed on the verification button.', 'guard-dog'),
            'default' => __('Verify Email Address', 'guard-dog'),
        ]);

        $this->add_control('expiry_notice', 'text', 'content', [
            'label' => __('Expiry Notice', 'guard-dog'),
            'description' => __('Text displayed about link expiration. Use {hours} for expiry hours.', 'guard-dog'),
            'default' => __('This verification link will expire in {hours} hours.', 'guard-dog'),
        ]);

        $this->add_control('footer_text', 'textarea', 'content', [
            'label' => __('Footer Text', 'guard-dog'),
            'description' => __('Text displayed in the email footer.', 'guard-dog'),
            // Translators: %s is the site name.
            'default' => sprintf(__('This email was sent by %s', 'guard-dog'), get_bloginfo('name')),
            'rows' => 3,
        ]);

        $this->add_control('security_notice', 'textarea', 'content', [
            'label' => __('Security Notice', 'guard-dog'),
            'description' => __('Security warning displayed at the bottom of the email.', 'guard-dog'),
            'default' => __('If you did not create an account, please ignore this email.', 'guard-dog'),
            'rows' => 2,
        ]);

        // ===== LAYOUT SECTION =====
        $this->add_section('layout', __('Layout & Style', 'guard-dog'), [
            'description' => __('Configure the layout and visual style of your emails.', 'guard-dog'),
            'priority' => 30,
        ]);

        $this->add_control('background_color', 'color', 'layout', [
            'label' => __('Background Color', 'guard-dog'),
            'description' => __('Email background color (outside the main content area).', 'guard-dog'),
            'default' => '#f4f4f4',
        ]);

        $this->add_control('content_background', 'color', 'layout', [
            'label' => __('Content Background', 'guard-dog'),
            'description' => __('Background color for the main content area.', 'guard-dog'),
            'default' => '#ffffff',
        ]);

        $this->add_control('button_background', 'color', 'layout', [
            'label' => __('Button Background Color', 'guard-dog'),
            'description' => __('Background color for the verification button.', 'guard-dog'),
            'default' => '#2271b1',
        ]);

        $this->add_control('button_text_color', 'color', 'layout', [
            'label' => __('Button Text Color', 'guard-dog'),
            'description' => __('Text color for the verification button.', 'guard-dog'),
            'default' => '#ffffff',
        ]);

        $this->add_control('border_radius', 'number', 'layout', [
            'label' => __('Border Radius (px)', 'guard-dog'),
            'description' => __('Rounded corners for boxes and buttons. Set to 0 for square corners.', 'guard-dog'),
            'default' => 4,
            'input_attrs' => [
                'min' => 0,
                'max' => 20,
                'step' => 1,
            ],
        ]);
    }

    /**
     * Register controls for password expiration template
     */
    protected function register_password_expiration_controls() {
        // ===== BRANDING SECTION =====
        $this->add_section('branding', __('Branding', 'guard-dog'), [
            'description' => __('Upload your logo and set your brand colors.', 'guard-dog'),
            'priority' => 10,
        ]);

        $this->add_control('logo', 'image', 'branding', [
            'label' => __('Logo', 'guard-dog'),
            'description' => __('Upload your company logo. Recommended size: 200x50 pixels. Leave empty to use site name.', 'guard-dog'),
            'storage_type' => 'url',
            'default' => '',
        ]);

        $this->add_control('logo_width', 'number', 'branding', [
            'label' => __('Logo Width (px)', 'guard-dog'),
            'description' => __('Maximum width for the logo in pixels.', 'guard-dog'),
            'default' => 200,
            'input_attrs' => [
                'min' => 50,
                'max' => 600,
                'step' => 10,
            ],
        ]);

        $this->add_control('primary_color', 'color', 'branding', [
            'label' => __('Primary Color', 'guard-dog'),
            'description' => __('Main brand color used for header and button.', 'guard-dog'),
            'default' => '#d63638',
        ]);

        $this->add_control('accent_color', 'color', 'branding', [
            'label' => __('Accent Color', 'guard-dog'),
            'description' => __('Secondary color used for borders and highlights.', 'guard-dog'),
            'default' => '#b32d2e',
        ]);

        $this->add_control('text_color', 'color', 'branding', [
            'label' => __('Text Color', 'guard-dog'),
            'description' => __('Main text color for email content.', 'guard-dog'),
            'default' => '#333333',
        ]);

        // ===== CONTENT SECTION =====
        $this->add_section('content', __('Content', 'guard-dog'), [
            'description' => __('Customize the text content of your password expiration emails.', 'guard-dog'),
            'priority' => 20,
        ]);

        $this->add_control('subject_warning', 'text', 'content', [
            'label' => __('Subject Line (Expiring Soon)', 'guard-dog'),
            'description' => __('Use {site_name} and {name} as placeholders.', 'guard-dog'),
            'default' => __( '[{site_name}] Password Expiring Soon', 'guard-dog' ),
        ]);

        $this->add_control('subject_expired', 'text', 'content', [
            'label' => __('Subject Line (Expired)', 'guard-dog'),
            'description' => __('Use {site_name} and {name} as placeholders.', 'guard-dog'),
            'default' => __( '[{site_name}] Password Expired', 'guard-dog' ),
        ]);

        $this->add_control('header_text', 'text', 'content', [
            'label' => __('Header Text', 'guard-dog'),
            'description' => __('Text displayed in the email header. Leave empty to use site name.', 'guard-dog'),
            'default' => get_bloginfo('name'),
            'placeholder' => get_bloginfo('name'),
        ]);

        $this->add_control('greeting_text', 'text', 'content', [
            'label' => __('Greeting Text', 'guard-dog'),
            'description' => __('Greeting message. Use {name} for user\'s display name.', 'guard-dog'),
            'default' => __('Hello {name},', 'guard-dog'),
            'placeholder' => __('Hello {name},', 'guard-dog'),
        ]);

        $this->add_control('warning_intro_text', 'textarea', 'content', [
            'label' => __('Warning Introduction Text', 'guard-dog'),
            'description' => __('Text displayed for password expiration warnings. Use {days_until} for days until expiration, {expiration_date} for expiration date.', 'guard-dog'),
            'default' => __('Your password will expire in {days_until} day(s) (on {expiration_date}). Please reset your password soon to avoid being locked out.', 'guard-dog'),
            'rows' => 3,
        ]);

        $this->add_control('expired_intro_text', 'textarea', 'content', [
            'label' => __('Expired Introduction Text', 'guard-dog'),
            'description' => __('Text displayed when password has expired.', 'guard-dog'),
            'default' => __('Your password has expired. Please reset your password to continue accessing your account.', 'guard-dog'),
            'rows' => 3,
        ]);

        $this->add_control('button_text', 'text', 'content', [
            'label' => __('Button Text', 'guard-dog'),
            'description' => __('Text displayed on the password reset button.', 'guard-dog'),
            'default' => __('Reset Password', 'guard-dog'),
        ]);

        $this->add_control('footer_text', 'textarea', 'content', [
            'label' => __('Footer Text', 'guard-dog'),
            'description' => __('Text displayed in the email footer.', 'guard-dog'),
            // Translators: %s is the site name.
            'default' => sprintf(__('This email was sent by %s', 'guard-dog'), get_bloginfo('name')),
            'rows' => 3,
        ]);

        $this->add_control('security_notice', 'textarea', 'content', [
            'label' => __('Security Notice', 'guard-dog'),
            'description' => __('Security warning displayed at the bottom of the email.', 'guard-dog'),
            'default' => __('If you did not request a password reset, please ignore this email and contact support if you have concerns.', 'guard-dog'),
            'rows' => 2,
        ]);

        // ===== LAYOUT SECTION =====
        $this->add_section('layout', __('Layout & Style', 'guard-dog'), [
            'description' => __('Configure the layout and visual style of your emails.', 'guard-dog'),
            'priority' => 30,
        ]);

        $this->add_control('background_color', 'color', 'layout', [
            'label' => __('Background Color', 'guard-dog'),
            'description' => __('Email background color (outside the main content area).', 'guard-dog'),
            'default' => '#f4f4f4',
        ]);

        $this->add_control('content_background', 'color', 'layout', [
            'label' => __('Content Background', 'guard-dog'),
            'description' => __('Background color for the main content area.', 'guard-dog'),
            'default' => '#ffffff',
        ]);

        $this->add_control('button_background', 'color', 'layout', [
            'label' => __('Button Background Color', 'guard-dog'),
            'description' => __('Background color for the password reset button.', 'guard-dog'),
            'default' => '#d63638',
        ]);

        $this->add_control('button_text_color', 'color', 'layout', [
            'label' => __('Button Text Color', 'guard-dog'),
            'description' => __('Text color for the password reset button.', 'guard-dog'),
            'default' => '#ffffff',
        ]);

        $this->add_control('border_radius', 'number', 'layout', [
            'label' => __('Border Radius (px)', 'guard-dog'),
            'description' => __('Rounded corners for boxes and buttons. Set to 0 for square corners.', 'guard-dog'),
            'default' => 4,
            'input_attrs' => [
                'min' => 0,
                'max' => 20,
                'step' => 1,
            ],
        ]);
    }

    /**
     * Register controls for suspicious activity admin template
     */
    protected function register_suspicious_activity_admin_controls() {
        // ===== BRANDING SECTION =====
        $this->add_section('branding', __('Branding', 'guard-dog'), [
            'description' => __('Upload your logo and set your brand colors.', 'guard-dog'),
            'priority' => 10,
        ]);

        $this->add_control('logo', 'image', 'branding', [
            'label' => __('Logo', 'guard-dog'),
            'description' => __('Upload your company logo. Recommended size: 200x50 pixels. Leave empty to use site name.', 'guard-dog'),
            'storage_type' => 'url',
            'default' => '',
        ]);

        $this->add_control('logo_width', 'number', 'branding', [
            'label' => __('Logo Width (px)', 'guard-dog'),
            'description' => __('Maximum width for the logo in pixels.', 'guard-dog'),
            'default' => 200,
            'input_attrs' => [
                'min' => 50,
                'max' => 600,
                'step' => 10,
            ],
        ]);

        $this->add_control('primary_color', 'color', 'branding', [
            'label' => __('Primary Color', 'guard-dog'),
            'description' => __('Main brand color used for header and accents.', 'guard-dog'),
            'default' => '#d63638',
        ]);

        $this->add_control('accent_color', 'color', 'branding', [
            'label' => __('Accent Color', 'guard-dog'),
            'description' => __('Secondary color used for borders and highlights.', 'guard-dog'),
            'default' => '#b32d2e',
        ]);

        $this->add_control('text_color', 'color', 'branding', [
            'label' => __('Text Color', 'guard-dog'),
            'description' => __('Main text color for email content.', 'guard-dog'),
            'default' => '#333333',
        ]);

        // ===== CONTENT SECTION =====
        $this->add_section('content', __('Content', 'guard-dog'), [
            'description' => __('Customize the text content of admin suspicious activity emails.', 'guard-dog'),
            'priority' => 20,
        ]);

        $this->add_control('subject', 'text', 'content', [
            'label' => __('Subject Line', 'guard-dog'),
            'description' => __('Use {site_name} and {type} as placeholders.', 'guard-dog'),
            'default' => __( '[{site_name}] Suspicious Session Activity Detected: {type}', 'guard-dog'),
        ]);

        $this->add_control('header_text', 'text', 'content', [
            'label' => __('Header Text', 'guard-dog'),
            'description' => __('Text displayed in the email header. Leave empty to use site name.', 'guard-dog'),
            'default' => get_bloginfo('name'),
            'placeholder' => get_bloginfo('name'),
        ]);

        $this->add_control('greeting_text', 'text', 'content', [
            'label' => __('Greeting Text', 'guard-dog'),
            'description' => __('Greeting for the admin alert.', 'guard-dog'),
            'default' => __('Admin,', 'guard-dog'),
        ]);

        $this->add_control('intro_text', 'textarea', 'content', [
            'label' => __('Introduction Text', 'guard-dog'),
            'description' => __('Text displayed before the activity details. Use {username} as placeholder.', 'guard-dog'),
            'default' => __( 'The following suspicious session activity was detected on your site for user \'{username}\':', 'guard-dog'),
            'rows' => 3,
        ]);

        $this->add_control('footer_text', 'textarea', 'content', [
            'label' => __('Footer Text', 'guard-dog'),
            'description' => __('Text displayed in the email footer.', 'guard-dog'),
            'default' => sprintf(__('This email was sent by %s', 'guard-dog'), get_bloginfo('name')),
            'rows' => 3,
        ]);

        // ===== LAYOUT SECTION =====
        $this->add_section('layout', __('Layout & Style', 'guard-dog'), [
            'description' => __('Configure the layout and visual style of your emails.', 'guard-dog'),
            'priority' => 30,
        ]);

        $this->add_control('background_color', 'color', 'layout', [
            'label' => __('Background Color', 'guard-dog'),
            'description' => __('Email background color (outside the main content area).', 'guard-dog'),
            'default' => '#f4f4f4',
        ]);

        $this->add_control('content_background', 'color', 'layout', [
            'label' => __('Content Background', 'guard-dog'),
            'description' => __('Background color for the main content area.', 'guard-dog'),
            'default' => '#ffffff',
        ]);

        $this->add_control('details_background', 'color', 'layout', [
            'label' => __('Details Box Background', 'guard-dog'),
            'description' => __('Background color for the activity details box.', 'guard-dog'),
            'default' => '#f8f9fa',
        ]);

        $this->add_control('border_radius', 'number', 'layout', [
            'label' => __('Border Radius (px)', 'guard-dog'),
            'description' => __('Rounded corners for boxes. Set to 0 for square corners.', 'guard-dog'),
            'default' => 4,
            'input_attrs' => [
                'min' => 0,
                'max' => 20,
                'step' => 1,
            ],
        ]);
    }

    /**
     * Register controls for suspicious activity user template
     */
    protected function register_suspicious_activity_user_controls() {
        // ===== BRANDING SECTION =====
        $this->add_section('branding', __('Branding', 'guard-dog'), [
            'description' => __('Upload your logo and set your brand colors.', 'guard-dog'),
            'priority' => 10,
        ]);

        $this->add_control('logo', 'image', 'branding', [
            'label' => __('Logo', 'guard-dog'),
            'description' => __('Upload your company logo. Recommended size: 200x50 pixels. Leave empty to use site name.', 'guard-dog'),
            'storage_type' => 'url',
            'default' => '',
        ]);

        $this->add_control('logo_width', 'number', 'branding', [
            'label' => __('Logo Width (px)', 'guard-dog'),
            'description' => __('Maximum width for the logo in pixels.', 'guard-dog'),
            'default' => 200,
            'input_attrs' => [
                'min' => 50,
                'max' => 600,
                'step' => 10,
            ],
        ]);

        $this->add_control('primary_color', 'color', 'branding', [
            'label' => __('Primary Color', 'guard-dog'),
            'description' => __('Main brand color used for header and accents.', 'guard-dog'),
            'default' => '#d63638',
        ]);

        $this->add_control('accent_color', 'color', 'branding', [
            'label' => __('Accent Color', 'guard-dog'),
            'description' => __('Secondary color used for borders and highlights.', 'guard-dog'),
            'default' => '#b32d2e',
        ]);

        $this->add_control('text_color', 'color', 'branding', [
            'label' => __('Text Color', 'guard-dog'),
            'description' => __('Main text color for email content.', 'guard-dog'),
            'default' => '#333333',
        ]);

        // ===== CONTENT SECTION =====
        $this->add_section('content', __('Content', 'guard-dog'), [
            'description' => __('Customize the text content of user suspicious activity emails.', 'guard-dog'),
            'priority' => 20,
        ]);

        $this->add_control('subject', 'text', 'content', [
            'label' => __('Subject Line', 'guard-dog'),
            'description' => __('Use {site_name} as placeholder.', 'guard-dog'),
            'default' => __( '[{site_name}] Security Alert: Unusual Session Activity', 'guard-dog'),
        ]);

        $this->add_control('header_text', 'text', 'content', [
            'label' => __('Header Text', 'guard-dog'),
            'description' => __('Text displayed in the email header. Leave empty to use site name.', 'guard-dog'),
            'default' => get_bloginfo('name'),
            'placeholder' => get_bloginfo('name'),
        ]);

        $this->add_control('greeting_text', 'text', 'content', [
            'label' => __('Greeting Text', 'guard-dog'),
            'description' => __('Use {name} for the user\'s display name.', 'guard-dog'),
            'default' => __('Hello {name},', 'guard-dog'),
        ]);

        $this->add_control('intro_text', 'textarea', 'content', [
            'label' => __('Introduction Text', 'guard-dog'),
            'description' => __('Main message to the user about unusual activity.', 'guard-dog'),
            'default' => __( "We detected unusual activity on your account. If this wasn't you, please change your password immediately and review your active sessions.", 'guard-dog'),
            'rows' => 3,
        ]);

        $this->add_control('footer_text', 'textarea', 'content', [
            'label' => __('Footer Text', 'guard-dog'),
            'description' => __('Text displayed in the email footer.', 'guard-dog'),
            'default' => sprintf(__('This email was sent by %s', 'guard-dog'), get_bloginfo('name')),
            'rows' => 3,
        ]);

        $this->add_control('security_notice', 'textarea', 'content', [
            'label' => __('Security Notice', 'guard-dog'),
            'description' => __('Optional security notice at the bottom.', 'guard-dog'),
            'default' => '',
            'rows' => 2,
        ]);

        // ===== LAYOUT SECTION =====
        $this->add_section('layout', __('Layout & Style', 'guard-dog'), [
            'description' => __('Configure the layout and visual style of your emails.', 'guard-dog'),
            'priority' => 30,
        ]);

        $this->add_control('background_color', 'color', 'layout', [
            'label' => __('Background Color', 'guard-dog'),
            'description' => __('Email background color (outside the main content area).', 'guard-dog'),
            'default' => '#f4f4f4',
        ]);

        $this->add_control('content_background', 'color', 'layout', [
            'label' => __('Content Background', 'guard-dog'),
            'description' => __('Background color for the main content area.', 'guard-dog'),
            'default' => '#ffffff',
        ]);

        $this->add_control('border_radius', 'number', 'layout', [
            'label' => __('Border Radius (px)', 'guard-dog'),
            'description' => __('Rounded corners for boxes. Set to 0 for square corners.', 'guard-dog'),
            'default' => 4,
            'input_attrs' => [
                'min' => 0,
                'max' => 20,
                'step' => 1,
            ],
        ]);
    }

    /**
     * Generate email HTML output based on settings
     *
     * @param array $settings Current settings
     * @return string Generated HTML
     */
    public function generate_output($settings_or_args = []) {
        // Route to appropriate template generator
        if ($this->template_type === 'email-verification') {
            return $this->generate_email_verification_output($settings_or_args);
        } elseif ($this->template_type === 'password-expiration') {
            return $this->generate_password_expiration_output($settings_or_args);
        } elseif ($this->template_type === 'suspicious-activity-admin') {
            return $this->generate_suspicious_activity_admin_output($settings_or_args);
        } elseif ($this->template_type === 'suspicious-activity-user') {
            return $this->generate_suspicious_activity_user_output($settings_or_args);
        } else {
            return $this->generate_two_factor_output($settings_or_args);
        }
    }

    /**
     * Generate two-factor authentication code email output
     *
     * @param array $settings_or_args Current settings or template args
     * @return string Generated HTML
     */
    protected function generate_two_factor_output($settings_or_args = []) {
        // Determine if this is preview mode (passing settings) or email mode (passing template args)
        // If 'code' or 'user' keys exist, it's email mode with template args
        $is_email_mode = isset($settings_or_args['code']) || isset($settings_or_args['user']);

        if ($is_email_mode) {
            // Email generation mode: merge external args with saved settings
            $settings = $this->get_settings();
            $external_args = $settings_or_args;
        } else {
            // Preview mode: use passed settings directly (may be unsaved)
            // If empty, use saved settings from database
            if (empty($settings_or_args)) {
                $settings = $this->get_settings();
            } else {
                $settings = $settings_or_args;
            }
            $external_args = [];
        }

        // Prepare template arguments with customized values
        $template_args = array_merge([
            // Mock data for preview
            'code' => '123456',
            'user' => wp_get_current_user(),
            'site_name' => !empty($settings['header_text']) ? $settings['header_text'] : get_bloginfo('name'),
            'expiry_minutes' => 10,
        ], $external_args, [
            // Customization settings (from passed settings or saved settings)
            'logo_url' => $settings['logo'] ?? '',
            'logo_width' => $settings['logo_width'] ?? 200,
            'primary_color' => $settings['primary_color'] ?? '#0073aa',
            'accent_color' => $settings['accent_color'] ?? '#00a0d2',
            'text_color' => $settings['text_color'] ?? '#333333',
            'background_color' => $settings['background_color'] ?? '#f4f4f4',
            'content_background' => $settings['content_background'] ?? '#ffffff',
            'code_background' => $settings['code_background'] ?? '#f8f9fa',
            'border_radius' => $settings['border_radius'] ?? 4,
            'greeting_text' => $settings['greeting_text'] ?? __('Hello {name},', 'guard-dog'),
            'intro_text' => $settings['intro_text'] ?? __('You have requested a two-factor authentication code to log in to your account.', 'guard-dog'),
            'code_label' => $settings['code_label'] ?? __('Your Verification Code', 'guard-dog'),
            // Translators: %s is the site name.
            'footer_text' => $settings['footer_text'] ?? sprintf(__('This email was sent from %s', 'guard-dog'), get_bloginfo('name')),
            'security_notice' => $settings['security_notice'] ?? __('If you did not request this code, please ignore this email and consider changing your password.', 'guard-dog'),
        ]);

        // Replace {name} placeholder in greeting
        if ($template_args['user']) {
            $template_args['greeting_text'] = str_replace(
                '{name}',
                $template_args['user']->display_name,
                $template_args['greeting_text']
            );
        }

        // Generate email HTML
        ob_start();
        $this->render_email_template($template_args);
        return ob_get_clean();
    }

    /**
     * Generate email verification email output
     *
     * @param array $settings_or_args Current settings or template args
     * @return string Generated HTML
     */
    protected function generate_email_verification_output($settings_or_args = []) {
        // Determine if this is preview mode (passing settings) or email mode (passing template args)
        // If 'verification_link' or 'user_name' keys exist, it's email mode with template args
        $is_email_mode = isset($settings_or_args['verification_link']) || isset($settings_or_args['user_name']);

        if ($is_email_mode) {
            // Email generation mode: merge external args with saved settings
            $settings = $this->get_settings();
            $external_args = $settings_or_args;
        } else {
            // Preview mode: use passed settings directly (may be unsaved)
            // If empty, use saved settings from database
            if (empty($settings_or_args)) {
                $settings = $this->get_settings();
            } else {
                $settings = $settings_or_args;
            }
            $external_args = [];
        }

        // Prepare template arguments with customized values
        $template_args = array_merge([
            // Mock data for preview
            'user_name' => wp_get_current_user()->display_name ?? 'John Doe',
            'verification_link' => home_url('/?action=guard_dog_verify_email&token=preview&key=preview'),
            'expires_in' => 48,
            'site_name' => !empty($settings['header_text']) ? $settings['header_text'] : get_bloginfo('name'),
            'site_url' => home_url(),
        ], $external_args, [
            // Customization settings (from passed settings or saved settings)
            'logo_url' => $settings['logo'] ?? '',
            'logo_width' => $settings['logo_width'] ?? 200,
            'primary_color' => $settings['primary_color'] ?? '#2271b1',
            'accent_color' => $settings['accent_color'] ?? '#135e96',
            'text_color' => $settings['text_color'] ?? '#333333',
            'background_color' => $settings['background_color'] ?? '#f4f4f4',
            'content_background' => $settings['content_background'] ?? '#ffffff',
            'button_background' => $settings['button_background'] ?? '#2271b1',
            'button_text_color' => $settings['button_text_color'] ?? '#ffffff',
            'border_radius' => $settings['border_radius'] ?? 4,
            'greeting_text' => $settings['greeting_text'] ?? __('Hello {name},', 'guard-dog'),
            'intro_text' => $settings['intro_text'] ?? __('Thank you for registering! Please verify your email address by clicking the button below:', 'guard-dog'),
            'button_text' => $settings['button_text'] ?? __('Verify Email Address', 'guard-dog'),
            'expiry_notice' => $settings['expiry_notice'] ?? __('This verification link will expire in {hours} hours.', 'guard-dog'),
            // Translators: %s is the site name.
            'footer_text' => $settings['footer_text'] ?? sprintf(__('This email was sent by %s', 'guard-dog'), get_bloginfo('name')),
            'security_notice' => $settings['security_notice'] ?? __('If you did not create an account, please ignore this email.', 'guard-dog'),
        ]);

        // Replace placeholders
        $template_args['greeting_text'] = str_replace('{name}', $template_args['user_name'], $template_args['greeting_text']);
        $template_args['expiry_notice'] = str_replace('{hours}', (string)$template_args['expires_in'], $template_args['expiry_notice']);

        // Generate email HTML
        ob_start();
        $this->render_email_verification_template($template_args);
        return ob_get_clean();
    }

    /**
     * Generate plain text email output
     *
     * @param array $external_args Optional external template arguments
     * @return string Plain text email content
     */
    public function generate_plain_text_output($external_args = []) {
        // Route to appropriate template generator
        if ($this->template_type === 'email-verification') {
            return $this->generate_email_verification_plain_text_output($external_args);
        } elseif ($this->template_type === 'password-expiration') {
            return $this->generate_password_expiration_plain_text_output($external_args);
        } elseif ($this->template_type === 'suspicious-activity-admin') {
            return $this->generate_suspicious_activity_admin_plain_text_output($external_args);
        } elseif ($this->template_type === 'suspicious-activity-user') {
            return $this->generate_suspicious_activity_user_plain_text_output($external_args);
        } else {
            return $this->generate_two_factor_plain_text_output($external_args);
        }
    }

    /**
     * Generate two-factor plain text email output
     *
     * @param array $external_args Optional external template arguments
     * @return string Plain text email content
     */
    protected function generate_two_factor_plain_text_output($external_args = []) {
        $settings = $this->get_settings();

        // Prepare template arguments with customized values
        $template_args = array_merge([
            // Mock data for preview
            'code' => '123456',
            'user' => wp_get_current_user(),
            'site_name' => !empty($settings['header_text']) ? $settings['header_text'] : get_bloginfo('name'),
            'expiry_minutes' => 10,
        ], $external_args);

        // Get text content from settings
        $header_text = $settings['header_text'] ?? get_bloginfo('name');
        $greeting_text = $settings['greeting_text'] ?? __('Hello {name},', 'guard-dog');
        $intro_text = $settings['intro_text'] ?? __('You have requested a two-factor authentication code to log in to your account.', 'guard-dog');
        $code_label = $settings['code_label'] ?? __('Your Verification Code', 'guard-dog');
        $security_notice = $settings['security_notice'] ?? __('If you did not request this code, please ignore this email and consider changing your password.', 'guard-dog');

        // Replace {name} placeholder in greeting
        if ($template_args['user']) {
            $greeting_text = str_replace(
                '{name}',
                $template_args['user']->display_name,
                $greeting_text
            );
        }

        // Build plain text email
        $plain_text = $header_text . "\n\n";
        $plain_text .= $greeting_text . "\n\n";
        $plain_text .= $intro_text . "\n\n";
        $plain_text .= $code_label . ": " . $template_args['code'] . "\n\n";
        $plain_text .= sprintf(
			// Translators: %d is the expiration time in minutes.
            _n(
                'This code will expire in %d minute.',
                'This code will expire in %d minutes.',
                $template_args['expiry_minutes'],
                'guard-dog'
            ),
            $template_args['expiry_minutes']
        ) . "\n\n";
        $plain_text .= __('Security Notice:', 'guard-dog') . " " . $security_notice . "\n";

        return $plain_text;
    }

    /**
     * Generate email verification plain text email output
     *
     * @param array $external_args Optional external template arguments
     * @return string Plain text email content
     */
    protected function generate_email_verification_plain_text_output($external_args = []) {
        $settings = $this->get_settings();

        // Prepare template arguments with customized values
        $template_args = array_merge([
            // Mock data for preview
            'user_name' => wp_get_current_user()->display_name ?? 'John Doe',
            'verification_link' => home_url('/?action=guard_dog_verify_email&token=preview&key=preview'),
            'expires_in' => 48,
            'site_name' => !empty($settings['header_text']) ? $settings['header_text'] : get_bloginfo('name'),
            'site_url' => home_url(),
        ], $external_args);

        // Get text content from settings
        $header_text = $settings['header_text'] ?? get_bloginfo('name');
        $greeting_text = $settings['greeting_text'] ?? __('Hello {name},', 'guard-dog');
        $intro_text = $settings['intro_text'] ?? __('Thank you for registering! Please verify your email address by visiting the following link:', 'guard-dog');
        $expiry_notice = $settings['expiry_notice'] ?? __('This verification link will expire in {hours} hours.', 'guard-dog');
        $security_notice = $settings['security_notice'] ?? __('If you did not create an account, please ignore this email.', 'guard-dog');
        // Translators: %s is the site name.
        $footer_text = $settings['footer_text'] ?? sprintf(__('This email was sent by %s', 'guard-dog'), get_bloginfo('name'));

        // Replace placeholders
        $greeting_text = str_replace('{name}', $template_args['user_name'], $greeting_text);
        $expiry_notice = str_replace('{hours}', (string)$template_args['expires_in'], $expiry_notice);

        // Build plain text email
        $plain_text = $header_text . "\n\n";
        $plain_text .= $greeting_text . "\n\n";
        $plain_text .= $intro_text . "\n\n";
        $plain_text .= $template_args['verification_link'] . "\n\n";
        $plain_text .= $expiry_notice . "\n\n";
        $plain_text .= __('Security Notice:', 'guard-dog') . " " . $security_notice . "\n\n";
        $plain_text .= "---\n";
        $plain_text .= $footer_text . "\n";
        $plain_text .= $template_args['site_url'] . "\n";

        return $plain_text;
    }

    /**
     * Generate password expiration email output
     *
     * @param array $settings_or_args Current settings or template args
     * @return string Generated HTML
     */
    protected function generate_password_expiration_output($settings_or_args = []) {
        // Determine if this is preview mode (passing settings) or email mode (passing template args)
        // If 'reset_link' or 'user_name' keys exist, it's email mode with template args
        $is_email_mode = isset($settings_or_args['reset_link']) || isset($settings_or_args['user_name']);

        if ($is_email_mode) {
            // Email generation mode: merge external args with saved settings
            $settings = $this->get_settings();
            $external_args = $settings_or_args;
        } else {
            // Preview mode: use passed settings directly (may be unsaved)
            // If empty, use saved settings from database
            if (empty($settings_or_args)) {
                $settings = $this->get_settings();
            } else {
                $settings = $settings_or_args;
            }
            $external_args = [];
        }

        // Determine if password is expired or just warning
        $is_expired = isset($external_args['is_expired']) ? $external_args['is_expired'] : false;

        // Prepare template arguments with customized values
        $template_args = array_merge([
            // Mock data for preview
            'user_name' => wp_get_current_user()->display_name ?? 'John Doe',
            'reset_link' => wp_lostpassword_url(),
            'days_until' => 7,
            'expiration_date' => date_i18n(get_option('date_format'), strtotime('+7 days')),
            'is_expired' => false,
            'site_name' => !empty($settings['header_text']) ? $settings['header_text'] : get_bloginfo('name'),
            'site_url' => home_url(),
        ], $external_args, [
            // Customization settings (from passed settings or saved settings)
            'logo_url' => $settings['logo'] ?? '',
            'logo_width' => $settings['logo_width'] ?? 200,
            'primary_color' => $settings['primary_color'] ?? '#d63638',
            'accent_color' => $settings['accent_color'] ?? '#b32d2e',
            'text_color' => $settings['text_color'] ?? '#333333',
            'background_color' => $settings['background_color'] ?? '#f4f4f4',
            'content_background' => $settings['content_background'] ?? '#ffffff',
            'button_background' => $settings['button_background'] ?? '#d63638',
            'button_text_color' => $settings['button_text_color'] ?? '#ffffff',
            'border_radius' => $settings['border_radius'] ?? 4,
            'greeting_text' => $settings['greeting_text'] ?? __('Hello {name},', 'guard-dog'),
            'warning_intro_text' => $settings['warning_intro_text'] ?? __('Your password will expire in {days_until} day(s) (on {expiration_date}). Please reset your password soon to avoid being locked out.', 'guard-dog'),
            'expired_intro_text' => $settings['expired_intro_text'] ?? __('Your password has expired. Please reset your password to continue accessing your account.', 'guard-dog'),
            'button_text' => $settings['button_text'] ?? __('Reset Password', 'guard-dog'),
            // Translators: %s is the site name.
            'footer_text' => $settings['footer_text'] ?? sprintf(__('This email was sent by %s', 'guard-dog'), get_bloginfo('name')),
            'security_notice' => $settings['security_notice'] ?? __('If you did not request a password reset, please ignore this email and contact support if you have concerns.', 'guard-dog'),
        ]);

        // Replace placeholders
        $template_args['greeting_text'] = str_replace('{name}', $template_args['user_name'], $template_args['greeting_text']);
        $template_args['warning_intro_text'] = str_replace('{days_until}', (string)$template_args['days_until'], $template_args['warning_intro_text']);
        $template_args['warning_intro_text'] = str_replace('{expiration_date}', $template_args['expiration_date'], $template_args['warning_intro_text']);

        // Generate email HTML
        ob_start();
        $this->render_password_expiration_template($template_args);
        return ob_get_clean();
    }

    /**
     * Generate password expiration plain text email output
     *
     * @param array $external_args Optional external template arguments
     * @return string Plain text email content
     */
    protected function generate_password_expiration_plain_text_output($external_args = []) {
        $settings = $this->get_settings();

        // Determine if password is expired or just warning
        $is_expired = isset($external_args['is_expired']) ? $external_args['is_expired'] : false;

        // Prepare template arguments with customized values
        $template_args = array_merge([
            // Mock data for preview
            'user_name' => wp_get_current_user()->display_name ?? 'John Doe',
            'reset_link' => wp_lostpassword_url(),
            'days_until' => 7,
            'expiration_date' => date_i18n(get_option('date_format'), strtotime('+7 days')),
            'is_expired' => false,
            'site_name' => !empty($settings['header_text']) ? $settings['header_text'] : get_bloginfo('name'),
            'site_url' => home_url(),
        ], $external_args);

        // Get text content from settings
        $header_text = $settings['header_text'] ?? get_bloginfo('name');
        $greeting_text = $settings['greeting_text'] ?? __('Hello {name},', 'guard-dog');
        $warning_intro_text = $settings['warning_intro_text'] ?? __('Your password will expire in {days_until} day(s) (on {expiration_date}). Please reset your password soon to avoid being locked out.', 'guard-dog');
        $expired_intro_text = $settings['expired_intro_text'] ?? __('Your password has expired. Please reset your password to continue accessing your account.', 'guard-dog');
        $button_text = $settings['button_text'] ?? __('Reset Password', 'guard-dog');
        $security_notice = $settings['security_notice'] ?? __('If you did not request a password reset, please ignore this email and contact support if you have concerns.', 'guard-dog');
        // Translators: %s is the site name.
        $footer_text = $settings['footer_text'] ?? sprintf(__('This email was sent by %s', 'guard-dog'), get_bloginfo('name'));

        // Replace placeholders
        $greeting_text = str_replace('{name}', $template_args['user_name'], $greeting_text);
        $warning_intro_text = str_replace('{days_until}', (string)$template_args['days_until'], $warning_intro_text);
        $warning_intro_text = str_replace('{expiration_date}', $template_args['expiration_date'], $warning_intro_text);

        // Build plain text email
        $plain_text = $header_text . "\n\n";
        $plain_text .= $greeting_text . "\n\n";
        if ($is_expired) {
            $plain_text .= $expired_intro_text . "\n\n";
        } else {
            $plain_text .= $warning_intro_text . "\n\n";
        }
        $plain_text .= $button_text . ": " . $template_args['reset_link'] . "\n\n";
        $plain_text .= __('Security Notice:', 'guard-dog') . " " . $security_notice . "\n\n";
        $plain_text .= "---\n";
        $plain_text .= $footer_text . "\n";
        $plain_text .= $template_args['site_url'] . "\n";

        return $plain_text;
    }

    /**
     * Generate suspicious activity admin email output
     *
     * @param array $settings_or_args Current settings or template args
     * @return string Generated HTML
     */
    protected function generate_suspicious_activity_admin_output( $settings_or_args = array() ) {
        $is_email_mode = isset( $settings_or_args['type'] ) || isset( $settings_or_args['details'] );

        if ( $is_email_mode ) {
            $settings   = $this->get_settings();
            $external_args = $settings_or_args;
        } else {
            $settings     = empty( $settings_or_args ) ? $this->get_settings() : $settings_or_args;
            $external_args = array();
        }

        $user     = isset( $external_args['user'] ) ? $external_args['user'] : wp_get_current_user();
        $username = $user && ! empty( $user->user_login ) ? $user->user_login : 'admin';
        $type     = isset( $external_args['type'] ) ? $external_args['type'] : 'ip_shift';
        $details  = isset( $external_args['details'] ) ? $external_args['details'] : "Old IP: 1.2.3.4 (US)\nNew IP: 5.6.7.8 (DE)\n\nThis may indicate a session hijacking attempt.";
        $site_name = isset( $external_args['site_name'] ) ? $external_args['site_name'] : ( ! empty( $settings['header_text'] ) ? $settings['header_text'] : get_bloginfo( 'name' ) );

        $template_args = array_merge(
            array(
                'user'      => $user,
                'username'  => $username,
                'type'      => $type,
                'details'   => $details,
                'site_name' => $site_name,
            ),
            array(
                'logo_url'          => $settings['logo'] ?? '',
                'logo_width'        => $settings['logo_width'] ?? 200,
                'primary_color'     => $settings['primary_color'] ?? '#d63638',
                'accent_color'      => $settings['accent_color'] ?? '#b32d2e',
                'text_color'        => $settings['text_color'] ?? '#333333',
                'background_color'  => $settings['background_color'] ?? '#f4f4f4',
                'content_background' => $settings['content_background'] ?? '#ffffff',
                'details_background' => $settings['details_background'] ?? '#f8f9fa',
                'border_radius'     => $settings['border_radius'] ?? 4,
                'greeting_text'     => $settings['greeting_text'] ?? __( 'Admin,', 'guard-dog' ),
                'intro_text'        => $settings['intro_text'] ?? __( "The following suspicious session activity was detected on your site for user '{username}':", 'guard-dog' ),
                'footer_text'       => $settings['footer_text'] ?? sprintf( __( 'This email was sent by %s', 'guard-dog' ), get_bloginfo( 'name' ) ),
            )
        );

        $template_args['intro_text'] = str_replace( '{username}', $username, $template_args['intro_text'] );

        ob_start();
        $this->render_suspicious_activity_admin_template( $template_args );
        return ob_get_clean();
    }

    /**
     * Generate suspicious activity admin plain text output
     *
     * @param array $external_args Template arguments
     * @return string Plain text email content
     */
    protected function generate_suspicious_activity_admin_plain_text_output( $external_args = array() ) {
        $settings = $this->get_settings();

        $user     = isset( $external_args['user'] ) ? $external_args['user'] : wp_get_current_user();
        $username = $user && ! empty( $user->user_login ) ? $user->user_login : 'admin';
        $type     = isset( $external_args['type'] ) ? $external_args['type'] : 'ip_shift';
        $details  = isset( $external_args['details'] ) ? $external_args['details'] : "Old IP: 1.2.3.4 (US)\nNew IP: 5.6.7.8 (DE)\n\nThis may indicate a session hijacking attempt.";
        $site_name = isset( $external_args['site_name'] ) ? $external_args['site_name'] : ( ! empty( $settings['header_text'] ) ? $settings['header_text'] : get_bloginfo( 'name' ) );

        $greeting_text = $settings['greeting_text'] ?? __( 'Admin,', 'guard-dog' );
        $intro_text    = $settings['intro_text'] ?? __( "The following suspicious session activity was detected on your site for user '{username}':", 'guard-dog' );
        $footer_text   = $settings['footer_text'] ?? sprintf( __( 'This email was sent by %s', 'guard-dog' ), get_bloginfo( 'name' ) );

        $intro_text = str_replace( '{username}', $username, $intro_text );

        $plain = $site_name . "\n\n";
        $plain .= $greeting_text . "\n\n";
        $plain .= $intro_text . "\n\n";
        $plain .= $details . "\n\n";
        $plain .= "---\n";
        $plain .= $footer_text . "\n";

        return $plain;
    }

    /**
     * Generate suspicious activity user email output
     *
     * @param array $settings_or_args Current settings or template args
     * @return string Generated HTML
     */
    protected function generate_suspicious_activity_user_output( $settings_or_args = array() ) {
        $is_email_mode = isset( $settings_or_args['user'] ) && ( isset( $settings_or_args['site_name'] ) || isset( $settings_or_args['name'] ) );

        if ( $is_email_mode ) {
            $settings      = $this->get_settings();
            $external_args = $settings_or_args;
        } else {
            $settings      = empty( $settings_or_args ) ? $this->get_settings() : $settings_or_args;
            $external_args = array();
        }

        $user      = isset( $external_args['user'] ) ? $external_args['user'] : wp_get_current_user();
        $name      = isset( $external_args['name'] ) ? $external_args['name'] : ( $user && ! empty( $user->display_name ) ? $user->display_name : 'User' );
        $site_name = isset( $external_args['site_name'] ) ? $external_args['site_name'] : ( ! empty( $settings['header_text'] ) ? $settings['header_text'] : get_bloginfo( 'name' ) );

        $template_args = array_merge(
            array(
                'user'      => $user,
                'name'      => $name,
                'site_name' => $site_name,
            ),
            array(
                'logo_url'           => $settings['logo'] ?? '',
                'logo_width'         => $settings['logo_width'] ?? 200,
                'primary_color'      => $settings['primary_color'] ?? '#d63638',
                'accent_color'       => $settings['accent_color'] ?? '#b32d2e',
                'text_color'         => $settings['text_color'] ?? '#333333',
                'background_color'   => $settings['background_color'] ?? '#f4f4f4',
                'content_background' => $settings['content_background'] ?? '#ffffff',
                'border_radius'      => $settings['border_radius'] ?? 4,
                'greeting_text'      => $settings['greeting_text'] ?? __( 'Hello {name},', 'guard-dog' ),
                'intro_text'         => $settings['intro_text'] ?? __( "We detected unusual activity on your account. If this wasn't you, please change your password immediately and review your active sessions.", 'guard-dog' ),
                'footer_text'        => $settings['footer_text'] ?? sprintf( __( 'This email was sent by %s', 'guard-dog' ), get_bloginfo( 'name' ) ),
                'security_notice'    => $settings['security_notice'] ?? '',
            )
        );

        $template_args['greeting_text'] = str_replace( '{name}', $name, $template_args['greeting_text'] );

        ob_start();
        $this->render_suspicious_activity_user_template( $template_args );
        return ob_get_clean();
    }

    /**
     * Generate suspicious activity user plain text output
     *
     * @param array $external_args Template arguments
     * @return string Plain text email content
     */
    protected function generate_suspicious_activity_user_plain_text_output( $external_args = array() ) {
        $settings = $this->get_settings();

        $user      = isset( $external_args['user'] ) ? $external_args['user'] : wp_get_current_user();
        $name      = isset( $external_args['name'] ) ? $external_args['name'] : ( $user && ! empty( $user->display_name ) ? $user->display_name : 'User' );
        $site_name = isset( $external_args['site_name'] ) ? $external_args['site_name'] : ( ! empty( $settings['header_text'] ) ? $settings['header_text'] : get_bloginfo( 'name' ) );

        $greeting_text    = $settings['greeting_text'] ?? __( 'Hello {name},', 'guard-dog' );
        $intro_text       = $settings['intro_text'] ?? __( "We detected unusual activity on your account. If this wasn't you, please change your password immediately and review your active sessions.", 'guard-dog' );
        $footer_text      = $settings['footer_text'] ?? sprintf( __( 'This email was sent by %s', 'guard-dog' ), get_bloginfo( 'name' ) );
        $security_notice  = $settings['security_notice'] ?? '';

        $greeting_text = str_replace( '{name}', $name, $greeting_text );

        $plain = $site_name . "\n\n";
        $plain .= $greeting_text . "\n\n";
        $plain .= $intro_text . "\n\n";
        if ( ! empty( $security_notice ) ) {
            $plain .= __( 'Security Notice:', 'guard-dog' ) . ' ' . $security_notice . "\n\n";
        }
        $plain .= "---\n";
        $plain .= $footer_text . "\n";

        return $plain;
    }

    /**
     * Render suspicious activity admin template
     *
     * @param array $args Template arguments
     */
    protected function render_suspicious_activity_admin_template( $args ) {
        extract( $args );
        $details_background = isset( $details_background ) && $details_background !== '' ? $details_background : '#f8f9fa';
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <?php // Translators: %s is the site name. ?>
            <title><?php echo esc_html( sprintf( __( '[%s] Suspicious Session Activity', 'guard-dog' ), $site_name ) ); ?></title>
            <style type="text/css">
                body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; line-height: 1.6; color: <?php echo esc_attr( $text_color ); ?>; background-color: <?php echo esc_attr( $background_color ); ?>; margin: 0; padding: 0; }
                .email-wrapper { max-width: 600px; margin: 0 auto; background-color: <?php echo esc_attr( $content_background ); ?>; }
                .email-header { background-color: <?php echo esc_attr( $primary_color ); ?>; color: #fff; padding: 20px; text-align: center; }
                .email-header img { max-width: <?php echo esc_attr( $logo_width ); ?>px; height: auto; }
                .email-header h1 { margin: 0; font-size: 24px; font-weight: 600; }
                .email-content { padding: 30px; }
                .details-box { background: <?php echo esc_attr( $details_background ); ?>; border: 1px solid <?php echo esc_attr( $accent_color ); ?>; border-radius: <?php echo esc_attr( $border_radius ); ?>px; padding: 16px; margin: 16px 0; white-space: pre-wrap; font-family: monospace; font-size: 14px; }
                .email-footer { background: #f9f9f9; padding: 20px 30px; text-align: center; font-size: 12px; color: #999; border-top: 1px solid #ddd; }
            </style>
        </head>
        <body>
            <div class="email-wrapper">
                <div class="email-header">
                    <?php if ( ! empty( $logo_url ) ) : ?>
                        <img src="<?php echo esc_url( $logo_url ); ?>" alt="<?php echo esc_attr( $site_name ); ?>">
                    <?php else : ?>
                        <h1><?php echo esc_html( $site_name ); ?></h1>
                    <?php endif; ?>
                </div>
                <div class="email-content">
                    <p><?php echo esc_html( $greeting_text ); ?></p>
                    <p><?php echo esc_html( $intro_text ); ?></p>
                    <div class="details-box"><?php echo esc_html( $details ); ?></div>
                </div>
                <div class="email-footer">
                    <p><?php echo esc_html( $footer_text ); ?></p>
                </div>
            </div>
        </body>
        </html>
        <?php
    }

    /**
     * Render suspicious activity user template
     *
     * @param array $args Template arguments
     */
    protected function render_suspicious_activity_user_template( $args ) {
        extract( $args );
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <?php // Translators: %s is the site name. ?>
            <title><?php echo esc_html( sprintf( __( '[%s] Security Alert', 'guard-dog' ), $site_name ) ); ?></title>
            <style type="text/css">
                body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; line-height: 1.6; color: <?php echo esc_attr( $text_color ); ?>; background-color: <?php echo esc_attr( $background_color ); ?>; margin: 0; padding: 0; }
                .email-wrapper { max-width: 600px; margin: 0 auto; background-color: <?php echo esc_attr( $content_background ); ?>; }
                .email-header { background-color: <?php echo esc_attr( $primary_color ); ?>; color: #fff; padding: 20px; text-align: center; }
                .email-header img { max-width: <?php echo esc_attr( $logo_width ); ?>px; height: auto; }
                .email-header h1 { margin: 0; font-size: 24px; font-weight: 600; }
                .email-content { padding: 30px; }
                .warning-text { color: #d63638; font-size: 14px; margin-top: 16px; }
                .email-footer { background: #f9f9f9; padding: 20px 30px; text-align: center; font-size: 12px; color: #999; border-top: 1px solid #ddd; }
            </style>
        </head>
        <body>
            <div class="email-wrapper">
                <div class="email-header">
                    <?php if ( ! empty( $logo_url ) ) : ?>
                        <img src="<?php echo esc_url( $logo_url ); ?>" alt="<?php echo esc_attr( $site_name ); ?>">
                    <?php else : ?>
                        <h1><?php echo esc_html( $site_name ); ?></h1>
                    <?php endif; ?>
                </div>
                <div class="email-content">
                    <p><?php echo esc_html( $greeting_text ); ?></p>
                    <p><?php echo esc_html( $intro_text ); ?></p>
                    <?php if ( ! empty( $security_notice ) ) : ?>
                        <p class="warning-text"><strong><?php esc_html_e( 'Security Notice:', 'guard-dog' ); ?></strong> <?php echo esc_html( $security_notice ); ?></p>
                    <?php endif; ?>
                </div>
                <div class="email-footer">
                    <p><?php echo esc_html( $footer_text ); ?></p>
                </div>
            </div>
        </body>
        </html>
        <?php
    }

    /**
     * Render email verification template with customizations
     *
     * @param array $args Template arguments
     */
    protected function render_email_verification_template($args) {
        extract($args);
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <?php // Translators: %s is the site name. ?>
            <title><?php echo esc_html(sprintf(__('[%s] Verify Your Email Address', 'guard-dog'), $site_name)); ?></title>
            <style type="text/css">
                body {
                    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
                    line-height: 1.6;
                    color: <?php echo esc_attr($text_color); ?>;
                    background-color: <?php echo esc_attr($background_color); ?>;
                    margin: 0;
                    padding: 0;
                }
                .email-wrapper {
                    max-width: 600px;
                    margin: 0 auto;
                    background-color: <?php echo esc_attr($content_background); ?>;
                }
                .email-header {
                    background-color: <?php echo esc_attr($primary_color); ?>;
                    color: #ffffff;
                    padding: 20px;
                    text-align: center;
                }
                .email-header img {
                    max-width: <?php echo esc_attr($logo_width); ?>px;
                    height: auto;
                }
                .email-header h1 {
                    margin: 0;
                    font-size: 24px;
                    font-weight: 600;
                }
                .email-content {
                    padding: 40px 30px;
                }
                .email-content p {
                    margin: 0 0 15px 0;
                    font-size: 16px;
                }
                .verification-button {
                    text-align: center;
                    margin: 30px 0;
                }
                .verification-button a {
                    display: inline-block;
                    background-color: <?php echo esc_attr($button_background); ?>;
                    color: <?php echo esc_attr($button_text_color); ?>;
                    padding: 12px 24px;
                    text-decoration: none;
                    border-radius: <?php echo esc_attr($border_radius); ?>px;
                    font-weight: bold;
                    font-size: 16px;
                }
                .verification-link-text {
                    word-break: break-all;
                    color: <?php echo esc_attr($primary_color); ?>;
                    font-size: 14px;
                }
                .expiry-notice {
                    color: #666;
                    font-size: 14px;
                    margin-top: 20px;
                }
                .email-footer {
                    background-color: #f9f9f9;
                    padding: 20px 30px;
                    text-align: center;
                    font-size: 12px;
                    color: #999;
                    border-top: 1px solid #ddd;
                }
                .warning-text {
                    color: #d63638;
                    font-size: 14px;
                    margin-top: 20px;
                }
            </style>
        </head>
        <body>
            <div class="email-wrapper">
                <div class="email-header">
                    <?php if (!empty($logo_url)): ?>
                        <img src="<?php echo esc_url($logo_url); ?>" alt="<?php echo esc_attr($site_name); ?>">
                    <?php else: ?>
                        <h1><?php echo esc_html($site_name); ?></h1>
                    <?php endif; ?>
                </div>

                <div class="email-content">
                    <p><?php echo esc_html($greeting_text); ?></p>

                    <p><?php echo esc_html($intro_text); ?></p>

                    <div class="verification-button">
                        <a href="<?php echo esc_url($verification_link); ?>"><?php echo esc_html($button_text); ?></a>
                    </div>

                    <p><?php esc_html_e('Or copy and paste this link into your browser:', 'guard-dog'); ?></p>
                    <p class="verification-link-text"><?php echo esc_url($verification_link); ?></p>

                    <p class="expiry-notice"><?php echo esc_html($expiry_notice); ?></p>

                    <p class="warning-text"><?php echo esc_html($security_notice); ?></p>
                </div>

                <div class="email-footer">
                    <p><?php echo esc_html($footer_text); ?></p>
                    <p><a href="<?php echo esc_url($site_url); ?>" style="color: #999;"><?php echo esc_url($site_url); ?></a></p>
                </div>
            </div>
        </body>
        </html>
        <?php
    }

    /**
     * Render password expiration template with customizations
     *
     * @param array $args Template arguments
     */
    protected function render_password_expiration_template($args) {
        extract($args);
        $is_expired = isset($is_expired) ? $is_expired : false;
        $intro_text = $is_expired ? $expired_intro_text : $warning_intro_text;
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <?php // Translators: %s is the site name. ?>
            <title><?php echo esc_html(sprintf(__('[%s] Password Expiration Notice', 'guard-dog'), $site_name)); ?></title>
            <style type="text/css">
                body {
                    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
                    line-height: 1.6;
                    color: <?php echo esc_attr($text_color); ?>;
                    background-color: <?php echo esc_attr($background_color); ?>;
                    margin: 0;
                    padding: 0;
                }
                .email-wrapper {
                    max-width: 600px;
                    margin: 0 auto;
                    background-color: <?php echo esc_attr($content_background); ?>;
                }
                .email-header {
                    background-color: <?php echo esc_attr($primary_color); ?>;
                    color: #ffffff;
                    padding: 20px;
                    text-align: center;
                }
                .email-header img {
                    max-width: <?php echo esc_attr($logo_width); ?>px;
                    height: auto;
                }
                .email-header h1 {
                    margin: 0;
                    font-size: 24px;
                    font-weight: 600;
                }
                .email-content {
                    padding: 30px;
                }
                .reset-button {
                    text-align: center;
                    margin: 30px 0;
                }
                .reset-button a {
                    display: inline-block;
                    background-color: <?php echo esc_attr($button_background); ?>;
                    color: <?php echo esc_attr($button_text_color); ?>;
                    padding: 12px 24px;
                    text-decoration: none;
                    border-radius: <?php echo esc_attr($border_radius); ?>px;
                    font-weight: bold;
                    font-size: 16px;
                }
                .reset-link-text {
                    word-break: break-all;
                    color: <?php echo esc_attr($primary_color); ?>;
                    font-size: 14px;
                }
                .email-footer {
                    background-color: #f9f9f9;
                    padding: 20px 30px;
                    text-align: center;
                    font-size: 12px;
                    color: #999;
                    border-top: 1px solid #ddd;
                }
                .warning-text {
                    color: #d63638;
                    font-size: 14px;
                    margin-top: 20px;
                }
            </style>
        </head>
        <body>
            <div class="email-wrapper">
                <div class="email-header">
                    <?php if (!empty($logo_url)): ?>
                        <img src="<?php echo esc_url($logo_url); ?>" alt="<?php echo esc_attr($site_name); ?>">
                    <?php else: ?>
                        <h1><?php echo esc_html($site_name); ?></h1>
                    <?php endif; ?>
                </div>

                <div class="email-content">
                    <p><?php echo esc_html($greeting_text); ?></p>

                    <p><?php echo esc_html($intro_text); ?></p>

                    <div class="reset-button">
                        <a href="<?php echo esc_url($reset_link); ?>"><?php echo esc_html($button_text); ?></a>
                    </div>

                    <p class="reset-link-text"><?php echo esc_html__('Or copy and paste this link into your browser:', 'guard-dog'); ?><br>
                    <a href="<?php echo esc_url($reset_link); ?>" style="color: <?php echo esc_attr($primary_color); ?>;"><?php echo esc_url($reset_link); ?></a></p>

                    <p class="warning-text"><?php echo esc_html($security_notice); ?></p>
                </div>

                <div class="email-footer">
                    <p><?php echo esc_html($footer_text); ?></p>
                    <p><a href="<?php echo esc_url($site_url); ?>" style="color: #999;"><?php echo esc_url($site_url); ?></a></p>
                </div>
            </div>
        </body>
        </html>
        <?php
    }

    /**
     * Render email template with customizations
     *
     * @param array $args Template arguments
     */
    protected function render_email_template($args) {
        extract($args);
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <?php // Translators: %s is the site name. ?>
            <title><?php echo esc_html(sprintf(__('[%s] Two-Factor Authentication Code', 'guard-dog'), $site_name)); ?></title>
            <style type="text/css">
                body {
                    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
                    line-height: 1.6;
                    color: <?php echo esc_attr($text_color); ?>;
                    background-color: <?php echo esc_attr($background_color); ?>;
                    margin: 0;
                    padding: 0;
                }
                .email-wrapper {
                    max-width: 600px;
                    margin: 0 auto;
                    background-color: <?php echo esc_attr($content_background); ?>;
                }
                .email-header {
                    background-color: <?php echo esc_attr($primary_color); ?>;
                    color: #ffffff;
                    padding: 20px;
                    text-align: center;
                }
                .email-header img {
                    max-width: <?php echo esc_attr($logo_width); ?>px;
                    height: auto;
                }
                .email-header h1 {
                    margin: 0;
                    font-size: 24px;
                    font-weight: 600;
                }
                .email-content {
                    padding: 40px 30px;
                }
                .email-content p {
                    margin: 0 0 15px 0;
                    font-size: 16px;
                }
                .verification-code {
                    background-color: <?php echo esc_attr($code_background); ?>;
                    border: 2px solid <?php echo esc_attr($accent_color); ?>;
                    border-radius: <?php echo esc_attr($border_radius); ?>px;
                    padding: 20px;
                    text-align: center;
                    margin: 30px 0;
                }
                .verification-code-label {
                    font-size: 14px;
                    color: <?php echo esc_attr($text_color); ?>;
                    margin-bottom: 10px;
                    text-transform: uppercase;
                    letter-spacing: 1px;
                    opacity: 0.8;
                }
                .verification-code-value {
                    font-size: 36px;
                    font-weight: bold;
                    color: <?php echo esc_attr($primary_color); ?>;
                    letter-spacing: 8px;
                    font-family: "Courier New", Courier, monospace;
                }
                .email-footer {
                    background-color: <?php echo esc_attr($code_background); ?>;
                    padding: 20px 30px;
                    text-align: center;
                    font-size: 14px;
                    color: <?php echo esc_attr($text_color); ?>;
                    border-top: 1px solid #e1e1e1;
                }
                .warning-text {
                    color: #d63638;
                    font-size: 14px;
                    margin-top: 20px;
                }
            </style>
        </head>
        <body>
            <div class="email-wrapper">
                <div class="email-header">
                    <?php if (!empty($logo_url)): ?>
                        <img src="<?php echo esc_url($logo_url); ?>" alt="<?php echo esc_attr($site_name); ?>">
                    <?php else: ?>
                        <h1><?php echo esc_html($site_name); ?></h1>
                    <?php endif; ?>
                </div>

                <div class="email-content">
                    <p><?php echo esc_html($greeting_text); ?></p>

                    <p><?php echo esc_html($intro_text); ?></p>

                    <div class="verification-code">
                        <div class="verification-code-label">
                            <?php echo esc_html($code_label); ?>
                        </div>
                        <div class="verification-code-value">
                            <?php echo esc_html($code); ?>
                        </div>
                    </div>

                    <p><?php
                        echo esc_html(sprintf(
                            // Translators: %d is the expiration time in minutes.
                            _n(
                                'This code will expire in %d minute.',
                                'This code will expire in %d minutes.',
                                $expiry_minutes,
                                'guard-dog'
                            ),
                            $expiry_minutes
                        ));
                    ?></p>

                    <p class="warning-text">
                        <strong><?php esc_html_e('Security Notice:', 'guard-dog'); ?></strong>
                        <?php echo esc_html($security_notice); ?>
                    </p>
                </div>

                <div class="email-footer">
                    <p><?php echo esc_html($footer_text); ?></p>
                    <p><?php esc_html_e('Please do not reply to this email.', 'guard-dog'); ?></p>
                </div>
            </div>
        </body>
        </html>
        <?php
    }

    /**
     * Check if theme override exists
     *
     * @return bool
     */
    protected function has_theme_override() {
        $theme_path = get_stylesheet_directory() . '/guard-dog/emails/' . $this->template_type . '.php';
        $parent_theme_path = get_template_directory() . '/guard-dog/emails/' . $this->template_type . '.php';

        return file_exists($theme_path) || file_exists($parent_theme_path);
    }

    /**
     * Export settings to theme file
     *
     * @return array Result with success status and message
     */
    protected function export_to_theme() {
        // Get current settings
        $settings = $this->get_settings();

        // Prepare theme directory
        $theme_dir = get_stylesheet_directory() . '/guard-dog/emails';

        // Check if directory exists, create if not
        if (!file_exists($theme_dir)) {
            if (!wp_mkdir_p($theme_dir)) {
                return [
                    'success' => false,
                    'message' => __('Failed to create theme directory. Please check file permissions.', 'guard-dog'),
                ];
            }
        }

        // Generate template file content
        $file_content = $this->generate_theme_template_file($settings);

        // Write file
        $file_path = $theme_dir . '/' . $this->template_type . '.php';

        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
        $result = file_put_contents($file_path, $file_content);

        if ($result === false) {
            return [
                'success' => false,
                'message' => __('Failed to write template file. Please check file permissions.', 'guard-dog'),
            ];
        }

        // Also export plain text version
        $plain_file_content = $this->generate_theme_template_file_plain($settings);
        $plain_file_path = $theme_dir . '/' . $this->template_type . '-plain.php';

        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
        file_put_contents($plain_file_path, $plain_file_content);

        do_action('guard_dog_customizer_exported_' . $this->get_customizer_id(), $file_path, $settings);

        return [
            'success' => true,
            'message' => sprintf(
                // Translators: %s is the file path.
                __('Template exported successfully to: %s', 'guard-dog'),
                str_replace(ABSPATH, '', $file_path)
            ),
            'file_path' => $file_path,
        ];
    }

    /**
     * Generate theme template file content
     *
     * @param array $settings Customizer settings
     * @return string PHP template file content
     */
    protected function generate_theme_template_file($settings) {
        if ( $this->template_type === 'suspicious-activity-admin' ) {
            return $this->generate_theme_template_file_suspicious_activity_admin( $settings );
        }
        if ( $this->template_type === 'suspicious-activity-user' ) {
            return $this->generate_theme_template_file_suspicious_activity_user( $settings );
        }

        // Extract settings (two-factor-code default)
        $logo_url = esc_js($settings['logo'] ?? '');
        $logo_width = absint($settings['logo_width'] ?? 200);
        $primary_color = esc_js($settings['primary_color'] ?? '#0073aa');
        $accent_color = esc_js($settings['accent_color'] ?? '#00a0d2');
        $text_color = esc_js($settings['text_color'] ?? '#333333');
        $background_color = esc_js($settings['background_color'] ?? '#f4f4f4');
        $content_background = esc_js($settings['content_background'] ?? '#ffffff');
        $code_background = esc_js($settings['code_background'] ?? '#f8f9fa');
        $border_radius = absint($settings['border_radius'] ?? 4);
        $header_text = esc_js($settings['header_text'] ?? get_bloginfo('name'));
        $greeting_text = esc_js($settings['greeting_text'] ?? 'Hello {name},');
        $intro_text = esc_js($settings['intro_text'] ?? 'You have requested a two-factor authentication code to log in to your account.');
        $code_label = esc_js($settings['code_label'] ?? 'Your Verification Code');
        $footer_text = esc_js($settings['footer_text'] ?? sprintf('This email was sent from %s', get_bloginfo('name')));
        $security_notice = esc_js($settings['security_notice'] ?? 'If you did not request this code, please ignore this email and consider changing your password.');

        // Build template file content as string using heredoc
        // This avoids PHP parsing issues with nested tags
        $template = <<<'TEMPLATE'
<?php
/**
 * Email Template: Two-Factor Authentication Code
 *
 * Generated by Guard Dog Email Template Customizer
 * Settings can be further customized by editing this file directly.
 *
 * Available variables:
 * @var string $code The 6-digit verification code
 * @var WP_User $user The user object
 * @var string $site_name The site name
 * @var int $expiry_minutes Code expiration time in minutes (default: 10)
 *
 * @package GuardDog
 * @since 1.8.45
 */

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

// Set default expiry if not provided
if (!isset($expiry_minutes)) {
    $expiry_minutes = 10;
}

// Customization settings (from customizer)
TEMPLATE;

        // Add the settings values
        $template .= "\n\$logo_url = '" . addslashes($logo_url) . "';\n";
        $template .= "\$logo_width = " . intval($logo_width) . ";\n";
        $template .= "\$primary_color = '" . addslashes($primary_color) . "';\n";
        $template .= "\$accent_color = '" . addslashes($accent_color) . "';\n";
        $template .= "\$text_color = '" . addslashes($text_color) . "';\n";
        $template .= "\$background_color = '" . addslashes($background_color) . "';\n";
        $template .= "\$content_background = '" . addslashes($content_background) . "';\n";
        $template .= "\$code_background = '" . addslashes($code_background) . "';\n";
        $template .= "\$border_radius = " . intval($border_radius) . ";\n";
        $template .= "\$header_text = '" . addslashes($header_text) . "';\n";
        $template .= "\$greeting_text = '" . addslashes($greeting_text) . "';\n";
        $template .= "\$intro_text = '" . addslashes($intro_text) . "';\n";
        $template .= "\$code_label = '" . addslashes($code_label) . "';\n";
        $template .= "\$footer_text = '" . addslashes($footer_text) . "';\n";
        $template .= "\$security_notice = '" . addslashes($security_notice) . "';\n";

        // Continue with the rest of the template
        $template .= <<<'TEMPLATE'

// Replace {name} placeholder
$greeting_text = str_replace('{name}', $user->display_name, $greeting_text);
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <?php // Translators: %s is the site name. ?>
    <title><?php echo esc_html(sprintf(__('[%s] Two-Factor Authentication Code', 'guard-dog'), $site_name)); ?></title>
    <style type="text/css">
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
            line-height: 1.6;
            color: <?php echo esc_attr($text_color); ?>;
            background-color: <?php echo esc_attr($background_color); ?>;
            margin: 0;
            padding: 0;
        }
        .email-wrapper {
            max-width: 600px;
            margin: 0 auto;
            background-color: <?php echo esc_attr($content_background); ?>;
        }
        .email-header {
            background-color: <?php echo esc_attr($primary_color); ?>;
            color: #ffffff;
            padding: 20px;
            text-align: center;
        }
        .email-header img {
            max-width: <?php echo esc_attr($logo_width); ?>px;
            height: auto;
        }
        .email-header h1 {
            margin: 0;
            font-size: 24px;
            font-weight: 600;
        }
        .email-content {
            padding: 40px 30px;
        }
        .email-content p {
            margin: 0 0 15px 0;
            font-size: 16px;
        }
        .verification-code {
            background-color: <?php echo esc_attr($code_background); ?>;
            border: 2px solid <?php echo esc_attr($accent_color); ?>;
            border-radius: <?php echo esc_attr($border_radius); ?>px;
            padding: 20px;
            text-align: center;
            margin: 30px 0;
        }
        .verification-code-label {
            font-size: 14px;
            color: <?php echo esc_attr($text_color); ?>;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 1px;
            opacity: 0.8;
        }
        .verification-code-value {
            font-size: 36px;
            font-weight: bold;
            color: <?php echo esc_attr($primary_color); ?>;
            letter-spacing: 8px;
            font-family: "Courier New", Courier, monospace;
        }
        .email-footer {
            background-color: <?php echo esc_attr($code_background); ?>;
            padding: 20px 30px;
            text-align: center;
            font-size: 14px;
            color: <?php echo esc_attr($text_color); ?>;
            border-top: 1px solid #e1e1e1;
        }
        .warning-text {
            color: #d63638;
            font-size: 14px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="email-wrapper">
        <div class="email-header">
            <?php if (!empty($logo_url)): ?>
                <img src="<?php echo esc_url($logo_url); ?>" alt="<?php echo esc_attr($header_text); ?>">
            <?php else: ?>
                <h1><?php echo esc_html($header_text); ?></h1>
            <?php endif; ?>
        </div>

        <div class="email-content">
            <p><?php echo esc_html($greeting_text); ?></p>

            <p><?php echo esc_html($intro_text); ?></p>

            <div class="verification-code">
                <div class="verification-code-label">
                    <?php echo esc_html($code_label); ?>
                </div>
                <div class="verification-code-value">
                    <?php echo esc_html($code); ?>
                </div>
            </div>

            <p><?php
                // Translators: %d is the expiration time in minutes.
                echo esc_html(sprintf(
                    _n(
                        'This code will expire in %d minute.',
                        'This code will expire in %d minutes.',
                        $expiry_minutes,
                        'guard-dog'
                    ),
                    $expiry_minutes
                ));
            ?></p>

            <p class="warning-text">
                <strong><?php esc_html_e('Security Notice:', 'guard-dog'); ?></strong>
                <?php echo esc_html($security_notice); ?>
            </p>
        </div>

        <div class="email-footer">
            <p><?php echo esc_html($footer_text); ?></p>
            <p><?php esc_html_e('Please do not reply to this email.', 'guard-dog'); ?></p>
        </div>
    </div>
</body>
</html>
TEMPLATE;

        return $template;
    }

    /**
     * Generate theme template file for suspicious-activity-admin
     *
     * @param array $settings Customizer settings
     * @return string PHP template file content
     */
    protected function generate_theme_template_file_suspicious_activity_admin( $settings ) {
        $logo_url = esc_js( $settings['logo'] ?? '' );
        $logo_width = absint( $settings['logo_width'] ?? 200 );
        $primary_color = esc_js( $settings['primary_color'] ?? '#d63638' );
        $accent_color = esc_js( $settings['accent_color'] ?? '#b32d2e' );
        $text_color = esc_js( $settings['text_color'] ?? '#333333' );
        $background_color = esc_js( $settings['background_color'] ?? '#f4f4f4' );
        $content_background = esc_js( $settings['content_background'] ?? '#ffffff' );
        $details_background = esc_js( $settings['details_background'] ?? '#f8f9fa' );
        $border_radius = absint( $settings['border_radius'] ?? 4 );
        $greeting_text = esc_js( $settings['greeting_text'] ?? 'Admin,' );
        $intro_text = esc_js( $settings['intro_text'] ?? "The following suspicious session activity was detected on your site for user '{username}':" );
        $footer_text = esc_js( $settings['footer_text'] ?? sprintf( 'This email was sent by %s', get_bloginfo( 'name' ) ) );

        $s = "<?php\n/**\n * Email Template: Suspicious Session Activity (Admin)\n * Generated by Guard Dog. Variables: \$user, \$type, \$details, \$site_name\n * Override: your-theme/guard-dog/emails/suspicious-activity-admin.php\n */\nif (!defined('ABSPATH')) exit;\n";
        $s .= "\$username = \$user && !empty(\$user->user_login) ? \$user->user_login : '';\n";
        $s .= "\$intro_text = str_replace('{username}', \$username, '" . addslashes( $intro_text ) . "');\n";
        $s .= "\$logo_url = '" . addslashes( $logo_url ) . "';\n\$logo_width = " . $logo_width . ";\n\$primary_color = '" . addslashes( $primary_color ) . "';\n\$accent_color = '" . addslashes( $accent_color ) . "';\n\$text_color = '" . addslashes( $text_color ) . "';\n\$background_color = '" . addslashes( $background_color ) . "';\n\$content_background = '" . addslashes( $content_background ) . "';\n\$details_background = '" . addslashes( $details_background ) . "';\n\$border_radius = " . $border_radius . ";\n\$greeting_text = '" . addslashes( $greeting_text ) . "';\n\$footer_text = '" . addslashes( $footer_text ) . "';\n?>\n";
        $s .= "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title><?php echo esc_html( sprintf( __( '[%s] Suspicious Session Activity', 'guard-dog' ), \$site_name ) ); ?></title><style>body{font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,sans-serif;line-height:1.6;color:<?php echo esc_attr(\$text_color); ?>;background:<?php echo esc_attr(\$background_color); ?>;margin:0;padding:0;}.email-wrapper{max-width:600px;margin:0 auto;background:<?php echo esc_attr(\$content_background); ?>;}.email-header{background:<?php echo esc_attr(\$primary_color); ?>;color:#fff;padding:20px;text-align:center;}.email-header img{max-width:<?php echo esc_attr(\$logo_width); ?>px;height:auto;}.email-header h1{margin:0;font-size:24px;}.email-content{padding:30px;}.details-box{background:<?php echo esc_attr(\$details_background); ?>;border:1px solid <?php echo esc_attr(\$accent_color); ?>;border-radius:<?php echo esc_attr(\$border_radius); ?>px;padding:16px;margin:16px 0;white-space:pre-wrap;font-family:monospace;font-size:14px;}.email-footer{background:#f9f9f9;padding:20px 30px;text-align:center;font-size:12px;color:#999;border-top:1px solid #ddd;}</style></head><body><div class=\"email-wrapper\"><div class=\"email-header\"><?php if (!empty(\$logo_url)): ?><img src=\"<?php echo esc_url(\$logo_url); ?>\" alt=\"<?php echo esc_attr(\$site_name); ?>\"><?php else: ?><h1><?php echo esc_html(\$site_name); ?></h1><?php endif; ?></div><div class=\"email-content\"><p><?php echo esc_html(\$greeting_text); ?></p><p><?php echo esc_html(\$intro_text); ?></p><div class=\"details-box\"><?php echo esc_html(\$details); ?></div></div><div class=\"email-footer\"><p><?php echo esc_html(\$footer_text); ?></p></div></div></body></html>\n";
        return $s;
    }

    /**
     * Generate theme template file for suspicious-activity-user
     *
     * @param array $settings Customizer settings
     * @return string PHP template file content
     */
    protected function generate_theme_template_file_suspicious_activity_user( $settings ) {
        $logo_url = esc_js( $settings['logo'] ?? '' );
        $logo_width = absint( $settings['logo_width'] ?? 200 );
        $primary_color = esc_js( $settings['primary_color'] ?? '#d63638' );
        $accent_color = esc_js( $settings['accent_color'] ?? '#b32d2e' );
        $text_color = esc_js( $settings['text_color'] ?? '#333333' );
        $background_color = esc_js( $settings['background_color'] ?? '#f4f4f4' );
        $content_background = esc_js( $settings['content_background'] ?? '#ffffff' );
        $border_radius = absint( $settings['border_radius'] ?? 4 );
        $greeting_text = esc_js( $settings['greeting_text'] ?? 'Hello {name},' );
        $intro_text = esc_js( $settings['intro_text'] ?? "We detected unusual activity on your account. If this wasn't you, please change your password immediately and review your active sessions." );
        $footer_text = esc_js( $settings['footer_text'] ?? sprintf( 'This email was sent by %s', get_bloginfo( 'name' ) ) );
        $security_notice = esc_js( $settings['security_notice'] ?? '' );

        $s = "<?php\n/**\n * Email Template: Suspicious Session Activity (User)\n * Generated by Guard Dog. Variables: \$user, \$site_name. Use \$name = \$user->display_name.\n * Override: your-theme/guard-dog/emails/suspicious-activity-user.php\n */\nif (!defined('ABSPATH')) exit;\n";
        $s .= "\$name = \$user && !empty(\$user->display_name) ? \$user->display_name : 'User';\n";
        $s .= "\$greeting_text = str_replace('{name}', \$name, '" . addslashes( $greeting_text ) . "');\n";
        $s .= "\$logo_url = '" . addslashes( $logo_url ) . "';\n\$logo_width = " . $logo_width . ";\n\$primary_color = '" . addslashes( $primary_color ) . "';\n\$accent_color = '" . addslashes( $accent_color ) . "';\n\$text_color = '" . addslashes( $text_color ) . "';\n\$background_color = '" . addslashes( $background_color ) . "';\n\$content_background = '" . addslashes( $content_background ) . "';\n\$border_radius = " . $border_radius . ";\n\$intro_text = '" . addslashes( $intro_text ) . "';\n\$footer_text = '" . addslashes( $footer_text ) . "';\n\$security_notice = '" . addslashes( $security_notice ) . "';\n?>\n";
        $s .= "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title><?php echo esc_html( sprintf( __( '[%s] Security Alert', 'guard-dog' ), \$site_name ) ); ?></title><style>body{font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,sans-serif;line-height:1.6;color:<?php echo esc_attr(\$text_color); ?>;background:<?php echo esc_attr(\$background_color); ?>;margin:0;padding:0;}.email-wrapper{max-width:600px;margin:0 auto;background:<?php echo esc_attr(\$content_background); ?>;}.email-header{background:<?php echo esc_attr(\$primary_color); ?>;color:#fff;padding:20px;text-align:center;}.email-header img{max-width:<?php echo esc_attr(\$logo_width); ?>px;height:auto;}.email-header h1{margin:0;font-size:24px;}.email-content{padding:30px;}.warning-text{color:#d63638;font-size:14px;margin-top:16px;}.email-footer{background:#f9f9f9;padding:20px 30px;text-align:center;font-size:12px;color:#999;border-top:1px solid #ddd;}</style></head><body><div class=\"email-wrapper\"><div class=\"email-header\"><?php if (!empty(\$logo_url)): ?><img src=\"<?php echo esc_url(\$logo_url); ?>\" alt=\"<?php echo esc_attr(\$site_name); ?>\"><?php else: ?><h1><?php echo esc_html(\$site_name); ?></h1><?php endif; ?></div><div class=\"email-content\"><p><?php echo esc_html(\$greeting_text); ?></p><p><?php echo esc_html(\$intro_text); ?></p><?php if (!empty(\$security_notice)): ?><p class=\"warning-text\"><strong><?php esc_html_e('Security Notice:', 'guard-dog'); ?></strong> <?php echo esc_html(\$security_notice); ?></p><?php endif; ?></div><div class=\"email-footer\"><p><?php echo esc_html(\$footer_text); ?></p></div></div></body></html>\n";
        return $s;
    }

    /**
     * Generate plain text theme template file for suspicious-activity-admin
     *
     * @param array $settings Customizer settings
     * @return string PHP template file content
     */
    protected function generate_theme_template_file_plain_suspicious_activity_admin( $settings ) {
        $greeting_text = esc_js( $settings['greeting_text'] ?? 'Admin,' );
        $intro_text = esc_js( $settings['intro_text'] ?? "The following suspicious session activity was detected on your site for user '{username}':" );
        $footer_text = esc_js( $settings['footer_text'] ?? sprintf( 'This email was sent by %s', get_bloginfo( 'name' ) ) );

        $s = "<?php\n/**\n * Email Template: Suspicious Session Activity (Admin) - Plain Text\n * Generated by Guard Dog. Variables: \$user, \$type, \$details, \$site_name\n */\nif (!defined('ABSPATH')) exit;\n";
        $s .= "\$username = \$user && !empty(\$user->user_login) ? \$user->user_login : '';\n";
        $s .= "\$intro_text = str_replace('{username}', \$username, '" . addslashes( $intro_text ) . "');\n";
        $s .= "\$greeting_text = '" . addslashes( $greeting_text ) . "';\n\$footer_text = '" . addslashes( $footer_text ) . "';\n";
        $s .= "echo esc_html(\$site_name) . \"\\n\\n\";\necho esc_html(\$greeting_text) . \"\\n\\n\";\necho esc_html(\$intro_text) . \"\\n\\n\";\necho esc_html(\$details) . \"\\n\\n---\\n\";\necho esc_html(\$footer_text) . \"\\n\";\n";
        return $s;
    }

    /**
     * Generate plain text theme template file for suspicious-activity-user
     *
     * @param array $settings Customizer settings
     * @return string PHP template file content
     */
    protected function generate_theme_template_file_plain_suspicious_activity_user( $settings ) {
        $greeting_text = esc_js( $settings['greeting_text'] ?? 'Hello {name},' );
        $intro_text = esc_js( $settings['intro_text'] ?? "We detected unusual activity on your account. If this wasn't you, please change your password immediately and review your active sessions." );
        $footer_text = esc_js( $settings['footer_text'] ?? sprintf( 'This email was sent by %s', get_bloginfo( 'name' ) ) );
        $security_notice = esc_js( $settings['security_notice'] ?? '' );

        $s = "<?php\n/**\n * Email Template: Suspicious Session Activity (User) - Plain Text\n * Generated by Guard Dog. Variables: \$user, \$site_name\n */\nif (!defined('ABSPATH')) exit;\n";
        $s .= "\$name = \$user && !empty(\$user->display_name) ? \$user->display_name : 'User';\n";
        $s .= "\$greeting_text = str_replace('{name}', \$name, '" . addslashes( $greeting_text ) . "');\n";
        $s .= "\$intro_text = '" . addslashes( $intro_text ) . "';\n\$footer_text = '" . addslashes( $footer_text ) . "';\n\$security_notice = '" . addslashes( $security_notice ) . "';\n";
        $s .= "echo esc_html(\$site_name) . \"\\n\\n\";\necho esc_html(\$greeting_text) . \"\\n\\n\";\necho esc_html(\$intro_text) . \"\\n\\n\";\n";
        $s .= "if (!empty(\$security_notice)) { echo esc_html(__('Security Notice:', 'guard-dog')) . ' ' . esc_html(\$security_notice) . \"\\n\\n\"; }\n";
        $s .= "echo \"---\\n\";\necho esc_html(\$footer_text) . \"\\n\";\n";
        return $s;
    }

    /**
     * Generate plain text theme template file
     *
     * @param array $settings Customizer settings
     * @return string PHP template file content
     */
    protected function generate_theme_template_file_plain($settings) {
        if ( $this->template_type === 'suspicious-activity-admin' ) {
            return $this->generate_theme_template_file_plain_suspicious_activity_admin( $settings );
        }
        if ( $this->template_type === 'suspicious-activity-user' ) {
            return $this->generate_theme_template_file_plain_suspicious_activity_user( $settings );
        }

        $header_text = esc_js($settings['header_text'] ?? get_bloginfo('name'));
        $greeting_text = esc_js($settings['greeting_text'] ?? 'Hello {name},');
        $intro_text = esc_js($settings['intro_text'] ?? 'You have requested a two-factor authentication code to log in to your account.');
        $code_label = esc_js($settings['code_label'] ?? 'Your Verification Code');
        $security_notice = esc_js($settings['security_notice'] ?? 'If you did not request this code, please ignore this email and consider changing your password.');

        // Build template file content as string
        $template = <<<'TEMPLATE'
<?php
/**
 * Email Template: Two-Factor Authentication Code (Plain Text)
 *
 * Generated by Guard Dog Email Template Customizer
 *
 * @package GuardDog
 * @since 1.8.45
 */

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

// Set default expiry if not provided
if (!isset($expiry_minutes)) {
    $expiry_minutes = 10;
}

// Customization settings
TEMPLATE;

        // Add the settings values
        $template .= "\n\$header_text = '" . addslashes($header_text) . "';\n";
        $template .= "\$greeting_text = '" . addslashes($greeting_text) . "';\n";
        $template .= "\$intro_text = '" . addslashes($intro_text) . "';\n";
        $template .= "\$code_label = '" . addslashes($code_label) . "';\n";
        $template .= "\$security_notice = '" . addslashes($security_notice) . "';\n";

        // Continue with the rest of the template
        $template .= <<<'TEMPLATE'

// Replace {name} placeholder
$greeting_text = str_replace('{name}', $user->display_name, $greeting_text);

echo esc_html($header_text);
echo "\n\n";
echo esc_html($greeting_text) . "\n\n";
echo esc_html($intro_text) . "\n\n";
echo esc_html($code_label) . ": " . esc_html($code) . "\n\n";
// Translators: %d is the expiration time in minutes.
echo sprintf(
    esc_html(_n(
        'This code expires in %d minute.',
        'This code expires in %d minutes.',
        $expiry_minutes,
        'guard-dog'
    )),
    $expiry_minutes
) . "\n\n";
echo esc_html__('Security Notice:', 'guard-dog') . " " . esc_html($security_notice) . "\n";
TEMPLATE;

        return $template;
    }

    /**
     * Check if current page is the customizer page
     *
     * @param string $hook Current admin page hook
     * @return bool
     */
    protected function is_customizer_page($hook) {
        // Debug: Log the hook value
        if (function_exists('Guard_Dog') && Guard_Dog()->debug && Guard_Dog()->debug->is_enabled()) {
            Guard_Dog()->debug->info('Customizer page check', 'customizer', [
                'hook' => $hook,
                'contains_slug' => strpos($hook, 'guard-dog-email-customizer') !== false
            ]);
        }

        return strpos($hook, 'guard-dog-email-customizer') !== false;
    }

    /**
     * AJAX handler for preview
     * Override to handle template type from POST data
     */
    public function ajax_preview() {
        check_ajax_referer('guard_dog_customizer_preview_' . $this->get_customizer_id(), 'nonce');

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

        // Get template type from POST data if provided
        if (isset($_POST['template_type']) && array_key_exists(sanitize_text_field(wp_unslash($_POST['template_type'])), $this->available_template_types)) {
            $new_template_type = sanitize_text_field(wp_unslash($_POST['template_type']));
            if ($new_template_type !== $this->template_type) {
                $this->template_type = $new_template_type;
                // Reload settings for the correct template type
                $this->load_settings();
                // Re-register controls for the new template type
                $this->controls = [];
                $this->sections = [];
                $this->register_controls();
            }
        }

        // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        // Settings are unslashed here but sanitized in the loop below using each control's sanitize() method.
        // Each control has its own sanitization logic appropriate for its type (text, color, number, etc.).
        // This pattern is necessary because we need to iterate through the settings array to apply type-specific sanitization.
        $settings = isset($_POST['settings']) ? wp_unslash($_POST['settings']) : [];
        // phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

        // Sanitize settings
        $sanitized = [];
        foreach ($settings as $key => $value) {
            if (isset($this->controls[$key])) {
                $sanitized[$key] = $this->controls[$key]->sanitize($value);
            }
        }

        // Generate preview
        $html = $this->generate_output($sanitized);

        // Apply filter
        $html = apply_filters(
            'guard_dog_customizer_preview_' . $this->get_customizer_id(),
            $html,
            $sanitized
        );

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

    /**
     * Render preview-specific actions
     */
    protected function render_preview_actions() {
        ?>
        <button type="button" class="button send-test-email">
            <span class="dashicons dashicons-email"></span>
            <?php esc_html_e('Send Test Email', 'guard-dog'); ?>
        </button>
        <?php
    }

    /**
     * Initialize hooks - override parent to add test email handler
     */
    protected function init_hooks() {
        // Call parent to register standard AJAX handlers
        parent::init_hooks();

        // Register test email AJAX handler
        add_action('wp_ajax_guard_dog_send_test_email', [$this, 'ajax_send_test_email']);
    }

    /**
     * Enqueue additional assets specific to email customizer
     */
    protected function enqueue_additional_assets() {
        // No longer needed - AJAX handlers registered in init_hooks()
    }

    /**
     * AJAX handler for sending test email
     */
    public function ajax_send_test_email() {
        check_ajax_referer('guard_dog_customizer_preview_' . $this->get_customizer_id(), 'nonce');

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

        // Get template type from POST data if provided
        if (isset($_POST['template_type']) && array_key_exists(sanitize_text_field(wp_unslash($_POST['template_type'])), $this->available_template_types)) {
            $new_template_type = sanitize_text_field(wp_unslash($_POST['template_type']));
            if ($new_template_type !== $this->template_type) {
                $this->template_type = $new_template_type;
                // Reload settings for the correct template type
                $this->load_settings();
                // Re-register controls for the new template type
                $this->controls = [];
                $this->sections = [];
                $this->register_controls();
            }
        }

        // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        // Settings are unslashed here but sanitized in the loop below using each control's sanitize() method.
        // Each control has its own sanitization logic appropriate for its type (text, color, number, etc.).
        // This pattern is necessary because we need to iterate through the settings array to apply type-specific sanitization.
        $settings = isset($_POST['settings']) ? wp_unslash($_POST['settings']) : $this->get_settings();
        // phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

        // Sanitize settings
        $sanitized = [];
        foreach ($settings as $key => $value) {
            if (isset($this->controls[$key])) {
                $sanitized[$key] = $this->controls[$key]->sanitize($value);
            }
        }

        // Get current user
        $user = wp_get_current_user();
        if (!$user || !$user->user_email) {
            wp_send_json_error([
                'message' => __('Unable to determine recipient email address.', 'guard-dog'),
            ]);
        }

        // Generate email HTML with template-specific args
        if ($this->template_type === 'email-verification') {
            $template_args = [
                'user_name' => $user->display_name,
                'verification_link' => home_url('/?action=guard_dog_verify_email&token=test&key=test'),
                'expires_in' => 48,
                'site_name' => get_bloginfo('name'),
                'site_url' => home_url(),
                'user' => $user,
                'name' => $user->display_name,
            ];
            $subject = $this->get_email_subject( $template_args );
            if ( $subject === null || $subject === '' ) {
                // Translators: %s is the site name.
                $subject = sprintf(__('[%s] Test Email - Email Verification', 'guard-dog'), get_bloginfo('name'));
            }
        } elseif ($this->template_type === 'password-expiration') {
            $template_args = [
                'user_name' => $user->display_name,
                'reset_link' => wp_lostpassword_url(),
                'days_until' => 7,
                'expiration_date' => date_i18n(get_option('date_format'), strtotime('+7 days')),
                'is_expired' => false,
                'site_name' => get_bloginfo('name'),
                'site_url' => home_url(),
                'user' => $user,
                'name' => $user->display_name,
            ];
            $subject = $this->get_email_subject( $template_args );
            if ( $subject === null || $subject === '' ) {
                // Translators: %s is the site name.
                $subject = sprintf(__('[%s] Test Email - Password Expiration', 'guard-dog'), get_bloginfo('name'));
            }
        } elseif ($this->template_type === 'suspicious-activity-admin') {
            $template_args = [
                'user' => $user,
                'type' => 'ip_shift',
                'details' => "Old IP: 1.2.3.4 (US)\nNew IP: 5.6.7.8 (DE)\n\n" . __( 'This may indicate a session hijacking attempt.', 'guard-dog' ),
                'site_name' => get_bloginfo('name'),
                'username' => $user->user_login,
            ];
            $subject = $this->get_email_subject( $template_args );
            if ( $subject === null || $subject === '' ) {
                $subject = sprintf( __( '[%1$s] Suspicious Session Activity Detected: %2$s', 'guard-dog' ), get_bloginfo( 'name' ), 'ip_shift' );
            }
        } elseif ($this->template_type === 'suspicious-activity-user') {
            $template_args = [
                'user' => $user,
                'site_name' => get_bloginfo( 'name' ),
                'name' => $user->display_name,
            ];
            $subject = $this->get_email_subject( $template_args );
            if ( $subject === null || $subject === '' ) {
                $subject = sprintf( __( '[%s] Security Alert: Unusual Session Activity', 'guard-dog' ), get_bloginfo( 'name' ) );
            }
        } else {
            $template_args = [
                'code' => '123456',
                'user' => $user,
                'site_name' => get_bloginfo('name'),
                'expiry_minutes' => 10,
                'name' => $user->display_name,
            ];
            $subject = $this->get_email_subject( $template_args );
            if ( $subject === null || $subject === '' ) {
                // Translators: %s is the site name.
                $subject = sprintf(__('[%s] Test Email - Two-Factor Authentication', 'guard-dog'), get_bloginfo('name'));
            }
        }

        $html_message = $this->generate_output($template_args);
        $plain_message = $this->generate_plain_text_output($template_args);

        // Use Guard Dog's email provider system (same as actual 2FA emails)
        if (!class_exists('Guard_Dog_Email_Provider')) {
            wp_send_json_error([
                'message' => __('Email provider not available. Please ensure Guard Dog is properly installed.', 'guard-dog'),
            ]);
        }

        $email_provider = new Guard_Dog_Email_Provider();

        // Check if email provider is configured
        if (!$email_provider->is_configured()) {
            wp_send_json_error([
                'message' => __('Email provider is not configured. Please configure email settings in Guard Dog Settings.', 'guard-dog'),
            ]);
        }

        // Send email using the configured provider
        $result = $email_provider->send_email($user->user_email, $subject, $html_message, $plain_message);

        if ($result['success']) {
            wp_send_json_success([
                'message' => sprintf(
                    // Translators: %s is the email address.
                    __('Test email sent successfully to %s! Check your inbox.', 'guard-dog'),
                    $user->user_email
                ),
            ]);
        } else {
            // Provide more detailed error message if available
            $error_message = isset($result['message']) ? $result['message'] : __('Failed to send test email. Please check your email configuration in Guard Dog Settings.', 'guard-dog');

            wp_send_json_error([
                'message' => $error_message,
            ]);
        }
    }

    /**
     * Render the customizer page
     * Override to add template selector
     */
    public function render() {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'guard-dog'));
        }

        ?>
        <div class="wrap guard-dog-customizer" data-customizer-id="<?php echo esc_attr($this->get_customizer_id()); ?>">
            <h1><?php echo esc_html($this->get_customizer_title()); ?></h1>

            <?php if ($this->get_customizer_description()): ?>
                <p class="description"><?php echo esc_html($this->get_customizer_description()); ?></p>
            <?php endif; ?>

            <?php if (count($this->available_template_types) > 1): ?>
                <div class="template-selector" style="margin: 20px 0; padding: 15px; background: #fff; border: 1px solid #ccd0d4; border-radius: 4px; box-shadow: 0 1px 1px rgba(0,0,0,.04);">
                    <label for="template-type-select" style="font-weight: 600; display: block; margin-bottom: 8px;">
                        <?php esc_html_e('Select Email Template:', 'guard-dog'); ?>
                    </label>
                    <select id="template-type-select" name="template_type" style="min-width: 300px; padding: 5px;">
                        <?php foreach ($this->available_template_types as $type => $info): ?>
                            <option value="<?php echo esc_attr($type); ?>" <?php selected($this->template_type, $type); ?>>
                                <?php echo esc_html($info['label']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (!empty($this->available_template_types[$this->template_type]['description'])): ?>
                        <p class="description" style="margin-top: 8px; margin-bottom: 0;">
                            <?php echo esc_html($this->available_template_types[$this->template_type]['description']); ?>
                        </p>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

            <div class="customizer-container">
                <div class="customizer-controls">
                    <?php $this->render_controls(); ?>
                </div>

                <div class="customizer-preview">
                    <?php $this->render_preview(); ?>
                </div>
            </div>

            <div class="customizer-actions">
                <?php $this->render_actions(); ?>
            </div>

            <?php $this->render_status(); ?>
        </div>
        <?php
    }

    /**
     * Render the customizer page (public method for admin menu)
     */
    public static function render_page() {
        $instance = new self();
        $instance->render();
    }
}
