<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @link       https://flothemes.com/
 * @since      1.0.0
 *
 * @package    Flo_Flex_Builder
 * @subpackage Flo_Flex_Builder/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the public-facing stylesheet and JavaScript.
 *
 * @package    Flo_Flex_Builder
 * @subpackage Flo_Flex_Builder/public
 * @author     Flothemes <alexb@flothemes.com>
 */
class Flo_Flex_Builder_Public
{
	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

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

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of the plugin.
	 * @param      string    $version    The version of this plugin.
	 */

	public function __construct($plugin_name, $version)
	{
		$this->plugin_name = $plugin_name;
		$this->version = $version;

		add_filter('flo_custom_blocks', function ($block) {
			$block = array_merge($block, $this->get_custom_blocks());
			return $block;
		});


		add_filter('flo_custom_blocks_plugins', function ($plugins_folders) {
			$plugins_folders[] = $this->plugin_name;
			return $plugins_folders;
		});

		// add_filter( 'flo_custom_blocks_plugins', function($plugins_folders) {
		// 	$plugins_folders[] = 'flo-pack-1';  // this is temporary only for this plugin, For new plugins use the commented code above
		// 	return $plugins_folders;
		// });

		add_action('wp_head', array($this, 'flo_flex_builder_viewport_render'), 4);
		add_filter('the_content', array($this, 'check_flex_contents'), 1);

		add_filter('acf_the_content', array($this, 'check_flex_acf_contents'), 1, 1);
		add_action('init', array($this, 'check_flex_in_options_init')); // Footer content
		add_action('wp', array($this, 'check_flex_in_global')); // Global G/P layout
		add_filter('acf/load_value/name=layout', array($this, 'check_flex_acf_contents'), 1, 1);
		add_filter('acf/load_value/name=custom_layout', array($this, 'check_flex_acf_contents'), 1, 1);
		add_filter('acf/load_value/name=flo-lyra-g_layout', array($this, 'check_flex_acf_contents'), 1, 1);
		add_filter('acf/load_value/name=flo-lyra-p_layout', array($this, 'check_flex_acf_contents'), 1, 1);
		add_filter('acf/load_value/name=blocks', array($this, 'check_flex_acf_contents'), 1, 1);

		add_filter('style_loader_tag', array($this, 'lazyload_styles'), 10, 4);
		add_action('init', array($this, 'register_scripts_and_styles'), 1);

		add_action('wp', array($this, 'check_flex_in_pronto'), 10000000);
	}

	/*
	*	Check flex in Pronto
	*/
	public function check_flex_in_pronto()
	{
		if (is_admin() || !defined('FLEX_GUTENBERG_THEME_VERSION')) {
			return;
		}

		global $fgt_header_render, $fgt_footer_render, $gut_flex_elements;

		if (!is_array($gut_flex_elements)) {
			$gut_flex_elements = array();
		}

		$parsed_blocks = [];
		if (isset($fgt_header_render)) {
			$parsed_blocks = array_merge($parsed_blocks, parse_blocks($fgt_header_render));
		}
		if (isset($fgt_footer_render)) {
			$parsed_blocks = array_merge($parsed_blocks, parse_blocks($fgt_footer_render));
		}

		$found_flex_block = FALSE;
		foreach ($parsed_blocks as $block) {
			if ($block['blockName'] === 'flo/flo-flex-builder') {
				$found_flex_block = TRUE;
				if (isset($block['attrs']['data'])) {
					$gut_flex_elements = array_merge($gut_flex_elements, $this->search_elements_in_string($block['attrs']['data']));
				}
			}
		}

		if ($found_flex_block) {
			$gut_flex_elements[] = 'flex';
			$gut_flex_elements = array_unique($gut_flex_elements);
			$this->enqueue_scripts();
		}
	}

	/*
	*	Check flex in global layout
	*/
	public function check_flex_in_global()
	{
		if (is_admin() || !class_exists('ACF') || defined('FLEX_GUTENBERG_THEME_VERSION')) {
			return;
		}

		global $post;
		global $gut_flex_elements;
		global $flo_options;

		if ($post->post_type !== 'gallery' && $post->post_type !== 'post') {
			return;
		}
		if (get_field('use_custom_layout', $post->ID)) {
			return;
		}

		if (!is_array($gut_flex_elements)) {
			$gut_flex_elements = array();
		}
		$flex_block_found = FALSE;

		$searchArr = $post->post_type === 'gallery' ? ['flo-lyra-g'] : ['flo-lyra-p'];
		$global_has_flex = get_deep_value($flo_options, $searchArr, []);

		if (isset($global_has_flex['layout']) && is_array($global_has_flex['layout'])) {
			foreach ($global_has_flex['layout'] as $key => $value) {
				if ($value['acf_fc_layout'] === 'flo_flex_builder_block') {
					$flex_block_found = TRUE;
				}
			}
		}

		// if is classic theme
		if (is_classic_theme() && is_single()) {
			// post global layout key differs in every classic theme, so we index $flo_options array till we find acf_fc_layout key
			foreach ($flo_options as $option) {
				if (is_array($option)) {
					foreach ($option as $nested_array) {
						if (is_array($nested_array)) {
							foreach ($nested_array as $value) {
								if (is_array($value) &&  isset($value['acf_fc_layout'])) {
									if ($value['acf_fc_layout'] === 'flo_flex_builder_block') {
										$flex_block_found = TRUE;
									}
								}
							}
						}
					}
				}
			}
		}

		if ($flex_block_found) {
			$gut_flex_elements[] = 'flex';
			$gut_flex_elements = array_unique($gut_flex_elements);
			$this->enqueue_scripts();
		}
	}

	/**
	 * Checking flex content in footer init
	 */
	public function check_flex_in_options_init()
	{
		if (is_admin()) {
			return;
		}

		global $gut_flex_elements;
		global $flo_options;

		if (!is_array($gut_flex_elements)) {
			$gut_flex_elements = array();
		}
		$flex_block_found = FALSE;

		$footer_has_flex = get_deep_value($flo_options, ['flo-lyra-footer__areas-order'], []);
		if (!in_array('flex__footer', $footer_has_flex)) {
			return;
		}

		$footer_flex = get_deep_value($flo_options, ['flex__footer', 'flo_flex_builder_obj']);

		if ($footer_flex) {
			$flex_block_found = TRUE;
			$gut_flex_elements = array_merge($gut_flex_elements, $this->search_elements_in_string($footer_flex));
		}

		if ($flex_block_found) {
			$gut_flex_elements[] = 'flex';
			$gut_flex_elements = array_unique($gut_flex_elements);
			$this->enqueue_scripts();
		}
	}

	/**
	 * Filter 'the_content' used to scan for FlexBuilder blocks (Gutemberg blocks)
	 * and inner elements. Considering results, some scripts may or may not be injected.
	 * It's a replacement for wp_scripts action.
	 */
	public function check_flex_contents($content)
	{
		if (is_admin()) {
			return $content;
		}

		global $gut_flex_elements;
		if (!is_array($gut_flex_elements)) {
			$gut_flex_elements = array();
		}

		$parsed_blocks = parse_blocks($content);
		$found_flex_block = FALSE;
		foreach ($parsed_blocks as $block) {
			if ($block['blockName'] === 'flo/flo-flex-builder') {
				$found_flex_block = TRUE;
				if (isset($block['attrs']['data'])) {
					$gut_flex_elements = array_merge($gut_flex_elements, $this->search_elements_in_string($block['attrs']['data']));
				}
			}
		}

		if ($found_flex_block) {
			$gut_flex_elements[] = 'flex';
			$gut_flex_elements = array_unique($gut_flex_elements);
			$this->enqueue_scripts();
		}
		return $content;
	}

	/**
	 * Filter 'acf/load_value/name=layout' used to scan for FlexBuilder blocks
	 * and inner elements. Considering results, some scripts may or may not be injected.
	 * It's a replacement for wp_scripts action.
	 */
	public function check_flex_acf_contents($acf_contents)
	{
		if (is_admin()) {
			return $acf_contents;
		}

		global $gut_flex_elements;
		if (!is_array($gut_flex_elements)) {
			$gut_flex_elements = array();
		}

		$flex_block_found = FALSE;

		if (is_array($acf_contents)) {
			foreach ($acf_contents as $block) {
				if (isset($block['acf_fc_layout']) && $block['acf_fc_layout'] === 'flo_flex_builder_block') {
					$block_contents = var_export($block, TRUE);
					$flex_block_found = TRUE;
					$gut_flex_elements = array_merge($gut_flex_elements, $this->search_elements_in_string($block_contents));
				}
			}
		}

		if ($flex_block_found) {
			$gut_flex_elements[] = 'flex';
			$gut_flex_elements = array_unique($gut_flex_elements);
			$this->enqueue_scripts();
		}
		return $acf_contents;
	}

	public function register_scripts_and_styles()
	{
		if (is_admin()) {
			return;
		}
		wp_register_style("flo-flex-builder", FALSE);
	}

	/**
	 * Register the stylesheets for the public-facing side of the site.
	 * ATTENTION: Script enqueuing was moved from wp_script to the_content and acf_the_content filters!!!
	 * @since    1.0.0
	 */
	public function enqueue_styles()
	{
		$script_version = $this->version;

		global $gut_flex_elements;

		// if (defined('FLO_ENVIROMENT') && FLO_ENVIROMENT == 'DEV') {
		// 	$script_version = mt_rand(0, 99999);
		// }

		// This one is printed inline
		// wp_enqueue_style('flex-' . $this->plugin_name, plugin_dir_url(dirname(__FILE__)) . 'dist/public.css', [], $script_version, 'all');
		wp_enqueue_style($this->plugin_name . '-icons', plugin_dir_url(dirname(__FILE__)) . 'public/static/icons/style.css', [], $script_version, 'all');

		// wp_add_inline_style("flo-flex-builder", file_get_contents(plugin_dir_path(__DIR__) . 'public/dev/icons/style.css'));

		if (is_array($gut_flex_elements)) {
			if (array_search('default Gfonts', $gut_flex_elements) !== FALSE) {
				wp_enqueue_style($this->plugin_name . "-google-fonts", "https://fonts.googleapis.com/css?family=Cormorant+Garamond:700|Montserrat|Nunito+Sans|Pinyon+Script|Raleway", [], $ver = NULL, 'all');
			}
		}
	}

	public function lazyload_styles($html, $handle, $href, $media)
	{
		$styles_to_optimize = [
			// 'flo-flex-builder',
			// 'flo-flex-builder-icons',
			'flo-flex-stylekits-google-fonts',
			'flo-flex-builder-google-fonts',
			'vendor-css',
			'core-icons',
			'wp-block-library',
			'flo-instagram',
			'default_stylesheet',
			'fancybox-css',
			'flo-slick-css',

			// Gutemberg Blocks
			// 'flo-slider-gallery-block',

			// // the styles below cannot be lazyloaded as this causes ugly appearance before full page load
			// 'theme-css',
			// 'flo-flex-stylekits',
		];

		if (in_array($handle, $styles_to_optimize)) {
			$html = str_replace("media='" . $media . "'", "media='none'", $html);
			$html = str_replace("id='" . $handle . "-css'", "id='" . $handle . "-css' onload=\"if(media!='all')media='all'\"", $html);
		}

		return $html;
	}

	public function search_elements_in_string($string_content)
	{
		$elements_found = array();

		// default Google Fonts
		$default_fonts =  [
			"Cormorant Garamond",
			"Montserrat",
			"Nunito Sans",
			"Pinyon Script",
			"Raleway"
		];

		foreach ($default_fonts as $font) {
			if (strpos($string_content, $font) > 0) {
				$elements_found[] = 'default Gfonts';
				break;
			}
		}

		if (strpos($string_content, '"type":"video"') > 0) {
			// $elements_found[] = 'video';

			if (strpos($string_content, '"videoPopup":true')) {
				$elements_found[] = 'video-popup';
			}
		}
		if (strpos($string_content, '"type":"countdown"') > 0) {
			$elements_found[] = 'countdown';
		}

		if (strpos($string_content, '"type":"tabs"') > 0) {
			$elements_found[] = 'tabs';
		}

		if (strpos($string_content, '"type":"tabs2"') > 0) {
			$elements_found[] = 'tabs2';
		}

		if (strpos($string_content, '"type":"tabs2Slideshow"') > 0) {
			$elements_found[] = 'tabs2Slideshow';
		}

		if (strpos($string_content, '"type":"search"') > 0) {
			$elements_found[] = 'search';
		}
		if (strpos($string_content, '"useFancybox":true')) {
			$elements_found[] = 'image-fancybox';
		}

		return $elements_found;
	}


	/**
	 * Looks for FLO_THEME_SUPPORTS const for specific strings
	 */
	public function this_flotheme_supports($support_key)
	{
		return defined("FLO_THEME_SUPPORTS") && strpos(FLO_THEME_SUPPORTS, $support_key) !== FALSE;
	}

	/**
	 * Register the JavaScript for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts()
	{
		$script_version = $this->version;

		// if (defined('FLO_ENVIROMENT') && FLO_ENVIROMENT == 'DEV') {
		// 	$script_version = mt_rand(0, 99999);
		// }

		global $gut_flex_elements;
		if (!is_array($gut_flex_elements)) {
			$gut_flex_elements = array();
		}

		if (array_search('search', $gut_flex_elements) !== FALSE) {
			wp_enqueue_script('jquery-ui-autocomplete');
		}

		if (count($gut_flex_elements)) {
			wp_enqueue_script($this->plugin_name, plugin_dir_url(dirname(__FILE__)) . 'dist/flex-public.min.js', ['jquery'], $script_version, TRUE);

			// wp_add_inline_style("flo-flex-builder", file_get_contents(plugin_dir_path(__DIR__) . 'dist/public.css'));
			wp_enqueue_style("flo-flex-builder");
		}
	}


	public function flo_flex_builder_viewport_render()
	{
		// global $gut_flex_elements;
		// no flex, no juice
		// if (!count($gut_flex_elements)) return;

		echo '<style class="' . $this->plugin_name . '-css">';
		// echo 'body{opacity: 0;}';
		// require plugin_dir_path(__DIR__) . 'public/dev/icons/style.css';
		require plugin_dir_path(__DIR__) . 'dist/public.css';
		echo '</style>';
		echo '<script id="flo_flex_builder_viewport_render" type="text/javascript">';
		require plugin_dir_path(__DIR__) . 'dist/flex-viewport-render.min.js';
		echo '</script>';
	}

	/**
	 *
	 * scan the blocks directory and add all the block names to an array
	 *
	 */
	public function get_custom_blocks()
	{
		//flo_custom_blocks
		$blocks_dir = plugin_dir_path(__FILE__) . 'views/blocks';
		$blocks = scandir($blocks_dir);


		$available_blocks = array();

		foreach ($blocks as $key => $file) {
			if ($file != '.' && $file != '..' && $file != '.DS_Store') {
				$available_blocks[str_replace('.blade.php', '', $file)] = get_class($this);
			}
		}

		return $available_blocks;
	}
}

// support for https://flothemes.com template
if (!function_exists('flo_data')) {
	function flo_data($data, $key, $default = FALSE)
	{
		if (isset($data[$key])) {
			return $data[$key];
		} else {
			return $default;
		}
	}
}

require_once(__DIR__ . '/get-elements.php');

/**
 * Siteground temporary lazyload fix. Delete when Siteground fixes his regex
 */
add_filter('sgo_lazy_load_exclude_classes', 'flo_exclude_images_with_specific_class');
function flo_exclude_images_with_specific_class($classes)
{
	// Add the class name that you want to exclude from lazy load.
	$classes[] = 'flex-img-tag';
	return $classes;
}
