<?php

namespace Lknwp\CrowdfundingExtension\Includes;

use Lknwp\CrowdfundingExtension\Admin\LknwpCrowdfundingExtensionAdmin;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\database\LknwpCrowdfundingListingQuery;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\helpers\LknwpCrowdfundingListingFunctions;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateAverageRating;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateCampaignTabs;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingListingWidget;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateAuthor;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateBiography;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateCustomAmount;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateDaysRemaining;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateEndMethod;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateFavoriteCampaign;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateFundingGoal;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateFundRaised;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateLocation;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateName;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateProductGallery;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateProductImage;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateRaisedPercent;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\LknwpCrowdfundingTemplateShortDescription;
use Lknwp\CrowdfundingExtension\PublicView\LknwpCrowdfundingExtensionPublic;

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

final class LknwpCrowdfundingExtension
{
    /**
     * The loader that's responsible for maintaining and registering all hooks that power
     * the plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      Lkn_Wp_Crowdfunding_Extension_Loader    $loader    Maintains and registers all hooks for the plugin.
     */
    protected $loader;

    /**
     * The unique identifier of this plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      string    $plugin_name    The string used to uniquely identify this plugin.
     */
    protected $plugin_name;

    /**
     * The current version of the plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      string    $version    The current version of the plugin.
     */
    protected $version;

    /**
     * Define the core functionality of the plugin.
     *
     * Set the plugin name and the plugin version that can be used throughout the plugin.
     * Load the dependencies, define the locale, and set the hooks for the admin area and
     * the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function __construct()
    {
        if (defined('LKNWP_CROWDFUNDING_EXTENSION_VERSION')) {
            $this->version = LKNWP_CROWDFUNDING_EXTENSION_VERSION;
        } else {
            $this->version = '1.0.0';
        }
        $this->plugin_name = 'lkn-wp-crowdfunding-extension';

        $this->load_dependencies();


        $this->set_locale();
        $this->define_admin_hooks();
        $this->define_public_hooks();
    }

    /**
     * Load the required dependencies for this plugin.
     *
     * Include the following files that make up the plugin:
     *
     * - Lkn_Wp_Crowdfunding_Extension_Loader. Orchestrates the hooks of the plugin.
     * - Lkn_Wp_Crowdfunding_Extension_Admin. Defines all hooks for the admin area.
     * - Lkn_Wp_Crowdfunding_Extension_Public. Defines all hooks for the public side of the site.
     *
     * Create an instance of the loader which will be used to register the hooks
     * with WordPress.
     *
     * @since    1.0.0
     * @access   private
     */
    private function load_dependencies(): void
    {
        $this->loader = new LknwpCrowdfundingExtensionLoader();
    }

    /**
     * Define the locale for this plugin for internationalization.
     *
     * with WordPress.
     *
     * @since    1.0.0
     * @access   private
     */
    private function set_locale(): void
    {
    }

    /**
     * Register all of the hooks related to the admin area functionality
     * of the plugin.
     *
     * @since    1.0.0
     * @access   private
     */
    private function define_admin_hooks(): void
    {
        $plugin_admin = new LknwpCrowdfundingExtensionAdmin($this->get_plugin_name(), $this->get_version());

        $this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_styles');
        $this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts');

        $this->loader->add_action('rest_api_init', $this, 'register_rest_routes');

        if (class_exists('Elementor\Plugin') && did_action('elementor/loaded')) {
            $this->loader->add_action('elementor/widgets/register', $this, 'register_lkn_elementor_widget');
            $this->loader->add_action('elementor/elements/categories_registered', $this, 'register_lkn_elementor_category');
            $this->loader->add_action('elementor/editor/before_enqueue_styles', $this, 'elementor_enqueue_styles');
            $this->loader->add_action('elementor/editor/before_enqueue_scripts', $this, 'elementor_enqueue_scripts');
        }

        $this->loader->add_filter('wpcf_settings_panel_tabs', $this, 'settings_tab');
        $this->loader->add_action('wp_insert_post', $this, 'add_url_rules', 10, 3);
    }

    public function lknscf_override_crowdfunding_template($template)
    {
        global $post;

        // Verifica se é um produto do tipo "crowdfunding"
        if (is_single() && get_post_type() === 'product') {
            $product = wc_get_product($post->ID);
            if ($product && $product->get_type() === 'crowdfunding') {
                // Checa se existe uma template do Elementor
                if (class_exists('\Elementor\Plugin')) {
                    $template_id = get_option('lkn_crowdfunding_custom_template_id'); 

                    $product_base = get_option('woocommerce_permalinks')['product_base'];

                    // Obtém a URL completa
                    $current_url = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';

                    // Remove a base do produto da URL para obter o restante da rota
                    $route = str_replace($product_base, '', $current_url);
                    $parts = explode('/', trim($route, '/'));

                    $rewrite_rules = get_option('lkn_custom_rewrite_rules', []);

                    if ($parts >= 2) {
                        foreach ($rewrite_rules as $id => $name) {
                            if ($name === $parts[0]) {
                                $template_id = $id;
                                break;
                            }
                        }
                    }

                    if (!empty($template_id)) {
                        get_header();
                        // Note: not needed to escape output here as Elementor handles it internally
                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        echo \Elementor\Plugin::$instance->frontend->get_builder_content_for_display($template_id);
                        get_footer();
                        exit;
                    }
                }
            }
        }

        return $template;
    }

    public function add_url_rules($post_ID, $post, $update)
    {
        if ($update) {
            global $wpdb;

            // Recupera a base da URL do produto configurada no WooCommerce
            $product_base = get_option('woocommerce_permalinks')['product_base'];
            $product_base = trim($product_base, '/');

            // Recupera a lista de páginas e seus slugs
            $pages = $wpdb->get_results("SELECT ID, post_name FROM {$wpdb->posts} WHERE post_type = 'page' AND post_status = 'publish'");

            $applied_rules = [];
            $new_rules_added = false;

            // Adiciona as novas regras
            foreach ($pages as $page) {
                $page_id = $page->ID;
                $page_slug = trim($page->post_name, ' ');

                if (!isset($applied_rules[$page_id])) {
                    add_rewrite_rule(
                        '^' . $product_base . '/' . $page_slug . '/([^/]+)/?$',
                        'index.php?product=$matches[1]',
                        'top'
                    );

                    $applied_rules[$page_id] = $page_slug;

                    $new_rules_added = true;
                }
            }

            if ($new_rules_added) {
                update_option('lkn_custom_rewrite_rules', $applied_rules);
                flush_rewrite_rules();
            }
        }
    }

    public function settings_tab($tabs)
    {
        $tabs['Lkn Extension Settings'] = array(
            'tab_name' => __('Extension Settings', 'link-nacional-wp-crowdfunding-extension'),
            'load_form_file' => __DIR__ . '/LknwpCrowdfundingExtensionLoaderTabSettings.php'
        );

        return $tabs;
    }

    public function elementor_enqueue_scripts()
    {
        wp_enqueue_script('lknWpCrowdfundingElementor');
    }

    public function elementor_enqueue_styles()
    {
        wp_enqueue_style('lknWpCrowdfundingElementor');
    }

    /**
     * Register all of the hooks related to the public-facing functionality
     * of the plugin.
     *
     * @since    1.0.0
     * @access   private
     */
    private function define_public_hooks(): void
    {
        $plugin_public = new LknwpCrowdfundingExtensionPublic($this->get_plugin_name(), $this->get_version());

        $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_styles');
        $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_scripts');
        $this->loader->add_action('init', $this, 'lkn_blocks_init');
        $this->loader->add_filter('script_loader_tag', $this, 'add_defer_attribute', 10, 2);

        $this->loader->add_action('woocommerce_before_calculate_totals', $this, 'customize_price_in_cart', 10, 1);
        $this->loader->add_filter('template_include', $this, 'lknscf_override_crowdfunding_template', 99);
    }

    public function add_defer_attribute($tag, $handle)
    {
        if ('lkn-wp-crowdfunding-public' === $handle) {
            return str_replace(' src', ' defer src', $tag);
        }
        return $tag;
    }

    public function lkn_load_more_campaigns($data)
    {
        $settings = isset($data['settings']) ? array_map('sanitize_text_field', wp_unslash($data['settings'])) : [];
        $offset = isset($data['offset']) ? intval(wp_unslash($data['offset'])) : 0;

        $campaign_query = LknwpCrowdfundingListingQuery::getQuery($settings, $offset);

        $lknwpHelper = new LknwpCrowdfundingListingFunctions();
        $campaigns = [];

        if ($campaign_query->have_posts()) {
            while ($campaign_query->have_posts()) {
                $campaign_query->the_post();

                $thumbnail_id = get_post_thumbnail_id(get_the_ID());
                if ($thumbnail_id) {
                    $thumbnail = get_the_post_thumbnail(get_the_ID(), $settings['thumbnail_size']);
                    $thumbnail = str_replace('class="', 'class="lknwp-image ', $thumbnail);
                } else {
                    $placeholder_id = get_option('woocommerce_placeholder_image');
                    $thumbnail = wp_get_attachment_image($placeholder_id, $settings['thumbnail_size']);
                    $thumbnail = str_replace('class="', 'class="lknwp-image ', $thumbnail);
                }

                $end_method = get_post_meta(get_the_ID(), 'wpneo_campaign_end_method', true);
                $days_remaining = $lknwpHelper->get_date_remaining(get_the_ID());

                if (isset($end_method) && $end_method === "never_end") {
                    $days_remaining = __('Never end', 'link-nacional-wp-crowdfunding-extension');
                } elseif (isset($days_remaining) && $days_remaining == '0') {
                    $days_remaining = __('Expired', 'link-nacional-wp-crowdfunding-extension');
                }

                $campaigns[] = [
                    'id'             => get_the_ID(),
                    'title'          => get_the_title(),
                    'permalink'      => get_permalink(),
                    'thumbnail'      => $thumbnail,
                    'excerpt'        => wp_kses(htmlspecialchars_decode(get_the_excerpt()), []),
                    'location'       => $lknwpHelper->campaign_location(),
                    'author_name'    => $lknwpHelper->get_author_name(),
                    'author_url'     => $lknwpHelper->get_author_url(get_the_author_meta('user_login')),
                    'raised_percent' => $lknwpHelper->get_raised_percent(get_the_ID()),
                    'funding_goal'   => wc_price($lknwpHelper->get_total_goal(get_the_ID())),
                    'fund_raised'    => wc_price($lknwpHelper->get_total_fund(get_the_ID())),
                    'days_remaining' => $days_remaining,
                    'end_method'     => $end_method,
                ];
            }

            return rest_ensure_response(['campaigns' => $campaigns]);
        } else {
            return rest_ensure_response('no_more_campaigns', __('No more campaigns found.', 'link-nacional-wp-crowdfunding-extension'));
        }

        wp_reset_postdata();
    }

    public function register_lkn_elementor_widget($widgets_manager)
    {
        // Verifica se Elementor está carregado
        if (! did_action('elementor/loaded')) {
            return;
        }

        $widgets_manager->register(new LknwpCrowdfundingListingWidget());

        $widgets_manager->register(new LknwpCrowdfundingTemplateName());
        $widgets_manager->register(new LknwpCrowdfundingTemplateAuthor());
        $widgets_manager->register(new LknwpCrowdfundingTemplateRaisedPercent());
        $widgets_manager->register(new LknwpCrowdfundingTemplateFundingGoal());
        $widgets_manager->register(new LknwpCrowdfundingTemplateFundRaised());
        $widgets_manager->register(new LknwpCrowdfundingTemplateDaysRemaining());
        $widgets_manager->register(new LknwpCrowdfundingTemplateEndMethod());
        $widgets_manager->register(new LknwpCrowdfundingTemplateLocation());
        $widgets_manager->register(new LknwpCrowdfundingTemplateCustomAmount());
        $widgets_manager->register(new LknwpCrowdfundingTemplateProductImage());
        $widgets_manager->register(new LknwpCrowdfundingTemplateProductGallery());
        $widgets_manager->register(new LknwpCrowdfundingTemplateShortDescription());
        $widgets_manager->register(new LknwpCrowdfundingTemplateBiography());
        $widgets_manager->register(new LknwpCrowdfundingTemplateFavoriteCampaign());
        $widgets_manager->register(new LknwpCrowdfundingTemplateCampaignTabs());
        $widgets_manager->register(new LknwpCrowdfundingTemplateAverageRating());
    }

    public function register_lkn_elementor_category($elements_manager)
    {
        $elements_manager->add_category(
            'lkn-wp-crowdfunding-extension', // ID da categoria
            [
                'title' => __('Crowdfunding Extension', 'link-nacional-wp-crowdfunding-extension'),
                'icon' => 'fa fa-plug', // Ícone da categoria
            ]
        );
    }

    public function lkn_blocks_init(): void
    {
        // include_once LKNWP_CROWDFUNDING_EXTENSION_DIR . 'Includes/LknwpCrowdfundingExtensionSimpleRegistration.php';
        $lkn_wpcf_simple_registraion = new LknwpCrowdfundingExtensionSimpleRegistration();
        $lkn_wpcf_listing = new LknwpCrowdfundingExtensionListingPage();

        add_shortcode('lkn_wpcf_simple_registration', array($lkn_wpcf_simple_registraion, 'lkn_simple_registration_callback'));
        add_shortcode('lkn_wpcf_listing', array($lkn_wpcf_listing, 'lkn_listing_callback'));
    }

    public function register_rest_routes(): void
    {
        register_rest_route('lknwpcrowdfunding/v1', '/complete-registration', [
            'methods' => 'GET',
            'callback' => array($this, 'lkn_handle_verification_email_route'),
            'permission_callback' => function (\WP_REST_Request $request) {
                $token = $request->get_param('token');
                $nonce = $request->get_param('nonce');

                if (empty($token) || empty($nonce)) {
                    return new \WP_Error(
                        'missing_parameters',
                        __('Missing required parameters: token or nonce.', 'link-nacional-wp-crowdfunding-extension'),
                        ['status' => 400]
                    );
                }

                return true;
            },
        ]);

        register_rest_route('lknwpcrowdfunding/v1', '/load-more-campaigns', [
            'methods' => 'POST',
            'callback' => array($this, 'lkn_load_more_campaigns'),
            'permission_callback' => function (\WP_REST_Request $request) {
                $offset = $request->get_param('offset');

                // Verifica se o parâmetro obrigatório está presente
                if (is_null($offset)) {
                    return new \WP_Error(
                        'missing_parameters',
                        __('Missing required parameter: offset.', 'link-nacional-wp-crowdfunding-extension'),
                        ['status' => 400]
                    );
                }

                return true; // Permite o acesso se os parâmetros estiverem presentes
            },
        ]);

        register_rest_route('lknwpcrowdfunding/v1', '/add-to-cart', [
            'methods' => 'POST',
            'callback' => array($this, 'add_to_cart_with_custom_value'),
            'permission_callback' => function (\WP_REST_Request $request) {
                $product_id = $request->get_param('product_id');
                $custom_amount = $request->get_param('custom_amount');

                if (empty($product_id) || empty($custom_amount)) {
                    return new \WP_Error(
                        'missing_parameters',
                        __('Missing required parameters: product_id or custom_amount.', 'link-nacional-wp-crowdfunding-extension'),
                        ['status' => 400]
                    );
                }

                return true;
            },
        ]);

        register_rest_route('lknwpcrowdfunding/v1', '/favorite-campaign', [
            'methods' => 'POST',
            'callback' => array($this, 'favorite_campaign_custom_value'),
            'permission_callback' => function (\WP_REST_Request $request) {
                $user_id = $request->get_param('user_id');
                $product_id = $request->get_param('product_id');
                $action = $request->get_param('action');

                // Verifica se os parâmetros obrigatórios estão presentes
                if (empty($user_id) || empty($product_id) || empty($action)) {
                    return new \WP_Error(
                        'missing_parameters',
                        __('Missing required parameters: user_id, product_id, or action.', 'link-nacional-wp-crowdfunding-extension'),
                        ['status' => 400]
                    );
                }

                return true; // Permite o acesso se os parâmetros estiverem presentes
            },
        ]);
    }

    public function favorite_campaign_custom_value(\WP_REST_Request $request)
    {
        // Obtém os dados da requisição via parâmetros de rota
        $user_id = $request->get_param('user_id');
        $campaign_id = $request->get_param('product_id');
        $action = $request->get_param('action');

        // Verifica se o user_id foi passado corretamente
        if (!$user_id) {
            wp_send_json_error(array('message' => __('Invalid user ID', 'link-nacional-wp-crowdfunding-extension')));
        }

        // Verifica se o campaign_id foi passado corretamente
        if (!$campaign_id) {
            wp_send_json_error(array('message' => __('Invalid product ID', 'link-nacional-wp-crowdfunding-extension')));
        }

        // Recupera as campanhas favoritas do usuário
        $loved_campaign_ids = get_user_meta($user_id, 'loved_campaign_ids', true); // Agora usa o user_id passado

        // Verifica se as campanhas favoritas existem e, se não, inicializa um array vazio
        if (empty($loved_campaign_ids)) {
            $loved_campaign_ids = [];
        } else {
            $loved_campaign_ids = json_decode($loved_campaign_ids, true); // Decodifica se já existir
            // Se não for um array válido, inicializa um novo array
            if (!is_array($loved_campaign_ids)) {
                $loved_campaign_ids = [];
            }
        }

        // Adicionar ou remover a campanha dependendo da ação
        if ($action === 'add' && !in_array($campaign_id, $loved_campaign_ids)) {
            // Adiciona a campanha ao array
            $loved_campaign_ids[] = $campaign_id;
            update_user_meta($user_id, 'loved_campaign_ids', wp_json_encode($loved_campaign_ids)); // Agora usa o user_id passado
            wp_send_json_success(array('message' => __('active', 'link-nacional-wp-crowdfunding-extension')));
        }

        if ($action === 'remove' && in_array($campaign_id, $loved_campaign_ids)) {
            // Remove a campanha do array
            $loved_campaign_ids = array_diff($loved_campaign_ids, [$campaign_id]);
            update_user_meta($user_id, 'loved_campaign_ids', wp_json_encode($loved_campaign_ids)); // Agora usa o user_id passado
            wp_send_json_success(array('message' => __('remove', 'link-nacional-wp-crowdfunding-extension')));
        }

        wp_send_json_error(array('message' => __('Invalid', 'link-nacional-wp-crowdfunding-extension')));
    }

    public function customize_price_in_cart($cart_object)
    {
        foreach ($cart_object->get_cart() as $item) {

            if (array_key_exists('custom_product_price', $item)) {
                $item[ 'data' ]->set_price($item['custom_product_price']);
            }

        }
    }

    public function add_to_cart_with_custom_value(\WP_REST_Request $request)
    {
        // Obtém os parâmetros da requisição
        $product_id = intval($request->get_param('product_id'));
        $custom_price = floatval($request->get_param('custom_amount'));

        // Verifica se WooCommerce está ativo
        if (!class_exists('WooCommerce')) {
            return new \WP_REST_Response(['error' => 'WooCommerce não está ativado'], 500);
        }

        if (WC()->cart === null) {
            wc_load_cart();
        }

        // Inicializa o carrinho
        if (WC()->cart) {
            // Limpa o carrinho para adicionar apenas um item
            WC()->cart->empty_cart();

            // Obtém uma instância do produto
            $product = wc_get_product($product_id);

            if (!$product) {
                return new \WP_REST_Response(['error' => 'Produto não encontrado.'], 404);
            }

            // Adiciona o produto ao carrinho com o preço customizado
            $added = WC()->cart->add_to_cart($product_id, 1, 0, array(), array('custom_product_price' => $custom_price));

            if ($added) {
                return new \WP_REST_Response([
                    'success' => true,
                    'message' => 'Pedido adicionado com sucesso!'
                ], 200);

            } else {
                return new \WP_REST_Response(['error' => 'Erro ao adicionar o produto ao carrinho.'], 500);
            }
        } else {
            return new \WP_REST_Response(['error' => 'Carrinho não inicializado.'], 500);
        }
    }



    public function lkn_handle_verification_email_route($request): mixed
    {
        $token = sanitize_text_field($request->get_param('token'));
        $nonce = $request->get_param('nonce');

        if (! wp_verify_nonce($nonce, 'lkn_registration_nonce')) {
            return new \WP_REST_Response(array(
                'success' => false,
                'message' => __('Invalid nonce', 'link-nacional-wp-crowdfunding-extension')
            ), 403);
        }

        // Recupera os dados do token do banco de dados
        $user_token_serialized = get_option('lkn_custom_email_verification_' . $token);
        $user_token = maybe_unserialize($user_token_serialized);

        delete_option('lkn_custom_email_verification_' . $token);
        delete_option('lkn_send_email_verification_' . $user_token['email']);

        if ($user_token) {
            $username = sanitize_text_field($user_token['username']);
            $password = sanitize_text_field($user_token['password']);
            $email = sanitize_email($user_token['email']);

            $userdata = array(
                'user_login' => $username,
                'user_email' => $email,
                'user_pass' => $password,
            );

            $user_id = wp_insert_user($userdata);

            if (! is_wp_error($user_id)) {
                // Marque o usuário como verificado ou atualize outros metadados do usuário, se necessário
                update_user_meta($user_id, 'is_email_verified', true);

                // Outras ações após o registro bem-sucedido, como enviar emails adicionais, etc.
                WC()->mailer(); // Carrega as classes de email do WooCommerce, se necessário
                do_action('wpcf_after_user_registration', $user_id);
                wp_set_current_user($user_id);
                wp_set_auth_cookie($user_id);

                $saved_redirect_uri = get_option('wpcf_redurl');
                $redirect = $saved_redirect_uri ? $saved_redirect_uri : esc_url(home_url('/'));

                wp_redirect(esc_url($redirect));
                exit;
            } else {
                // Lidar com erros de registro aqui
                $lknwp_reg_errors = $user_id->get_error_message();
                // Por exemplo, retornar mensagens de erro adequadas para o cliente

                $redirect_uri = get_option('lkn_wpcf_redurl_falha_email');
                $redirect = (! empty($redirect_uri)) ? $redirect_uri : esc_url(site_url());

                die(wp_json_encode(array(
                    'success' => 0,
                    'message' => $lknwp_reg_errors,
                    'redirect' => $redirect
                )));
            }
        } else {
            //Email ainda não foi validado!
            $redirect_uri = get_option('lkn_wpcf_redurl_envio_email');
            $redirect = (! empty($redirect_uri)) ? $redirect_uri : esc_url(site_url());
            wp_redirect($redirect);
            exit;
        }
    }

    /**
     * Run the loader to execute all of the hooks with WordPress.
     *
     * @since    1.0.0
     */
    public function run(): void
    {
        $this->loader->run();
    }

    /**
     * The name of the plugin used to uniquely identify it within the context of
     * WordPress and to define internationalization functionality.
     *
     * @since     1.0.0
     * @return    string    The name of the plugin.
     */
    public function get_plugin_name()
    {
        return $this->plugin_name;
    }

    /**
     * The reference to the class that orchestrates the hooks with the plugin.
     *
     * @since     1.0.0
     * @return    Lkn_Wp_Crowdfunding_Extension_Loader    Orchestrates the hooks of the plugin.
     */
    public function get_loader()
    {
        return $this->loader;
    }

    /**
     * Retrieve the version number of the plugin.
     *
     * @since     1.0.0
     * @return    string    The version number of the plugin.
     */
    public function get_version()
    {
        return $this->version;
    }
}
