<?php
declare(strict_types=1);

namespace EHxMe\Helpers;

use EHxMe\Classes\Settings;
use EHxMe\Models\Payment;

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

/**
 * Helper
 * A helper class
 */
class Helper
{
    public const NONCE_NAME = '__ehxme_nonce';
    public const NONCE_GET_ACTION = 'ehxme_get_nonce_action';

    /**
     * A function for debugging purposes. It outputs the provided value(s) and stops the script execution.
     *
     * @param mixed ...$values The value to be dumped.
     *
     * @return void The function does not return a value.
     */
    public static function dd(mixed ...$values)
    {
        if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true) && !headers_sent()) {
            header('HTTP/1.1 500 Internal Server Error');
        }

        echo '<pre>';
        var_dump($values);  // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        exit(1);
    }
    
    /**
     * Sends an email using WordPress's wp_mail function.
     *
     * @param string|array $to          Email address or array of email addresses to send the email to.
     * @param string       $subject     The subject of the email.
     * @param string       $message     The body of the email. Can be HTML or plain text.
     * @param string|array $headers     Optional. Additional headers to send with the email.
     * @param string|array $attachments Optional. Files to attach to the email.
     * @param bool         $is_html     Optional. Whether the email is HTML. Default true.
     * @param string|array $cc          Optional. CC email address or array of CC email addresses.
     * @param string|array $bcc         Optional. BCC email address or array of BCC email addresses.
     * @param string       $reply_to    Optional. Reply-To email address.
     *
     * @return bool Whether the email was sent successfully.
     */
    public static function send_email($to, $subject, $message, $headers = [], $attachments = [], $is_html = true, $cc = [], $bcc = [], $reply_to = '') 
    {
        // Validate email addresses
        if (!is_email($to)) {
            error_log('Invalid recipient email address: ' . $to); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            return false;
        }

        $allowedHtml = (bool) Settings::extractSettingValue('content_type', false);
        // Set the default headers
        $default_headers = [
            "Content-Type: " . ($is_html && $allowedHtml ? "text/html" : "text/plain") . "; charset=UTF-8"
        ];

        // Set the default "From" name and email
        $fromName  = Settings::extractSettingValue('mail_appears_from', get_bloginfo('name'));

        if (!empty($fromName)) {
            $from = "From: {$fromName}";
            $fromEmail = Settings::extractSettingValue('mail_appears_from_address', get_option('admin_email'));
            if(is_email($fromEmail)) {
                $from .= " <{$fromEmail}>";
            }

            $default_headers[] = $from;
        }

        // Add Reply-To header if provided
        if (!empty($reply_to) && is_email($reply_to)) {
            $default_headers[] = "Reply-To: {$reply_to}";
        }

        // Add CC headers if provided
        if (!empty($cc)) {
            $cc = is_array($cc) ? $cc : [$cc];
            foreach ($cc as $cc_email) {
                if (is_email($cc_email)) {
                    $default_headers[] = "Cc: {$cc_email}";
                }
            }
        }

        // Add BCC headers if provided
        if (!empty($bcc)) {
            $bcc = is_array($bcc) ? $bcc : [$bcc];
            foreach ($bcc as $bcc_email) {
                if (is_email($bcc_email)) {
                    $default_headers[] = "Bcc: {$bcc_email}";
                }
            }
        }

        // Merge default headers with custom headers
        $headers = array_merge($default_headers, (array)$headers);

        // Allow filtering of headers
        $headers = apply_filters('ehxme_email_headers', $headers, $to, $subject, $message);

        // Allow filtering of message
        $message = apply_filters('ehxme_email_message', $message, $to, $subject, $headers);

        // Send the email
        $result = wp_mail($to, $subject, $message, $headers, $attachments);

        // Log errors if the email fails to send
        if (!$result) {
            error_log('Failed to send email to: ' . $to); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }

        return $result;
    }

    /**
     * Displays a notice to the user.
     *
     * @param string $message The message to display to the user.
     * @param string $type    The type of notice. Default is 'success'.
     *                        Accepted values: 'success', 'error', 'warning', 'info'.
     *
     * @return void
     */
    public static function display_notice($message, $type = 'success'): void
    {
        add_settings_error(
            'ehxme_options', 
            'ehxme_message', 
            esc_html($message),
            $type
        );
        settings_errors('ehxme_options');
    }

    /**
     * Renders an input group field for WordPress settings pages.
     *
     * @param array  $args   Configuration for the input field.
     * @param string $option Option group name for WordPress settings.
     */
    public static function inputGroup($args, $option = 'ehxme_settings')
    {
        // Extract field properties
        $field_name = isset($args['field_name']) ? $args['field_name'] : '';
        $field_name = strtolower(str_replace(' ', '_', $field_name));
        $type       = $args['type'] ?? 'text';
        $input_type = $args['is_type'] ?? 'input';
        $value      = Settings::extractSettingValue($field_name);
        $input_name = esc_attr($option . "[$field_name]");
        $placeholder = isset($args['placeholder']) ? esc_attr($args['placeholder']) : '';
        $data       = $args['data'] ?? [];

        $depend_field = isset($args['depend_field']) ? Settings::extractSettingValue($args['depend_field']) : '';
        $depend_value = $args['depend_value'] ?? null;
        $dependable = isset($args['depend_field']) && $depend_field == $depend_value;

        // Ensure a valid field name exists
        if (empty($field_name)) {
            return;
        }
        
        require EHXME_PLUGIN_DIR . 'views/admin/inc/input-group.php';
    }

    /**
     * Renders an input field for WordPress settings pages.
     *
     * @param string  $label
     * @param string  $for
     * @param string  $type
     * @param string  $placeholder
     */
    public static function input_field($label, $for = null, $type = 'text', $placeholder = '')
    {
        $htmlFor = $for != null ? $for : $label;
        $value   = Settings::extractSettingValue($htmlFor);

        require EHXME_PLUGIN_DIR . 'views/admin/inc/input-fields.php';
    }

    /**
     * Displays a 404 page and terminates execution.
     *
     * This function sets the 404 status code, updates the global $wp_query to reflect a 404 status,
     * and then includes the 404 template part.
     *
     * @return void
     */
    public static function show_404()
    {
        global $wp_query;
        $wp_query->set_404();
        status_header(404);
        get_template_part('404');
        exit();
    }

    /**
     * Returns an array of custom roles for the EHX Member plugin.
     *
     * @return array An associative array with role slugs as keys and their display names as values.
     */
    public static function customRoles()
    {
        return [
            'free_member' => esc_html__("Free Member", 'ehx-members'),
            'paid_member' => esc_html__("Paid Member", 'ehx-members'),
        ];
    }

    /**
     * Generate and return customization settings for forms.
     *
     * This method provides a structured object containing customization options for forms,
     * including form settings, privacy options, login redirection, and membership configurations.
     *
     * @return object An object containing all customization settings.
     */
    public static function customize()
    {
        $roles = array_merge(array_map(fn($role) => esc_html($role['name']), wp_roles()->roles), ['default' => esc_html__('Default', 'ehx-members')]);
        
        return (object) [
            "customize" => (object) [
                (object) [
                    "label" => esc_html__("Apply custom settings to this form", 'ehx-members'),
                    "tooltip" => esc_html__("Switch to yes if you want to customize this form settings, styling & appearance", 'ehx-members'),
                    "id" => "register_use_custom_settings",
                    "type" => "select",
                    "options" => [
                        0 => esc_html__("No", 'ehx-members'),
                        1 => esc_html__("Yes", 'ehx-members'),
                    ],
                    "value" => 0
                ],
                (object) [
                    "label" => esc_html__("Assign role to form", 'ehx-members'),
                    "id" => "register_role",
                    "type" => "select",
                    "options" => $roles,
                    "value" => 0
                ],
                (object) [
                    "label" => esc_html__("Max. Width (px)", 'ehx-members'),
                    "tooltip" => esc_html__("The maximum width of shortcode in pixels e.g. 600px", 'ehx-members'),
                    "id" => "max_width",
                    "type" => "text",
                    "value" => "450px"
                ],
                (object) [
                    "label" => esc_html__("Primary Button Text", 'ehx-members'),
                    "tooltip" => esc_html__("Customize the button text", 'ehx-members'),
                    "id" => "primary_btn_word",
                    "type" => "text",
                    "value" => "Register",
                    "class" => "ehxme-forms-line-conditioned"
                ],
                (object) [
                    "label" => esc_html__("Show Secondary Button", 'ehx-members'),
                    "id" => "show_secondary_btn",
                    "type" => "select",
                    "options" => [
                        1 => esc_html__("Yes", 'ehx-members'),
                        0 => esc_html__("No", 'ehx-members')
                    ],
                    "value" => 1
                ],
                (object) [
                    "label" => esc_html__("Secondary Button Text", 'ehx-members'),
                    "tooltip" => esc_html__("Customize the button text", 'ehx-members'),
                    "id" => "secondary_btn_word",
                    "type" => "text"
                ]
            ],
            "privacy" => (object) [
                (object) [
                    "label" => esc_html__("Enable on this form", 'ehx-members'),
                    "id" => "register_use_gdpr",
                    "type" => "select",
                    "options" => [
                        0 => esc_html__("No", 'ehx-members'),
                        1 => esc_html__("Yes", 'ehx-members'),
                    ]
                ],
                (object) [
                    "label" => esc_html__("Content", 'ehx-members'),
                    "id" => "register_use_gdpr_content_id",
                    "type" => "select",
                    "options" => "pages"
                ],
                (object) [
                    "label" => esc_html__("Toggle Show text", 'ehx-members'),
                    "id" => "register_use_gdpr_toggle_show",
                    "type" => "text",
                    "placeholder" => esc_html__("Show privacy policy", 'ehx-members')
                ],
                (object) [
                    "label" => esc_html__("Toggle Hide text", 'ehx-members'),
                    "id" => "register_use_gdpr_toggle_hide",
                    "type" => "text",
                    "placeholder" => esc_html__("Hide privacy policy", 'ehx-members')
                ],
                (object) [
                    "label" => esc_html__("Checkbox agreement description", 'ehx-members'),
                    "id" => "register_use_gdpr_agreement",
                    "type" => "text",
                    "placeholder" => esc_html__("Please confirm that you agree to our privacy policy", 'ehx-members')
                ],
                (object) [
                    "label" => esc_html__("Error Text", 'ehx-members'),
                    "id" => "register_use_gdpr_error_text",
                    "type" => "text",
                    "placeholder" => esc_html__("Please confirm your acceptance of our privacy policy", 'ehx-members')
                ]
            ],
            "options" => (object) [
                (object) [
                    "label" => esc_html__("Redirection after Login", 'ehx-members'),
                    "id" => "login_after_login",
                    "type" => "select",
                    "options" => [
                        "" => esc_html__("Default", 'ehx-members'),
                        "redirect_profile" => esc_html__("Redirect to profile", 'ehx-members'),
                        "redirect_url" => esc_html__("Redirect to URL", 'ehx-members'),
                        "refresh" => esc_html__("Refresh active page", 'ehx-members'),
                        "redirect_admin" => esc_html__("Redirect to WordPress Admin", 'ehx-members')
                    ]
                ],
                (object) [
                    "label" => esc_html__("Set Custom Redirect URL", 'ehx-members'),
                    "id" => "login_redirect_url",
                    "type" => "text",
                    "placeholder" => esc_html__("Set Custom Redirect URL", 'ehx-members')
                ],
                (object) [
                    "label" => esc_html__("Enable Recaptcha", 'ehx-members'),
                    "id" => "enable_recaptcha",
                    "type" => "select",
                    "options" => [
                        0 => esc_html__("No", 'ehx-members'),
                        1 => esc_html__("Yes", 'ehx-members'),
                    ]
                ],
            ],
            "memberships" => (object) [
                (object) [
                    "label" => esc_html__("Member Role", 'ehx-members'),
                    "id" => "member_role",
                    "type" => "select",
                    "options" => self::customRoles()
                ],
                (object) [
                    "label" => esc_html__("Amount", 'ehx-members'),
                    "id" => "ehx_amount",
                    "type" => "number",
                    "placeholder" => esc_html__("Enter Amount", 'ehx-members')
                ],
            ]
        ];
    }

    /**
     * Returns an object containing predefined and custom field buttons for the EHX Member plugin.
     *
     * @return object An object with two properties: 'custom' and 'predefined'.
     * - 'custom' property contains an array of custom field buttons.
     * - 'predefined' property contains an array of predefined field buttons.
     *
     * Each field button is represented as an object with the following properties:
     * - 'text': The text displayed on the button.
     * - 'meta': The meta key associated with the button.
     * - 'type': The type of the field represented by the button.
     */
    public static function fieldButtons()
    {
        return (object) [
            "custom" => (object) [
                (object) [
                    "text" => esc_html__("Text Box", "ehx-members"),
                    "meta" => "",
                    "type" => "text"
                ],
                (object) [
                    "text" => esc_html__("Telephone", "ehx-members"),
                    "meta" => "",
                    "type" => "tel"
                ],
                (object) [
                    "text" => esc_html__("Textarea", "ehx-members"),
                    "meta" => "",
                    "type" => "textarea",
                    "height" => "100px",
                ],
                (object) [
                    "text" => esc_html__("Dropdown", "ehx-members"),
                    "meta" => "",
                    "type" => "select"
                ],
                (object) [
                    "text" => esc_html__("Multi-Select", "ehx-members"),
                    "meta" => "",
                    "type" => "multiselect"
                ],
                (object) [
                    "text" => esc_html__("Radio", "ehx-members"),
                    "meta" => "",
                    "type" => "radio"
                ],
                (object) [
                    "text" => esc_html__("Checkbox", "ehx-members"),
                    "meta" => "",
                    "type" => "checkbox"
                ],
                (object) [
                    "text" => esc_html__("URL", "ehx-members"),
                    "meta" => "",
                    "type" => "url"
                ],
                (object) [
                    "text" => esc_html__("Password", "ehx-members"),
                    "meta" => "",
                    "type" => "password"
                ],
                (object) [
                    "text" => esc_html__("File Upload", "ehx-members"),
                    "meta" => "",
                    "type" => "file"
                ],
                (object) [
                    "text" => esc_html__("Date Picker", "ehx-members"),
                    "meta" => "",
                    "type" => "date"
                ],
                (object) [
                    "text" => esc_html__("Time Picker", "ehx-members"),
                    "meta" => "",
                    "type" => "time"
                ],
                (object) [
                    "text" => esc_html__("Hidden Box", "ehx-members"),
                    "meta" => "",
                    "type" => "hidden"
                ]
            ],
            "predefined" => (object) [
                (object) [
                    "_type" => "text",
                    "_title" => esc_html__("Username", "ehx-members"),
                    "_metakey" => "user_login",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "",
                    "_visibility" => "",
                    "_label" => esc_html__("Username", "ehx-members"),
                    "_placeholder" => esc_html__("Enter username", "ehx-members"),
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "text",
                    "_title" => esc_html__("Username or Email", "ehx-members"),
                    "_metakey" => "username",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "",
                    "_visibility" => "",
                    "_label" => esc_html__("Username or Email", "ehx-members"),
                    "_placeholder" => esc_html__("Enter username or email", "ehx-members"),
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "password",
                    "_title" => esc_html__("Password", "ehx-members"),
                    "_metakey" => "user_pass",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "6",
                    "_visibility" => "",
                    "_label" => esc_html__("Password", "ehx-members"),
                    "_placeholder" => esc_html__("Enter Password", "ehx-members"),
                    "_public" => "",
                    "_validate" => "",
                    // "_validate" => "required|string|min:8|same:confirm_password",
                    "_max_chars" => "",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "text",
                    "_title" => esc_html__("First Name", "ehx-members"),
                    "_metakey" => "first_name",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "2",
                    "_visibility" => "",
                    "_label" => esc_html__("First Name", "ehx-members"),
                    "_placeholder" => esc_html__("Enter first name", "ehx-members"),
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "20",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "text",
                    "_title" => esc_html__("Last Name", "ehx-members"),
                    "_metakey" => "last_name",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "2",
                    "_visibility" => "",
                    "_label" => esc_html__("Last Name", "ehx-members"),
                    "_placeholder" => esc_html__("Enter last name", "ehx-members"),
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "text",
                    "_title" => esc_html__("Name", "ehx-members"),
                    "_metakey" => "name",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "2",
                    "_visibility" => "",
                    "_label" => esc_html__("Name", "ehx-members"),
                    "_placeholder" => esc_html__("Enter name", "ehx-members"),
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "text",
                    "_title" => esc_html__("Full Name", "ehx-members"),
                    "_metakey" => "full_name",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "2",
                    "_visibility" => "",
                    "_label" => esc_html__("Full Name", "ehx-members"),
                    "_placeholder" => esc_html__("Enter full name", "ehx-members"),
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "text",
                    "_title" => esc_html__("Nickname", "ehx-members"),
                    "_metakey" => "nickname",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "",
                    "_visibility" => "",
                    "_label" => esc_html__("Nickname", "ehx-members"),
                    "_placeholder" => esc_html__("Enter Nickname", "ehx-members"),
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "url",
                    "_title" => esc_html__("Website URL", "ehx-members"),
                    "_metakey" => "user_url",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "",
                    "_visibility" => "",
                    "_label" => esc_html__("Website URL", "ehx-members"),
                    "_placeholder" => esc_html__("Enter Valid URL", "ehx-members"),
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "date",
                    "_title" => esc_html__("Registration Date", "ehx-members"),
                    "_metakey" => "user_registered",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "",
                    "_visibility" => "",
                    "_label" => esc_html__("Registration Date", "ehx-members"),
                    "_placeholder" => "Enter Valid URL",
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "date",
                    "_title" => esc_html__("Last Login", "ehx-members"),
                    "_metakey" => "_ehx_last_login",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "",
                    "_visibility" => "",
                    "_label" => esc_html__("Last Login", "ehx-members"),
                    "_placeholder" => esc_html__("Last Login", "ehx-members"),
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "email",
                    "_title" => esc_html__("Email Address", "ehx-members"),
                    "_metakey" => "user_email",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "",
                    "_visibility" => "",
                    "_label" => esc_html__("Email Address", "ehx-members"),
                    "_placeholder" => esc_html__("Enter Valid Email Address", "ehx-members"),
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "email",
                    "_title" => esc_html__("Secondary Email Address", "ehx-members"),
                    "_metakey" => "secondary_user_email",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "",
                    "_visibility" => "",
                    "_label" => esc_html__("Secondary Email Address", "ehx-members"),
                    "_placeholder" => esc_html__("Enter Valid Email Address", "ehx-members"),
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "textarea",
                    "_title" => esc_html__("Biography", "ehx-members"),
                    "_metakey" => "biography",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_height" => "100px",
                    "_min_chars" => "",
                    "_visibility" => "",
                    "_label" => esc_html__("Biography", "ehx-members"),
                    "_placeholder" => esc_html__("Enter Biography", "ehx-members"),
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "2"
                ],
                (object) [
                    "_type" => "date",
                    "_title" => esc_html__("Birth Date", "ehx-members"),
                    "_metakey" => "birth_date",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "",
                    "_visibility" => "",
                    "_label" => esc_html__("Birth Date", "ehx-members"),
                    "_placeholder" => "Enter Birth Date",
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "radio",
                    "_title" => esc_html__("Gender", "ehx-members"),
                    "_metakey" => "gender",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "Male,Female",
                    "_min_chars" => "4",
                    "_visibility" => "",
                    "_label" => esc_html__("Gender", "ehx-members"),
                    "_placeholder" => "",
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "8",
                    "_column" => "1"
                ],
                (object) [
                    "_type" => "text",
                    "_title" => esc_html__("Address", "ehx-members"),
                    "_metakey" => "address",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_min_chars" => "",
                    "_visibility" => "",
                    "_label" => esc_html__("Address", "ehx-members"),
                    "_placeholder" => "",
                    "_public" => "",
                    "_validate" => "",
                    "_max_chars" => "",
                    "_column" => "2"
                ],
                (object) [
                    "_type" => "file",
                    "_title" => esc_html__("Profile Picture", "ehx-members"),
                    "_metakey" => "profile_picture",
                    "_help" => "",
                    "_default" => "",
                    "_options" => "",
                    "_allowed_types" => ["jpg", "jpeg", "png", "gif"],
                    "_visibility" => "",
                    "_label" => esc_html__("Profile Picture", "ehx-members"),
                    "_placeholder" => "",
                    "_public" => "",
                    "_validate" => "",
                    "_max_size" => "1024",
                    "_column" => "1"
                ],
            ]
        ];
    }

    /**
     * Retrieves custom fields for the EHX Member plugin.
     *
     * @return object An object containing custom field objects. Each object represents a custom field and has the following properties:
     *                - label: The label of the field.
     *                - name: The name of the field.
     *                - type: The type of the field.
     *                - tooltip: The tooltip for the field.
     *                - value: The default value of the field.
     *                - condition: The condition for displaying the field.
     *
     * @return object An object containing custom field objects.
     */
    public static function fields()
    {
        return (object) [
            (object) [
                "label" => esc_html__("Title", "ehx-members"),
                "name" => "_title",
                "type" => "text",
                "tooltip" => esc_html__("This is the title of the field for your reference in the backend. The title will not appear on the front-end of your website.", "ehx-members"),
                "value" => "",
                "condition" => []
            ],
            (object) [
                "label" => esc_html__("Label", "ehx-members"),
                "name" => "_label",
                "type" => "text",
                "tooltip" => esc_html__("The field label is the text that appears above the field on your front-end form. Leave blank to not show a label above field.", "ehx-members"),
                "value" => "",
                "condition" => []
            ],
            (object) [
                "label" => esc_html__("Meta Key", "ehx-members"),
                "name" => "_metakey",
                "type" => "text",
                "tooltip" => esc_html__("A meta key is required to store the entered info in this field in the database. The meta key should be unique to this field and be written in lowercase with an underscore ( _ ) separating words e.g country_list or job_title.", "ehx-members"),
                "value" => "",
                "condition" => []
            ],
            (object) [
                "label" => esc_html__("Help Text", "ehx-members"),
                "name" => "_help",
                "type" => "text",
                "tooltip" => esc_html__("This is the text that appears in a tooltip when a user hovers over the info icon. Help text is useful for providing users with more information about what they should enter in the field. Leave blank if no help text is needed for field.", "ehx-members"),
                "value" => "",
                "condition" => []
            ],
            (object) [
                "label" => esc_html__("Placeholder", "ehx-members"),
                "name" => "_placeholder",
                "type" => "text",
                "tooltip" => esc_html__("This is the text that appears within the field e.g please enter your email address. Leave blank to not show any placeholder text.", "ehx-members"),
                "value" => "",
                "condition" => [
                    "text",
                    "tel",
                    "password",
                    "textarea",
                    "url"
                ]
            ],
            (object) [
                "label" => esc_html__("Default Value", "ehx-members"),
                "name" => "_default",
                "type" => "text",
                "tooltip" => esc_html__("This option allows you to pre-fill the field with a default value prior to the user entering a value in the field. Leave blank to have no default value.", "ehx-members"),
                "value" => "",
                "condition" => [
                    "text",
                    "tel",
                    "textarea",
                    "url",
                    "select",
                ]
            ],
            (object) [
                "label" => esc_html__("Textarea Height", "ehx-members"),
                "name" => "_height",
                "type" => "text",
                "tooltip" => esc_html__("The height of textarea in pixels. Default is 100 pixels", "ehx-members"),
                "value" => "100px",
                "condition" => [
                    "textarea"
                ]
            ],
            (object) [
                "label" => esc_html__("Maximum allowed words", "ehx-members"),
                "name" => "_max_words",
                "type" => "number",
                "tooltip" => esc_html__("If you want to enable a maximum number of words to be input in this textarea. Leave empty to disable this setting", "ehx-members"),
                "value" => "",
                "condition" => [
                    "textarea"
                ]
            ],
            (object) [
                "label" => esc_html__("Privacy", "ehx-members"),
                "name" => "_public",
                "type" => "select",
                "tooltip" => esc_html__("Field privacy allows you to select who can view this field on the front-end. The site admin can view all fields regardless of the option set here.", "ehx-members"),
                "options" => [
                    "Everyone" => esc_html__("Everyone", "ehx-members"),
                    "Members" => esc_html__("Members", "ehx-members"),
                    "Only visible to profile owner and users who can edit other member accounts" => esc_html__("Only visible to profile owner and users who can edit other member accounts", "ehx-members"),
                    "Only visible to profile owner and specific roles" => esc_html__("Only visible to profile owner and specific roles", "ehx-members"),
                    "Only specific member roles" => esc_html__("Only specific member roles", "ehx-members")
                ],
                "value" => "1",
                "condition" => []
            ],
            (object) [
                "label" => esc_html__("Edit Choices", "ehx-members"),
                "name" => "_options",
                "type" => "textarea",
                "tooltip" => esc_html__("Use , one choice per line. This will represent the available choices or selections available for user.", "ehx-members"),
                "value" => "",
                "condition" => [
                    "radio",
                    "checkbox",
                    "select",
                    "multiselect"
                ]
            ],
            (object) [
                "label" => esc_html__("Additional Instructions Text", "ehx-members"),
                "name" => "_upload_help_text",
                "type" => "text",
                "tooltip" => esc_html__("If you need to add information or secondary line below the headline of upload box, enter it here", "ehx-members"),
                "value" => "",
                "condition" => [
                    "image",
                    "file"
                ]
            ],
            (object) [
                "label" => esc_html__("Validate", "ehx-members"),
                "name" => "_validate",
                "type" => "text",
                "tooltip" => esc_html__("Does this field require a special validation. Use | for separation.", "ehx-members"),
                "value" => "",
                "placeholder" => "ex: required|string|min:20|max:255",
                "condition" => ['unknown']
            ],
            (object) [
                "label" => esc_html__("Allowed File Types", "ehx-members"),
                "name" => "_allowed_types",
                "type" => "select",
                "tooltip" => esc_html__("Select the file types that you want to allow to be uploaded via this field.", "ehx-members"),
                "options" => [
                    "jpg" => "JPG",
                    "jpeg" => "JPEG",
                    "png" => "PNG",
                    "gif" => "GIF",
                    "pdf" => "PDF",
                    "txt" => "TXT",
                    "csv" => "CSV",
                    "doc" => "DOCS",
                    "docx" => "DOCX",
                    "odt" => "ODT",
                    "ods" => "ODS",
                    "xls" => "XLS",
                    "xlsx" => "XLSX",
                    "zip" => "ZIP",
                    "rar" => "RAR",
                    "mp3" => "MP3",
                    "eps" => "EPS",
                    "psd" => "PSD",
                    "tif" => "TIF",
                    "tiff" => "TIFF"
                ],
                "value" => [
                    "jpg",
                    "jpeg",
                    "png",
                    "gif"
                ],
                "is_multiple" => true,
                "condition" => [
                    "file"
                ]
            ],
            (object) [
                "label" => esc_html__("Column", "ehx-members"),
                "name" => "_column",
                "type" => "select",
                "tooltip" => esc_html__("Select where this field should appear. This option should only be changed on the profile form and allows you to show a field in one mode only (edit or view) or in both modes.", "ehx-members"),
                "options" => [
                    1 => esc_html__("1 Column", "ehx-members"),
                    2 => esc_html__("2 Column", "ehx-members")
                ],
                "value" => "all",
                "condition" => []
            ],
            (object) [
                "label" => esc_html__("Maximum Size in bytes", "ehx-members"),
                "name" => "_max_size",
                "type" => "number",
                "tooltip" => esc_html__("The maximum size for image that can be uploaded through this field. Leave empty for unlimited size.", "ehx-members"),
                "value" => "",
                "condition" => [
                    "image",
                    "file"
                ]
            ],
            (object) [
                "label" => esc_html__("Visibility", "ehx-members"),
                "name" => "_visibility",
                "type" => "select",
                "tooltip" => esc_html__("Select where this field should appear. This option should only be changed on the profile form and allows you to show a field in one mode only (edit or view) or in both modes.", "ehx-members"),
                "options" => [
                    "all" => esc_html__("View everywhere", "ehx-members"),
                    "edit" => esc_html__("Edit mode only", "ehx-members"),
                    "view" => esc_html__("View mode only", "ehx-members")
                ],
                "value" => "all",
                "condition" => []
            ],
            (object) [
                "label" => esc_html__("Force strong password?", "ehx-members"),
                "name" => "_force_good_pass",
                "type" => "checkbox",
                "tooltip" => esc_html__("Turn on to force users to create a strong password (A combination of one lowercase letter, one uppercase letter, and one number). If turned on this option is only applied to register forms and not to login forms.", "ehx-members"),
                "value" => "1",
                "condition" => [
                    "password"
                ]
            ],
            (object) [
                "label" => esc_html__("Automatically add a confirm password field?", "ehx-members"),
                "name" => "_force_confirm_pass",
                "type" => "checkbox",
                "tooltip" => esc_html__("Turn on to add a confirm password field. If turned on the confirm password field will only show on register forms and not on login forms.", "ehx-members"),
                "value" => "1",
                "condition" => [
                    "password"
                ]
            ],
            (object) [
                "label" => esc_html__("Confirm password field label", "ehx-members"),
                "name" => "_label_confirm_pass",
                "type" => "text",
                "tooltip" => esc_html__("This label is the text that appears above the confirm password field. Leave blank to show default label.", "ehx-members"),
                "value" => esc_html__("Confirm Password", "ehx-members"),
                "condition" => [
                    "password"
                ]
            ],
            (object) [
                "label" => esc_html__("Is check multiple?", "ehx-members"),
                "name" => "_multiple",
                "type" => "checkbox",
                "tooltip" => esc_html__("Enable this option to allow multiple selections for this field.", "ehx-members"),
                "value" => "1",
                "condition" => ['checkbox']
            ],
            (object) [
                "label" => esc_html__("Is this field required?", "ehx-members"),
                "name" => "_required",
                "type" => "checkbox",
                "tooltip" => esc_html__("This option allows you to set whether the field must be filled in before the form can be processed.", "ehx-members"),
                "value" => "1",
                "condition" => []
            ]
        ];
    }

    /**
     * Extracts validation rules for custom fields from an array of fields.
     *
     * @param array $fields An array of custom field objects. Each object should have a '_metakey' and optional '_required', '_min_chars', '_max_chars' properties.
     *
     * @return array An associative array where the keys are metakeys and the values are validation rules as strings.
     *               Each rule is a combination of 'required', 'min:n', and 'max:n' where 'n' is the specified minimum or maximum characters.
     *               If no validation rules are specified, the default rule is 'nullable'.
     */
    public static function extractRules(array $fields): array
    {
        $rules = [];
        foreach ($fields as $field) {
            $metaKey = esc_attr($field['_metakey'] ?? '');
            if ($metaKey) {
                // $rules[$metaKey] = !empty($field['_validate']) ? $field['_validate'] : 'nullable';
                $rule = [!empty($field['_required']) ? 'required' : 'nullable'];
                if (!empty($field['_min_chars'])) {
                    $rule[] = 'min:'. $field['_min_chars'];
                }
                if (!empty($field['_max_chars'])) {
                    $rule[] = 'max:'. $field['_max_chars'];
                }
                $rules[$metaKey] = implode('|', $rule);
            }
        }
        return $rules;
    }

    /**
     * Retrieves the dynamic field label from a given form ID and metakey.
     *
     * @param int|string $form_id The ID of the form.
     * @param string $metakey The metakey of the field.
     *
     * @return string The label of the dynamic field. If not found, returns an empty string.
     */
    public static function getDynamicFieldLabel(int|string $form_id, string $metakey): string
    {
        $fields = get_post_meta($form_id, '_ehx_custom_field', true) ?: [];

        foreach ($fields as $field) {
            if (($field['_metakey'] ?? '') === $metakey) {
                return $field['_title'] ?? '';
            }
        }
        return '';
    }

    /**
     * Retrieves the member roles from an array of roles and formats them into a comma-separated string.
     *
     * @param array $roles An array of member roles. Each role should be a string in snake_case format.
     *
     * @return string The formatted member roles as a comma-separated string.
     *                Each role is converted to title case and underscores are replaced with spaces.
     */
    public static function memberRole(array $roles): string
    {
        return implode(', ', array_map(fn($role) => esc_html(ucwords(str_replace('_', ' ', $role))), $roles));
    }
    
    /**
     * Retrieves the status text or toggle text for a member based on their ID and type.
     *
     * @param int|string $bool The user_status of the member.
     * @param null|string $type The type of status text or toggle text to retrieve.
     *                      Accepted values: 'status_text', 'toggle_text', 'toggle_status'.
     *                      Default value: 'status_text'.
     *
     * @return string|bool The status text or toggle text for the member.
     *                     Returns false if the type is not recognized.
     */
    public static function memberStatus(int|bool $status, $type = 'status_text'): string|bool
    {
        $approve = esc_html__('Approve', 'ehx-members');
        $deny = esc_html__('Deny', 'ehx-members');
        $activate = esc_html__('Activate', 'ehx-members');
        $deactivate = esc_html__('Deactivate', 'ehx-members');

        $current_status = match($type) {
            'status_text' => !$status ? $deny : $approve,
            'toggle_text' => !$status ? $approve : $deny,
            'toggle_status' => !$status ? $activate : $deactivate,
            default => $status ?? false,
        };

        return $current_status;
    }

    /**
     * Checks if a specific plugin is active.
     *
     * @param string $name The name of the plugin to check.
     *
     * @return string|bool Returns the name of the plugin if it is active, or false if it is not active.
     */
    public static function check_other_plugin(string $name): string|bool
    {
        return is_plugin_active($name);
    }

    /**
     * Formats a monetary amount into a currency string with a pound sign and two decimal places.
     *
     * @param mixed $amount The monetary amount to be formatted.
     *
     * @return string The formatted currency string.
     */
    public static function currencyFormat(mixed $amount): string
    {
        return '£' . number_format((float) $amount, 2);
    }
    
    /**
     * Allowed HTML Tags
     *
     * @return array
     */
    public static function allowedHTMLTags(): array
    {
        // Base attributes allowed for most tags
        $base_attrs = [
            'id' => true,
            'class' => true,
            'style' => true,
            'title' => true,
            'role' => true,
            'aria-*' => true,
            'data-*' => true,
        ];

        // SVG-specific tags and attributes
        $svg_tags = [
            'svg' => [
                'xmlns' => true,
                'width' => true,
                'height' => true,
                'viewbox' => true,
                'fill' => true,
            ] + $base_attrs,
            'g' => [
                'fill' => true,
            ] + $base_attrs,
            'title' => $base_attrs,
            'path' => [
                'd' => true,
                'fill' => true,
                'stroke' => true,
            ] + $base_attrs,
        ];

        // Standard HTML tags with their specific attributes
        $html_tags = [
            'a' => [
                'href' => true,
                'target' => ['_blank', '_self', '_parent', '_top'],
                'rel' => true,
                'download' => true,
            ],
            'img' => [
                'src' => true,
                'alt' => true,
                'srcset' => true,
                'sizes' => true,
                'decoding' => ['async', 'auto', 'sync'],
                'loading' => ['lazy', 'eager'],
            ],
            'input' => [
                'type' => true,
                'name' => true,
                'value' => true,
                'autocomplete' => true,
                'placeholder' => true,
                'required' => true,
                'disabled' => true,
                'checked' => true,
                'min' => true,
                'max' => true,
                'step' => true,
            ],
            'textarea' => [
                'name' => true,
                'placeholder' => true,
                'rows' => true,
                'cols' => true,
                'required' => true,
                'disabled' => true,
            ],
            'select' => [
                'name' => true,
                'required' => true,
                'disabled' => true,
                'multiple' => true,
            ],
            'option' => [
                'value' => true,
                'selected' => true,
                'disabled' => true,
            ],
            'button' => [
                'type' => ['button', 'submit', 'reset'],
                'name' => true,
                'value' => true,
                'disabled' => true,
            ],
            'form' => [
                'action' => true,
                'method' => ['get', 'post'],
                'enctype' => true,
                'novalidate' => true,
                'target' => true,
            ],
            'label' => [
                'for' => true,
            ],
            // Router components (Vue.js, etc.)
            'router-view' => $base_attrs,
            'router-link' => [
                'to' => true,
                'exact' => true,
                'active-class' => true,
                'exact-active-class' => true,
            ] + $base_attrs,
        ];

        // Additional standard HTML tags that only need base attributes
        $simple_tags = [
            'div', 'span', 'p', 'table', 'thead', 'tbody', 'tr', 'td', 'th',
            'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'ul', 'li', 'i'
        ];

        // Merge all tags with their attributes
        $allowed_tags = $svg_tags;
        
        foreach ($html_tags as $tag => $attrs) {
            $allowed_tags[$tag] = $attrs + $base_attrs;
        }
        
        foreach ($simple_tags as $tag) {
            $allowed_tags[$tag] = $base_attrs;
        }

        return $allowed_tags;
    }

    /**
     * Retrieves payment data for the current user.
     *
     * This function connects to the WordPress database, retrieves payment data for the current user,
     * and returns the data as an array of associative arrays.
     *
     * @return array|object
     */
    public static function getPayments(): array|object
    {
        global $wpdb;
        $payment_table = esc_sql((new Payment)->getTableName());

        // Query: Join with wp_users and wp_usermeta
        $query = $wpdb->prepare("SELECT * FROM %1s WHERE user_id = %d ORDER BY id DESC", $payment_table, get_current_user_id());

        $data = $wpdb->get_results($query);

        return $data ?? [];
    }

    /**
     * Generate get link with nonce
     *
     * @return string
     */
    public static function generateQueryArg($params = [], $page = 'admin.php'): string
    {
        $link = add_query_arg(array(
            ...$params, 
            Helper::NONCE_NAME  => wp_create_nonce(Helper::NONCE_NAME)
        ), admin_url($page));

        return $link;
    }

}
