<?php
/*
Plugin Name: HTML Email Templates
Plugin URI: https://wedevs.com/docs/wp-user-frontend-pro/modules/html-email-templates/
Thumbnail Name: email-templates.png
Description: Send Email Notifications with HTML Template
Version: 1.0
Author: weDevs
Author URI: http://wedevs.com/
License: GPL2
*/

/**
 * Copyright (c) 2014 weDevs (email: info@wedevs.com). All rights reserved.
 *
 * Released under the GPL license
 * http://www.opensource.org/licenses/gpl-license.php
 *
 * This is an add-on for WordPress
 * http://wordpress.org/
 *
 * **********************************************************************
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 * **********************************************************************
 */

// don't call the file directly
if ( !defined( 'ABSPATH' ) ) exit;

// if ( is_admin() ) {
//    require_once dirname( __FILE__ ) . '/lib/wedevs-updater.php';
//    new WeDevs_Plugin_Update_Checker( plugin_basename( __FILE__ ), 'wpuf-mailchimp' );
// }

/**
 * WPUF_Email_Templates class
 *
 * @class WPUF_Email_Templates The class that holds the entire WPUF_Email_Templates plugin
 */
class WPUF_Email_Templates {

    /**
     * Option key for storing role-based templates
     *
     * @var string
     */
    const ROLE_TEMPLATES_OPTION = 'wpuf_role_based_email_templates';

    /**
     * Collects QuickTags editor IDs to initialise in a single footer script.
     *
     * @var string[]
     */
    private $pending_editor_ids = [];

    /**
     * Constructor for the WPUF_Email_Templates class
     *
     * Sets up all the appropriate hooks and actions
     * within our plugin.
     *
     * @uses is_admin()
     * @uses add_action()
     */
    function __construct() {
        add_filter( 'wp_mail_content_type', array( $this, 'mail_content_type' ), 10, 1 );
        add_filter( 'wp_mail_from', array( $this, 'custom_wp_mail_from' ), 10, 1 );
        add_filter( 'wp_mail_from_name', array( $this, 'custom_wp_mail_from_name' ), 10, 1 );
        add_filter( 'retrieve_password_title', array( $this, 'retrieve_password_title' ), 10 );
        add_filter( 'retrieve_password_message', array( $this, 'replace_retrieve_password_message' ), 10, 3 );
        add_filter( 'wpuf_settings_fields', array( $this, 'add_settings_fields' ), 10, 1 );

        // Role-based email templates - hook into mail options to add labels and role-based fields (priority 20 to run after other plugins)
        add_filter( 'wpuf_mail_options', array( $this, 'add_role_based_email_settings' ), 20, 1 );
        add_action( 'admin_init', array( $this, 'save_role_templates' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_role_template_scripts' ) );
        add_action( 'admin_footer', [ $this, 'render_quicktags_init_script' ] );

        // Hook into account activation email filters (accept optional $user_id as 2nd arg for async/cron safety)
        add_filter( 'wpuf_mail_after_confirmation_subject', array( $this, 'filter_activation_email_subject' ), 10, 2 );
        add_filter( 'wpuf_mail_after_confirmation_body', array( $this, 'filter_activation_email_body' ), 10, 2 );
    }

    /**
     * Initializes the WPUF_Email_Templates() class
     *
     * Checks for an existing WPUF_Email_Templates() instance
     * and if it doesn't find one, creates it.
     */
    public static function init() {
        static $instance = false;

        if ( ! $instance ) {
            $instance = new WPUF_Email_Templates();
        }

        return $instance;
    }

    /**
     *Set mail content type
     */
    public function mail_content_type( $content_type ) {
        return 'text/html';
    }

    /**
     *Set mail content type
     */
    public function custom_wp_mail_from( $email ) {
        $email = wpuf_get_option( 'from_address', 'wpuf_mails', get_option( 'admin_email' ) );
        return $email;
    }

    /**
     *Set mail from name
     */
    public function custom_wp_mail_from_name( $name ) {
        $name = wpuf_get_option( 'from_name', 'wpuf_mails', get_bloginfo() );
        return $name;
    }

    /**
     * Add Settings Fields
     */
    public function add_settings_fields( $settings_fields ) {

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'email_setting',
            'label'   => '<span class="dashicons dashicons-admin-generic"></span> ' . __( 'Template Settings', 'wpuf-pro' ),
            'type'    => 'html',
            'class'   => 'email-setting',
        );

        $settings_fields['wpuf_mails'][] =array(
            'name'    => 'from_name',
            'label'   => __( '"From" name', 'wpuf-pro' ),
            'desc'    => __( 'How the sender name appears in outgoing WPUF emails.', 'wpuf-pro' ),
            'default' => get_bloginfo(),
            'type'    => 'text',
            'class'   => 'email-setting-option',
        );

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'from_address',
            'label'   => __( '"From" address', 'wpuf-pro' ),
            'desc'    => __( 'How the sender email appears in outgoing WPUF emails.', 'wpuf-pro' ),
            'default' => get_option( 'admin_email' ),
            'type'    => 'text',
            'class'   => 'email-setting-option',
        );

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'header_image',
            'label'   => __( 'Header Image', 'wpuf-pro' ),
            'desc'    => __( 'URL to an image you want to show in the email header. For best performance select image of max Width 200px', 'wpuf-pro' ),
            'default' => '',
            'type'    => 'file',
            'class'   => 'email-setting-option',
        );

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'footer_text',
            'label'   => __( 'Footer Text', 'wpuf-pro' ),
            'desc'    => __( 'The text to appear in the footer of WPUF emails.', 'wpuf-pro' ),
            'default' => get_bloginfo(),
            'type'    => 'textarea',
            'class'   => 'email-setting-option',
        );

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'base_color',
            'label'   => __( 'Base Color', 'wpuf-pro' ),
            'desc'    => __( 'The base color for WPUF email templates.', 'wpuf-pro' ),
            'default' => '#cccccc',
            'type'    => 'color',
            'class'   => 'email-setting-option',
        );

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'background_color',
            'label'   => __( 'Background color', 'wpuf-pro' ),
            'desc'    => __( 'The background color for WooCommerce email templates.', 'wpuf-pro' ),
            'default' => '#ffffff',
            'type'    => 'color',
            'class'   => 'email-setting-option',
        );

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'body_background_color',
            'label'   => __( 'Body Background color', 'wpuf-pro' ),
            'desc'    => __( 'The main body background color.', 'wpuf-pro' ),
            'default' => '#f5f5f5',
            'type'    => 'color',
            'class'   => 'email-setting-option',
        );

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'body_text_color',
            'label'   => __( 'Body text color', 'wpuf-pro' ),
            'desc'    => __( 'The main body text color.', 'wpuf-pro' ),
            'default' => '#000000',
            'type'    => 'color',
            'class'   => 'email-setting-option',
        );

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'reset_email_setting',
            'label'   => '<span class="dashicons dashicons-unlock"></span> ' . __( 'Reset Email', 'wpuf-pro' ),
            'type'    => 'html',
            'class'   => 'reset-email-setting',
        );

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'reset_email_subject',
            'label'   => __( 'Password reset request mail subject', 'wpuf-pro' ),
            'desc'    => __( 'Subject for the email when any user on your website changes the password, the user will get password reset request notification email', 'wpuf-pro' ),
            'default' => __( 'Password Reset', 'wpuf-pro' ),
            'type'    => 'text',
            'class'   => 'reset-email-setting-option',
        );

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'reset_email_body',
            'label'   => __( 'Password reset request mail body', 'wpuf-pro' ),
            'desc'    => __( "Content for the email when any user on your website changes the password, the user will get password reset request notification email <br><strong>You may use: </strong><code>{username}</code><code>{blogname}</code><code>{password_reset_link}</code>", 'wpuf-pro' ),
            'default' => "Hello!

            You asked us to reset your password for your account.

            To reset your password, visit the following address:
            <a href='{password_reset_link}'>Click Here</a>

            Thanks!",
            'type'    => 'wysiwyg',
            'class'   => 'reset-email-setting-option',
        );

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'confirmation_email_setting',
            'label'   => '<span class="dashicons dashicons-email-alt"></span> ' . __( 'Resend Confirmation Email', 'wpuf-pro' ),
            'type'    => 'html',
            'class'   => 'confirmation-email-setting',
        );

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'confirmation_mail_subject',
            'label'   => __( 'Subject', 'wpuf-pro' ),
            'desc'    => __( 'Subject for the confirmation email', 'wpuf-pro' ),
            'default' => 'Account Activation',
            'type'    => 'text',
            'class'   => 'confirmation-email-setting-option'
        );

        $settings_fields['wpuf_mails'][] = array(
            'name'    => 'confirmation_mail_body',
            'label'   => __( 'Body', 'wpuf-pro' ),
            'desc'    => __( "Content for the confirmation email <br><strong>You may use: </strong><code>{username}</code><code>{blogname}</code><code>{activation_link}</code>", 'wpuf-pro' ),
            'default' => "Congrats! You are Successfully registered to {blogname}

            To activate your account, please click the link below
            {activation_link}

            Thanks!",
            'type'    => 'wysiwyg',
            'class'   => 'confirmation-email-setting-option'
        );

        return $settings_fields;
    }

    /**
     *Set reset password title
     */
    public function retrieve_password_title( $title ) {
        $title = wpuf_get_option( 'reset_email_subject', 'wpuf_mails' );
        return $title;
    }

    /**
     * Returns the message body for the password reset mail.
     * Called through the retrieve_password_message filter.
     *
     * @param string  $message    Default mail message.
     * @param string  $key        The activation key.
     * @param string  $user_login The username for the user.
     * @param WP_User $user_data  WP_User object.
     *
     * @return string   The mail message to send.
     */
    public function replace_retrieve_password_message( $message, $key, $user_login ) {

        $subject    = wpuf_get_option( 'reset_email_subject', 'wpuf_mails' );
        $message    = wpuf_get_option( 'reset_email_body', 'wpuf_mails' );
        $blogname   = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);

        $reset_link = add_query_arg( array(
            'action' => 'rp',
            'key'    => $key,
            'login'  => rawurlencode( $user_login )
        ), wp_login_url() );

        $field_search = array( '{username}', '{blogname}', '{password_reset_link}' );

        $field_replace = array(
            $user_login,
            $blogname,
            $reset_link
        );

        $message = str_replace( $field_search, $field_replace, $message );
        $message = get_formatted_mail_body( $message, $subject );

        return $message;

    }

    /**
     * Enqueue scripts for role-based email templates
     *
     * @since 4.2.12
     *
     * @return void
     */
    public function enqueue_role_template_scripts() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $screen = get_current_screen();

        // Check if we're on the WPUF settings page
        $is_wpuf_settings = false;

        if ( $screen ) {
            // Check for various possible screen IDs
            if (
                strpos( $screen->id, 'wpuf-settings' ) !== false ||
                strpos( $screen->id, 'wpuf_settings' ) !== false ||
                strpos( $screen->id, 'user-frontend' ) !== false
            ) {
                $is_wpuf_settings = true;
            }
        }

        // Also check URL as fallback
        if ( ! $is_wpuf_settings && isset( $_GET['page'] ) ) {
            $page = sanitize_text_field( wp_unslash( $_GET['page'] ) );

            if (
                strpos( $page, 'wpuf-settings' ) !== false ||
                strpos( $page, 'wpuf_settings' ) !== false
            ) {
                $is_wpuf_settings = true;
            }
        }

        if ( ! $is_wpuf_settings ) {
            return;
        }

        // Enqueue quicktags for the editor
        wp_enqueue_script( 'quicktags' );

        wp_enqueue_script(
            'wpuf-role-email-templates',
            plugins_url( 'assets/js/role-email-templates.js', __FILE__ ),
            [ 'jquery', 'quicktags' ],
            WPUF_PRO_VERSION,
            true
        );

        wp_localize_script(
            'wpuf-role-email-templates',
            'wpufRoleTemplates',
            [
                'roles'        => self::get_user_roles(),
                'placeholders' => [
                    'approved_post_email'          => [ '{username}', '{user_email}', '{display_name}', '{post_title}', '{post_link}' ],
                    'account_activated_user_email' => [ '{username}', '{user_email}', '{display_name}', '{login_url}' ],
                    'default'                      => [ '{username}', '{user_email}', '{display_name}', '{user_status}' ],
                ],
                'i18n'         => [
                    'selectRoles'    => __( 'Select Roles', 'wpuf-pro' ),
                    'allRoles'       => __( 'All Roles', 'wpuf-pro' ),
                    'emailSubject'   => __( 'Email Subject', 'wpuf-pro' ),
                    'emailBody'      => __( 'Email Body', 'wpuf-pro' ),
                    'removeTemplate' => __( 'Remove Template', 'wpuf-pro' ),
                    'codeEditorBtn'  => __( 'Code', 'wpuf-pro' ),
                    'youMayUse'      => __( 'You may use:', 'wpuf-pro' ),
                    'confirmDelete'  => __( 'Are you sure you want to remove this template?', 'wpuf-pro' ),
                    'rolePriority'   => __( 'If a user has multiple roles, the first matching template (top-to-bottom) applies.', 'wpuf-pro' ),
                ],
            ]
        );

        wp_enqueue_style(
            'wpuf-role-email-templates',
            plugins_url( 'assets/css/role-email-templates.css', __FILE__ ),
            [],
            WPUF_PRO_VERSION
        );
    }

    /**
     * Add role-based email settings via filter hook
     *
     * This method modifies email settings to:
     * - Add "(Default - All Roles)" label to subject/body fields
     * - Insert role-based templates callback after each email body field
     *
     * @since 4.2.12
     *
     * @param array $mail_settings The mail settings array
     *
     * @return array Modified mail settings
     */
    public function add_role_based_email_settings( $mail_settings ) {
        // Checkbox fields after which we insert roles dropdown
        $checkbox_fields = [
            'enable_pending_user_email_notification'     => 'pending_user_email',
            'enable_denied_user_email_notification'      => 'denied_user_email',
            'enable_approved_user_email_notification'    => 'approved_user_email',
            'account_activated_user_email_notification'  => 'account_activated_user_email',
            'enable_post_approval_notification'          => 'approved_post_email',
        ];

        // Fields after which we should insert role-based templates callback
        $body_fields = [
            'pending_user_email_body'             => 'pending_user_email',
            'denied_user_email_body'              => 'denied_user_email',
            'approved_user_email_body'            => 'approved_user_email',
            'account_activated_user_email_body'   => 'account_activated_user_email',
            'approved_post_email_body'            => 'approved_post_email',
        ];

        $class_map = [
            'pending_user_email'           => 'pending-user-email-option',
            'denied_user_email'            => 'denied-user-email-option',
            'approved_user_email'          => 'approved-user-email-option',
            'account_activated_user_email' => 'account-activated-user-email-option',
            'approved_post_email'          => 'approved-post-email-option',
        ];

        $new_settings = [];

        foreach ( $mail_settings as $setting ) {
            $field_name = isset( $setting['name'] ) ? $setting['name'] : '';

            $new_settings[] = $setting;

            // After checkbox fields, insert roles dropdown with all roles selected
            if ( isset( $checkbox_fields[ $field_name ] ) ) {
                $email_type = $checkbox_fields[ $field_name ];

                $new_settings[] = [
                    'name'       => $email_type . '_default_roles',
                    'label'      => __( 'Select Roles', 'wpuf-pro' ),
                    'type'       => 'callback',
                    'callback'   => [ $this, 'render_default_roles_dropdown' ],
                    'email_type' => $email_type,
                    'class'      => isset( $class_map[ $email_type ] ) ? $class_map[ $email_type ] : '',
                ];
            }

            // After body fields, insert role-based templates callback (Add New button)
            if ( isset( $body_fields[ $field_name ] ) ) {
                $email_type = $body_fields[ $field_name ];

                $new_settings[] = [
                    'name'       => str_replace( '_email_body', '_role_templates', $field_name ),
                    'label'      => '',
                    'type'       => 'callback',
                    'callback'   => [ $this, 'wpuf_role_email_templates' ],
                    'email_type' => $email_type,
                    'class'      => isset( $class_map[ $email_type ] ) ? $class_map[ $email_type ] : '',
                ];
            }
        }

        return $new_settings;
    }

    /**
     * Render default roles checkboxes
     *
     * @since 4.2.12
     *
     * @param array $args Field arguments
     *
     * @return void
     */
    public function render_default_roles_dropdown( $args ) {
        $roles = self::get_user_roles();

        // Get field_name from args['id'] - this is the actual field name like 'approved_user_email_default_roles'
        // The WeDevs Settings API passes 'id' which is the field name
        $field_name = isset( $args['id'] ) ? $args['id'] : '';

        // Extract email_type from field_name (e.g., 'approved_user_email_default_roles' -> 'approved_user_email')
        $email_type = str_replace( '_default_roles', '', $field_name );

        // Get saved value from wpuf_mails option
        $saved_options = get_option( 'wpuf_mails', [] );

        // Check if this field has ever been saved
        $field_exists = array_key_exists( $field_name, $saved_options );

        if ( $field_exists && ! empty( $saved_options[ $field_name ] ) ) {
            // Field was saved with values - use those values
            $saved_roles = (array) $saved_options[ $field_name ];
        } else {
            // Field was never saved OR was saved empty - default to 'all_roles'
            $saved_roles = [ 'all_roles' ];
        }

        // Determine if "All Roles" is selected
        $is_all_roles = in_array( 'all_roles', $saved_roles, true );
        ?>
        <div class="wpuf-roles-checkbox-wrapper" data-field-name="<?php echo esc_attr( $field_name ); ?>">
            <label class="wpuf-role-checkbox wpuf-role-checkbox-all">
                <input
                    type="checkbox"
                    name="wpuf_mails[<?php echo esc_attr( $field_name ); ?>][]"
                    value="all_roles"
                    class="wpuf-role-all-checkbox"
                    <?php checked( $is_all_roles ); ?>
                >
                <?php esc_html_e( 'All Roles', 'wpuf-pro' ); ?>
            </label>

            <div class="wpuf-specific-roles"<?php echo $is_all_roles ? ' style="opacity: 0.5; pointer-events: none;"' : ''; ?>>
                <?php foreach ( $roles as $role_key => $role_name ) : ?>
                    <label class="wpuf-role-checkbox">
                        <input
                            type="checkbox"
                            name="wpuf_mails[<?php echo esc_attr( $field_name ); ?>][]"
                            value="<?php echo esc_attr( $role_key ); ?>"
                            class="wpuf-role-specific-checkbox"
                            <?php checked( ! $is_all_roles && in_array( $role_key, $saved_roles, true ) ); ?>
                            <?php disabled( $is_all_roles ); ?>
                        >
                        <?php echo esc_html( $role_name ); ?>
                    </label>
                <?php endforeach; ?>
            </div>
        </div>
        <p class="description"><?php esc_html_e( 'Select "All Roles" or choose specific roles. Use "+ Add New" below to create role-specific templates.', 'wpuf-pro' ); ?></p>
        <?php
    }

    /**
     * Save role-based email templates on settings save
     *
     * @since 4.2.12
     *
     * @return void
     */
    public function save_role_templates() {
        if ( ! isset( $_SERVER['REQUEST_METHOD'] ) || 'POST' !== $_SERVER['REQUEST_METHOD'] ) {
            return;
        }

        $option_page = isset( $_POST['option_page'] ) ? sanitize_text_field( wp_unslash( $_POST['option_page'] ) ) : '';

        if ( 'wpuf_mails' !== $option_page ) {
            return;
        }

        if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
            return;
        }

        // Verify nonce for security
        if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'wpuf_mails-options' ) ) {
            return;
        }

        $templates = ( isset( $_POST['wpuf_role_email_templates'] ) && is_array( $_POST['wpuf_role_email_templates'] ) )
            ? $this->sanitize_role_templates( wp_unslash( $_POST['wpuf_role_email_templates'] ) )
            : [];

        update_option( self::ROLE_TEMPLATES_OPTION, $templates );
    }

    /**
     * Sanitize role-based templates data
     *
     * @since 4.2.12
     *
     * @param array $templates Raw templates data
     *
     * @return array Sanitized templates
     */
    private function sanitize_role_templates( $templates ) {
        $sanitized = [];

        foreach ( $templates as $email_type => $type_templates ) {
            $email_type = sanitize_text_field( $email_type );

            if ( ! is_array( $type_templates ) ) {
                continue;
            }

            $sanitized[ $email_type ] = [];

            foreach ( $type_templates as $template ) {
                if ( empty( $template['roles'] ) && empty( $template['subject'] ) && empty( $template['body'] ) ) {
                    continue;
                }

                $sanitized[ $email_type ][] = [
                    'roles'   => isset( $template['roles'] ) ? array_map( 'sanitize_text_field', (array) $template['roles'] ) : [],
                    'subject' => isset( $template['subject'] ) ? sanitize_text_field( $template['subject'] ) : '',
                    'body'    => isset( $template['body'] ) ? wp_kses_post( $template['body'] ) : '',
                ];
            }

            // Re-index array
            $sanitized[ $email_type ] = array_values( $sanitized[ $email_type ] );
        }

        return $sanitized;
    }

    /**
     * Get all user roles
     *
     * @since 4.2.12
     *
     * @return array
     */
    public static function get_user_roles() {
        global $wp_roles;

        if ( ! $wp_roles ) {
            $wp_roles = new \WP_Roles();
        }

        $roles = [];

        foreach ( $wp_roles->role_names as $role => $name ) {
            $roles[ $role ] = translate_user_role( $name );
        }

        return $roles;
    }

    /**
     * Get role-based templates for an email type
     *
     * @since 4.2.12
     *
     * @param string $email_type Email type identifier
     *
     * @return array
     */
    public static function get_role_templates( $email_type ) {
        $all_templates = get_option( self::ROLE_TEMPLATES_OPTION, [] );

        if ( isset( $all_templates[ $email_type ] ) && is_array( $all_templates[ $email_type ] ) ) {
            return $all_templates[ $email_type ];
        }

        return [];
    }

    /**
     * Get template for a specific user based on their role
     *
     * @since 4.2.12
     *
     * @param string $email_type Email type identifier
     * @param int    $user_id    User ID
     *
     * @return array|null Template data or null if no match
     */
    public static function get_template_for_user( $email_type, $user_id ) {
        $user = get_userdata( $user_id );

        if ( ! $user ) {
            return null;
        }

        $user_roles = $user->roles;
        $templates  = self::get_role_templates( $email_type );

        if ( empty( $templates ) ) {
            return null;
        }

        // Try to find a template that matches the user's role
        foreach ( $templates as $template ) {
            $template_roles = isset( $template['roles'] ) ? $template['roles'] : [];

            if ( empty( $template_roles ) ) {
                continue;
            }

            // If "all_roles" is selected, this template matches all users
            if ( in_array( 'all_roles', $template_roles, true ) ) {
                return $template;
            }

            // Check if any of the user's roles match this template
            foreach ( $user_roles as $role ) {
                if ( in_array( $role, $template_roles, true ) ) {
                    return $template;
                }
            }
        }

        return null;
    }

    /**
     * Check if a user should receive the default email based on their role
     *
     * This checks the default roles setting for each email type.
     * If "all_roles" is selected, all users receive the email.
     * If specific roles are selected, only users with those roles receive the email.
     *
     * @since 4.2.12
     *
     * @param string $email_type Email type identifier (e.g., 'pending_user_email')
     * @param int    $user_id    User ID
     *
     * @return bool True if user should receive email, false otherwise
     */
    public static function should_user_receive_default_email( $email_type, $user_id ) {
        $user = get_userdata( $user_id );

        if ( ! $user ) {
            return false;
        }

        $user_roles = $user->roles;

        // Get the default roles setting for this email type
        $field_name    = $email_type . '_default_roles';
        $saved_options = get_option( 'wpuf_mails', [] );
        $default_roles = isset( $saved_options[ $field_name ] ) ? (array) $saved_options[ $field_name ] : [ 'all_roles' ];

        // If no roles are saved, default to all_roles (send to everyone)
        if ( empty( $default_roles ) ) {
            return true;
        }

        // If "all_roles" is selected, send to all users
        if ( in_array( 'all_roles', $default_roles, true ) ) {
            return true;
        }

        // Check if user has any of the selected roles
        foreach ( $user_roles as $role ) {
            if ( in_array( $role, $default_roles, true ) ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Render role-based email templates callback
     *
     * @since 4.2.12
     *
     * @param array $args Field arguments
     *
     * @return void
     */
    public function wpuf_role_email_templates( $args ) {
        // The email_type is always passed via add_role_based_email_settings().
        // The name/id fallbacks are kept only for safety if the WeDevs Settings
        // API strips custom keys from callback args.
        $email_type = isset( $args['email_type'] ) ? $args['email_type'] : '';

        if ( empty( $email_type ) ) {
            $lookup_key = isset( $args['name'] ) ? $args['name'] : '';

            // Strip the option-group prefix that WeDevs Settings API may add (e.g. "wpuf_mails[field_name]" → "field_name")
            if ( empty( $lookup_key ) && isset( $args['id'] ) ) {
                $lookup_key = preg_replace( '/^wpuf_mails\[(.+)\]$/', '$1', $args['id'] );
            }

            $name_to_email_type = [
                'pending_user_role_templates'      => 'pending_user_email',
                'denied_user_role_templates'       => 'denied_user_email',
                'approved_user_role_templates'     => 'approved_user_email',
                'account_activated_role_templates' => 'account_activated_user_email',
                'approved_post_role_templates'     => 'approved_post_email',
            ];

            if ( isset( $name_to_email_type[ $lookup_key ] ) ) {
                $email_type = $name_to_email_type[ $lookup_key ];
            }
        }

        $templates = self::get_role_templates( $email_type );
        $roles     = self::get_user_roles();
        ?>
        <div style="text-align: right; margin-bottom: 10px;">
            <span class="button button-primary wpuf-add-role-template" data-email-type="<?php echo esc_attr( $email_type ); ?>">
                <?php esc_html_e( '+ Add New', 'wpuf-pro' ); ?>
            </span>
        </div>
        <div class="wpuf-role-templates-wrapper" id="wpuf_role_templates_<?php echo esc_attr( $email_type ); ?>" data-email-type="<?php echo esc_attr( $email_type ); ?>">
            <?php if ( ! empty( $templates ) ) : ?>
                <?php foreach ( $templates as $key => $template ) : ?>
                    <?php $this->render_template_block( $email_type, $key, $template, $roles ); ?>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Render a single template block
     *
     * @since 4.2.12
     *
     * @param string $email_type Email type
     * @param int    $index      Block index
     * @param array  $template   Template data
     * @param array  $roles      Available roles
     *
     * @return void
     */
    private function render_template_block( $email_type, $index, $template, $roles ) {
        $selected_roles = isset( $template['roles'] ) ? (array) $template['roles'] : [];
        $subject        = isset( $template['subject'] ) ? $template['subject'] : '';
        $body           = isset( $template['body'] ) ? $template['body'] : '';
        $field_name     = 'wpuf_role_email_templates[' . $email_type . '][' . $index . ']';
        $editor_id      = 'wpuf_role_body_' . $email_type . '_' . $index;
        ?>
        <div class="wpuf-role-template-block" data-index="<?php echo esc_attr( $index ); ?>">
            <button type="button" class="wpuf-remove-role-template" title="<?php esc_attr_e( 'Remove', 'wpuf-pro' ); ?>">
                <span class="dashicons dashicons-no-alt"></span>
            </button>

            <?php
            $is_all_roles = in_array( 'all_roles', $selected_roles, true );
            ?>
            <table class="form-table wpuf-role-form-table">
                <tr>
                    <th scope="row"><?php esc_html_e( 'Select Roles', 'wpuf-pro' ); ?></th>
                    <td>
                        <div class="wpuf-roles-checkbox-wrapper">
                            <label class="wpuf-role-checkbox wpuf-role-checkbox-all">
                                <input
                                    type="checkbox"
                                    name="<?php echo esc_attr( $field_name ); ?>[roles][]"
                                    value="all_roles"
                                    class="wpuf-role-all-checkbox"
                                    <?php checked( $is_all_roles ); ?>
                                >
                                <?php esc_html_e( 'All Roles', 'wpuf-pro' ); ?>
                            </label>

                            <div class="wpuf-specific-roles"<?php echo $is_all_roles ? ' style="opacity: 0.5; pointer-events: none;"' : ''; ?>>
                                <?php foreach ( $roles as $role_key => $role_name ) : ?>
                                    <label class="wpuf-role-checkbox">
                                        <input
                                            type="checkbox"
                                            name="<?php echo esc_attr( $field_name ); ?>[roles][]"
                                            value="<?php echo esc_attr( $role_key ); ?>"
                                            class="wpuf-role-specific-checkbox"
                                            <?php checked( ! $is_all_roles && in_array( $role_key, $selected_roles, true ) ); ?>
                                            <?php disabled( $is_all_roles ); ?>
                                        >
                                        <?php echo esc_html( $role_name ); ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <p class="description"><?php esc_html_e( 'If a user has multiple roles, the first matching template (top-to-bottom) applies.', 'wpuf-pro' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e( 'Email Subject', 'wpuf-pro' ); ?></th>
                    <td>
                        <input type="text" name="<?php echo esc_attr( $field_name ); ?>[subject]" value="<?php echo esc_attr( $subject ); ?>" class="regular-text">
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e( 'Email Body', 'wpuf-pro' ); ?></th>
                    <td>
                        <div class="wpuf-role-editor-wrapper">
                            <div class="wp-core-ui wp-editor-wrap html-active">
                                <div class="wp-editor-tools">
                                    <div class="wp-editor-tabs">
                                        <button type="button" class="wp-switch-editor switch-html" data-editor="<?php echo esc_attr( $editor_id ); ?>"><?php esc_html_e( 'Code', 'wpuf-pro' ); ?></button>
                                    </div>
                                </div>
                                <div class="wp-editor-container">
                                    <div id="qt_<?php echo esc_attr( $editor_id ); ?>_toolbar" class="quicktags-toolbar"></div>
                                    <textarea
                                        id="<?php echo esc_attr( $editor_id ); ?>"
                                        name="<?php echo esc_attr( $field_name ); ?>[body]"
                                        rows="8"
                                        class="wp-editor-area wpuf-role-email-body"
                                        style="width: 100%;"
                                    ><?php echo esc_textarea( $body ); ?></textarea>
                                </div>
                            </div>
                        </div>
                        <p class="description">
                            <?php esc_html_e( 'You may use:', 'wpuf-pro' ); ?>
                            <?php if ( 'approved_post_email' === $email_type ) : ?>
                                <code>{username}</code> <code>{user_email}</code> <code>{display_name}</code> <code>{post_title}</code> <code>{post_link}</code>
                            <?php else : ?>
                                <code>{username}</code> <code>{user_email}</code> <code>{display_name}</code> <code>{user_status}</code>
                            <?php endif; ?>
                        </p>
                    </td>
                </tr>
            </table>
        </div>
        <?php

        // Queue editor ID for initialisation — all IDs are emitted in a single footer script
        // by render_quicktags_init_script() to avoid N separate inline <script> tags.
        $this->pending_editor_ids[] = $editor_id;
    }

    /**
     * Emit a single footer script that initialises all queued QuickTags editors.
     *
     * Hooked to admin_footer so that QTags is guaranteed to be loaded before
     * this runs, and so that all editor IDs collected by render_template_block()
     * across every email type are handled in one pass.
     *
     * @since 4.2.12
     *
     * @return void
     */
    public function render_quicktags_init_script() {
        if ( empty( $this->pending_editor_ids ) ) {
            return;
        }

        // Sanitise editor IDs to alphanumeric + underscore only (defence-in-depth)
        $safe_ids = array_filter(
            $this->pending_editor_ids,
            function ( $id ) {
                return preg_match( '/^[a-zA-Z0-9_]+$/', $id );
            }
        );

        if ( empty( $safe_ids ) ) {
            return;
        }

        $editor_ids_json = wp_json_encode( array_values( $safe_ids ) );
        ?>
        <script>
            (function() {
                var editorIds = <?php echo $editor_ids_json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- values validated alphanumeric above, json_encode is safe ?>;
                function initEditors() {
                    if ( typeof QTags === 'undefined' ) {
                        return;
                    }
                    editorIds.forEach( function( id ) {
                        new QTags( {
                            id: id,
                            buttons: 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close'
                        } );
                    } );
                    QTags._buttonsInit();
                }
                if ( document.readyState === 'complete' ) {
                    initEditors();
                } else {
                    window.addEventListener( 'load', initEditors );
                }
            } )();
        </script>
        <?php
    }

    /**
     * Get user ID from activation request
     *
     * Reads $_GET['id'] only as a last resort. Callers should prefer passing
     * the user ID directly via the filter's second argument so this works
     * in async/cron contexts where $_GET is empty.
     *
     * @since 4.2.12
     *
     * @return int User ID, or 0 if not determinable.
     */
    private function get_activation_user_id() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- nonce not applicable here.
        // This runs during the activation request where the free plugin's
        // Simple_Login::activation_user_registration() has already validated
        // the activation key hash against the user's stored key, so the user
        // ID is trustworthy by the time this filter fires. We only use it
        // to resolve the correct role-based email template — no state changes.
        if ( isset( $_GET['id'] ) && isset( $_GET['wpuf_registration_activation'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $user_id = absint( $_GET['id'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended

            if ( $user_id && get_userdata( $user_id ) ) {
                return $user_id;
            }
        }

        return 0;
    }

    /**
     * Filter account activation email subject
     *
     * @since 4.2.12
     *
     * @param string $subject Email subject
     * @param int    $user_id Optional user ID passed by caller (preferred over $_GET).
     *
     * @return string
     */
    public function filter_activation_email_subject( $subject, $user_id = 0 ) {
        $user_id = absint( $user_id );

        if ( empty( $user_id ) ) {
            $user_id = $this->get_activation_user_id();
        }

        if ( empty( $user_id ) ) {
            return $subject;
        }

        $template = self::get_template_for_user( 'account_activated_user_email', $user_id );

        if ( $template && ! empty( $template['subject'] ) ) {
            return $template['subject'];
        }

        return $subject;
    }

    /**
     * Filter account activation email body
     *
     * @since 4.2.12
     *
     * @param string $message Email body
     * @param int    $user_id Optional user ID passed by caller (preferred over $_GET).
     *
     * @return string
     */
    public function filter_activation_email_body( $message, $user_id = 0 ) {
        $user_id = absint( $user_id );

        if ( empty( $user_id ) ) {
            $user_id = $this->get_activation_user_id();
        }

        if ( empty( $user_id ) ) {
            return $message;
        }

        $template = self::get_template_for_user( 'account_activated_user_email', $user_id );

        if ( $template && ! empty( $template['body'] ) ) {
            $user = get_userdata( $user_id );

            if ( ! $user ) {
                return $message;
            }

            $body = wpautop( $template['body'] );

            $search  = [ '{login_url}', '{username}', '{user_email}', '{display_name}' ];
            $replace = [
                '<a href="' . wp_login_url() . '">' . __( 'Login', 'wpuf-pro' ) . '</a>',
                $user->user_login,
                $user->user_email,
                $user->display_name,
            ];

            $body = str_replace( $search, $replace, $body );

            return get_formatted_mail_body( $body, $template['subject'] );
        }

        return $message;
    }

} // WPUF_Email_Templates

$wpuf_email_templates = WPUF_Email_Templates::init();
