<?php
/**
 * EnvisionBlocks Utils class.
 *
 * @link       https://deothemes.com
 * @since      1.0.0
 *
 * @package    EnvisionBlocks
 * @subpackage EnvisionBlocks/includes/
 */

namespace EnvisionBlocks;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * EnvisionBlocks Utils.
 */
class Utils {

	public static $plugin_url = 'https://envision-blocks.deothemes.com';

	/**
	* A list of safe tage for `validate_html_tag` method.
	*/
	const ALLOWED_HTML_WRAPPER_TAGS = array( 'article', 'aside', 'div', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'main', 'nav', 'p', 'section', 'span' );

	/**
	 * Get registered modules
	 */
	public static function get_registered_modules() {
		return [
			'Animated Text' => [ 'animated-text', self::$plugin_url . '/animated-text', '', '' ],
			'Before & After' => [ 'before-after', self::$plugin_url . '/before-after', '', '' ],
			'Contact Form 7' => [ 'contact-form-7', self::$plugin_url . '/contact-form-7', '', '' ],
			'Graph' => [ 'graph', self::$plugin_url . '/graph', '', '' ],
			'Google Maps' => [ 'google-maps', self::$plugin_url . '/google-maps', '', '' ],
			'Hero Slider' => [ 'hero-slider', self::$plugin_url . '/hero-slider', '', '' ],
			'Hotspot' => [ 'hotspot', self::$plugin_url . '/hotspot', '', '' ],
			'Share Buttons' => [ 'share-buttons', self::$plugin_url . '/share-buttons', '', '' ],
			'Testimonials Feed' => [ 'testimonials-feed', self::$plugin_url . '/testimonials-feed', '', '' ],
			'Marquee' => [ 'marquee', self::$plugin_url . '/marquee', '', '' ],
			'Parallax' => [ 'parallax', self::$plugin_url . '/parallax', '', '' ],
			'Posts' => [ 'posts', self::$plugin_url . '/posts', '', '' ],
			'Vertical Tabs' => [ 'vertical-tabs', self::$plugin_url . '/vertical-tabs', '', '' ],
			'Video Lightbox' => [ 'video-lightbox', self::$plugin_url . '/video-lightbox', '', '' ],
			'Mailchimp Form' => [ 'mailchimp-form', self::$plugin_url . '/mailchimp-form', '', '' ],
			'Icon Box' => [ 'icon-box', self::$plugin_url . '/icon-box', '', '' ],
		];
	}

	/**
	 * Get registered pro modules
	 */
	public static function get_registered_pro_modules() {
		return [
			'Creative Cursor' => [ 'creative-cursor', self::$plugin_url . '/creative-cursor', '', 'pro' ],
			'Creative Cards Carousel' => [ 'creative-cards-carousel', self::$plugin_url . '/creative-cards-carousel', '', 'pro' ],
			'Dark Mode' => [ 'dark-mode', self::$plugin_url . '/dark-mode', '', 'pro' ],
			'Expanding Cards' => [ 'expanding-cards', self::$plugin_url . '/expanding-cards', '', 'pro' ],
			'Interactive Quiz' => [ 'interactive-quiz', self::$plugin_url . '/interactive-quiz', '', 'pro' ],
			'Image Hover Menu' => [ 'image-hover-menu', self::$plugin_url . '/image-hover-menu', '', 'pro' ],
			'Menu Icon' => [ 'menu-icon', self::$plugin_url . '/header-builder', '', 'pro' ],
			'Menu Photo Reveal' => [ 'menu-photo-reveal', self::$plugin_url . '/menu-photo-reveal', '', 'pro' ],
			'Nav Menu' => [ 'nav-menu', self::$plugin_url . '/header-builder', '', 'pro' ],
			'Site Logo' => [ 'site-logo', self::$plugin_url . '/header-builder', '', 'pro' ],
			'Sticky Scroll Section' => [ 'sticky-scroll-section', self::$plugin_url . '/sticky-scroll-section', '', 'pro' ],
			'Offcanvas' => [ 'offcanvas', self::$plugin_url . '/offcanvas', '', 'pro' ],
			'Parallax Carousel' => [ 'parallax-carousel', self::$plugin_url . '/parallax-carousel', '', 'pro' ],
			'Portfolio' => [ 'portfolio', self::$plugin_url . '/portfolio', '', 'pro' ],
			'Table' => [ 'table', self::$plugin_url . '/table', '', 'pro' ],
			'Testimonials Slider' => [ 'testimonials-slider', self::$plugin_url . '/testimonials-slider', '', 'pro' ],
			'Post Title' => [ 'post-title', self::$plugin_url . '/portfolio/sneakers/', '', 'pro' ],
			'Post Navigation' => [ 'post-navigation', self::$plugin_url . '/portfolio/sneakers/', '', 'pro' ],
		];
	}

	/**
	** Get Enabled Modules
	*/
	public static function get_available_modules( $modules ) {
		foreach ( $modules as $title => $data ) {
			$slug = $data[0];
			if ( 'on' !== get_option( 'envision-blocks-widget-'. $slug, 'on' ) ) {
				unset( $modules[$title] );
			}
		}

		return $modules;
	}

	/**
	** Get Woo Builder Modules
	*/
	public static function get_woocommerce_builder_modules() {
		return [
			'Woo Products' => [ 'woo-products', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Categories' => [ 'woo-product-categories', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Image' => [ 'woo-product-image', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Title' => [ 'woo-product-title', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Price' => [ 'woo-product-price', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Add To Cart' => [ 'woo-product-add-to-cart', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Short Description' => [ 'woo-product-short-description', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Tabs' => [ 'woo-product-tabs', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Related' => [ 'woo-product-related', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Rating' => [ 'woo-product-rating', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Stock' => [ 'woo-product-stock', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Additional Information' => [ 'woo-product-additional-information', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Meta' => [ 'woo-product-meta', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Upsell' => [ 'woo-product-upsell', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Notices' => [ 'woo-product-notices', self::$plugin_url . '#pricing', '', 'pro' ],
			'Woo Product Breadcrumbs' => [ 'woo-product-breadcrumbs', self::$plugin_url . '#pricing', '', 'pro' ],
		];
	}

	/**
	* Get the value of a settings field
	*
	* @param string  $option  settings field name
	* @param string  $section the section name this field belongs to
	* @param string  $default default text if it's not found
	* @return string
	*/
	public static function get_option( $option, $section, $default = 0 ) {
		$options = get_option( $section );

		if ( isset( $options[$option] ) ) {
			return $options[$option];
		}

		return $default;
	}


	/**
	** Get Available Custom Post Types or Taxonomies
	*/
	public static function get_custom_types_of( $query, $exclude_defaults = true ) {
		// Taxonomies
		if ( 'tax' === $query ) {
			$custom_types = get_taxonomies( [ 'show_in_nav_menus' => true ], 'objects' );
		
		// Post Types
		} else {
			$custom_types = get_post_types( [ 'show_in_nav_menus' => true ], 'objects' );
		}

		$custom_type_list = [];

		unset( $custom_types['e-landing-page'] );

		foreach ( $custom_types as $key => $value ) {

			if ( $exclude_defaults ) {
				if ( $key != 'post' && $key != 'page' && $key != 'category' && $key != 'post_tag' ) {
					$custom_type_list[ $key ] = $value->label;
				}
			} else {
				$custom_type_list[ $key ] = $value->label;
			}
		}

		return $custom_type_list;
	}


	/**
	* Register Google Maps script.
	*
	*
	* @since 1.0.0
	* @access public
	*/
	public static function register_google_maps_script() {
	
		$google_maps_api_url = 'https://maps.googleapis.com';
		$language = '';
		$settings = self::get_integrations_options();

		if ( isset( $settings['language'] ) && '' !== $settings['language'] ) {
			$language = 'language=' . $settings['language'];

			if ( 'zh-CN' === $settings['language'] || 'zh-TW' === $settings['language'] ) {
				$google_maps_api_url = 'http://maps.googleapis.cn';
			}
		}

		if ( isset( $settings['google_maps_key'] ) && '' !== $settings['google_maps_key'] ) {
			$language = '&' . $language;
			$google_maps_url = $google_maps_api_url . '/maps/api/js?key=' . esc_html( $settings['google_maps_key'] ) . $language . '&loading=async';
		} else {
			$google_maps_url = $google_maps_api_url . '/maps/api/js?' . $language . '&loading=async';
		}

		wp_register_script( 'envision-blocks-google-maps-api', $google_maps_url, [ 'jquery' ], true );

	}

	/**
	 * Provide Integrations settings array().
	 *
	 * @param string $name slug.
	 * @return array()
	 * @since 1.0.0
	 */
	public static function get_integrations_options( $name = '' ) {

		$defaults = [
			'google_maps_key' => '',
			'language'	=> ''
		];

		$integrations = get_option( 'envision_blocks_integrations_settings' );
		$integrations = wp_parse_args( $integrations, $defaults );

		if ( '' !== $name && isset( $integrations[ $name ] ) && '' !== $integrations[ $name ] ) {
			return $integrations[ $name ];
		} else {
			return $integrations;
		}

	}


	/**
	* Validate an HTML tag against a safe allowed list.
	*
	* @since 1.0.0
	* @param string $tag specifies the HTML Tag.
	* @access public
	*/
	public static function validate_html_tag( $tag ) {

		// Check if Elementor method exists, else we will run custom validation code.
		if ( method_exists( '\Elementor\Utils', 'validate_html_tag' ) ) {
			return \Elementor\Utils::validate_html_tag( $tag );
		} else {
			return in_array( strtolower( $tag ), self::ALLOWED_HTML_WRAPPER_TAGS, true ) ? $tag : 'div';
		}
	}

	/**
	* Check if page built with Elementor
	*
	* @since  1.0.0
	*/
	public static function is_elementor_page() {
		$elementor_page = get_post_meta( get_the_ID(), '_elementor_edit_mode', true );

		if ( is_search() || is_archive() ) {
			return false;
		}		

		if ( (bool)$elementor_page ) {
			return true;
		} else {
			return false;
		}	
	}


	/**
	* Function that does escaping of specific html.
	* It uses wp_kses function with predefined attributes array.
	*
	* @see wp_kses()
	*
	* @param string $type - type of html element
	* @param string $content - string to escape
	*
	* @return string escaped output
	*/
	public static function sanitize_svg( $type, $content ) {
		switch ( $type ) {
			case 'svg':
				$atts = apply_filters(
					'envision_blocks_wp_kses_svg_atts',
					array(
						'svg'     => array(
							'xmlns'             => true,
							'version'           => true,
							'id'                => true,
							'class'             => true,
							'x'                 => true,
							'y'                 => true,
							'aria-hidden'       => true,
							'aria-labelledby'   => true,
							'role'              => true,
							'width'             => true,
							'height'            => true,
							'viewbox'           => true,
							'enable-background' => true,
							'focusable'         => true,
							'data-prefix'       => true,
							'data-icon'         => true,
						),
						'g'       => array(
							'stroke'       => true,
							'stroke-width' => true,
							'fill'         => true,
							'fill-opacity' => true,
						),
						'rect'    => array(
							'x'      => true,
							'y'      => true,
							'width'  => true,
							'height' => true,
						),
						'title'   => array(
							'title' => true,
						),
						'path'    => array(
							'd'            => true,
							'stroke'       => true,
							'stroke-width' => true,
							'fill'         => true,
							'fill-opacity' => true,
						),
						'polygon' => array(
							'points' => true,
						),
					)
				);
				break;

			default:
				return apply_filters( 'envision_blocks_wp_kses_custom', $content, $type );
				break;
		}

		return wp_kses( $content, $atts );
	}


	/**
	 * Get page ID by title
	 */
	public static function get_page_by_title( $page_title, $post_type = 'page' ) {
		$posts = get_posts(
			array(
				'post_type'              => $post_type,
				'title'                  => $page_title,
				'post_status'            => 'all',
				'numberposts'            => 1,
				'update_post_term_cache' => false,
				'update_post_meta_cache' => false,           
				'orderby'                => 'post_date ID',
				'order'                  => 'ASC',
			)
		);

		if ( ! empty( $posts ) ) {
			$post = $posts[0];
		} else {
			$post = null;
		}

		return $post;
	}

}