<?php

/**
 * The file that defines the core plugin class
 *
 * A class definition that includes attributes and functions used across both the
 * public-facing side of the site and the admin area.
 *
 * @link       https://envytheme.com
 * @since      1.0.5
 *
 * @package    Endless_Addons
 * @subpackage Endless_Addons/includes
 */

/**
 * The core plugin class.
 *
 * This is used to define internationalization, admin-specific hooks, and
 * public-facing site hooks.
 *
 * Also maintains the unique identifier of this plugin as well as the current
 * version of the plugin.
 *
 * @since      1.0.5
 * @package    Endless_Addons
 * @subpackage Endless_Addons/includes
 * @author     EnvyTheme <hello@envytheme.com>
 */
class Endless_Addons {

	/**
	 * The loader that's responsible for maintaining and registering all hooks that power
	 * the plugin.
	 *
	 * @since    1.0.5
	 * @access   protected
	 * @var      Endless_Addons_Loader    $loader    Maintains and registers all hooks for the plugin.
	 */
	protected $loader;

	/**
	 * The unique identifier of this plugin.
	 *
	 * @since    1.0.5
	 * @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.5
	 * @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.5
	 */
	public function __construct() {
		if ( defined( 'ENDLESS_ADDONS_VERSION' ) ) {
			$this->version = ENDLESS_ADDONS_VERSION;
		} else {
			$this->version = '1.0.5';
		}
		$this->plugin_name = 'endless-addons';

		$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:
	 *
	 * - Endless_Addons_Loader. Orchestrates the hooks of the plugin.
	 * - Endless_Addons_i18n. Defines internationalization functionality.
	 * - Endless_Addons_Admin. Defines all hooks for the admin area.
	 * - Endless_Addons_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.5
	 * @access   private
	 */
	private function load_dependencies() {

		/**
		 * The class responsible for orchestrating the actions and filters of the
		 * core plugin.
		 */
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-endless-addons-loader.php';

		/**
		 * The class responsible for defining internationalization functionality
		 * of the plugin.
		 */
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-endless-addons-i18n.php';

		/**
		 * The class responsible for defining all actions that occur in the admin area.
		 */
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/class-endless-addons-admin.php';

		/**
		 * The class responsible for defining all actions that occur in the public-facing
		 * side of the site.
		 */
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'public/class-endless-addons-public.php';

		/**
		 * The class responsible for endless addons elementor custom icons        * functionality of the plugin.
		 */
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-endless-addons-icons.php';

		/**
		 * The class responsible for endless addons options functionality of the plugin.
		 */
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-endless-addons-options.php';

		/**
		 * The class responsible for endless addons asset load functionality of the plugin.
		 */
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-endless-addons-asset-load.php';

		/**
		 * The class responsible for endless addons menu functionality of the plugin.
		 */
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-endless-addons-navwalker.php';

		$this->loader = new Endless_Addons_Loader();

	}

	/**
	 * Define the locale for this plugin for internationalization.
	 *
	 * Uses the Endless_Addons_i18n class in order to set the domain and to register the hook
	 * with WordPress.
	 *
	 * @since    1.0.5
	 * @access   private
	 */
	private function set_locale() {

		$plugin_i18n = new Endless_Addons_i18n();

		$this->loader->add_action( 'plugins_loaded', $plugin_i18n, 'load_plugin_textdomain' );

	}

	/**
	 * Register all of the hooks related to the admin area functionality
	 * of the plugin.
	 *
	 * @since    1.0.5
	 * @access   private
	 */
	private function define_admin_hooks() {

		$plugin_admin = new Endless_Addons_Admin( $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' );

	}

	/**
	 * Register all of the hooks related to the public-facing functionality
	 * of the plugin.
	 *
	 * @since    1.0.5
	 * @access   private
	 */
	private function define_public_hooks() {

		$plugin_public = new Endless_Addons_Public( $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' );

	}

	/**
	 * Run the loader to execute all of the hooks with WordPress.
	 *
	 * @since    1.0.5
	 */
	public function run() {
		$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.5
	 * @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.5
	 * @return    Endless_Addons_Loader    Orchestrates the hooks of the plugin.
	 */
	public function get_loader() {
		return $this->loader;
	}

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

}

/**
 * Endless Addons JS Load
 */

if  ( ! function_exists( 'endless_addons_scripts' ) ) :

	function endless_addons_scripts() {

		$theme = wp_get_theme(); // gets the current theme
		if ( 'Xenax' == $theme->name || 'Xenax' == $theme->parent_theme ) { } else {
			wp_enqueue_script( 'endless-addons-bootstrap', plugin_dir_url( __FILE__ ) . '../public/js/bootstrap.bundle.min.js', array( 'jquery' ), false );
			wp_enqueue_script( 'endless-addons-magnific-popup', plugin_dir_url( __FILE__ ) . '../public/js/magnific-popup.min.js', array( 'jquery' ), false );
			wp_enqueue_script( 'endless-addons-meanmenu', plugin_dir_url( __FILE__ ) . '../public/js/meanmenu.min.js', array( 'jquery' ), false );
			wp_enqueue_script( 'endless-addons-owl-carousel', plugin_dir_url( __FILE__ ) . '../public/js/owl.carousel.min.js', array( 'jquery' ), false );
			wp_enqueue_script( 'endless-addons-appear', plugin_dir_url( __FILE__ ) . '../public/js/appear.min.js', array( 'jquery' ), false );
			wp_enqueue_script( 'endless-addons-ajax-chimp', plugin_dir_url( __FILE__ ) . '../public/js/jquery.ajaxchimp.min.js', array( 'jquery' ), false );
			wp_enqueue_script( 'endless-addons-odometer', plugin_dir_url( __FILE__ ) . '../public/js/odometer.min.js', array( 'jquery' ), false );
			wp_enqueue_script( 'endless-addons-aos', plugin_dir_url( __FILE__ ) . '../public/js/aos.js', array( 'jquery' ), false );
		}
		wp_enqueue_script( 'endless-addons-sidebar-menu', plugin_dir_url( __FILE__ ) . '../public/js/sidebar-menu.js', array( 'jquery' ), false );
		wp_enqueue_script( 'endless-addons-progress-bar', plugin_dir_url( __FILE__ ) . '../public/js/progressbar.min.js', array( 'jquery' ), false );
		wp_enqueue_script( 'endless-addons-anime', plugin_dir_url( __FILE__ ) . '../public/js/ea-anime.js', array( 'jquery' ), false );
		wp_enqueue_script( 'endless-addons-floating-effect', plugin_dir_url( __FILE__ ) . '../public/js/ea-floating-effect.js', array( 'jquery' ), false );

		wp_enqueue_script( 'endless-addons-calendar', plugin_dir_url( __FILE__ ) . '../public/js/calendar.js', array( 'jquery' ), false );

		wp_enqueue_script( 'endless-addons-calendar-min', plugin_dir_url( __FILE__ ) . '../public/js/calendar.min.js', array( 'jquery' ), false );
		wp_enqueue_script( 'endless-addons-main-script', plugin_dir_url( __FILE__ ) . '../public/js/main.js', array( 'jquery' ), false );
	}
	add_action('wp_footer', 'endless_addons_scripts');

endif;

// Elementor Editor CSS File
add_action( 'elementor/editor/before_enqueue_scripts', function() { wp_enqueue_style( 'endless-addons-editor', plugin_dir_url( __FILE__ ) . '../admin/css/editor.css', [ 'elementor-editor'], '1.0.5', 'all' ); } );

// Elementor Editor Font Awesome File
add_action( 'elementor/editor/before_enqueue_scripts', function() { wp_enqueue_script( 'endless-addons-font-awesome', 'https://kit.fontawesome.com/6ee3230338.js', [ 'elementor-editor'], '1.0.5', array( 'jquery' ), false ); } );


/**
 * WC Products Category List
 */

function endless_addons_get_products_cat_list() {
	include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
	if ( ! is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
		return;
	} 
	$products_category_id = get_queried_object_id();
	$endless_addons_wc_args = array(
		'parent' => $products_category_id
	);
	$endless_addons_wc_terms = get_terms( 'product_cat', get_the_ID());
	$endless_addons_cat_options = array( '' => __('Select Category', 'endless-addons') );
	if ($endless_addons_wc_terms) {
		foreach ($endless_addons_wc_terms as $term) {
			$endless_addons_cat_options[$term->name] = $term->name;
		}
	}
	return $endless_addons_cat_options;
}

/**
 * Blog Category List
 */

function endless_addons_get_blog_cat_list() {
	$blog_category_id = get_queried_object_id();
	$endless_addons_blog_args = array(
		'parent' => $blog_category_id
	);
	$endless_addons_blog_terms = get_terms( 'category', get_the_ID());
	$endless_addons_cat_options = array( '' => __('Select Category', 'endless-addons') );
	if ($endless_addons_blog_terms) {
		foreach ($endless_addons_blog_terms as $term) {
			$endless_addons_cat_options[$term->name] = $term->name;
		}
	}
	return $endless_addons_cat_options;
}

/**
 * Blog Tag List
 */

function endless_addons_get_blog_tag_list() {
	$blog_tag_id = get_queried_object_id();
	$endless_addons_blog_args = array(
		'parent' => $blog_tag_id
	);
	$endless_addons_blog_terms = get_terms( 'post_tag', get_the_ID());
	$endless_addons_tag_options = array( '' => __('Select Tag', 'endless-addons') );
	if ($endless_addons_blog_terms) {
		foreach ($endless_addons_blog_terms as $term) {
			$endless_addons_tag_options[$term->name] = $term->name;
		}
	}
	return $endless_addons_tag_options;
}

/**
 * Elementor Version Check For Icon Library
 */

function endad_is_elementor_version($operator = '<', $version = '1.0.0') {
	return defined('ELEMENTOR_VERSION') && version_compare(ELEMENTOR_VERSION, $version, $operator);
}

/**
 * Elementor Icon Library
 */

function endad_render_icon($settings = [], $old_icon_id = 'icon', $new_icon_id = 'selected_icon', $attributes = []) {
	$migrated = isset($settings['__fa4_migrated'][$new_icon_id]);
	$is_new = empty($settings[$old_icon_id]);

	$attributes['aria-hidden'] = 'true';

	if (endad_is_elementor_version('>=', '1.0.0') && ($is_new || $migrated)) {
		\Elementor\Icons_Manager::render_icon($settings[$new_icon_id], $attributes);
	} else {
		if (empty($attributes['class'])) {
			$attributes['class'] = $settings[$old_icon_id];
		} else {
			if (is_array($attributes['class'])) {
				$attributes['class'][] = $settings[$old_icon_id];
			} else {
				$attributes['class'] .= ' ' . $settings[$old_icon_id];
			}
		}
		printf('<i %s></i>', \Elementor\Utils::render_html_attributes($attributes));
	}
}

/**
 * Get the existing menus in array format
 */

function endless_addons_get_menu_array() {
    $menus = wp_get_nav_menus();
    $menu_array = [];
    foreach ( $menus as $menu ) {
        $menu_array[$menu->slug] = $menu->name;
    }
    return $menu_array;
}

// Select Page For Button Link
function endless_addons_get_page_as_list() {
    $args = wp_parse_args(array(
        'post_type' => 'page',
        'numberposts' => -1,
    ));
    $posts = get_posts($args);
    $post_options = array('' => '');
    if ($posts) {
        foreach ($posts as $post) {
            $post_options[$post->post_title] = $post->ID;
        }
    }
    $flipped = array_flip($post_options);
    return $flipped;
}

// WC Mini Cart Count
if ( ! function_exists( 'ea_wc_refresh_mini_cart_count' ) ) :
    function ea_wc_refresh_mini_cart_count($fragments){
        ob_start();
        ?>
        <span class="mini-cart-count"> 
            <?php echo esc_html(WC()->cart->get_cart_contents_count()); ?>
        </span>
        <?php
            $fragments['.mini-cart-count'] = ob_get_clean();
        return $fragments;
    }
endif;
add_filter( 'woocommerce_add_to_cart_fragments', 'ea_wc_refresh_mini_cart_count');

// Blog Post Content
function ea_blog_read_more($limit) {
  $ea_post_content = explode(' ' , get_the_content()); 
  $ea_less_content = array_slice($ea_post_content, 0, $limit);
  echo implode(' ', $ea_less_content);
}

// Contact Forms List
function endless_addons_get_wpcf7_list() {
    $options = array();
    if (function_exists('wpcf7')) {
        $wpcf7_form_list = get_posts(array(
            'post_type' => 'wpcf7_contact_form',
            'showposts' => 999,
        ));
        $options[0] = esc_html__('Select a Contact Form', 'endless-addons');
        if (!empty($wpcf7_form_list) && !is_wp_error($wpcf7_form_list)) {
            foreach ($wpcf7_form_list as $post) {
                $options[$post->ID] = $post->post_title;
            }
        } else {
            $options[0] = esc_html__('Create a Form First', 'endless-addons');
        }
    }
    return $options;
}

// WP Forms List
function endless_addons_get_wpforms_list() {
    $options = array();

    if (class_exists('\WPForms\WPForms')) {
        $args = array(
            'post_type' => 'wpforms',
            'posts_per_page' => -1,
        );

        $contact_forms = get_posts($args);

        if (!empty($contact_forms) && !is_wp_error($contact_forms)) {
            $options[0] = esc_html__('Select a WPForm', 'endless-addons');
            foreach ($contact_forms as $post) {
                $options[$post->ID] = $post->post_title;
            }
        }
    } else {
        $options[0] = esc_html__('Create a Form First', 'endless-addons');
    }

    return $options;
}

// Ninja Forms List
function endless_addons_get_ninjaforms_list() {
    $options = array();

    if (class_exists('Ninja_Forms')) {
        $contact_forms = Ninja_Forms()->form()->get_forms();

        if (!empty($contact_forms) && !is_wp_error($contact_forms)) {

            $options[0] = esc_html__('Select Ninja Form', 'endless-addons');

            foreach ($contact_forms as $form) {
                $options[$form->get_id()] = $form->get_setting('title');
            }
        }
    } else {
        $options[0] = esc_html__('Create a Form First', 'endless-addons');
    }

    return $options;
}

/**
 * Get a list of all the allowed html tags.
 */
function ea_get_allowed_html_tags($level = 'basic') {
	$allowed_html = [
		'b'      => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'i'      => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'u'      => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		's'      => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'br'     => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'em'     => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'del'    => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'ins'    => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'sub'    => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'sup'    => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'code'   => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'mark'   => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'small'  => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'strike' => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'abbr'   => [
			'title' => [],
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'span'   => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
		'strong' => [
			'class' => [],
			'id'    => [],
			'style' => [],
		],
	];

	if ('intermediate' === $level) {
		$tags = [
			'a'       => [
				'href'  => [],
				'title' => [],
				'class' => [],
				'id'    => [],
				'style' => [],
			],
			'q'       => [
				'cite'  => [],
				'class' => [],
				'id'    => [],
				'style' => [],
			],
			'img'     => [
				'src'    => [],
				'alt'    => [],
				'height' => [],
				'width'  => [],
				'class'  => [],
				'id'     => [],
				'style'  => [],
			],
			'dfn'     => [
				'title' => [],
				'class' => [],
				'id'    => [],
				'style' => [],
			],
			'time'    => [
				'datetime' => [],
				'class'    => [],
				'id'       => [],
				'style'    => [],
			],
			'cite'    => [
				'title' => [],
				'class' => [],
				'id'    => [],
				'style' => [],
			],
			'acronym' => [
				'title' => [],
				'class' => [],
				'id'    => [],
				'style' => [],
			],
			'hr'      => [
				'class' => [],
				'id'    => [],
				'style' => [],
			],
		];

		$allowed_html = array_merge($allowed_html, $tags);
	}

	return $allowed_html;
}

/**
 * Strip all the tags except allowed html tags
 */
function ea_kses_intermediate($string = '') {
	return wp_kses($string, ea_get_allowed_html_tags('intermediate'));
}

/**
 * Strip all the tags except allowed html tags
 */
function ea_kses_basic($string = '') {
	return wp_kses($string, ea_get_allowed_html_tags('basic'));
}

/**
 * Get all query post list
 */
function ea_get_query_post_list($post_type = 'any', $limit = -1, $search = '') {
    global $wpdb;
    $where = '';
    $data = [];

    if (-1 == $limit) {
        $limit = '';
    } elseif (0 == $limit) {
        $limit = "limit 0,1";
    } else {
        $limit = $wpdb->prepare(" limit 0,%d", esc_sql($limit));
    }

    if ('any' === $post_type) {
        $in_search_post_types = get_post_types(['exclude_from_search' => false]);
        if (empty($in_search_post_types)) {
            $where .= ' AND 1=0 ';
        } else {
            $where .= " AND {$wpdb->posts}.post_type IN ('" . join("', '",
                array_map('esc_sql', $in_search_post_types)) . "')";
        }
    } elseif (!empty($post_type)) {
        $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_type = %s", esc_sql($post_type));
    }

    if (!empty($search)) {
        $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_title LIKE %s", '%' . esc_sql($search) . '%');
    }

    $query = "select post_title,ID  from $wpdb->posts where post_status = 'publish' $where $limit";
    $results = $wpdb->get_results($query);
    if (!empty($results)) {
        foreach ($results as $row) {
            $data[$row->ID] = $row->post_title;
        }
    }
    return $data;
}

/**
 * Get all elementor page templates
 */
function ea_get_elementor_templates($type = null) {
    $options = [];

    if ($type) {
        $args = [
            'post_type' => 'elementor_library',
            'posts_per_page' => -1,
        ];
        $args['tax_query'] = [
            [
                'taxonomy' => 'elementor_library_type',
                'field' => 'slug',
                'terms' => $type,
            ],
        ];

        $page_templates = get_posts($args);

        if (!empty($page_templates) && !is_wp_error($page_templates)) {
            foreach ($page_templates as $post) {
                $options[$post->ID] = $post->post_title;
            }
        }
    } else {
        $options = ea_get_query_post_list('elementor_library');
    }

    return $options;
}
