<?php
if (! defined('ABSPATH')) {
    exit;
}
add_action('wp_enqueue_scripts', 'chama_template_styles_and_scripts');
function chama_template_styles_and_scripts()
{
    /* Template  CSS */
    $accent_background_color            = get_option('chama_accent_background_color') ? get_option('chama_accent_background_color') : '#FF4557';
    $accent_text_color                  = get_option('chama_accent_text_color') ? get_option('chama_accent_text_color') : '#FFFFFF';
    $content_background_color           = get_option('chama_content_background_color') ? get_option('chama_content_background_color') : '#FFFFFF';
    $content_background_secondary_color = get_option('chama_content_background_secondary_color') ? get_option('chama_content_background_secondary_color') : '#f4f4f4';
    $content_text_color                 = get_option('chama_content_text_color') ? get_option('chama_content_text_color') : '#000000';
    $css                                = sprintf(
        ':root { --chama-accent-background-color: %s; --chama-accent-text-color: %s; --chama-content-background-color: %s; --chama-content-text-color: %s; --chama-accent-background-trans-color: %s; --chama-content-background-secondary-color: %s; }',
        esc_attr($accent_background_color),
        esc_attr($accent_text_color),
        esc_attr($content_background_color),
        esc_attr($content_text_color),
        esc_attr($accent_background_color . '25'),
        esc_attr($content_background_secondary_color)
    );

    /* Toocheke  CSS */
    $toocheke_css = '.page.chama-body-class header.entry-header{display: none !important;}';
    $toocheke_js  = "document.getElementsByTagName('body')[0].className += ' chama-body-class';";

    /* Newsletter  CSS */
   // Form background options
    $form_bg_color      = ( $val = get_option('chama_newsletter_form_background_color', '#f9fafb') )      ? $val : '#f9fafb';
    $form_border_color  = ( $val = get_option('chama_newsletter_form_border_color', '#d4d4d4') )          ? $val : '#d4d4d4';
    $form_border_radius = ( $val = get_option('chama_newsletter_form_border_radius', '4') ) && $val != '0' ? $val : '4';
    $form_bg_image      = esc_url( get_option('chama_newsletter_form_background_image', '') );
    $form_bg_opacity    = ( $val = get_option('chama_newsletter_form_background_transparency', '20') ) && $val != '0' ? $val : '20';

    // Header text options
    $header_color  = ( $val = get_option('chama_newsletter_header_font_color', '#000000') )      ? $val : '#000000';
    $header_size   = ( $val = get_option('chama_newsletter_header_font_size', '24') ) && $val != '0' ? $val : '24';
    $header_weight = ( $val = get_option('chama_newsletter_header_font_weight', 'normal') )      ? $val : 'normal';

    // Sub Header text options
    $sub_header_color = ( $val = get_option('chama_newsletter_sub_header_font_color', '#686868') )      ? $val : '#686868';
    $sub_header_size  = ( $val = get_option('chama_newsletter_sub_header_font_size', '18') ) && $val != '0' ? $val : '18';

    // Email field options
    $email_color         = ( $val = get_option('chama_newsletter_email_font_color', '#000000') )     ? $val : '#000000';
    $email_border_color  = ( $val = get_option('chama_newsletter_email_border_color', '#e3e3e3') )   ? $val : '#e3e3e3';
    $email_border_radius = ( $val = get_option('chama_newsletter_email_field_border_radius', '4') ) && $val != '0' ? $val : '4';
    $email_weight        = ( $val = get_option('chama_newsletter_email_font_weight', 'normal') )     ? $val : 'normal';

    // Button options
    $button_color            = ( $val = get_option('chama_newsletter_button_font_color', '#ffffff') )         ? $val : '#ffffff';
    $button_border_radius    = ( $val = get_option('chama_newsletter_button_border_radius', '4') ) && $val != '0' ? $val : '4';
    $button_weight           = ( $val = get_option('chama_newsletter_button_font_weight', 'normal') )         ? $val : 'normal';
    $button_background_color = ( $val = get_option('chama_newsletter_button_background_color', '#ff4757') )   ? $val : '#ff4757';


    $newsletter_css = sprintf(
        '.chama-newsletter-form {
        position: relative;
        background: %s;
        border: 1px solid %s;
        border-radius: %dpx;
        padding: 20px;
        max-width: 700px;
        margin: 20px auto;
        overflow: hidden;
    }
    %s
    .chama-newsletter-form h2 {
        color: %s;
        font-size: %dpx;
        font-weight: %s;
        margin-bottom: 10px;
    }
    .chama-newsletter-form p {
        margin-bottom: 15px;
        color: %s;
        font-size: %dpx;
    }
    .chama-newsletter-form input[type="email"] {
        width: 100%%;
        height: 45px;
        line-height: 45px;
        padding: 0px 15px;
        margin-bottom: 10px;
        border: 1px solid %s;
        border-radius: %dpx;
        color: %s;
        font-weight: %s;
    }   
    .chama-newsletter-form input[type="email"]::placeholder {
        opacity: 1;
        color: %s;
    }
    .chama-newsletter-form input[type="submit"] {
        background: %s;
        color: %s;
        height: 45px;
        line-height: 45px;
        padding: 0px 15px;
        border: none;
        border-radius: %dpx;
        cursor: pointer;
        font-weight: %s;
    }
    .chama-newsletter-form input[type="submit"]:hover {
        opacity: 0.9;
    }
     .chama-newsletter-form input[type="email"]:disabled  {
    background: #ddd;
    }
     .chama-newsletter-form input[type="email"]:disabled, .chama-newsletter-form input[type="submit"]:disabled{
    cursor: not-allowed; 
    pointer-events: none; 
    opacity: 0.5;
    }
     .widget .chama-newsletter-form {
        padding:15px;
    }
    .widget .chama-newsletter-form input[type="email"],.widget .chama-newsletter-form input[type="submit"]{
        height: 35px;
        line-height: 35px;
        padding: 0px 10px;
    }',
        esc_html($form_bg_color),
        esc_html($form_border_color),
        intval($form_border_radius),

        // background image block if set
        $form_bg_image ? sprintf(
            '.chama-newsletter-form::before {
            content: "";
            position: absolute;
            inset: 0;
            background: url("%s") center/cover no-repeat;
            opacity: %s;
            z-index: 0;
        }
        .chama-newsletter-form > * {position: relative; z-index: 1;}',
            esc_url($form_bg_image),
            floatval($form_bg_opacity) / 100
        ) : '',

        esc_html($header_color),
        intval($header_size),
        esc_html($header_weight),

        esc_html($sub_header_color),
        intval($sub_header_size),

        esc_html($email_border_color),
        intval($email_border_radius),
        esc_html($email_color),
        esc_html($email_weight),

        esc_html($email_color),

        esc_html($button_background_color),
        esc_html($button_color),
        intval($button_border_radius),
        esc_html($button_weight)
    );


    wp_register_script('chama-jquery-validate', CHAMA_ASSETS_URL . 'lib/jquery-validation/jquery.validate.min.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_style('chama-font-awesome', CHAMA_ASSETS_URL . 'fonts/font-awesome/css/all.min.css', [], CHAMA_VERSION, 'all');
    wp_register_style('chama-featherlight-min', CHAMA_ASSETS_URL . 'lib/featherlight/featherlight.min.css', [], CHAMA_VERSION, 'all');
    wp_register_style('chama-featherlight-gallery-min', CHAMA_ASSETS_URL . 'lib/featherlight/featherlight.gallery.min.css', [], CHAMA_VERSION, 'all');
    wp_register_script('chama-featherlight-min', CHAMA_ASSETS_URL . 'lib/featherlight/featherlight.min.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-featherlight-gallery-min', CHAMA_ASSETS_URL . 'lib/featherlight/featherlight.gallery.min.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_style('chama-micromodal', CHAMA_ASSETS_URL . 'lib/micromodal/micromodal.css', [], CHAMA_VERSION, 'all');
    wp_register_script('chama-micromodal', CHAMA_ASSETS_URL . 'lib/micromodal/micromodal.min.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-google-api-recaptcha', 'https://www.google.com/recaptcha/api.js?onload=onloadCallback', [], CHAMA_VERSION, true);
    wp_register_script('chama-stripe', 'https://js.stripe.com/v3/', [], CHAMA_VERSION, true);
    wp_register_script('chama-form-functions', CHAMA_ASSETS_URL . 'js/chama-form.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-gallery', CHAMA_ASSETS_URL . 'js/chama-gallery.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-tabs', CHAMA_ASSETS_URL . 'js/chama-tabs.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-share-button', CHAMA_ASSETS_URL . 'js/chama-share-button.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-panels', CHAMA_ASSETS_URL . 'js/chama-panels.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-password-validation-functions', CHAMA_ASSETS_URL . 'js/chama-password-validation.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-payment', CHAMA_ASSETS_URL . 'js/chama-payment.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-subscription', CHAMA_ASSETS_URL . 'js/chama-subscription.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-recaptcha', CHAMA_ASSETS_URL . 'js/chama-recaptcha.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-crowdfunding', CHAMA_ASSETS_URL . 'js/chama-crowdfunding.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-commissions', CHAMA_ASSETS_URL . 'js/chama-commissions.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-account', CHAMA_ASSETS_URL . 'js/chama-account.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-billing', CHAMA_ASSETS_URL . 'js/chama-billing.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_script('chama-accordion', CHAMA_ASSETS_URL . 'js/chama-accordion.js', ['jquery'], CHAMA_VERSION, true);
    wp_register_style('chama-template', CHAMA_ASSETS_URL . 'css/frontend.css', [], CHAMA_VERSION, 'all');
    wp_register_style('chama-no-header', CHAMA_ASSETS_URL . 'css/noheader.css', [], CHAMA_VERSION, 'all');
    wp_register_style('chama-dynamic-style', false, [], CHAMA_VERSION);
    wp_add_inline_style('chama-dynamic-style', $css);
    wp_register_style('chama-toocheke-style', false, [], CHAMA_VERSION);
    wp_add_inline_style('chama-toocheke-style', $toocheke_css);   
    wp_register_script('chama-toocheke-script', false);
    wp_add_inline_script('chama-toocheke-script', $toocheke_js, 'after');
    wp_register_style('chama-newsletter-style', false, [], CHAMA_VERSION);
    wp_add_inline_style('chama-newsletter-style', $newsletter_css);
}

//page variables
add_action('init', 'chama_setup_pages');
function chama_setup_pages()
{
    chama_setup_links('chama_hub_page', 'CHAMA_HUB_URL');
    chama_setup_links('chama_donate_page', 'CHAMA_DONATE_URL');
    chama_setup_links('chama_membership_page', 'CHAMA_MEMBERSHIP_URL');
    chama_setup_links('chama_crowdfunding_page', 'CHAMA_CROWDFUNDING_URL');
    chama_setup_links('chama_commissions_page', 'CHAMA_COMMISSIONS_URL');
    chama_setup_links('chama_login_page', 'CHAMA_LOGIN_URL');
    chama_setup_links('chama_registration_page', 'CHAMA_REGISTRATION_URL');
    chama_setup_links('chama_edit_account_page', 'CHAMA_EDIT_ACCOUNT_URL');
    chama_setup_links('chama_edit_password_page', 'CHAMA_EDIT_PASSWORD_URL');
    chama_setup_links('chama_forgot_password_page', 'CHAMA_FORGOT_PASSWORD_URL');
    chama_setup_links('chama_reset_password_page', 'CHAMA_RESET_PASSWORD_URL');
    chama_setup_links('chama_verify_email_page', 'CHAMA_VERIFY_EMAIL_URL');
    chama_setup_links('chama_account_page', 'CHAMA_ACCOUNT_URL');
    chama_setup_links('chama_payment_page', 'CHAMA_PAYMENT_URL');
    chama_setup_links('chama_payment_confirmation_page', 'CHAMA_PAYMENT_CONFIRMATION_URL');
    chama_setup_links('chama_subscription_page', 'CHAMA_SUBSCRIPTION_URL');
    chama_setup_links('chama_subscription_confirmation_page', 'CHAMA_SUBSCRIPTION_CONFIRMATION_URL');
    chama_setup_links('chama_newsletter_sign_up_confirmation_page', 'CHAMA_NEWSLETTER_SIGN_UP_CONFIRMATION_URL');
    chama_setup_links('chama_newsletter_opt_out_confirmation_page', 'CHAMA_NEWSLETTER_OPT_OUT_CONFIRMATION_URL');
    chama_setup_vars('chama_email_from_name', 'CHAMA_FROM_NAME');
    chama_setup_vars('chama_email_from_address', 'CHAMA_FROM_EMAIL');
}
function chama_setup_vars($option, $variable_name)
{
    $variable = get_option($option);
    if (! defined($variable_name)) {
        define($variable_name, $variable);
    }
}
function chama_setup_links($option, $variable_name)
{

    $page_id = get_option($option);
    if ($page_id) {
        $permalink = get_permalink($page_id);
        if (! defined($variable_name)) {
            define($variable_name, $permalink);
        }
    }
}
//misc variables
add_action('init', 'chama_setup_misc_variables');
function chama_setup_misc_variables()
{
    $recaptcha_site_key          = get_option('chama_recaptcha_site_key');
    $recaptcha_secret_key        = get_option('chama_recaptcha_secret_key');
    $stripe_test_publishable_key = get_option('chama_stripe_test_publishable_key');
    $stripe_test_secret_key      = get_option('chama_stripe_test_secret_key');
    $stripe_live_publishable_key = get_option('chama_stripe_live_publishable_key');
    $stripe_live_secret_key      = get_option('chama_stripe_live_secret_key');
    $stripe_test_account_id      = get_option('chama_stripe_test_account_id');
    $stripe_live_account_id      = get_option('chama_stripe_live_account_id');
    $currency                    = get_option('chama_stripe_currency');
    $symbol                      = chama_get_currency_symbol($currency);
    $currency_position           = get_option('chama_currency_position');
    $currency_minimum            = chama_get_currency_minimum($currency);

    if (! defined('CHAMA_RECAPTCHA_SITE_KEY')) {
        define('CHAMA_RECAPTCHA_SITE_KEY', $recaptcha_site_key);
    }

    if (! defined('CHAMA_RECAPTCHA_SECRET_KEY')) {
        define('CHAMA_RECAPTCHA_SECRET_KEY', $recaptcha_secret_key);

    }
    if (! defined('CHAMA_STRIPE_TEST_PUBLISHABLE_KEY')) {
        define('CHAMA_STRIPE_TEST_PUBLISHABLE_KEY', $stripe_test_publishable_key);
    }
    if (! defined('CHAMA_STRIPE_TEST_SECRET_KEY')) {
        define('CHAMA_STRIPE_TEST_SECRET_KEY', $stripe_test_secret_key);
    }
    if (! defined('CHAMA_STRIPE_LIVE_PUBLISHABLE_KEY')) {
        define('CHAMA_STRIPE_LIVE_PUBLISHABLE_KEY', $stripe_live_publishable_key);
    }
    if (! defined('CHAMA_STRIPE_LIVE_SECRET_KEY')) {
        define('CHAMA_STRIPE_LIVE_SECRET_KEY', $stripe_live_secret_key);
    }
    if (! defined('CHAMA_STRIPE_LIVE_ACCOUNT_ID')) {
        define('CHAMA_STRIPE_LIVE_ACCOUNT_ID', $stripe_live_account_id);
    }
    if (! defined('CHAMA_STRIPE_TEST_ACCOUNT_ID')) {
        define('CHAMA_STRIPE_TEST_ACCOUNT_ID', $stripe_test_account_id);
    }

    if (! defined('CHAMA_CURRENCY')) {
        define('CHAMA_CURRENCY', $currency);
    }
    if (! defined('CHAMA_SYMBOL')) {
        define('CHAMA_SYMBOL', $symbol);
    }
    if (! defined('CHAMA_POSITION')) {
        define('CHAMA_POSITION', $currency_position);
    }
    if (! defined('CHAMA_CURRENCY_MINIMUM')) {
        define('CHAMA_CURRENCY_MINIMUM', $currency_minimum);
    }
    if (! defined('CHAMA_SUBSCRIPTION_INTERVAL')) {
        define('CHAMA_SUBSCRIPTION_INTERVAL', 'month');
    }
}
// logs in user
function chama_login_user()
{
    try {
        if (isset($_POST['chama_action']) && sanitize_text_field(wp_unslash($_POST['chama_action'])) == 'login') {
            if (isset($_POST['chama_login_nonce']) && wp_verify_nonce(sanitize_key($_POST['chama_login_nonce']), 'chama-login-nonce')) {

                // Rate limit check
                $ip        = chama_get_user_ip_address() ?? 'unknown';
                $login_key = 'chama_login_attempts_' . md5($ip);
                $attempts  = (int) get_transient($login_key);

                if ($attempts >= 5) {
                    chama_errors()->add('too_many_attempts', __('Too many login attempts. Please try again in 15 minutes.', 'chama'));
                    return;
                }
                //captcha
                if (isset($_POST['chama-captcha-response']) && ! empty($_POST['chama-captcha-response'])) {

                    $gRecaptchaResponse    = sanitize_text_field(wp_unslash($_POST['chama-captcha-response']));
                    $has_invalid_recaptcha = chama_validate_recaptcha($gRecaptchaResponse);
                    if ($has_invalid_recaptcha) {
                        chama_errors()->add('captcha_error', __('Could not validate the reCaptcha. Please complete it again.', 'chama'));
                    }

                }
                // retrieve all error messages
                $errors = chama_errors()->get_error_messages();

                if (isset($_POST['chama_username']) && empty($errors)) {

                    // this returns the user ID and other info from the user name
                    $user = get_user_by('login', sanitize_text_field(wp_unslash($_POST['chama_username'])));
                    $user = $user ? $user : get_user_by('email', sanitize_text_field(wp_unslash($_POST['chama_username'])));

                    if (! $user) {
                        // if the user name doesn't exist
                        chama_errors()->add('empty_username', __('Invalid username', 'chama'));
                    }

                    if (! isset($_POST['chama_password']) || $_POST['chama_password'] == '') {
                        // if no password was entered
                        chama_errors()->add('empty_password', __('Please enter a password', 'chama'));
                    }

                    // check the user's login with their password
                    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Passwords should not be sanitized; wp_unslash is sufficient
                    if ($user && ! wp_check_password(wp_unslash($_POST['chama_password']), $user->user_pass, $user->ID)) {
                        // if the password is incorrect for the specified user
                        chama_errors()->add('empty_password', __('Incorrect password', 'chama'));
                    }

                    // retrieve all error messages
                    $errors = chama_errors()->get_error_messages();

                    // only log the user in if there are no errors
                    if (empty($errors)) {
                        delete_transient($login_key);

                        wp_set_auth_cookie($user->ID, true);
                        wp_set_current_user($user->ID, $user->user_login);
                        //do_action('wp_login', $user->user_login);
                        //if admin redirect to dashboard
                        if (user_can($user, 'administrator')) {
                            wp_redirect(admin_url());
                            exit;
                        }

                        //update account if necessary
                        chama_check_subscription_status();

                        //check if redirect url has been set
                        if (isset($_POST['chama_redirect_url'])) {
                            $raw_url      = filter_input(INPUT_POST, 'chama_redirect_url', FILTER_SANITIZE_URL);
                            $decoded_url  = urldecode($raw_url);
                            $redirect_url = esc_url(add_query_arg(
                                [
                                    'uid' => uniqid(),
                                ],
                                $decoded_url
                            ));
                            wp_redirect($redirect_url);
                            exit;
                        } else {
                            $home_url = esc_url(add_query_arg(
                                [
                                    'uid' => uniqid(),
                                ],
                                home_url()
                            ));
                            wp_redirect($home_url);
                            exit;
                        }

                    } else {
                        set_transient($login_key, $attempts + 1, 15 * MINUTE_IN_SECONDS);
                    }
                }
            }
        }
    } catch (Exception $e) {
        chama_errors()->add('exception_error', esc_html($e->getMessage()));
    }

}
add_action('init', 'chama_login_user');
// registers user
function chama_register_user()
{
    try {
        if (isset($_POST['chama_action']) && $_POST['chama_action'] == 'register') {
            if (isset($_POST['chama_register_nonce']) && wp_verify_nonce(sanitize_key($_POST['chama_register_nonce']), 'chama-register-nonce')) {
                // Rate limit check
                $ip       = chama_get_user_ip_address() ?? 'unknown';
                $reg_key  = 'chama_register_attempts_' . md5($ip);
                $attempts = (int) get_transient($reg_key);

                if ($attempts >= 3) {
                    chama_errors()->add('too_many_registrations', __('Too many registration attempts. Please try again in 30 minutes.', 'chama'));
                    return;
                }
                //captcha
                if (isset($_POST['chama-captcha-response']) && ! empty($_POST['chama-captcha-response'])) {

                    $gRecaptchaResponse    = sanitize_text_field(wp_unslash($_POST['chama-captcha-response']));
                    $has_invalid_recaptcha = chama_validate_recaptcha($gRecaptchaResponse);
                    if ($has_invalid_recaptcha) {
                        chama_errors()->add('captcha_error', __('Could not validate the reCaptcha. Please complete it again.', 'chama'));
                    }

                }

                // retrieve all error messages
                $errors = chama_errors()->get_error_messages();

                if (isset($_POST["chama_username"]) && empty($errors)) {
                    $username         = sanitize_text_field(wp_unslash($_POST["chama_username"]));
                    $email            = isset($_POST["chama_email"]) ? sanitize_text_field(wp_unslash($_POST["chama_email"])) : '';
                    $password         = isset($_POST["chama_password"]) ? sanitize_text_field(wp_unslash($_POST["chama_password"])) : '';
                    $password_confirm = isset($_POST["chama_password_confirm"]) ? sanitize_text_field(wp_unslash($_POST["chama_password_confirm"])) : '';

                    if (username_exists($username)) {
                        // Username already registered
                        chama_errors()->add('username_unavailable', __('Username already taken', 'chama'));
                    }
                    if (! validate_username($username)) {
                        // invalid username
                        chama_errors()->add('username_invalid', __('Invalid username', 'chama'));
                    }
                    if ($username == '') {
                        // empty username
                        chama_errors()->add('username_empty', __('Please enter a username', 'chama'));
                    }
                    if (! is_email($email)) {
                        //invalid email
                        chama_errors()->add('email_invalid', __('Invalid email', 'chama'));
                    }
                    if (email_exists($email)) {
                        //Email address already registered
                        chama_errors()->add('email_used', __('Email already registered', 'chama'));
                    }
                    if ($password == '') {
                        // passwords do not match
                        chama_errors()->add('password_empty', __('Please enter a password', 'chama'));
                    }
                    if ($password != $password_confirm) {
                        // passwords do not match
                        chama_errors()->add('password_mismatch', __('Passwords do not match', 'chama'));
                    }

                    $errors = chama_errors()->get_error_messages();

                    // only create the user in if there are no errors
                    if (empty($errors)) {
                        delete_transient($reg_key);

                        $new_user_id = wp_insert_user([
                            'user_login'      => $username,
                            'user_pass'       => $password,
                            'user_email'      => $email,
                            'user_registered' => gmdate('Y-m-d H:i:s'),
                            'role'            => 'subscriber',
                        ]
                        );
                        if ($new_user_id) {
                            $send_user_notification = get_option('chama_new_user_notification');
                            if ($send_user_notification) {
                                // send an email to the admin alerting them of the registration
                                wp_new_user_notification($new_user_id);
                            }

                            // log the new user in
                            wp_set_auth_cookie($new_user_id, true);
                            wp_set_current_user($new_user_id, $username);
                            //do_action('wp_login', $username);

                            //check if redirect url has been set
                            if (isset($_POST['chama_redirect_url'])) {
                                $raw_url      = filter_input(INPUT_POST, 'chama_redirect_url', FILTER_SANITIZE_URL);
                                $redirect_url = urldecode($raw_url);
                                wp_redirect($redirect_url);
                                exit;
                            } else {
                                // send the newly created user to the account page after logging them in
                                wp_redirect(CHAMA_ACCOUNT_URL);
                                exit;
                            }

                        }

                    } else {
                        set_transient($reg_key, $attempts + 1, 30 * MINUTE_IN_SECONDS);
                    }

                }
            }
        }
    } catch (Exception $e) {
        chama_errors()->add('exception_error', esc_html($e->getMessage()));
    }

}
add_action('init', 'chama_register_user');
// update user
function chama_update_user()
{
    try {
        if (isset($_POST['chama_action']) && $_POST['chama_action'] == 'edit-account') {
            global $user_ID;

            if (! is_user_logged_in()) {
                return;
            }

            if (isset($_POST['chama_edit_account_nonce']) && wp_verify_nonce(sanitize_key($_POST['chama_edit_account_nonce']), 'chama-edit-account-nonce')) {

                if (isset($_POST["chama_email"]) && isset($_POST["chama_display_name"])) {
                    $user = wp_get_current_user();
                    if ($user) {
                        $current_email = $user->user_email;
                        $email         = sanitize_text_field(wp_unslash($_POST["chama_email"]));
                        $display_name  = sanitize_text_field(wp_unslash($_POST["chama_display_name"]));
                        $first_name    = isset($_POST["chama_first_name"]) ? sanitize_text_field(wp_unslash($_POST["chama_first_name"])) : '';
                        $last_name     = isset($_POST["chama_last_name"]) ? sanitize_text_field(wp_unslash($_POST["chama_last_name"])) : '';

                        if (! is_email($email)) {
                            //invalid email
                            chama_errors()->add('email_invalid', __('Invalid email', 'chama'));
                        }
                        if (email_exists($email) && $email !== $current_email) {
                            //Email address already registered
                            chama_errors()->add('email_used', __('Email already registered', 'chama'));
                        }

                        $errors = chama_errors()->get_error_messages();

                        // only create the user in if there are no errors
                        if (empty($errors)) {

                            wp_update_user([
                                'ID'           => $user_ID,
                                'user_pass'    => $password,
                                'user_email'   => $email,
                                'first_name'   => $first_name,
                                'last_name'    => $last_name,
                                'display_name' => $display_name,
                            ]
                            );
                    
                            $current_url = home_url(chama_get_current_request_uri());
                            wp_redirect(add_query_arg('account-updated', 'true', $current_url));
                            exit;

                        }
                    }

                }
            }
        }
    } catch (Exception $e) {
        chama_errors()->add('exception_error', esc_html($e->getMessage()));
    }

}
add_action('init', 'chama_update_user');
// update user
function chama_update_password()
{
    try {
        if (isset($_POST['chama_action']) && $_POST['chama_action'] == 'edit-password') {
            global $user_ID;

            if (! is_user_logged_in()) {
                return;
            }

            if (isset($_POST['chama_edit_password_nonce']) && wp_verify_nonce(sanitize_key($_POST['chama_edit_password_nonce']), 'chama-edit-password-nonce')) {

                if (isset($_POST["chama_password"])) {
                    $user = wp_get_current_user();
                    if ($user) {
                        $password         = sanitize_text_field(wp_unslash($_POST['chama_password']));
                        $password_confirm = isset($_POST['chama_password_confirm']) ? sanitize_text_field(wp_unslash($_POST['chama_password_confirm'])) : '';
                        $current_password = isset($_POST['chama_current_password']) ? sanitize_text_field(wp_unslash($_POST['chama_current_password'])) : '';
                        // check the user's login with their password
                        if ($user && ! wp_check_password($current_password, $user->user_pass, $user->ID)) {
                            // if the password is incorrect for the specified user
                            chama_errors()->add('empty_password', __('Incorrect password', 'chama'));
                        }

                        if ($password == '') {
                            // passwords do not match
                            chama_errors()->add('password_empty', __('Please enter a password', 'chama'));
                        }
                        if ($password != $password_confirm) {
                            // passwords do not match
                            chama_errors()->add('password_mismatch', __('Passwords do not match', 'chama'));
                        }

                        $errors = chama_errors()->get_error_messages();

                        // only create the user in if there are no errors
                        if (empty($errors)) {

                            wp_update_user([
                                'ID'        => $user_ID,
                                'user_pass' => $password,
                            ]
                            );
                   
                            $current_url = home_url(chama_get_current_request_uri());
                            wp_redirect(add_query_arg('password-updated', 'true', $current_url));
                            exit;

                        }
                    }

                }
            }
        }
    } catch (Exception $e) {
        chama_errors()->add('exception_error', esc_html($e->getMessage()));
    }

}
add_action('init', 'chama_update_password');
// send password reset link
function chama_send_password_reset()
{
    try {
        if (isset($_POST['chama_action']) && $_POST['chama_action'] == 'forgot-password') {
            if (isset($_POST['chama_forgot_password_nonce']) && wp_verify_nonce(sanitize_key($_POST['chama_forgot_password_nonce']), 'chama-forgot-password-nonce')) {
                if (isset($_POST['chama-captcha-response']) && ! empty($_POST['chama-captcha-response'])) {

                    $gRecaptchaResponse    = sanitize_text_field(wp_unslash($_POST['chama-captcha-response']));
                    $has_invalid_recaptcha = chama_validate_recaptcha($gRecaptchaResponse);
                    if ($has_invalid_recaptcha) {
                        chama_errors()->add('captcha_error', __('Could not validate the reCaptcha. Please complete it again.', 'chama'));
                    }

                }

                $email = isset($_POST['chama_email']) ? sanitize_email(wp_unslash($_POST['chama_email'])) : '';
                if (! is_email($email)) {
                    //invalid email
                    chama_errors()->add('email_invalid', __('Invalid email', 'chama'));
                }
                if (! email_exists($email)) {
                    //Email address already registered
                    chama_errors()->add('email_used', __('No such email exists.', 'chama'));
                }

                // retrieve all error messages
                $errors = chama_errors()->get_error_messages();

                // only send email if there is no error
                if (empty($errors)) {
                    $password_reset_link = '';
                    $user                = get_user_by("email", $email);
                    if ($user) {
                        $key                 = get_password_reset_key($user);
                        $user_login          = $user->user_login;
                        $password_reset_link = esc_url_raw(CHAMA_RESET_PASSWORD_URL . "?chama_action=process_reset&key=$key&login=" . rawurlencode($user_login));
                        $from                = sprintf("%s <%s>", CHAMA_FROM_NAME, CHAMA_FROM_EMAIL);
                        $from_header         = 'From: ' . $from;
                        $headers             = ['Content-Type: text/html; charset=UTF-8', $from_header];
                        $subject             = 'Password Reset';
                        $message             = __('Someone has requested a password reset for the following account:', 'chama') . "\r\n\r\n";
                        $message .= network_home_url('/') . "\r\n\r\n";
                        /* translators: %s username. */
                        $message .= sprintf(__('Username: %s', 'chama'), $user_login) . "\r\n\r\n";
                        $message .= __('If this was a mistake, just ignore this email and nothing will happen.', 'chama') . "\r\n\r\n";
                        $message .= __('To reset your password, visit the following address:', 'chama') . "\r\n\r\n";
                        $message .= '<a href="' . $password_reset_link . '">' . $password_reset_link . ' </a>' . "\r\n";
                        chama_send_email($email, $subject, $message, $headers);

                        $current_url = home_url(chama_get_current_request_uri());
                        wp_redirect(add_query_arg('sent-link', 'true', $current_url));
                    }
                }
            }
        }
    } catch (Exception $e) {
        chama_errors()->add('exception_error', esc_html($e->getMessage()));
    }

}
add_action('init', 'chama_send_password_reset');
// reset password
function chama_reset_password()
{
    try {
        if (isset($_POST['chama_action']) && $_POST['chama_action'] == 'reset-password') {

            if (isset($_POST['chama_password_reset_nonce']) && wp_verify_nonce(sanitize_key($_POST['chama_password_reset_nonce']), 'chama-password-reset-nonce')) {

                if (isset($_POST["chama_user_login"])) {
                    $username = sanitize_text_field(wp_unslash($_POST["chama_user_login"]));
                    $user     = get_user_by("login", $username);
                    if ($user) {

                    }

                    $password         = isset($_POST['chama_password']) ? sanitize_text_field(wp_unslash($_POST['chama_password'])) : '';
                    $password_confirm = isset($_POST['chama_password_confirm']) ? sanitize_text_field(wp_unslash($_POST['chama_password_confirm'])) : '';

                    if ($password == '') {
                        // passwords do not match
                        chama_errors()->add('password_empty', __('Please enter a password', 'chama'));
                    }
                    if ($password != $password_confirm) {
                        // passwords do not match
                        chama_errors()->add('password_mismatch', __('Passwords do not match', 'chama'));
                    }

                    $errors = chama_errors()->get_error_messages();

                    // only update the user in if there are no errors
                    if (empty($errors)) {

                        wp_update_user([
                            'ID'        => $user->ID,
                            'user_pass' => $password,
                        ]
                        );

                        wp_redirect(add_query_arg('password-reset', 'true', CHAMA_RESET_PASSWORD_URL));
                        exit;

                    }

                }
            }
        }
    } catch (Exception $e) {
        chama_errors()->add('exception_error', esc_html($e->getMessage()));
    }

}
add_action('init', 'chama_reset_password');
// resend confirmation
function chama_account_resend_confirmation()
{
    try {
        if (isset($_GET['chama_action']) && $_GET['chama_action'] == 'resend-confirmation') {

            if (isset($_GET['chama_nonce']) && wp_verify_nonce(sanitize_key($_GET['chama_nonce']), 'chama_resend_confirmation_nonce')) {

                if (isset($_GET["user_id"])) {
                    $user_id = sanitize_text_field(wp_unslash($_GET['user_id']));
                    $user    = get_userdata($user_id);
                    $email   = $user->user_email;
                    chama_user_register($user_id, true);
                    wp_redirect(add_query_arg('sent-link', 'true', CHAMA_ACCOUNT_URL));
                    exit;

                }
            }
        }
    } catch (Exception $e) {
        chama_errors()->add('exception_error', esc_html($e->getMessage()));
    }

}
add_action('init', 'chama_account_resend_confirmation');
// process donation
function chama_process_one_time()
{
    try {
        if (isset($_POST['chama_action']) && $_POST['chama_action'] == 'one-time') {
            if (isset($_POST['chama_one_time_nonce']) && wp_verify_nonce(sanitize_key($_POST['chama_one_time_nonce']), 'chama-one-time-nonce')) {

                if (isset($_POST["one_time_amount"])) {
                    $one_time_amount    = sanitize_text_field(wp_unslash($_POST["one_time_amount"]));
                    $donation_min_limit = get_option('chama_donation_min_limit');
                    $require_login      = get_option('chama_require_login');

                    if ($one_time_amount < $donation_min_limit) {
                        // Did not make minimum donation
                        chama_errors()->add('minimum_one_time_amount', __('You did not make the minimum donation', 'chama'));
                    }

                    $errors = chama_errors()->get_error_messages();

                    $payment_data         = ['amount' => $one_time_amount, 'type' => 'one-time'];
                    $encoded_payment_data = base64_encode(serialize($payment_data));
                    $payment_link         = add_query_arg(
                        [
                            'meta' => $encoded_payment_data,
                        ],
                        CHAMA_PAYMENT_URL
                    );
                    if ($require_login) {
                        if (! is_user_logged_in()) {
                            $login_link = add_query_arg(
                                [
                                    'redirect_url' => urlencode($payment_link),
                                ],
                                CHAMA_LOGIN_URL
                            );
                            wp_redirect($login_link);
                            exit;
                        } else {

                            wp_redirect($payment_link);
                            exit;
                        }
                    }
                    wp_redirect($payment_link);
                    exit;
                }
            }
        }
    } catch (Exception $e) {
        chama_errors()->add('exception_error', esc_html($e->getMessage()));
    }

}
add_action('init', 'chama_process_one_time');
function chama_process_commission()
{

    if (isset($_POST['chama_action']) && $_POST['chama_action'] == 'commission') {
        if (isset($_POST['chama_commission_nonce']) && wp_verify_nonce(sanitize_key($_POST['chama_commission_nonce']), 'chama-commission-nonce')) {

            if (isset($_POST["commission_id"]) && isset($_POST["commission_description"]) && isset($_POST["chama-commission-request"]) && isset($_POST["commission_price"]) && isset($_POST["commission_amount"]) && isset($_POST["commission_shipping"])) {
                $commission_id          = sanitize_text_field(wp_unslash($_POST["commission_id"]));
                $commission_description = sanitize_text_field(wp_unslash($_POST["commission_description"]));
                $commission_request     = sanitize_text_field(wp_unslash($_POST["chama-commission-request"]));
                $commission_amount      = sanitize_text_field(wp_unslash($_POST["commission_amount"]));
                $commission_price       = sanitize_text_field(wp_unslash($_POST["commission_price"]));
                $commission_shipping    = sanitize_text_field(wp_unslash($_POST["commission_shipping"]));
                $comission_addons       = '';
                if (isset($_POST["commission_add_ons"])) {
                    $comission_addons = sanitize_text_field(wp_unslash($_POST["commission_add_ons"]));
                }

                $require_login = get_option('chama_require_login');

                $payment_data = ['id' => $commission_id, 'description' => $commission_description, 'request' => $commission_request, 'price' => $commission_price, 'amount' => $commission_amount, 'shipping' => $commission_shipping, 'type' => 'commission'];
                if ($comission_addons) {
                    $payment_data['addons'] = $comission_addons;
                }
                $encoded_payment_data = base64_encode(serialize($payment_data));
                $payment_link         = add_query_arg(
                    [
                        'meta' => $encoded_payment_data,
                    ],
                    CHAMA_PAYMENT_URL
                );
                if ($require_login) {
                    if (! is_user_logged_in()) {
                        $login_link = add_query_arg(
                            [
                                'redirect_url' => urlencode($payment_link),
                            ],
                            CHAMA_LOGIN_URL
                        );
                        wp_redirect($login_link);
                        exit;
                    } else {

                        wp_redirect($payment_link);
                        exit;
                    }
                }
                wp_redirect($payment_link);
                exit;
            }
        }
    }

}
add_action('init', 'chama_process_commission');
// process commission
// issue receipt
function chama_issue_receipt()
{
    if (isset($_GET['chama_action']) && $_GET['chama_action'] == 'receipt') {

        if (isset($_GET['chama_nonce']) && wp_verify_nonce(sanitize_key($_GET['chama_nonce']), 'chama_issue_receipt')) {

            if (isset($_GET["type"]) && isset($_GET['payment_intent']) && isset($_GET['receipt_id'])) {
                try {
                    $subscription_id          = $receipt_id          = '';
                    $type                     = sanitize_text_field(wp_unslash($_GET['type']));
                    $stripe_payment_intent_id = sanitize_text_field(wp_unslash($_GET['payment_intent']));
                    if (isset($_GET["receipt_id"])) {
                        $receipt_id = sanitize_text_field(wp_unslash($_GET["receipt_id"]));
                    }
                    //get transaction post
                    if ($stripe_payment_intent_id) {
                        switch ($type) {
                            case 'one-time':
                                $cpt = 'chama_donation';
                                break;
                            case 'membership':
                                $cpt        = 'chama_subscription';
                                $secret_key = chama_is_live_mode()  ?CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;
                                if ($secret_key) {
                                    $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                                        $secret_key // API Secret here
                                    );
                                    $payment_intent = $stripe->paymentIntents->retrieve(
                                        $stripe_payment_intent_id,
                                    );

                                    if ($payment_intent) {
                                        update_post_meta($receipt_id, 'chama_stripe_payment_intent_id', $stripe_payment_intent_id);
                                        if ($payment_intent->currency) {
                                            $currency         = $payment_intent->currency;
                                            $currency_minimum = chama_get_currency_minimum($currency);
                                            if ($payment_intent->amount) {
                                                $total_amount_cents     = sanitize_text_field($payment_intent->amount);
                                                $total_amount           = $total_amount_cents / $currency_minimum;
                                                $total_amount_formatted = number_format(floatval($total_amount), 2);
                                                update_post_meta($receipt_id, $cpt . '_currency', sanitize_text_field($currency));
                                                update_post_meta($receipt_id, $cpt . '_total_amount', sanitize_text_field($total_amount_formatted));
                                            }
                                        }
                                    } else {
                                        wp_die('An error occured while processing your receipt. Could not get transaction for payment intent: ' . esc_html($stripe_payment_intent_id) . ' and receipt #: ' . esc_html($receipt_id));
                                    }
                                }

                                break;
                            case 'crowdfunding':
                                $cpt = 'chama_fund';
                                break;
                            case 'commission':
                                $cpt = 'chama_com_order';
                                break;
                            default:
                        }

                        if ($receipt_id) {
                            $confirmation_receipt_id = base64_encode($receipt_id);
                            $confirmation_url        = $type == 'membership'  ?CHAMA_SUBSCRIPTION_CONFIRMATION_URL : CHAMA_PAYMENT_CONFIRMATION_URL;
                            $receipt_url             = add_query_arg(
                                [
                                    'receipt-id' => $confirmation_receipt_id,
                                    'type'       => $type,
                                ],
                                $confirmation_url
                            );
                            wp_redirect($receipt_url);
                        } else {
                            wp_die('An error occured while processing your receipt. Could not get transaction for payment intent: ' . esc_html($stripe_payment_intent_id) . ' and receipt #: ' . esc_html($receipt_id));
                        }

                    } else {
                        wp_die('An error occured while processing your receipt. Could not get payment intent id');
                    }

                    exit;
                } catch (\ChamaWP\Vendor\Stripe\ApiErrorException $e) {

                    wp_die(esc_html($e->getError()->message));
                } catch (Exception $e) {
                    wp_die('An error occured with the payment processor');
                }

            }
        }
    }

}
add_action('init', 'chama_issue_receipt');
//Build donation processing email
// used for tracking error messages
function chama_errors()
{
    static $wp_error; // Will hold global variable safely
    return isset($wp_error) ? $wp_error : ($wp_error = new WP_Error(null, null, null));
}
function chama_show_error_messages()
{
    if ($codes = chama_errors()->get_error_codes()) {
        echo '<div class="chama-alert chama-alert-error">';
        // Loop error codes and display errors
        foreach ($codes as $code) {
            $message = chama_errors()->get_error_message($code);
            echo '<span class="error"><strong>' . esc_html('Error') . '</strong>: ' . esc_html($message) . '</span><br/>';
        }
        echo '</div>';
    }
}

add_action('init', 'chama_logout_user');
function chama_logout_user()
{
    $is_logout = false;

    if ( isset($_GET['chama-logout']) && isset($_GET['chama-logout-nonce']) ) {
        $logout_action = sanitize_text_field( wp_unslash( $_GET['chama-logout'] ) );
        $nonce         = sanitize_text_field( wp_unslash( $_GET['chama-logout-nonce'] ) );

        if ( $logout_action && wp_verify_nonce( $nonce, 'chama_logout_action' ) ) {
            $is_logout = true;
        }
    }

    if ( $is_logout && is_user_logged_in() ) {
        wp_logout();
        wp_set_current_user(0);
        if ( function_exists('wp_destroy_current_session') ) {
            wp_destroy_current_session();
        }
        if ( function_exists('wp_clear_auth_cookie') ) {
            wp_clear_auth_cookie();
        }

        $current_url = home_url(chama_get_current_request_uri());
        header("refresh:0.5;url=" . $current_url);
        exit();
    }
}
//rewrite for displaying crowdfunding page
add_action('init', 'chama_pages_rewrite_rule');
function chama_pages_rewrite_rule()
{
    $crowdfunding_page = chama_get_page_data('chama_crowdfunding_page');
    $commissions_page  = chama_get_page_data('chama_commissions_page');
    if ($crowdfunding_page && $crowdfunding_page['slug']) {
        $crowdfunding_page_slug = $crowdfunding_page['slug'];
        add_rewrite_rule(sprintf('^%s/([^/]+)([/]?)(.*)', $crowdfunding_page_slug),
            sprintf('index.php?pagename=%s&slug=$matches[1]', $crowdfunding_page_slug),
            'top'
        );
    }
    if ($commissions_page && $commissions_page['slug']) {
        $commissions_page_slug = $commissions_page['slug'];
        add_rewrite_rule(sprintf('^%s/([^/]+)([/]?)(.*)', $commissions_page_slug),
            sprintf('index.php?pagename=%s&slug=$matches[1]', $commissions_page_slug),
            'top'
        );
    }

}
add_filter('query_vars', function ($vars) {
    $vars[] = 'pagename';
    $vars[] = 'slug';
    return $vars;
});
add_action('user_register', 'chama_user_register');

add_action('init', 'chama_redirect_users_for_protected_content');

function chama_redirect_users_for_protected_content()
{

    $account_page_id = get_option('chama_account_page');

    if (! is_user_logged_in() && is_page($account_page_id)) {
        wp_redirect(CHAMA_LOGIN_URL);
        exit;
    }
}

add_action('template_redirect', 'chama_redirect_users_for_protected_content');

function chama_redirect_users_for_login_page()
{
    $login_page_id = get_option('chama_login_page');
    if (is_user_logged_in() && is_page($login_page_id)) {

        wp_redirect(CHAMA_ACCOUNT_URL);
        exit;
    }
}
add_action('template_redirect', 'chama_redirect_users_for_login_page');

function chama_rest_end_point()
{
    register_rest_route('v1/stripe', 'payment', [
        'methods'             => 'POST',
        'callback'            => 'chama_handle_payment_intent',
        'permission_callback' => function () {
            return check_ajax_referer('wp_rest', '_wpnonce', false);
        },

    ]);
    register_rest_route('v1/stripe', 'subscription', [
        'methods'             => 'POST',
        'callback'            => 'chama_handle_subscription_creation',
        'permission_callback' => function () {
            return check_ajax_referer('wp_rest', '_wpnonce', false);
        },

    ]);
    register_rest_route('v1/stripe', 'validate', [
        'methods'             => 'POST',
        'callback'            => 'chama_handle_form_validation',
        'permission_callback' => function () {
            return check_ajax_referer('wp_rest', '_wpnonce', false);
        },

    ]);
    register_rest_route('v1/stripe', 'cancel', [
        'methods'             => 'POST',
        'callback'            => 'chama_handle_subscription_cancelation',
        'permission_callback' => function () {
            return check_ajax_referer('wp_rest', '_wpnonce', false);
        },

    ]);
    register_rest_route('v1/stripe', 'delete', [
        'methods'             => 'POST',
        'callback'            => 'chama_handle_account_deletion',
        'permission_callback' => function () {
            return check_ajax_referer('wp_rest', '_wpnonce', false);
        },

    ]);
    register_rest_route('v1/stripe', 'pause', [
        'methods'             => 'POST',
        'callback'            => 'chama_handle_subscription_pause',
        'permission_callback' => function () {
            return check_ajax_referer('wp_rest', '_wpnonce', false);
        },

    ]);
    register_rest_route('v1/stripe', 'resume', [
        'methods'             => 'POST',
        'callback'            => 'chama_handle_subscription_resume',
        'permission_callback' => function () {
            return check_ajax_referer('wp_rest', '_wpnonce', false);
        },

    ]);
    register_rest_route('v1/stripe', 'setup', [
        'methods'             => 'POST',
        'callback'            => 'chama_handle_setup_intent',
        'permission_callback' => function () {
            return check_ajax_referer('wp_rest', '_wpnonce', false);
        },

    ]);

}
add_action('rest_api_init', 'chama_rest_end_point');
function chama_handle_account_deletion($data)
{
    $params    = $data->get_params();
    $message   = '';
    $has_error = false;
    if (isset($params['_wpnonce']) && wp_verify_nonce($params['_wpnonce'], 'wp_rest')) {
        try {
            $user = wp_get_current_user();
            // Proceed only if a user is logged in and NOT an admin.
            if ($user && ! current_user_can('manage_options')) {
                $user_id                = $user->ID;
                $user_email             = $user->user_email;
                $username               = $user->user_login;
                $stripe_subscription_id = get_user_meta($user_id, 'chama_stripe_subscription_id', true);
                $tier_id                = get_user_meta($user_id, 'chama_tier_id', true);
                $subscription_status    = get_user_meta($user_id, 'chama_subscription_status', true);

                /*=============================================CANCEL SUBSCRIPTION ON STRIPE=============================================*/
                if ($subscription_status == 'active') {
                    if ($stripe_subscription_id && $tier_id) {
                        $mode       = chama_is_live_mode() ? 'live' : 'test';
                        $secret_key = chama_is_live_mode()  ?CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;
                        if ($secret_key) {
                            $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                                $secret_key // API Secret here
                            );
                            $subscription = $stripe->subscriptions->cancel($stripe_subscription_id, []);
                            chama_update_subscription_transactions($stripe_subscription_id, 'canceled');
                            chama_remove_user_membership($user_id, $tier_id);
                        }
                    } else {
                        $message   = 'An error occured while retrieving your subscription. Try again. If issue persists, contact us.';
                        $has_error = true;
                    }
                }
                /*=============================================DELETE ALL TRANSACTIONS=============================================*/
                chama_delete_transactions($user_id);
                /*=============================================DELETE ACCOUNT=============================================*/
                // Load wp_delete_user only if it's not already available.
                // This function lives in a core file not loaded front-end by default.
                if (! function_exists('wp_delete_user')) {
                    require_once ABSPATH . 'wp-admin/includes/user.php';
                }
                //Not an admin user so it is safe to delete this user.
                $deleted = wp_delete_user($user_id);

                if ($deleted) {
                    /*=============================================SEND EMAIL=============================================*/
                    $from        = sprintf("%s <%s>", CHAMA_FROM_NAME, CHAMA_FROM_EMAIL);
                    $from_header = 'From: ' . $from;
                    $headers     = ['Content-Type: text/html; charset=UTF-8', $from_header];
                    //send to admin
                    if (get_option('chama_supporter_enable_payment_notification')) {
                        $subject = 'Heads up! A user deleted their account.';
                        $message = sprintf('A user %s - %s has deleted their account.', $username, $user_email);
                        chama_send_email(get_option('chama_admin_email'), $subject, $message, $headers);

                    }
                    //send to user
                    $subject = 'Your account has been deleted successfully.';
                    $message = 'Your account has been deleted. In case this is a mistake, please contact the site administrator at ' . site_url();
                    chama_send_email($user_email, $subject, $message, $headers);

                    /*=============================================DELETE COMMENTS=============================================*/
                    // Load wp_delete_comment only if it's not already available.
                    // This file is only included in an admin context, and we check permissions above.
                    if (! function_exists('wp_delete_comment')) {
                        require_once ABSPATH . 'wp-admin/includes/comment.php';
                    }

                    // Get and delete all comments made by this user.
                    $comments = get_comments(['user_id' => $user_id]);

                    foreach ($comments as $comment) {

                        // Delete comments.
                        wp_delete_comment($comment, true);
                    }
                }

            } else {
                $message   = 'An error occured while retrieving your account. Try again. If issue persists, contact us.';
                $has_error = true;

            }
            if ($has_error) {
                return new WP_REST_Response(['status' => 'error', 'message' => $message], 500);
            } else {
                return new WP_REST_Response(['status' => 'canceled', 'message' => 'Successfully canceled!'], 200);
            }

        } catch (Exception $e) {
            return new WP_REST_Response(['status' => 'failed', 'message' => 'An error occured while deleting your account. Try again. If issue persists, contact us.'], 500);
        }
    }
}
function chama_handle_subscription_cancelation($data)
{
    $params    = $data->get_params();
    $message   = '';
    $has_error = false;
    if (isset($params['_wpnonce']) && wp_verify_nonce($params['_wpnonce'], 'wp_rest')) {
        try {
            $subscription_id = (int) $params['id'];
            if ($subscription_id) {
                $stripe_subscription_id = get_post_meta($subscription_id, 'chama_stripe_subscription_id', true);
                $user_id                = get_post_meta($subscription_id, 'chama_user_id', true);
                $tier_id                = get_post_meta($subscription_id, 'chama_tier_id', true);
                if ($stripe_subscription_id) {
                    $mode       = chama_is_live_mode() ? 'live' : 'test';
                    $secret_key = chama_is_live_mode()  ?CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;
                    if ($secret_key) {
                        $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                            $secret_key // API Secret here
                        );
                        $subscription = $stripe->subscriptions->cancel($stripe_subscription_id, []);
                        chama_update_subscription_transactions($stripe_subscription_id, 'canceled');
                    }
                } else {
                    $has_error = true;
                }
            } else {
                $has_error = true;

            }
            if ($has_error) {
                return new WP_REST_Response(['status' => 'error', 'message' => 'An error occured while retrieving your subscription. Try again. If issue persists, contact us.'], 500);
            } else {
                return new WP_REST_Response(['status' => 'canceled', 'message' => 'Successfully canceled!'], 200);
            }

        } catch (Exception $e) {
            return new WP_REST_Response(['status' => 'failed', 'message' => 'An error occured while canceling your subscription. Try again. If issue persists, contact us.'], 500);
        }
    }
}
function chama_handle_subscription_pause($data)
{
    $params    = $data->get_params();
    $message   = '';
    $has_error = false;
    if (isset($params['_wpnonce']) && wp_verify_nonce($params['_wpnonce'], 'wp_rest')) {
        try {
            $subscription_id = (int) $params['id'];
            if ($subscription_id) {
                $stripe_subscription_id = get_post_meta($subscription_id, 'chama_stripe_subscription_id', true);
                $user_id                = get_post_meta($subscription_id, 'chama_user_id', true);
                if ($stripe_subscription_id) {
                    $mode       = chama_is_live_mode() ? 'live' : 'test';
                    $secret_key = chama_is_live_mode()  ?CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;
                    if ($secret_key) {
                        $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                            $secret_key // API Secret here
                        );
                        $stripe->subscriptions->update(
                            $stripe_subscription_id,
                            ['pause_collection' => ['behavior' => 'void']]
                        );
                        chama_update_subscription_transactions($stripe_subscription_id, 'paused');
                        chama_pause_user_membership($user_id);
                    }
                } else {
                    $has_error = true;
                }
            } else {
                $has_error = true;

            }
            if ($has_error) {
                return new WP_REST_Response(['status' => 'error', 'message' => 'An error occured while retrieving your subscription. Try again. If issue persists, contact us.'], 500);
            } else {
                return new WP_REST_Response(['status' => 'canceled', 'message' => 'Successfully paused!'], 200);
            }

        } catch (Exception $e) {
            return new WP_REST_Response(['status' => 'failed', 'message' => 'An error occured while pausing your subscription. Try again. If issue persists, contact us.'], 500);
        }
    }
}
function chama_handle_subscription_resume($data)
{
    $params    = $data->get_params();
    $message   = '';
    $has_error = false;
    if (isset($params['_wpnonce']) && wp_verify_nonce($params['_wpnonce'], 'wp_rest')) {
        try {
            $subscription_id = (int) $params['id'];
            if ($subscription_id) {
                $stripe_subscription_id = get_post_meta($subscription_id, 'chama_stripe_subscription_id', true);
                $user_id                = get_post_meta($subscription_id, 'chama_user_id', true);
                if ($stripe_subscription_id) {
                    $mode       = chama_is_live_mode() ? 'live' : 'test';
                    $secret_key = chama_is_live_mode()  ?CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;
                    if ($secret_key) {
                        $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                            $secret_key // API Secret here
                        );
                        $stripe->subscriptions->update(
                            $stripe_subscription_id,
                            ['pause_collection' => '']
                        );
                        chama_update_subscription_transactions($stripe_subscription_id, 'active');
                        chama_resume_user_membership($user_id);
                    }
                } else {
                    $has_error = true;
                }
            } else {
                $has_error = true;

            }
            if ($has_error) {
                return new WP_REST_Response(['status' => 'error', 'message' => 'An error occured while retrieving your subscription. Try again. If issue persists, contact us.'], 500);
            } else {
                return new WP_REST_Response(['status' => 'canceled', 'message' => 'Successfully paused!'], 200);
            }

        } catch (Exception $e) {
            return new WP_REST_Response(['status' => 'failed', 'message' => 'An error occured while pausing your subscription. Try again. If issue persists, contact us.'], 500);
        }
    }
}
function chama_handle_form_validation($data)
{
    $params  = $data->get_params();
    $message = $display_min_limit = '';
    $amount  = 0;

    if (isset($params['_wpnonce']) && wp_verify_nonce($params['_wpnonce'], 'wp_rest')) {
        $amount = floatval($params['amount']);
        $type   = $params['type'];
        try {
            switch ($type) {
                case 'one-time':
                    $donation_min_limit       = floatval(get_option('chama_donation_min_limit'));
                    $donation_min_limit_cents = $donation_min_limit * CHAMA_CURRENCY_MINIMUM;
                    $display_min_limit        = chama_get_formatted_price($donation_min_limit_cents);
                    if ($amount < $donation_min_limit) {
                        $message = 'You must donate at least: ' . $display_min_limit;
                    }
                    break;
                case 'membership':
                    $tier_id                   = $params['tier_id'];
                    $tier_minimum_amount       = floatval(get_post_meta($tier_id, 'tier_price', true));
                    $tier_minimum_amount_cents = $tier_minimum_amount * CHAMA_CURRENCY_MINIMUM;
                    $display_min_limit         = chama_get_formatted_price($tier_minimum_amount_cents);
                    if ($amount < $tier_minimum_amount) {
                        $message = 'You must donate at least: ' . $display_min_limit;
                    }
                    break;
                case 'crowdfunding':
                    $campaign_id                       = $params['campaign_id'];
                    $crowdfunding_minimum_amount       = get_post_meta($campaign_id, 'campaign_min_donation', true) ? floatval(get_post_meta($campaign_id, 'campaign_min_donation', true)) : 0;
                    $crowdfunding_minimum_amount_cents = $crowdfunding_minimum_amount * CHAMA_CURRENCY_MINIMUM;
                    $display_min_limit                 = chama_get_formatted_price($crowdfunding_minimum_amount_cents);
                    if ($amount < $crowdfunding_minimum_amount) {
                        $message = 'You must donate at least: ' . $display_min_limit;
                    }
                    break;
                case 'commission':
                    $commission_id                    = $params['commission_id'];
                    $commission_minimum_amount        = get_post_meta($commission_id, 'commission_price', true);
                    $commmission_minimum_amount_cents = $commission_minimum_amount * CHAMA_CURRENCY_MINIMUM;
                    $display_min_limit                = chama_get_formatted_price($commmission_minimum_amount_cents);
                    if ($amount < $commission_minimum_amount) {
                        $message = 'You must pay at least: ' . $display_min_limit;
                    }
                    break;
                default:
            }
            if ($message) {
                return new WP_REST_Response(['status' => 'failed', 'message' => $message], 500);
            } else {
                return new WP_REST_Response(['status' => 'passed', 'message' => ''], 200);
            }

        } catch (Exception $e) {
            return new WP_REST_Response(['status' => 'failed', 'message' => 'An error occured while processing your form.'], 500);
        }

    }
}
function chama_handle_payment_intent($data)
{
    $payment_intent = null;
    $params         = $data->get_params();
    if (isset($params['_wpnonce']) && wp_verify_nonce($params['_wpnonce'], 'wp_rest')) {
        if (isset($params['captcha_response']) && ! empty($params['captcha_response'])) {

            $gRecaptchaResponse    = sanitize_text_field(wp_unslash($params['captcha_response']));
            $has_invalid_recaptcha = chama_validate_recaptcha($gRecaptchaResponse);
            if ($has_invalid_recaptcha) {
                return new WP_REST_Response('Captcha validation failed!', 500);
            }

        }

        $secret_key = chama_is_live_mode()  ?CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;
        $receipt_id = '';
        if ($secret_key) {
            $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                $secret_key // API Secret here
            );
            if (isset($params['amount']) && isset($params['email']) && isset($params['description'])) {
                try {
                    $amount              = $params['amount'];
                    $email               = $params['email'];
                    $type                = $params['type'];
                    $description         = $params['description'];
                    $customer_ID         = '';
                    $user                = null;
                    $full_name           = $params['name'];
                    $user_id             = 0;
                    $campaign_id         = 0;
                    $commission_id       = 0;
                    $commission_request  = '';
                    $commission_price    = '';
                    $commission_shipping = '';
                    $commission_addons   = '';
                    $tier_id             = '';
                    $product_id          = '';
                    $price_id            = '';
                    $payment_intent_id   = '';
                    $item_id             = 0;

                    if (isset($params['tier_id'])) {
                        $tier_id = (int) $params['tier_id'];
                    }
                    if (isset($params['product_id'])) {
                        $product_id = $params['product_id'];
                    }
                    if (isset($params['price_id'])) {
                        $price_id = $params['price_id'];
                    }
                    if (isset($params['campaign_id'])) {
                        $campaign_id = (int) $params['campaign_id'];
                    }
                    if (isset($params['commission_id'])) {
                        $commission_id = (int) $params['commission_id'];
                    }
                    if (isset($params['commission_request'])) {
                        $commission_request = $params['commission_request'];
                    }
                    if (isset($params['commission_price'])) {
                        $commission_price = $params['commission_price'];
                    }
                    if (isset($params['commission_shipping'])) {
                        $commission_shipping = $params['commission_shipping'];
                    }
                    if (isset($params['commission_addons'])) {
                        $commission_addons = $params['commission_addons'];
                    }
                    //handle user
                    if (! is_user_logged_in()) {

                        if (username_exists($email) || email_exists($email)) {
                            $user    = get_user_by('email', $email) ? get_user_by('email', $email) : get_user_by('login', $email);
                            $user_id = $user->ID;
                        }

                        if (! $user) {
                            $password = wp_generate_password(12);
                            $user_id  = wp_insert_user([
                                'user_login'      => $email,
                                'user_pass'       => $password,
                                'user_email'      => $email,
                                'user_registered' => gmdate('Y-m-d H:i:s'),
                                'role'            => 'subscriber',
                            ]
                            );

                        }

                    } else {
                        $user_id = get_current_user_id();
                    }

                    //check if customer exists
                    $customer_ID = get_user_meta($user_id, 'chama_stripe_customer_id', true);
                    if ($customer_ID) {
                        $customer = $stripe->customers->retrieve($customer_ID, []);
                        if (isset($customer->deleted) && $customer->deleted) {
                            $customer_ID = null;
                            update_user_meta($user_id, 'chama_stripe_customer_id', false);
                        }
                    }
                    /*=============================================STRIPE CUSTOMER ACCOUNT=============================================*/
                    if (! $customer_ID) {
                        //search for user by email
                        $query = $stripe->customers->search([
                            'query' => 'email:\'' . $email . '\'',
                        ]);
                        foreach ($query->data as $key) {
                            if (strcmp($key->email, $email) == 0) {
                                $customer_ID = $key->id;
                                update_user_meta($user_id, 'chama_stripe_customer_id', $customer_ID);
                                break;
                            }
                        }
                    }

                    if (! $customer_ID) {
                        $new_customer = ['email' => $email, 'metadata' => ["user_id" => $user_id]];
                        if ($full_name) {
                            $new_customer["name"] = $full_name;
                        }
                        $customer_response = $stripe->customers->create($new_customer);
                        $customer_ID       = $customer_response->id;
                    }

                    /*=============================================STRIPE PAYMENT INTENT=============================================*/
                    $metadata = ['type' => $type];
                    if ($campaign_id) {
                        $metadata['campaign_id'] = $campaign_id;
                        $item_id                 = $campaign_id;
                    }
                    if ($commission_id) {
                        $metadata['commission_id'] = $commission_id;
                        $item_id                   = $commission_id;
                    }
                    if ($tier_id) {
                        $metadata['tier_id'] = $tier_id;
                        $item_id             = $tier_id;
                    }
                    if ($commission_request) {
                        $metadata['commission_request'] = $commission_request;
                    }
                    if ($commission_price) {
                        $metadata['commission_price'] = $commission_price;
                    }
                    if ($commission_shipping) {
                        $metadata['commission_shipping'] = $commission_shipping;
                    }
                    if ($commission_addons) {
                        $metadata['commission_addons'] = $commission_addons;
                    }
                    //create intent
                    $payment_intent_args = [
                        'customer'           => $customer_ID,
                        'amount'             => $amount,
                        'currency'           => CHAMA_CURRENCY,
                        'receipt_email'      => $email,
                        'description'        => $description,
                        'metadata'           => $metadata,
                        'setup_future_usage' => 'on_session',
                    ];
                    $payment_intent_args = chama_add_application_fee($payment_intent_args, false);
                    $payment_intent      = $stripe->paymentIntents->create($payment_intent_args);
                    $payment_intent_id   = $payment_intent->id;

                    /*=============================================ADD TO DATABASE=============================================*/
                    $cpt_args                 = [];
                    $cpt                      = '';
                    $commission_addons_html   = '';
                    $shipping_location        = '';
                    $shipping_display_cost    = '';
                    $commission_display_price = '';
                    $subject                  = '';
                    $receipt_email            = '';

                    if ($payment_intent->receipt_email) {
                        $receipt_email = $payment_intent->receipt_email;
                    }

                    switch ($type) {
                        case 'one-time':
                            $role     = 'chama_donor';
                            $cpt      = 'chama_donation';
                            $cpt_args = [
                                'post_type'   => 'chama_donation',
                                'post_status' => 'publish',
                            ];
                            $subject = 'Processing Donation Receipt';
                            break;

                        case 'crowdfunding':
                            $role     = 'chama_funder';
                            $cpt      = 'chama_fund';
                            $cpt_args = [
                                'post_type'   => 'chama_fund',
                                'post_status' => 'publish',
                            ];
                            $subject = 'Processing Crowdfunding Receipt';
                            break;
                        case 'commission':
                            $role     = 'chama_comissioner';
                            $cpt      = 'chama_com_order';
                            $cpt_args = [
                                'post_type'   => 'chama_com_order',
                                'post_status' => 'publish',
                            ];

                            $commission_price_cents   = $commission_price * CHAMA_CURRENCY_MINIMUM;
                            $commission_display_price = chama_get_formatted_price($commission_price_cents);
                            if ($payment_intent->metadata->commission_addons) {
                                $commission_addons = $payment_intent->metadata->commission_addons;
                            }

                            $subject = 'Processing Commission Receipt';
                            break;
                        default:
                    }
                    //add to database
                    $receipt_id = wp_insert_post($cpt_args);
                    if ($receipt_id) {
                        //confirm we have user id
                        if (! $user_id && $receipt_email) {
                            $user    = get_user_by('email', $receipt_email);
                            $user_id = $user->ID;
                        }
                        if ($receipt_email && $user_id) {
                            $user = get_user_by('id', $user_id);
                            if ($user) {
                                update_post_meta($receipt_id, 'chama_user_id', $user_id);
                                update_post_meta($receipt_id, 'chama_email', $receipt_email);
                                if ($user->first_name && $user->last_name) {
                                    update_post_meta($receipt_id, 'chama_full_name', $user->first_name . ' ' . $user->last_name);
                                }
                            }

                        }
                        if ($payment_intent->customer) {
                            update_post_meta($receipt_id, 'chama_stripe_customer_id', sanitize_text_field($payment_intent->customer));
                        }
                        if ($description) {
                            update_post_meta($receipt_id, $cpt . '_description', sanitize_text_field($description));
                        }
                        if ($item_id) {
                            update_post_meta($receipt_id, $cpt . '_item_id', sanitize_text_field($item_id));
                        }

                        update_post_meta($receipt_id, 'chama_payment_status', 'processing');
                        if ($payment_intent->currency) {
                            $currency         = $payment_intent->currency;
                            $currency_minimum = chama_get_currency_minimum($currency);
                            if ($payment_intent->amount) {
                                $total_amount_cents     = sanitize_text_field($payment_intent->amount);
                                $total_amount           = $total_amount_cents / $currency_minimum;
                                $total_amount_formatted = number_format(floatval($total_amount), 2);
                                update_post_meta($receipt_id, $cpt . '_currency', sanitize_text_field($currency));
                                update_post_meta($receipt_id, $cpt . '_total_amount', sanitize_text_field($total_amount_formatted));
                            }
                        }

                        //add commission fields
                        if ($cpt == 'chama_com_order') {
                            update_post_meta($receipt_id, $cpt . '_request', sanitize_text_field($commission_request));
                            update_post_meta($receipt_id, $cpt . '_price', sanitize_text_field($commission_price));
                            if ($commission_shipping) {
                                update_post_meta($receipt_id, $cpt . '_shipping', sanitize_text_field($commission_shipping));
                            }

                            if ($commission_addons) {
                                update_post_meta($receipt_id, $cpt . '_addons', sanitize_text_field($commission_addons));
                            }
                        }

                        update_post_meta($receipt_id, $cpt . '_date_time', gmdate('Y-m-d H:i:s'));
                        update_post_meta($receipt_id, 'chama_is_test_' . $cpt, ! chama_is_live_mode());
                        update_post_meta($receipt_id, 'chama_stripe_payment_intent_id', $payment_intent_id);

                    }
                    /*=============================================SEND EMAIL=============================================*/
                    if (get_option('chama_supporter_enable_payment_notification')) {
                        $from        = sprintf("%s <%s>", CHAMA_FROM_NAME, CHAMA_FROM_EMAIL);
                        $from_header = 'From: ' . $from;
                        $headers     = ['Content-Type: text/html; charset=UTF-8', $from_header];
                        if (get_option($cpt . '_processing_template')) {
                            $message = get_option($cpt . '_processing_template');
                            $message = wpautop($message);
                            switch ($cpt) {
                                case 'chama_donation':
                                    //replace donation email template variables
                                    foreach ([
                                        "{date}"       => gmdate('F j, Y'),
                                        "{amount}"     => CHAMA_SYMBOL . $total_amount_formatted,
                                        "{receipt_id}" => $receipt_id,
                                    ] as $k => $v) {$message = str_replace($k, $v, $message);}
                                    break;
                                case 'chama_subscription':
                                    //replace subscription email template variables
                                    $today = gmdate('Y-m-d');
                                    foreach ([
                                        "{description}"  => $description,
                                        "{date}"         => gmdate('F j, Y'),
                                        "{renewal-date}" => gmdate("F, j, Y", strtotime('+1 month', strtotime($today))),
                                        "{amount}"       => CHAMA_SYMBOL . $total_amount_formatted,
                                        "{receipt_id}"   => $receipt_id,
                                    ] as $k => $v) {$message = str_replace($k, $v, $message);}
                                    break;
                                case 'chama_fund':
                                    //replace fund email template variables
                                    foreach ([
                                        "{description}" => $description,
                                        "{date}"        => gmdate('F j, Y'),
                                        "{amount}"      => CHAMA_SYMBOL . $total_amount_formatted,
                                        "{receipt_id}"  => $receipt_id,
                                    ] as $k => $v) {$message = str_replace($k, $v, $message);}
                                    break;
                                case 'chama_com_order':
                                    //replace Commission Order email template
                                    if ($commission_shipping) {
                                        $shipping              = explode('|', $commission_shipping);
                                        $shipping_cost         = $shipping[1];
                                        $shipping_location     = $shipping[0];
                                        $shipping_cost_cents   = $shipping_cost * CHAMA_CURRENCY_MINIMUM;
                                        $shipping_display_cost = chama_get_formatted_price($shipping_cost_cents);
                                    }
                                    if ($commission_addons) {
                                        $addons = explode(',', $commission_addons);

                                        foreach ($addons as $addon) {
                                            $item                   = explode('|', $addon);
                                            $item_amount            = $item[1];
                                            $item_amount_cents      = $item_amount * CHAMA_CURRENCY_MINIMUM;
                                            $item_display_amount    = chama_get_formatted_price($item_amount_cents);
                                            $commission_addons_html = $commission_addons_html . '<strong>' . esc_html($item[0]) . '</strong>: ' . esc_html($item_display_amount) . "<br/>";
                                        }
                                    }

                                    foreach ([
                                        "{description}"       => $description,
                                        "{price}"             => $commission_display_price,
                                        "{date}"              => gmdate('F j, Y'),
                                        "{request}"           => $commission_request,
                                        "{add_ons}"           => $commission_addons_html,
                                        "{shipping-location}" => $shipping_location,
                                        "{shipping-fee}"      => $shipping_display_cost,
                                        "{amount}"            => CHAMA_SYMBOL . $total_amount_formatted,
                                        "{receipt_id}"        => $receipt_id,
                                    ] as $k => $v) {$message = str_replace($k, $v, $message);}
                                    break;
                                default:
                            }
                            chama_send_email($receipt_email, $subject, $message, $headers);
                        }

                    }
                } catch (\ChamaWP\Vendor\Stripe\ApiErrorException $e) {

                    return new WP_REST_Response($e->getError()->message, 400);
                } catch (Exception $e) {
                    return new WP_REST_Response($e->getMessage(), 500);
                }
                return new WP_REST_Response(['clientSecret' => $payment_intent->client_secret, 'receiptId' => $receipt_id], 200);
            } else {
                return new WP_REST_Response($e->getMessage(), 500);
            }

        }

    } else {
        return new WP_REST_Response('Unauthorized request', 422);
    }

}

function chama_handle_setup_intent($data)
{
    $setup_intent = null;
    $params       = $data->get_params();
    if (isset($params['_wpnonce']) && wp_verify_nonce($params['_wpnonce'], 'wp_rest')) {
        $secret_key         = chama_is_live_mode()  ?CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;
        $stripe_customer_id = $setup_intent_id = '';
        if ($secret_key) {
            $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                $secret_key // API Secret here
            );
            if (isset($params['customer_id'])) {
                try {
                    $stripe_customer_id = $params['customer_id'];

                    /*=============================================STRIPE SETUP INTENT=============================================*/

                    //create intent
                    $setup_intent_args = [
                        'customer'                  => $stripe_customer_id,
                        'automatic_payment_methods' => ['enabled' => true],
                    ];
                    $setup_intent    = $stripe->setupIntents->create($setup_intent_args);
                    $setup_intent_id = $setup_intent->id;

                } catch (\ChamaWP\Vendor\Stripe\ApiErrorException $e) {

                    return new WP_REST_Response($e->getError()->message, 400);
                } catch (Exception $e) {
                    return new WP_REST_Response($e->getMessage(), 500);
                }
                return new WP_REST_Response(['clientSecret' => $setup_intent->client_secret, 'setupIntent' => $setup_intent_id], 200);
            } else {
                return new WP_REST_Response($e->getMessage(), 500);
            }

        }

    } else {
        return new WP_REST_Response('Unauthorized request', 422);
    }

}

function chama_handle_subscription_creation($data)
{
    $subscription = null;
    $params       = $data->get_params();
    if (isset($params['_wpnonce']) && wp_verify_nonce($params['_wpnonce'], 'wp_rest')) {
        if (isset($params['captcha_response']) && ! empty($params['captcha_response'])) {

            $gRecaptchaResponse    = sanitize_text_field(wp_unslash($params['captcha_response']));
            $has_invalid_recaptcha = chama_validate_recaptcha($gRecaptchaResponse);
            if ($has_invalid_recaptcha) {
                return new WP_REST_Response('Captcha validation failed!', 500);
            }

        }
        $secret_key = chama_is_live_mode()  ?CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;
        $receipt_id = '';
        if ($secret_key) {
            $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                $secret_key // API Secret here
            );
            if (isset($params['amount']) && isset($params['email']) && isset($params['description'])) {
                try {
                    $amount                 = $params['amount'];
                    $base_amount            = floatval($params['base_amount']);
                    $tier_price             = 0;
                    $email                  = $params['email'];
                    $type                   = $params['type'];
                    $description            = $params['description'];
                    $customer_ID            = '';
                    $user                   = null;
                    $full_name              = $params['name'];
                    $user_id                = null;
                    $tier_id                = '';
                    $product_id             = '';
                    $price_id               = '';
                    $subscription_id        = '';
                    $total_amount_formatted = '';

                    if (isset($params['tier_id'])) {
                        $tier_id    = (int) $params['tier_id'];
                        $tier_price = floatval(get_post_meta($tier_id, 'tier_price', true));
                    }
                    if (isset($params['product_id'])) {
                        $product_id = $params['product_id'];
                    }
                    if (isset($params['price_id'])) {
                        $price_id = $params['price_id'];
                    }

                    //handle user
                    if (! is_user_logged_in()) {

                        if (username_exists($email) || email_exists($email)) {
                            $user    = get_user_by('email', $email) ? get_user_by('email', $email) : get_user_by('login', $email);
                            $user_id = $user->ID;
                        }

                        if (! $user) {
                            $password = wp_generate_password(12);
                            $user_id  = wp_insert_user([
                                'user_login'      => $email,
                                'user_pass'       => $password,
                                'user_email'      => $email,
                                'user_registered' => gmdate('Y-m-d H:i:s'),
                                'role'            => 'chama_temp',
                            ]
                            );

                        }

                    } else {
                        $user_id = get_current_user_id();
                    }

                    //check if customer exists
                    $customer_ID = get_user_meta($user_id, 'chama_stripe_customer_id', true);
                    if ($customer_ID) {
                        $customer = $stripe->customers->retrieve($customer_ID, []);
                        if (isset($customer->deleted) && $customer->deleted) {
                            $customer_ID = null;
                            update_user_meta($user_id, 'chama_stripe_customer_id', false);
                        }
                    }
                    /*=============================================STRIPE CUSTOMER ACCOUNT=============================================*/
                    if (! $customer_ID) {
                        //search for user by email
                        $query = $stripe->customers->search([
                            'query' => 'email:\'' . $email . '\'',
                        ]);
                        foreach ($query->data as $key) {
                            if (strcmp($key->email, $email) == 0) {
                                $customer_ID = $key->id;
                                update_user_meta($user_id, 'chama_stripe_customer_id', $customer_ID);
                                break;
                            }
                        }
                    }

                    if (! $customer_ID) {
                        $new_customer = ['email' => $email];
                        if ($full_name) {
                            $new_customer["name"] = $full_name;
                        }
                        $customer_response = $stripe->customers->create($new_customer);
                        $customer_ID       = $customer_response->id;
                        if ($customer_ID) {
                            $stripe->customers->update(
                                $customer_ID,
                                ['metadata' => ['user_id' => $user_id]]
                            );
                        }
                    }
                    /*=============================================STRIPE SUBSCRIPTION=============================================*/
                    $metadata = ['type' => $type, 'description' => $description];

                    if ($tier_id) {
                        $metadata['tier_id'] = $tier_id;
                    }
                    $base_amount        = floatval($params['base_amount']);
                    $tier_price         = floatval(get_post_meta($tier_id, 'tier_price', true));
                    $subscription_items = null;
                    if ($base_amount > $tier_price) {
                        $subscription_items = [[
                            'price_data' => [
                                'unit_amount' => $amount,
                                'currency'    => CHAMA_CURRENCY,
                                'product'     => $product_id,
                                'recurring'   => ['interval' => CHAMA_SUBSCRIPTION_INTERVAL],
                            ],
                        ]];
                    }
                    if ($base_amount == $tier_price) {
                        $subscription_items = [['price' => $price_id]];
                    }
                    if ($subscription_items) {
                        $subscription_args = [
                            'customer'         => $customer_ID,
                            'items'            => $subscription_items,
                            'payment_behavior' => 'default_incomplete',
                            'payment_settings' => ['save_default_payment_method' => 'on_subscription'],
                            'expand'           => ['latest_invoice.payment_intent', 'latest_invoice.confirmation_secret'],
                            'description'      => $description,
                            'metadata'         => $metadata,
                        ];
                        $subscription_args = chama_add_application_fee($subscription_args, true);
                        $subscription      = $stripe->subscriptions->create($subscription_args);
                        $subscription_id   = $subscription->id;
                        $invoice           = $stripe->invoices->retrieve(
                            $subscription->latest_invoice->id,
                            ['expand' => ['payment_intent']]
                        );
                        $stripe_payment_intent_id = $invoice->payment_intent ?? '';
                        if ($subscription->currency) {
                            $currency         = $subscription->currency;
                            $currency_minimum = chama_get_currency_minimum($currency);
                            if ($amount) {
                                $total_amount_cents     = sanitize_text_field($amount);
                                $total_amount           = $total_amount_cents / $currency_minimum;
                                $total_amount_formatted = number_format(floatval($total_amount), 2);
                            }
                        }
                    }
                    /*=============================================ADD TO DATABASE=============================================*/
                    $cpt_args = [
                        'post_type'   => 'chama_subscription',
                        'post_status' => 'publish',
                    ];
                    $cpt     = 'chama_subscription';
                    $subject = 'Processing Subscription Receipt';
                    //add to database
                    $receipt_id = wp_insert_post($cpt_args);
                    if ($receipt_id) {
                        //check if we have stripe payment intent
                        if ($stripe_payment_intent_id) {
                            update_post_meta($receipt_id, 'chama_stripe_payment_intent_id', $stripe_payment_intent_id);
                        }

                        //confirm we have user id
                        if (! $user_id && $email) {
                            $user    = get_user_by('email', $email);
                            $user_id = $user->ID;
                        }
                        if ($email && $user_id) {
                            $user = get_user_by('id', $user_id);
                            if ($user) {
                                update_post_meta($receipt_id, 'chama_user_id', $user_id);
                                update_post_meta($receipt_id, 'chama_email', $email);
                                if ($user->first_name && $user->last_name) {
                                    update_post_meta($receipt_id, 'chama_full_name', $user->first_name . ' ' . $user->last_name);
                                }
                            }

                        }
                        if ($customer_ID) {
                            update_post_meta($receipt_id, 'chama_stripe_customer_id', sanitize_text_field($customer_ID));
                        }

                        if ($description) {
                            update_post_meta($receipt_id, $cpt . '_description', sanitize_text_field($description));
                        }
                        if ($tier_id) {
                            update_post_meta($receipt_id, $cpt . '_item_id', sanitize_text_field($tier_id));
                        }

                        update_post_meta($receipt_id, 'chama_payment_status', 'processing');

                        update_post_meta($receipt_id, $cpt . '_date_time', gmdate('Y-m-d H:i:s'));
                        update_post_meta($receipt_id, 'chama_is_test_' . $cpt, ! chama_is_live_mode());

                        if ($subscription_id) {
                            update_user_meta($user_id, 'chama_subscription_status', 'incomplete');
                            update_post_meta($receipt_id, 'chama_subscription_status', 'incomplete');
                            update_post_meta($receipt_id, 'chama_subscription_event', 'creation');
                            update_post_meta($receipt_id, 'chama_stripe_subscription_id', $subscription_id);
                        }

                    }
                    /*=============================================SEND EMAIL=============================================*/
                    if (get_option('chama_supporter_enable_payment_notification')) {
                        $from        = sprintf("%s <%s>", CHAMA_FROM_NAME, CHAMA_FROM_EMAIL);
                        $from_header = 'From: ' . $from;
                        $headers     = ['Content-Type: text/html; charset=UTF-8', $from_header];
                        if (get_option($cpt . '_processing_template')) {
                            $message = get_option($cpt . '_processing_template');
                            $message = wpautop($message);
                            $today   = gmdate('Y-m-d');
                            foreach ([
                                "{description}"  => $description,
                                "{date}"         => gmdate('F j, Y'),
                                "{renewal-date}" => gmdate("F, j, Y", strtotime('+1 month', strtotime($today))),
                                "{amount}"       => CHAMA_SYMBOL . $total_amount_formatted,
                                "{receipt_id}"   => $receipt_id,
                            ] as $k => $v) {$message = str_replace($k, $v, $message);}
                            chama_send_email($email, $subject, $message, $headers);
                        }

                    }

                } catch (\ChamaWP\Vendor\Stripe\ApiErrorException $e) {

                    return new WP_REST_Response($e->getError()->message, 400);
                } catch (Exception $e) {
                    return new WP_REST_Response($e->getMessage(), 500);
                }
                if ($subscription->pending_setup_intent !== null) {
                    return new WP_REST_Response(['type' => 'setup', 'clientSecret' => $subscription->pending_setup_intent->client_secret, 'subscriptionId' => $subscription_id, 'receiptId' => $receipt_id], 200);
                } else {
                    if (
                        isset($subscription->latest_invoice) &&
                        isset($subscription->latest_invoice->confirmation_secret) &&
                        isset($subscription->latest_invoice->confirmation_secret->client_secret)
                    ) {
                        return new WP_REST_Response([
                            'type'           => 'payment',
                            'clientSecret'   => $subscription->latest_invoice->confirmation_secret->client_secret,
                            'subscriptionId' => $subscription_id,
                            'paymentIntent'  => $stripe_payment_intent_id,
                            'receiptId'      => $receipt_id,
                        ], 200);
                    } else {
                        return new WP_REST_Response('Missing confirmation secret on latest invoice', 400);
                    }
                }
            } else {
                return new WP_REST_Response($e->getMessage(), 500);
            }

        }

    } else {
        return new WP_REST_Response('Unauthorized request', 422);
    }

}

//user display functions
add_filter('show_admin_bar', 'chama_hide_admin_bar');
function chama_hide_admin_bar()
{
    $hide_admin_bar = get_option('chama_hide_admin_bar');

    //Never show admin toolbar if the user is not even logged in
    if (function_exists('is_user_logged_in') && ! is_user_logged_in()) {
        return false;
    }

    if ($hide_admin_bar) {
        if (current_user_can('administrator')) {
            //This is an admin user so show the tooldbar
            return true;
        } else {
            return false;
        }
    } else {
        return true;
    }
}
add_action('admin_init', 'chama_prevent_dashboard_access');
function chama_prevent_dashboard_access()
{
    $prevent_access = get_option('chama_prevent_dashboard_access');
    if ($prevent_access) {
        if ((defined('DOING_AJAX') && DOING_AJAX)) {
            //This is an ajax request. Don't do the disable dashboard check for ajax.
        } else {
            //Not an ajax request. Do the check.
            if (! current_user_can('administrator')) {
                //This is a non-admin user. Do not show the wp dashboard.
                $message = '<p>' . esc_html('The admin of this site does not allow users to access the wp dashboard.') . '</p>';
                $message .= '<p>' . esc_html('Go back to the home page by ') . '<a href="' . home_url() . '">' . esc_html('clicking here') . '</a>.' . '</p>';
                wp_die(wp_kses($message, chama_allowed_html()));
            }
        }
    }
}
add_action('init', 'chama_register_menu_locations');
/**
 *  Clone existing theme_locations and add menu items for logged in and logged out users.
 */
if (! function_exists('chama_register_menu_locations')) {
    function chama_register_menu_locations()
    {
        $default_menus    = get_registered_nav_menus();
        $logged_in_menus  = [];
        $logged_out_menus = [];
        foreach ($default_menus as $slug => $name) {
            $logged_in_menus[$slug . '_chama_logged_in'] = $name . ' Logged-in';
        }
        foreach ($default_menus as $slug => $name) {
            $logged_out_menus[$slug . '_chama_logged_out'] = $name . ' Logged Out';
        }
        register_nav_menus(
            $logged_in_menus
        );
        register_nav_menus(
            $logged_out_menus
        );
    }
}
add_filter('wp_nav_menu_args', 'chama_display_nav_menu');
function chama_display_nav_menu($content)
{

    $logged_in_theme_location  = $content['theme_location'] . '_chama_logged_in';
    $logged_out_theme_location = $content['theme_location'] . '_chama_logged_out';
    $active_menu_locations     = get_nav_menu_locations();
    //wp_die( var_dump($content['theme_location']));
    if (is_user_logged_in() && $content['theme_location'] && array_key_exists($logged_in_theme_location, $active_menu_locations)) {

        $content['theme_location'] = $content['theme_location'] . '_chama_logged_in';
        return $content;
    } else if (! is_user_logged_in() && ! empty($content['theme_location']) && array_key_exists($logged_out_theme_location, $active_menu_locations)) {
        $content['theme_location'] = $content['theme_location'] . '_chama_logged_out';
        return $content;
    } else {
        return $content;
    }
}
add_filter('wp_get_nav_menu_items', 'chama_add_nav_parameter', 11, 3);

function chama_add_nav_parameter($items, $menu, $args)
{
    if (is_admin() || ! is_user_logged_in()) {
        return $items;
    }

    foreach ($items as $item) {
        if ('Logout' == $item->post_title) {
            $item->url = esc_url(add_query_arg(
                [
                    'uid'          => uniqid(),
                    'chama-logout' => 'true',
                    'chama-logout-nonce'  => wp_create_nonce('chama_logout_action'),
                ],
                $item->url
            ));

        } else {
            $item->url = esc_url(add_query_arg(
                [
                    'uid' => uniqid(),
                ],
                $item->url
            ));
        }

    }
    return $items;
}
function chama_check_subscription_status()
{
    $from = $from_header = $headers = $subject = $message = '';
    if ( !current_user_can( 'administrator' ) ) {
    $from        = sprintf("%s <%s>", CHAMA_FROM_NAME, CHAMA_FROM_EMAIL);
    $from_header = 'From: ' . $from;
    $headers     = ['Content-Type: text/html; charset=UTF-8', $from_header];
    $subject     = 'Payment issue with your website';
    }

    try {
        global $current_user;
        if ($current_user) {
            $user_id = $current_user->ID;

            if ($user_id) {
                $stripe_subscription_id      = get_user_meta($user_id, 'chama_stripe_subscription_id', true);
                $current_subscription_status = get_user_meta($user_id, 'chama_subscription_status', true);
                $tier_id                     = get_user_meta($user_id, 'chama_tier_id', true);

                if ($stripe_subscription_id && $current_subscription_status == 'active') {
                    $mode       = chama_is_live_mode() ? 'live' : 'test';
                    $secret_key = chama_is_live_mode()  ?CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;
                    if ($secret_key) {
                        $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                            $secret_key // API Secret here
                        );
                        $subscription = $stripe->subscriptions->retrieve(
                            $stripe_subscription_id, []
                        );
                        if ($subscription) {
                            $stripe_current_period_start = gmdate("F, j, Y", $subscription->current_period_start);
                            $stripe_current_period_end   = gmdate("F, j, Y", $subscription->current_period_end);
                            $stripe_subscription_status  = $subscription->status;
                            if ($stripe_subscription_status === 'active') {
                                if ($current_subscription_status !== 'active') {
                                    $latest_invoice_id  = $subscription->latest_invoice;
                                    $latest_invoice     = $stripe->invoices->retrieve($latest_invoice_id, []);
                                    $total_amount_cents = $latest_invoice->amount_paid;
                                    if ($total_amount_cents) {
                                        $currency_minimum       = chama_get_currency_minimum($currency);
                                        $total_amount           = $total_amount_cents / $currency_minimum;
                                        $total_amount_formatted = number_format(floatval($total_amount), 2);
                                        update_user_meta($user_id, 'chama_subscription_level', $total_amount_formatted);
                                    }
                                    update_user_meta($user_id, 'chama_subscription_status', 'active');

                                    chama_update_subscription_transactions($stripe_subscription_id, 'active');
                                    chama_add_user_to_role('chama_member', 'chama_member', true, $tier_id);
                                }

                            } else {
                                if ($stripe_subscription_status !== $current_subscription_status) {
                                    update_post_meta($subscription_id, 'chama_subscription_status', $stripe_subscription_status);
                                    chama_update_subscription_transactions($stripe_subscription_id, $stripe_subscription_status);
                                    //determine whether to deactivate membership
                                    $current_period_end           = str_replace(',', '', $stripe_current_period_end);
                                    $current_period_end_timestamp = strtotime($current_period_end);
                                    $today                        = gmdate('Y-m-d');
                                    $today_timestamp              = strtotime($today);
                                    if ($current_period_end_timestamp < $today_timestamp) {
                                        if ($user_id && $tier_id) {
                                            chama_remove_user_membership($user_id, $tier_id);
                                        }
                                    }
                                }

                            }
                            update_user_meta($user_id, 'chama_subscription_current_period_start', $stripe_current_period_start);
                            update_user_meta($user_id, 'chama_subscription_current_period_end', $stripe_current_period_end);
                        }
                    }

                }

            }

        }
    } catch (\ChamaWP\Vendor\Stripe\ApiErrorException $e) {
        $message = esc_html($e->getError()->message) . "\r\n\r\n";

    } catch (Exception $e) {
        $message = esc_html($e->getMessage()) . "\r\n\r\n";
    }
    if ($message && get_option('chama_admin_enable_payment_notification')) {
        chama_send_email(get_option('chama_admin_email'), $subject, $message, $headers);
    }

}
add_action('wp_login', 'chama_check_subscription_status');
function chama_get_user_ip_address()
{

    $ip_address = '';

    foreach ([
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_X_CLUSTER_CLIENT_IP',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR',
    ] as $key) {
        if (array_key_exists($key, $_SERVER)) {
            $raw_header_value = sanitize_text_field(wp_unslash($_SERVER[$key])); // sanitized before use
            foreach (array_map('trim', explode(',', $raw_header_value)) as $ip) {
                if (filter_var($ip, FILTER_VALIDATE_IP)) {
                    return $ip;
                }
            }
        }
    }

    return $ip_address;

}
function chama_validate_recaptcha($recaptcha_response)
{
    $has_error = false;
    $response  = wp_remote_post('https://www.google.com/recaptcha/api/siteverify',
        [
            'timeout' => 15,
            'body'    => [
                'secret'   => (! empty(CHAMA_RECAPTCHA_SECRET_KEY)  ?CHAMA_RECAPTCHA_SECRET_KEY : ''),
                'response' => $recaptcha_response,
                'remoteip' => chama_get_user_ip_address(),
            ],
        ]
    );

    if (wp_remote_retrieve_response_code($response) === 200) {

        $body = json_decode(wp_remote_retrieve_body($response), ARRAY_A);

        if (empty($body['success']) && $body['success'] != true) {
            $has_error = true;
        }

    } else {
        $has_error = true;
    }
    return $has_error;

}
// Handle newsletter subscription form submissions
  add_action('init', 'chama_process_newsletter_subscription');
function chama_process_newsletter_subscription()
{

    // Verify nonce
    $message = 'error';

    if (isset($_POST['chama_newsletter_nonce']) && wp_verify_nonce(sanitize_key($_POST['chama_newsletter_nonce']), 'chama_newsletter_signup')) {
        // Rate limit check
        $ip       = chama_get_user_ip_address() ?? 'unknown';
        $reg_key  = 'chama_register_attempts_' . md5($ip);
        $attempts = (int) get_transient($reg_key);

        if ($attempts >= 3) {
            chama_errors()->add('too_many_registrations', __('Too many registration attempts. Please try again in 30 minutes.', 'chama'));
            return;
        }
        //captcha
        if (isset($_POST['chama-captcha-response']) && ! empty($_POST['chama-captcha-response'])) {

            $gRecaptchaResponse    = sanitize_text_field(wp_unslash($_POST['chama-captcha-response']));
            $has_invalid_recaptcha = chama_validate_recaptcha($gRecaptchaResponse);
            if ($has_invalid_recaptcha) {
                chama_errors()->add('captcha_error', __('Could not validate the reCaptcha. Please complete it again.', 'chama'));
                return;
            }

        }

        if (isset($_POST["chama_newsletter_email"])) {
            $email = sanitize_email(wp_unslash($_POST["chama_newsletter_email"]));

            if (empty($email) || ! is_email($email)) {
                chama_errors()->add('email_error', __('Invalid email address. Please enter a valid email address.', 'chama'));
                return;
            }

            $user = get_user_by('email', $email);
            if (! $user && username_exists($email)) {
                $user = get_user_by('login', $email);
            }

             //user exists
            if ($user) {
                $user_id     = $user->ID;
                $is_opted_in = get_user_meta($user_id, 'newsletter_optin', true);
                if (! empty($is_opted_in)) {
                    chama_errors()->add('already_subscribed', __('Your email address is already subscribed to our list', 'chama'));
                    return;
                } else {
                    $optout_code = wp_generate_password(20, false); // Secure, random string
                    update_user_meta($user_id, 'optout_code', $optout_code);
                    update_user_meta($user_id, 'newsletter_optin', 1);
                    wp_redirect(esc_url(CHAMA_NEWSLETTER_SIGN_UP_CONFIRMATION_URL));
                }

            }

            // If user does not exist, create one
            if (! $user && empty($errors)) {
                $password = wp_generate_password(12);
                $user_id  = wp_insert_user([
                    'user_login'      => $email,
                    'user_pass'       => $password,
                    'user_email'      => $email,
                    'user_registered' => gmdate('Y-m-d H:i:s'),
                    'role'            => 'subscriber',
                ]);

                if (is_wp_error($user_id)) {
                    chama_errors()->add(
                        'newsletter_signup_error',
                        sprintf(
                            // translators: %s: Error message returned during newsletter signup.
                            __('Newsletter signup error: %s', 'chama'),
                            $user_id->get_error_message()
                        )
                    );
                    return;
                } else {
                    $send_user_notification = get_option('chama_new_user_notification');
                    if ($send_user_notification) {
                        // send an email to the admin alerting them of the registration
                        wp_new_user_notification($user_id);
                    }
                    wp_redirect(esc_url(CHAMA_NEWSLETTER_SIGN_UP_CONFIRMATION_URL));
                }
            }

        }
    }

}

   