<?php
    /**
     * Plugin Name: Chama
     * Plugin URI:  https://www.chamawp.com
     * Description: Monetize your content with donations, paid subscriptions, crowdfunding and commissions.
     * Version:     1.0.12
     * Author:      Leetoo
     * Author URI:  https://leetoo.net/
     * License:     GPLv3 or later
     * License URI: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
     * Text Domain: chama
     * Domain Path: /languages
     *
     * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
     * General Public License version 2, as published by the Free Software Foundation. You may NOT assume
     * that you can use any other version of the GPL.
     *
     * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
     * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     */

    if (! defined('ABSPATH')) {
        exit;
    }
    if (! class_exists('Chama_Plugin')) {
        class Chama_Plugin
        {
            public function __construct()
            {

                if (! defined('CHAMA_MAIN_FILE')) {
                    define('CHAMA_MAIN_FILE', __FILE__);
                }

                if (! defined('CHAMA_VERSION')) {
                    define('CHAMA_VERSION', '1.0.12');
                }
                if (! defined('CHAMAWP_URL')) {
                    define('CHAMAWP_URL', 'https://www.chamawp.com');
                }
                if (! defined('CHAMA_CONNECT_URL')) {
                    define('CHAMA_CONNECT_URL', 'https://connect.chamawp.com');
                }
                if (! defined('CHAMA_STRIPE_DASHBOARD_URL')) {
                    define('CHAMA_STRIPE_DASHBOARD_URL', 'https://dashboard.stripe.com');
                }
                if (! defined('CHAMA_DOCS_URL')) {
                    define('CHAMA_DOCS_URL', 'https://docs.chamawp.com');
                }
                if (! defined('CHAMA_URL')) {
                    define('CHAMA_URL', plugin_dir_url(CHAMA_MAIN_FILE));
                }

                if (! defined('CHAMA_PATH')) {
                    define('CHAMA_PATH', plugin_dir_path(CHAMA_MAIN_FILE));
                }

                if (! defined('CHAMA_INC_URL')) {
                    define('CHAMA_INC_URL', plugin_dir_url(CHAMA_MAIN_FILE) . 'inc/');
                }

                if (! defined('CHAMA_INC_PATH')) {
                    define('CHAMA_INC_PATH', plugin_dir_path(CHAMA_MAIN_FILE) . 'inc/');
                }

                if (! defined('CHAMA_ASSETS_URL')) {
                    define('CHAMA_ASSETS_URL', plugin_dir_url(CHAMA_MAIN_FILE) . 'assets/');
                }

                if (! defined('CHAMA_ASSETS_PATH')) {
                    define('CHAMA_ASSETS_PATH', plugin_dir_path(CHAMA_MAIN_FILE) . 'assets/');
                }

                if (! defined('CHAMA_UPGRADE_URL')) {
                    define('CHAMA_UPGRADE_URL', CHAMAWP_URL . '/pro');
                }
                if (! defined('CHAMA_WEBHOOK_URL')) {
                    define('CHAMA_WEBHOOK_URL', get_home_url() . '/?chama-listener=stripe');
                }

                // Include dependencies
                //Add vendor libraries
                if (file_exists(CHAMA_PATH . 'vendor-prefixed/autoload.php')) {
                    require_once CHAMA_PATH . 'vendor-prefixed/autoload.php';
                }
                //Add stripe apple pay
                if (file_exists(CHAMA_PATH . 'inc/gateways/stripe/stripe-apple-pay.php')) {
                    require_once CHAMA_PATH . 'inc/gateways/stripe/stripe-apple-pay.php';
                }

            }

            /**
             * Initialize the class and start calling our hooks and filters
             */
            public function init()
            {
                add_filter('plugin_action_links_' . plugin_basename(__FILE__), [$this, 'chama_settings_link']);
                include_once CHAMA_PATH . 'inc/shared.php';
                include_once CHAMA_PATH . 'inc/options.php';
                include_once CHAMA_PATH . 'inc/utilities.php';
                include_once CHAMA_PATH . 'inc/shortcodes.php';
                include_once CHAMA_PATH . 'inc/pages.php';
                add_action('init', [$this, 'chama_create_tier_cpt'], 0);
                add_action('init', [$this, 'chama_create_campaign_cpt'], 0);
                add_action('init', [$this, 'chama_create_commission_cpt'], 0);
                add_action('init', [$this, 'chama_create_donation_cpt'], 0);
                add_action('init', [$this, 'chama_create_subscription_cpt'], 0);
                add_action('init', [$this, 'chama_create_fund_cpt'], 0);
                add_action('init', [$this, 'chama_create_commission_order_cpt'], 0);
                add_action('init', [$this, 'chama_create_newsletter_cpt'], 0);
                add_action('admin_notices', [$this, 'chama_admin_notices'], 9999);
                add_action('chama_cron_sync_pending_payments', [$this, 'chama_cron_sync_pending_payments']);
                add_action('chama_cron_sync_pending_subscriptions', [$this, 'chama_cron_sync_pending_subscriptions']);
                add_action('chama_cron_sync_missing_subscription_renewals', [$this, 'chama_cron_sync_missing_subscription_renewals']);
                include_once CHAMA_PATH . 'inc/cpt.php';
                include_once CHAMA_PATH . 'inc/metaboxes.php';
                include_once CHAMA_PATH . 'inc/terms.php';
                include_once CHAMA_PATH . 'inc/users.php';
                include_once CHAMA_PATH . 'inc/webhooks.php';
                include_once CHAMA_PATH . 'inc/protection.php';

                register_activation_hook(__FILE__, [$this, 'chama_activate']);
                register_deactivation_hook(__FILE__, [$this, 'chama_deactivate']);
            }
            public function chama_activate()
            {
                //create custom post types
                $this->chama_create_tier_cpt();
                $this->chama_create_campaign_cpt();
                $this->chama_create_commission_cpt();
                $this->chama_create_donation_cpt();
                $this->chama_create_subscription_cpt();
                $this->chama_create_fund_cpt();
                $this->chama_create_commission_order_cpt();
                $this->chama_create_newsletter_cpt();

                //add pages
                $this->chama_generate_pages();
                flush_rewrite_rules();

                //create custom roles
                $this->chama_create_roles();

                //Schedule the cron job events.
                wp_schedule_event(time(), 'daily', 'chama_cron_sync_pending_payments');
                wp_schedule_event(time(), 'daily', 'chama_cron_sync_pending_subscriptions');
                wp_schedule_event(time(), 'daily', 'chama_cron_sync_missing_subscription_renewals');

            }
            public function chama_deactivate()
            {
                //Remove scheduled cron job events.
                wp_clear_scheduled_hook('chama_cron_sync_pending_payments');
                wp_clear_scheduled_hook('chama_cron_sync_pending_subscriptions');
                wp_clear_scheduled_hook('chama_cron_sync_missing_subscription_renewals');

            }
            public function chama_generate_pages()
            {
                $this->chama_add_page('Hub', '[chama_hub_page]', 'chama_hub_page');
                $this->chama_add_page('Donate', '[chama_donate_page]', 'chama_donate_page');
                $this->chama_add_page('Membership', '[chama_membership_page]', 'chama_membership_page');
                $this->chama_add_page('Crowdfunding', '[chama_crowdfunding_page]', 'chama_crowdfunding_page');
                $this->chama_add_page('Commissions', '[chama_commissions_page]', 'chama_commissions_page');
                $this->chama_add_page('Login', '[chama_login_page]', 'chama_login_page');
                $this->chama_add_page('Registration', '[chama_registration_page]', 'chama_registration_page');
                $this->chama_add_page('Edit Account', '[chama_edit_account_page]', 'chama_edit_account_page');
                $this->chama_add_page('Edit Password', '[chama_edit_password_page]', 'chama_edit_password_page');
                $this->chama_add_page('Forgot Password', '[chama_forgot_password_page]', 'chama_forgot_password_page');
                $this->chama_add_page('Reset Password', '[chama_reset_password_page]', 'chama_reset_password_page');
                $this->chama_add_page('Verify Email', '[chama_verify_email_page]', 'chama_verify_email_page');
                $this->chama_add_page('Account', '[chama_account_page]', 'chama_account_page');
                $this->chama_add_page('Payment', '[chama_payment_page]', 'chama_payment_page');
                $this->chama_add_page('Payment Confirmation', '[chama_payment_confirmation_page]', 'chama_payment_confirmation_page');
                $this->chama_add_page('Subscription', '[chama_subscription_page]', 'chama_subscription_page');
                $this->chama_add_page('Subscription Confirmation', '[chama_subscription_confirmation_page]', 'chama_subscription_confirmation_page');
                $this->chama_add_page('Newsletter Signup Confirmation', '[chama_newsletter_sign_up_confirmation_page]', 'chama_newsletter_sign_up_confirmation_page');
                $this->chama_add_page('Newsletter Opt-Out Confirmation', '[chama_newsletter_opt_out_confirmation_page]', 'chama_newsletter_opt_out_confirmation_page');
            }
            public function chama_add_page($title, $content, $option)
            {
                if (! get_post(get_option($option))) {
                    // Create page args
                    $page_args = [
                        'post_title'     => esc_html($title, 'chama'),
                        'post_content'   => $content,
                        'post_status'    => 'publish',
                        'comment_status' => 'closed',
                        'ping_status'    => 'closed',
                        'post_author'    => 1,
                        'post_type'      => 'page',
                    ];

                    // Insert the page into the database
                    $new_page_id = wp_insert_post($page_args);
                    update_option($option, $new_page_id);
                }
            }

            public function chama_create_tier_cpt()
            {

                // Set UI labels for Custom Post Type
                $labels = [
                    'name'               => _x('Tiers', 'Post Type General Name', 'chama'),
                    'singular_name'      => _x('Tier', 'Post Type Singular Name', 'chama'),
                    'menu_name'          => __('Tier', 'chama'),
                    'all_items'          => __('All Tiers', 'chama'),
                    'view_item'          => __('View Tiers', 'chama'),
                    'add_new_item'       => __('Add Tier', 'chama'),
                    'add_new'            => __('Add New', 'chama'),
                    'edit_item'          => __('Edit Tier', 'chama'),
                    'update_item'        => __('Update Tier', 'chama'),
                    'search_items'       => __('Search Tiers', 'chama'),
                    'not_found'          => __('No Tiers found', 'chama'),
                    'not_found_in_trash' => __('Not Tiers found in Trash', 'chama'),
                ];

                // Set other options for Custom Post Type

                $args = [

                    'labels'               => $labels,
                    // Features this CPT supports in Post Editor
                    'supports'             => ['title', 'editor', 'thumbnail'],
                    'public'               => true,
                    'publicly_queryable'   => false,
                    'exclude_from_search'  => true,
                    'show_ui'              => true,
                    'show_in_menu'         => false,
                    'show_in_nav_menus'    => false,
                    'show_in_rest'         => false,
                    'show_in_admin_bar'    => true,
                    'archive_in_nav_menus' => false,
                    'capability_type'      => 'post',
                    'map_meta_cap'         => true,
                    'has_archive'          => false,
                    'hierarchical'         => false,
                    'exclude_from_search'  => true,
                ];

                // Registering your Custom Post Type
                register_post_type('chama_tier', $args);
            }
            public function chama_create_campaign_cpt()
            {

                // Set UI labels for Custom Post Type
                $labels = [
                    'name'               => _x('Campaigns', 'Post Type General Name', 'chama'),
                    'singular_name'      => _x('Campaign', 'Post Type Singular Name', 'chama'),
                    'menu_name'          => __('Campaign', 'chama'),
                    'all_items'          => __('All Campaigns', 'chama'),
                    'view_item'          => __('View Campaigns', 'chama'),
                    'add_new_item'       => __('Add Campaign', 'chama'),
                    'add_new'            => __('Add New', 'chama'),
                    'edit_item'          => __('Edit Campaign', 'chama'),
                    'update_item'        => __('Update Campaign', 'chama'),
                    'search_items'       => __('Search Campaigns', 'chama'),
                    'not_found'          => __('No Campaigns found', 'chama'),
                    'not_found_in_trash' => __('Not Campaigns found in Trash', 'chama'),
                ];

                // Set other options for Custom Post Type

                $args = [

                    'labels'               => $labels,
                    // Features this CPT supports in Post Editor
                    'supports'             => ['title', 'editor', 'thumbnail'],
                    'public'               => true,
                    'publicly_queryable'   => false,
                    'exclude_from_search'  => true,
                    'show_ui'              => true,
                    'show_in_menu'         => false,
                    'show_in_nav_menus'    => false,
                    'show_in_rest'         => false,
                    'show_in_admin_bar'    => true,
                    'archive_in_nav_menus' => false,
                    'capability_type'      => 'post',
                    'map_meta_cap'         => true,
                    'has_archive'          => false,
                    'hierarchical'         => false,
                    'exclude_from_search'  => true,
                ];

                // Registering your Custom Post Type
                register_post_type('chama_campaign', $args);
            }
            public function chama_create_commission_cpt()
            {

                // Set UI labels for Custom Post Type
                $labels = [
                    'name'               => _x('Commissions', 'Post Type General Name', 'chama'),
                    'singular_name'      => _x('Commission', 'Post Type Singular Name', 'chama'),
                    'menu_name'          => __('Commission', 'chama'),
                    'all_items'          => __('All Commissions', 'chama'),
                    'view_item'          => __('View Commissions', 'chama'),
                    'add_new_item'       => __('Add Commission', 'chama'),
                    'add_new'            => __('Add New', 'chama'),
                    'edit_item'          => __('Edit Commission', 'chama'),
                    'update_item'        => __('Update Commission', 'chama'),
                    'search_items'       => __('Search Commissions', 'chama'),
                    'not_found'          => __('No Commissions found', 'chama'),
                    'not_found_in_trash' => __('Not Commissions found in Trash', 'chama'),
                ];

                // Set other options for Custom Post Type

                $args = [

                    'labels'               => $labels,
                    // Features this CPT supports in Post Editor
                    'supports'             => ['title', 'thumbnail'],
                    'public'               => true,
                    'publicly_queryable'   => false,
                    'exclude_from_search'  => true,
                    'show_ui'              => true,
                    'show_in_menu'         => false,
                    'show_in_nav_menus'    => false,
                    'show_in_rest'         => false,
                    'show_in_admin_bar'    => true,
                    'archive_in_nav_menus' => false,
                    'capability_type'      => 'post',
                    'map_meta_cap'         => true,
                    'has_archive'          => false,
                    'hierarchical'         => false,
                    'exclude_from_search'  => true,
                ];

                // Registering your Custom Post Type
                register_post_type('chama_commission', $args);
            }
            public function chama_create_donation_cpt()
            {
                // Set UI labels for Custom Post Type
                $labels = [
                    'name'               => _x('Donations', 'Post Type General Name', 'chama'),
                    'singular_name'      => _x('Donation', 'Post Type Singular Name', 'chama'),
                    'menu_name'          => __('Donation', 'chama'),
                    'all_items'          => __('All Donations', 'chama'),
                    'view_item'          => __('View Donations', 'chama'),
                    'add_new_item'       => __('Add Donation', 'chama'),
                    'add_new'            => __('Add New', 'chama'),
                    'edit_item'          => __('Edit Donation', 'chama'),
                    'update_item'        => __('Update Donation', 'chama'),
                    'search_items'       => __('Search Donations', 'chama'),
                    'not_found'          => __('No Donations found', 'chama'),
                    'not_found_in_trash' => __('Not Donations found in Trash', 'chama'),
                ];

                // Set other options for Custom Post Type

                $args = [

                    'labels'               => $labels,
                    // Features this CPT supports in Post Editor
                    'supports'             => false,
                    'public'               => false,
                    'publicly_queryable'   => false,
                    'exclude_from_search'  => true,
                    'show_ui'              => true,
                    'show_in_menu'         => false,
                    'show_in_nav_menus'    => false,
                    'show_in_rest'         => false,
                    'show_in_admin_bar'    => false,
                    'archive_in_nav_menus' => false,
                    'capability_type'      => 'post',
                    'capabilities'         => ['create_posts' => false],
                    'map_meta_cap'         => true,
                    'has_archive'          => false,
                    'hierarchical'         => false,
                    'exclude_from_search'  => true,
                ];

                // Registering your Custom Post Type
                register_post_type('chama_donation', $args);
            }
            public function chama_create_subscription_cpt()
            {
                // Set UI labels for Custom Post Type
                $labels = [
                    'name'               => _x('Subscriptions', 'Post Type General Name', 'chama'),
                    'singular_name'      => _x('Subscription', 'Post Type Singular Name', 'chama'),
                    'menu_name'          => __('Subscription', 'chama'),
                    'all_items'          => __('All Subscriptions', 'chama'),
                    'view_item'          => __('View Subscriptions', 'chama'),
                    'add_new_item'       => __('Add Subscription', 'chama'),
                    'add_new'            => __('Add New', 'chama'),
                    'edit_item'          => __('Edit Subscription', 'chama'),
                    'update_item'        => __('Update Subscription', 'chama'),
                    'search_items'       => __('Search Subscriptions', 'chama'),
                    'not_found'          => __('No Subscriptions found', 'chama'),
                    'not_found_in_trash' => __('Not Subscriptions found in Trash', 'chama'),
                ];

                // Set other options for Custom Post Type

                $args = [

                    'labels'               => $labels,
                    // Features this CPT supports in Post Editor
                    'supports'             => false,
                    'public'               => false,
                    'publicly_queryable'   => false,
                    'exclude_from_search'  => true,
                    'show_ui'              => true,
                    'show_in_menu'         => false,
                    'show_in_nav_menus'    => false,
                    'show_in_rest'         => false,
                    'show_in_admin_bar'    => false,
                    'archive_in_nav_menus' => false,
                    'capability_type'      => 'post',
                    'capabilities'         => ['create_posts' => false],
                    'map_meta_cap'         => true,
                    'has_archive'          => false,
                    'hierarchical'         => false,
                    'exclude_from_search'  => true,
                ];

                // Registering your Custom Post Type
                register_post_type('chama_subscription', $args);
            }
            public function chama_create_fund_cpt()
            {
                // Set UI labels for Custom Post Type
                $labels = [
                    'name'               => _x('Funds', 'Post Type General Name', 'chama'),
                    'singular_name'      => _x('Fund', 'Post Type Singular Name', 'chama'),
                    'menu_name'          => __('Fund', 'chama'),
                    'all_items'          => __('All Funds', 'chama'),
                    'view_item'          => __('View Funds', 'chama'),
                    'add_new_item'       => __('Add Fund', 'chama'),
                    'add_new'            => __('Add New', 'chama'),
                    'edit_item'          => __('Edit Fund', 'chama'),
                    'update_item'        => __('Update Fund', 'chama'),
                    'search_items'       => __('Search Funds', 'chama'),
                    'not_found'          => __('No Funds found', 'chama'),
                    'not_found_in_trash' => __('Not Funds found in Trash', 'chama'),
                ];

                // Set other options for Custom Post Type

                $args = [

                    'labels'               => $labels,
                    // Features this CPT supports in Post Editor
                    'supports'             => false,
                    'public'               => false,
                    'publicly_queryable'   => false,
                    'exclude_from_search'  => true,
                    'show_ui'              => true,
                    'show_in_menu'         => false,
                    'show_in_nav_menus'    => false,
                    'show_in_rest'         => false,
                    'show_in_admin_bar'    => false,
                    'archive_in_nav_menus' => false,
                    'capability_type'      => 'post',
                    'capabilities'         => ['create_posts' => false],
                    'map_meta_cap'         => true,
                    'has_archive'          => false,
                    'hierarchical'         => false,
                    'exclude_from_search'  => true,
                ];

                // Registering your Custom Post Type
                register_post_type('chama_fund', $args);
            }
            public function chama_create_commission_order_cpt()
            {
                // Set UI labels for Custom Post Type
                $labels = [
                    'name'               => _x('Commission Orders', 'Post Type General Name', 'chama'),
                    'singular_name'      => _x('Commission Order', 'Post Type Singular Name', 'chama'),
                    'menu_name'          => __('Commission Order', 'chama'),
                    'all_items'          => __('All Commission Orders', 'chama'),
                    'view_item'          => __('View Commission Orders', 'chama'),
                    'add_new_item'       => __('Add Commission Order', 'chama'),
                    'add_new'            => __('Add New', 'chama'),
                    'edit_item'          => __('Edit Commission Order', 'chama'),
                    'update_item'        => __('Update Commission Order', 'chama'),
                    'search_items'       => __('Search Commission Orders', 'chama'),
                    'not_found'          => __('No Commission Orders found', 'chama'),
                    'not_found_in_trash' => __('Not Commission Orders found in Trash', 'chama'),
                ];

                // Set other options for Custom Post Type

                $args = [

                    'labels'               => $labels,
                    // Features this CPT supports in Post Editor
                    'supports'             => false,
                    'public'               => false,
                    'publicly_queryable'   => false,
                    'exclude_from_search'  => true,
                    'show_ui'              => true,
                    'show_in_menu'         => false,
                    'show_in_nav_menus'    => false,
                    'show_in_rest'         => false,
                    'show_in_admin_bar'    => false,
                    'archive_in_nav_menus' => false,
                    'capability_type'      => 'post',
                    'capabilities'         => ['create_posts' => false],
                    'map_meta_cap'         => true,
                    'has_archive'          => false,
                    'hierarchical'         => false,
                    'exclude_from_search'  => true,
                ];

                // Registering your Custom Post Type
                register_post_type('chama_com_order', $args);
            }
            public function chama_create_newsletter_cpt()
            {

                // Set UI labels for Custom Post Type
                $labels = [
                    'name'               => _x('Newsletters', 'Post Type General Name', 'chama'),
                    'singular_name'      => _x('Newsletter', 'Post Type Singular Name', 'chama'),
                    'menu_name'          => __('Newsletter', 'chama'),
                    'all_items'          => __('All Newsletters', 'chama'),
                    'view_item'          => __('View Newsletters', 'chama'),
                    'add_new_item'       => __('Add Newsletter', 'chama'),
                    'add_new'            => __('Add New', 'chama'),
                    'edit_item'          => __('Edit Newsletter', 'chama'),
                    'update_item'        => __('Update Newsletter', 'chama'),
                    'search_items'       => __('Search Newsletters', 'chama'),
                    'not_found'          => __('No Newsletters found', 'chama'),
                    'not_found_in_trash' => __('Not Newsletters found in Trash', 'chama'),
                ];

                // Set other options for Custom Post Type

                $args = [

                    'labels'               => $labels,
                    // Features this CPT supports in Post Editor
                    'supports'             => ['title', 'editor', 'author'],
                    'public'               => true,
                    'publicly_queryable'   => true,
                    'exclude_from_search'  => false,
                    'show_ui'              => true,
                    'show_in_menu'         => false,
                    'show_in_nav_menus'    => false,
                    'show_in_rest'         => false,
                    'show_in_admin_bar'    => true,
                    'archive_in_nav_menus' => false,
                    'capability_type'      => 'post',
                    'map_meta_cap'         => true,
                    'has_archive'          => false,
                    'hierarchical'         => false,
                    'exclude_from_search'  => true,
                    // ✅ This sets the permalink slug
                    'rewrite'              => [
                        'slug'       => 'newsletter',
                        'with_front' => false,
                    ],
                ];

                // Registering your Custom Post Type
                register_post_type('chama_newsletter', $args);
            }
            public function chama_admin_notices()
            {
                $this->chama_stripe_connect_notice();
                $this->chama_ssl_notice();
            }
            public function chama_stripe_connect_notice()
            {
                $mode               = chama_is_live_mode() ? 'live' : 'test';
                $publishable_key    = get_option('chama_stripe_' . $mode . '_publishable_key');
                $secret_key         = get_option('chama_stripe_' . $mode . '_secret_key');
                $connected          = $publishable_key && $secret_key;
                $stripe_connect_url = admin_url('admin.php?page=chama-settings');
                $stripe_docs_url    = CHAMA_DOCS_URL . '/how-to-connect-your-stripe-account-to-chamawp';
                // Safe: sanitized and unslashed $_GET values for display logic only
                $page = sanitize_text_field(wp_unslash(filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS)));
                $tab  = sanitize_text_field(wp_unslash(filter_input(INPUT_GET, 'tab', FILTER_SANITIZE_FULL_SPECIAL_CHARS)));

                $is_stripe_page = ($page === 'chama-settings' && (empty($tab) || $tab === 'stripe'));
                if (! $connected && ! $is_stripe_page) {
                ?>

	<div class="notice notice-info">
		<p>
			<?php
                echo wp_kses(
                                    (
                                        '<p> ' .
                                        __(
                                            'ChamaWP requires a Stripe connection to process your payments. Connect now to start accepting payments instantly.',
                                            'chama'
                                        ) .
                                        '</p>' .
                                        '<p>' .
                                        '<a href="' . esc_url($stripe_connect_url) . '" aria-label="Connect with Stripe" class="chama-stripe-connect chama-btn">' .
                                        '<span>	Connect with&nbsp;</span>' .
                                        '<svg width="49" height="20" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M48.4718 10.3338c0-3.41791-1.6696-6.11484-4.8607-6.11484-3.2045 0-5.1434 2.69693-5.1434 6.08814 0 4.0187 2.289 6.048 5.5743 6.048 1.6023 0 2.8141-.3604 3.7296-.8678v-2.6702c-.9155.4539-1.9658.7343-3.2987.7343-1.3061 0-2.464-.4539-2.6121-2.0294h6.5841c0-.1735.0269-.8678.0269-1.1882Zm-6.6514-1.26838c0-1.50868.929-2.13618 1.7773-2.13618.8213 0 1.6965.6275 1.6965 2.13618h-3.4738Zm-8.5499-4.84646c-1.3195 0-2.1678.61415-2.639 1.04139l-.1751-.82777h-2.9621V20l3.3661-.7076.0134-3.7784c.4847.3471 1.1984.8411 2.3832.8411 2.4102 0 4.6048-1.9225 4.6048-6.1548-.0134-3.87186-2.235-5.98134-4.5913-5.98134Zm-.8079 9.19894c-.7944 0-1.2656-.2804-1.5888-.6275l-.0134-4.95328c.35-.38719.8348-.65421 1.6022-.65421 1.2253 0 2.0735 1.36182 2.0735 3.11079 0 1.7891-.8347 3.1242-2.0735 3.1242Zm-9.6001-9.98666 3.3796-.72096V0l-3.3796.70761v2.72363Zm0 1.01469h3.3796V16.1282h-3.3796V4.44593Zm-3.6219.98798-.2154-.98798h-2.9083V16.1282h3.3661V8.21095c.7944-1.02804 2.1408-.84112 2.5582-.69426V4.44593c-.4309-.16022-2.0062-.45394-2.8006.98798Zm-6.7322-3.88518-3.2853.69426-.01346 10.69421c0 1.976 1.49456 3.4313 3.48726 3.4313 1.1041 0 1.912-.2003 2.3563-.4406v-2.7103c-.4309.1736-2.5583.7877-2.5583-1.1882V7.28972h2.5583V4.44593h-2.5583l.0135-2.8972ZM3.40649 7.83712c0-.5207.43086-.72096 1.14447-.72096 1.0233 0 2.31588.30707 3.33917.85447V4.83311c-1.11755-.44059-2.22162-.61415-3.33917-.61415C1.81769 4.21896 0 5.63418 0 7.99733c0 3.68487 5.11647 3.09747 5.11647 4.68627 0 .6141-.53858.8144-1.29258.8144-1.11755 0-2.54477-.4539-3.675782-1.0681v3.1776c1.252192.534 2.517842.761 3.675782.761 2.80059 0 4.72599-1.3752 4.72599-3.765-.01346-3.97867-5.14339-3.27106-5.14339-4.76638Z" fill="#fff"></path></svg>' .
                                        '</a>' .
                                        '<a href="' . esc_url($stripe_docs_url) . '" target="_blank" rel="noopener noreferrer" class="button button-secondary" style="margin-left: 10px;">' .
                                        __(
                                            'Learn More',
                                            'chama'
                                        ) .
                                        '</a>' .
                                        '</p>'
                                    ),
                                    [
                                        'p'      => [
                                            'class' => true,
                                            'style' => true,
                                        ],
                                        'span'   => [
                                            'class' => true,
                                            'style' => true,
                                        ],
                                        'strong' => true,
                                        'br'     => true,
                                        'a'      => [
                                            'href'       => true,
                                            'target'     => true,
                                            'rel'        => true,
                                            'aria-label' => true,
                                            'class'      => true,
                                            'style'      => true,
                                        ],
                                        'svg'    => [
                                            'xmlns'       => true,
                                            'fill'        => true,
                                            'viewbox'     => true,
                                            'role'        => true,
                                            'aria-hidden' => true,
                                            'focusable'   => true,
                                            'width'       => true,
                                            'height'      => true,
                                        ],
                                        'path'   => [
                                            'd'         => true,
                                            'fill'      => true,
                                            'fill-rule' => true,
                                            'clip-rule' => true,
                                        ],
                                    ]
                                );
                            ?>
		</p>
	</div>

	<?php
        } else {
                        return false;
                    }
                }
                public function chama_ssl_notice()
                {
                    if (is_ssl()) {
                        return false;
                    }
                ?>

	<div class="notice notice-error">
		<p>
			<?php
                echo wp_kses(
                                (
                                    '<p> ' .
                                    __(
                                        'SSL (HTTPS) is not enabled. You will not be able to process live Stripe transactions until SSL is enabled.',
                                        'chama'
                                    ) .
                                    '</p>'
                                ),
                                [
                                    'p' => [
                                        'class' => true,
                                        'style' => true,
                                    ],
                                ]
                            );
                        ?>
		</p>
	</div>

	<?php
        }
                public function chama_settings_link($links)
                {
                    // Build the URL.
                    $url = add_query_arg(
                        'page',
                        'chama-settings',
                        get_admin_url() . 'admin.php'
                    );

                    // Create the link.
                    $settings_link = "<a href='$url'>" . __('Settings', 'chama') . '</a>';

                    // Adds the link to the end of the array.
                    array_push(
                        $links,
                        $settings_link
                    );

                    return $links;
                }

                public function chama_create_roles()
                {
                    $this->chama_create_role('chama_donor', 'Chama Donor');
                    $this->chama_create_role('chama_member', 'Chama Member');
                    $this->chama_create_role('chama_funder', 'Chama Funder');
                    $this->chama_create_role('chama_comissioner', 'Chama Comissioner');
                    $this->chama_create_role('chama_complimentary', 'Chama Complimentary');
                    $this->chama_create_role('chama_temp', 'Chama Temp');

                }
                public function chama_create_role($role_slug, $role_name)
                {
                    $result = add_role($role_slug, esc_html(
                        $role_name, 'chama'),
                        []);
                }

                public function chama_cron_sync_pending_payments()
                {
                    try {
                        $secret_key = chama_is_live_mode() ? CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;

                        global $wpdb;
                        for ($counter = 0;; $counter += 100) {

                            $results = $wpdb->get_results(
                                $wpdb->prepare(
                                    "
        SELECT p.ID, p.post_type, pm2.meta_value as stripe_payment_intent_id, pm3.meta_value as user_id
        FROM {$wpdb->posts} p
        JOIN {$wpdb->postmeta} pm1 ON p.ID = pm1.post_ID
        JOIN {$wpdb->postmeta} pm2 ON p.ID = pm2.post_ID
        JOIN {$wpdb->postmeta} pm3 ON p.ID = pm3.post_ID
        WHERE p.post_type IN ('chama_donation', 'chama_subscription', 'chama_fund', 'chama_com_order')
        AND pm1.meta_key = 'chama_payment_status' AND pm1.meta_value = 'processing'
        AND pm2.meta_key = 'chama_stripe_payment_intent_id'
        AND pm3.meta_key = 'chama_user_id'
        LIMIT %d, 100
        ",
                                    $counter
                                )
                            );

                            if (empty($results)) {
                                //No more records to process. Break out of the loop.
                                break;
                            }
                            foreach ($results as $result) {
                                $payment_id               = $result->ID;
                                $cpt                      = $result->post_type;
                                $stripe_payment_intent_id = $result->stripe_payment_intent_id;
                                $user_id                  = $result->user_id;
                                $payment_intent           = null;
                                if ($stripe_payment_intent_id && $secret_key) {
                                    $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                                        $secret_key // API Secret here
                                    );
                                    $payment_intent = $stripe->paymentIntents->retrieve(
                                        $stripe_payment_intent_id,
                                    );
                                }

                                //process incomplete payment
                                if ($payment_id && $cpt && $user_id && $payment_intent) {
                                    chama_process_incomplete_payment($payment_id, $cpt, $payment_intent, $user_id, false);
                                }

                            }
                        }
                    } catch (Exception $e) {

                        wp_die(esc_html($e->getMessage()));
                    }
                }
                public function chama_cron_sync_pending_subscriptions()
                {
                    try {
                        $secret_key = chama_is_live_mode() ? CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;

                        global $wpdb;
                        for ($counter = 0;; $counter += 100) {

                            $results = $wpdb->get_results($wpdb->prepare("SELECT p.ID, p.post_type, pm2.meta_value as stripe_customer_id, pm3.meta_value as user_id, pm4.meta_value as stripe_subscription_id, pm5.meta_value as tier_id, pm6.meta_value as tier_description, pm7.meta_value as subscription_level
                FROM {$wpdb->posts} p, {$wpdb->postmeta} pm1, {$wpdb->postmeta} pm2, {$wpdb->postmeta} pm3, {$wpdb->postmeta} pm4, {$wpdb->postmeta} pm5, {$wpdb->postmeta} pm6, {$wpdb->postmeta} pm7
                WHERE p.post_type = 'chama_subscription'
                AND p.ID = pm1.post_ID
                AND pm1.meta_key = 'chama_subscription_status'  AND pm1.meta_value = 'incomplete'
                AND p.ID = pm2.post_ID
                AND pm2.meta_key = 'chama_stripe_customer_id'
                AND p.ID = pm3.post_ID
                AND pm3.meta_key = 'chama_user_id'
                AND p.ID = pm4.post_ID
                AND pm4.meta_key = 'chama_stripe_subscription_id'
                AND p.ID = pm5.post_ID
                AND pm5.meta_key = 'chama_subscription_item_id'
                AND p.ID = pm6.post_ID
                AND pm6.meta_key = 'chama_subscription_description'
                AND p.ID = pm7.post_ID
                AND pm7.meta_key = 'chama_subscription_total_amount'
                LIMIT %d, 100", $counter));
                            if (empty($results)) {
                                //No more records to process. Break out of the loop.
                                break;
                            }
                            foreach ($results as $result) {
                                $subscription_id        = $result->ID;
                                $cpt                    = $result->post_type;
                                $stripe_customer_id     = $result->stripe_customer_id;
                                $user_id                = $result->user_id;
                                $stripe_subscription_id = $result->stripe_subscription_id;
                                $tier_id                = $result->tier_id;
                                $tier_description       = $result->tier_description;
                                $subscription_level     = $result->subscription_level;
                                $subscription           = null;
                                if ($stripe_subscription_id && $secret_key) {
                                    $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                                        $secret_key // API Secret here
                                    );
                                    $subscription = $stripe->subscriptions->retrieve(
                                        $stripe_subscription_id, []
                                    );
                                }

                                //process incomplete subscription
                                if ($subscription_id && $cpt && $user_id && $subscription) {
                                    chama_process_incomplete_subscription($subscription_id, $cpt, $stripe_customer_id, $stripe_subscription_id, $tier_id, $tier_description, $subscription_level, $subscription, $user_id, false);
                                }

                            }
                        }
                    } catch (Exception $e) {

                        wp_die(esc_html($e->getMessage()));
                    }
                }
                public function chama_cron_sync_missing_subscription_renewals()
                {
                    try {
                        $secret_key = chama_is_live_mode() ? CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;

                        global $wpdb;
                        for ($counter = 0;; $counter += 100) {
                            $results = $wpdb->get_results($wpdb->prepare("SELECT u.ID, um1.meta_value as subscription_status, um2.meta_value as next_renewal_date, um3.meta_value as stripe_subscription_id, um4.meta_value as stripe_customer_id
                FROM {$wpdb->users} u, {$wpdb->usermeta} um1, {$wpdb->usermeta} um2, {$wpdb->usermeta} um3, {$wpdb->usermeta} um4
                WHERE u.ID = um1.user_id
                AND um1.meta_key = 'chama_subscription_status'  AND um1.meta_value = 'active'
                AND u.ID = um2.user_id
                AND um2.meta_key = 'chama_subscription_current_period_end' AND um2.meta_value < NOW()
                AND u.ID = um3.user_id
                AND um3.meta_key = 'chama_stripe_subscription_id'
                AND u.ID = um4.user_id
                AND um4.meta_key = 'chama_stripe_customer_id'
                LIMIT %d, 100", $counter));
                            if (empty($results)) {
                                //No more records to process. Break out of the loop.
                                break;
                            }

                            foreach ($results as $result) {
                                try {
                                    $user_id                = $result->ID;
                                    $stripe_subscription_id = $result->stripe_subscription_id;
                                    $stripe_customer_id     = $result->stripe_customer_id;
                                    $subscription           = null;
                                    if ($stripe_subscription_id && $secret_key) {
                                        $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                                            $secret_key // API Secret here
                                        );
                                        /*=============================================GET MISSING RENEWALS===========================================*/
                                        //first try and get subscription
                                        //loop completed update subscription

                                        try {
                                            $subscription = $stripe->subscriptions->retrieve(
                                                $stripe_subscription_id, []
                                            );
                                        } catch (Exception $e) {
                                            continue;
                                        }

                                        if ($subscription && $subscription->status === 'active') {
                                            //we have a subscription, we can proceed
                                            $invoices = $stripe->invoices->all([
                                                'limit'        => 12,
                                                'subscription' => $stripe_subscription_id,
                                            ]);
                                            $payment_date = $renewal_date = $stripe_current_period_start = $stripe_current_period_end = '';
                                            if ($invoices) {
                                                foreach ($invoices->autoPagingIterator() as $invoice) {
                                                    if ($invoice->billing_reason == 'subscription_cycle') {
                                                        $stripe_payment_intent_id = $invoice->payment_intent;

                                                        /*=============================================CHECK IF IT IS ALREADY IN DATABASE=============================================*/
                                                        $transaction_in_db = false;
                                                        $payment_args      = [
                                                            'meta_key'       => 'chama_stripe_payment_intent_id', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
                                                            'meta_value'     => $invoice->payment_intent,         // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
                                                            'post_status'    => 'any',
                                                            'post_type'      => 'chama_subscription',
                                                            'posts_per_page' => 1,
                                                        ];
                                                        $payment           = get_posts($payment_args);
                                                        $transaction_in_db = $payment && $payment[0]->ID;

                                                        /*=============================================PROCEED IF NOT IN DATABASE=============================================*/
                                                        if (! $transaction_in_db) {
                                                            $stripe_billing_reason  = $invoice->billing_reason;
                                                            $total_amount_cents     = $invoice->amount_paid;
                                                            $stripe_subscription_id = $invoice->subscription;
                                                            $tier_id                = $invoice->subscription_details->metadata->tier_id;
                                                            $customer_email         = $invoice->customer_email;
                                                            $stripe_customer_id     = $invoice->customer;
                                                            $currency               = $invoice->currency;
                                                            $description            = $invoice->subscription_details->metadata->description;
                                                            $total_amount_formatted = '0.00';
                                                            $total_amount           = 0;
                                                            $receipt_id             = 0;
                                                            $user_id                = 0;
                                                            $user                   = null;

                                                            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);
                                                            }

                                                            if ($invoice->period_start) {
                                                                $payment_date = gmdate("Y-m-d H:i:s", $invoice->period_start);
                                                            }
                                                            if ($invoice->period_end) {
                                                                $renewal_date = gmdate("F, j, Y", $invoice->period_end);
                                                            }

                                                            /*=============================================ADD TO DATABASE=============================================*/
                                                            $cpt_args = [
                                                                'post_type'   => 'chama_subscription',
                                                                'post_status' => 'publish',
                                                            ];
                                                            $receipt_id = wp_insert_post($cpt_args);
                                                            if ($receipt_id) {
                                                                if ($customer_email) {
                                                                    $user = null;
                                                                    if ($user_id) {
                                                                        $user = get_user_by('id', $user_id);
                                                                    } else {
                                                                        $user = get_user_by('email', $customer_email);
                                                                    }

                                                                    if ($user) {
                                                                        $user_id = $user->ID;
                                                                        update_post_meta($receipt_id, 'chama_user_id', $user_id);
                                                                        update_post_meta($receipt_id, 'chama_email', $customer_email);
                                                                        if ($user->first_name && $user->last_name) {
                                                                            update_post_meta($receipt_id, 'chama_full_name', $user->first_name . ' ' . $user->last_name);
                                                                        }
                                                                    }

                                                                }
                                                                if ($stripe_customer_id) {
                                                                    update_post_meta($receipt_id, 'chama_stripe_customer_id', sanitize_text_field($stripe_customer_id));
                                                                }
                                                                if ($description) {
                                                                    update_post_meta($receipt_id, 'chama_subscription_description', sanitize_text_field($description));
                                                                }
                                                                if ($tier_id) {
                                                                    update_post_meta($receipt_id, 'chama_subscription_item_id', sanitize_text_field($tier_id));
                                                                }

                                                                update_post_meta($receipt_id, 'chama_payment_status', 'complete');
                                                                if ($total_amount_cents) {
                                                                    update_post_meta($receipt_id, 'chama_subscription_currency', sanitize_text_field($currency));
                                                                    update_post_meta($receipt_id, 'chama_subscription_total_amount', sanitize_text_field($total_amount_formatted));

                                                                }

                                                                update_post_meta($receipt_id, 'chama_subscription_date_time', $payment_date);
                                                                update_post_meta($receipt_id, 'chama_is_test_subscription', ! chama_is_live_mode());
                                                                update_post_meta($receipt_id, 'chama_stripe_payment_intent_id', $stripe_payment_intent_id);
                                                                if ($stripe_subscription_id) {
                                                                    update_post_meta($receipt_id, 'chama_subscription_status', 'active');
                                                                    update_post_meta($receipt_id, 'chama_subscription_event', 'renewal');
                                                                    update_post_meta($receipt_id, 'chama_stripe_subscription_id', $stripe_subscription_id);
                                                                }
                                                            }
                                                            /*=============================================UPDATE PERIODS=============================================*/

                                                            if ($renewal_date) {
                                                                update_post_meta($receipt_id, 'chama_subscription_renewal_date', $renewal_date);
                                                            }
                                                            /*=============================================COMPLETED DATA ENTRY============================================*/
                                                        }

                                                    }

                                                }
                                                //loop completed update subscription

                                                $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');

                                                if ($subscription->current_period_start) {
                                                    $stripe_current_period_start = gmdate("F, j, Y", $subscription->current_period_start);
                                                    update_user_meta($user_id, 'chama_subscription_current_period_start', $stripe_current_period_start);
                                                }
                                                if ($subscription->current_period_end) {
                                                    $stripe_current_period_end = gmdate("F, j, Y", $subscription->current_period_end);
                                                    update_user_meta($user_id, 'chama_subscription_current_period_end', $stripe_current_period_end);
                                                }

                                            } else {
                                                //wp_die('No invoices found!');
                                                continue;
                                            }
                                        }

                                        /*=============================================FINISH GETTING MISSING RENEWALS===========================================*/
                                    }
                                } catch (Exception $e) {
                                    continue;
                                }
                            }
                        }
                    } catch (Exception $e) {
                        wp_die(esc_html($e->getMessage()));
                    }
                }

            }

        }
        define('CHAMA_PLUGIN_DIR', plugin_dir_path(__FILE__));

        if (! class_exists('Chama_Gamajo_Template_Loader')) {
            require CHAMA_PLUGIN_DIR . 'classes/class-gamajo-template-loader.php';
        }
        require CHAMA_PLUGIN_DIR . 'classes/class-chama-template-loader.php';
        require CHAMA_PLUGIN_DIR . 'inc/template-functions.php';
        $Chama_Plugin = new Chama_Plugin;
        $Chama_Plugin->init();
    //Helpers
