<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @link       https://flothemes.com/plugins/
 * @since      1.0.0
 *
 * @package    Flo_Guten_Blocks
 * @subpackage Flo_Guten_Blocks/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_Guten_Blocks
 * @subpackage Flo_Guten_Blocks/public
 * @author     Flothemes <alexg@flothemes.com>
 */
class Flo_Guten_Blocks_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;
	}

	public function extend_has_block($name)
	{
		if (function_exists('flo_theme_has_block')) {
			return flo_theme_has_block($name);
		}

		return has_block($name);
	}

	/**
	 * Register the stylesheets for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles()
	{
		$font_contents = file_get_contents(
			plugin_dir_path(__DIR__) . 'src/blocks/assets/fontello/css/flo-icons.css'
		);
		$plugin_url = plugin_dir_url(__FILE__);

		$font_contents = str_replace(
			'../font/flo-icons',
			$plugin_url . '../src/blocks/assets/fontello/font/flo-icons',
			$font_contents
		);

		wp_add_inline_style('flo-gutenberg-blocks-style', $font_contents);

		// wp_enqueue_style(
		// 	'flo-fontello',
		// 	plugin_dir_url(__FILE__) .
		// 		'../src/blocks/assets/fontello/css/flo-icons.css',
		// 	[],
		// 	false
		// );

		wp_enqueue_style('flo-gutenberg-blocks-style');

		add_filter(
			'style_loader_tag',
			function ($html, $handle, $href, $media) {
				if (is_admin()) {
					return $html;
				}

				if ($handle==='flo-gutenberg-blocks-style') {
					$html = <<<EOT
		<link rel='preload' as='style' onload="this.onload=null;this.rel='stylesheet'" id='$handle' href='$href' type='text/css' media='all' />
EOT;
					return $html;
				} else {
					return $html;
				}
			},
			10,
			4
		);

		// enqueue Slider block scripts
		/*if ($this->extend_has_block('flo-block/slider') || flo_has_reusable_block('flo-block/slider')) {
			wp_enqueue_style('flo-fancyb', plugin_dir_url(__FILE__) . '../src/blocks/assets/jquery.fancybox.min.css', array(), false);
			wp_enqueue_style('flo-fontello', plugin_dir_url(__FILE__) . '../src/blocks/assets/fontello/css/flo-icons.css', array(), false);
		}

		// enqueue Gallery block scripts
		if ($this->extend_has_block('flo-block/gallery') || flo_has_reusable_block('flo-block/gallery') || get_post_type() === 'gallery') {
			wp_enqueue_style('flo-fontello', plugin_dir_url(__FILE__) . '../src/blocks/assets/fontello/css/flo-icons.css', array(), false);
			wp_enqueue_style('flo-fancyb', plugin_dir_url(__FILE__) . '../src/blocks/assets/jquery.fancybox.min.css', array(), false);
		}

		if ($this->extend_has_block('flo-block/testimonials')) {
			wp_enqueue_style('flo-fontello', plugin_dir_url(__FILE__) . '../src/blocks/assets/fontello/css/flo-icons.css', array(), false);
		}
		*/
	}

	/**
	 * Register the JavaScript for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	/*	public function enqueue_scripts() {

		// enqueue Slider block scripts



		if ($this->extend_has_block('flo-block/slider') || flo_has_reusable_block('flo-block/slider')) {
			wp_enqueue_script(
				'flo-frontend-scripts'
			);
		}

		// enqueue Gallery block scripts
		if ($this->extend_has_block('flo-block/gallery') || flo_has_reusable_block('flo-block/gallery') || get_post_type() === 'gallery') {
			//wp_enqueue_script('slick-slider-load-frontend');
			wp_enqueue_script('flo-frontend-scripts');
		}

		// enqueue Slider block scripts
		if ($this->extend_has_block('flo-block/faq2') || $this->extend_has_block('flo-block/faq1') || $this->extend_has_block('flo-block/post-list')  || $this->extend_has_block('flo-block/post-grid') || $this->extend_has_block('flo-block/post-cards') || $this->extend_has_block('flo-block/related-items') || $this->extend_has_block('flo-block/comments') || $this->extend_has_block('flo-block/testimonials') || $this->extend_has_block('flo-block/title-block')) {
			wp_enqueue_script(
				'flo-frontend-scripts'
			);
		}
	}
*/
	/**
	 * Registers all block assets so that they can be enqueued through the block editor
	 * in the corresponding context.
	 *
	 * @see https://developer.wordpress.org/block-editor/tutorials/block-tutorial/applying-styles-with-stylesheets/
	 */
	public function flo_guten_blocks_init()
	{
		$dir = dirname(__FILE__);

		$script_asset_path = "$dir/../build/index.asset.php";
		$front_script_asset_path = "$dir/../build/frontend.asset.php";

		if (
			!file_exists($script_asset_path) ||
			!file_exists($front_script_asset_path)
		) {
			throw new Error(
				'You need to run `npm start` or `npm run build` for the "create-block/flo-blocks" first.'
			);
		}

		$index_js = 'build/index.js';
		$script_asset = require $script_asset_path;
		//$front_asset = require($front_script_asset_path);

		if (isset($script_asset['dependencies'])) {
			// $script_asset (index.asset.php) is being regenerated each time the build scripts are started, therefore we can not add new dependencies in index.asset.php
			// We add our own depandencies by merging the existing with what we need:
			$flo_slideshow_dependencies = [
				'lodash',
				'flo-slick-js',
				'jquery-ui-sortable',
				'media-editor',
			];
			$script_asset['dependencies'] = array_merge(
				$script_asset['dependencies'],
				$flo_slideshow_dependencies
			);
		}

		/*if (isset($front_asset['dependencies'])) {

			$flo_front_dependencies = array('fancybox-js', 'flo-slick-js');
			$front_asset['dependencies'] = $flo_front_dependencies;
		}*/

		wp_register_script(
			'flo-slick-js',
			plugins_url('../src/blocks/slider-block/slick.min.js', __FILE__),
			['jquery'],
			$this->version,
			TRUE
		);
		wp_register_script(
			'fancybox-js',
			plugin_dir_url(__FILE__) . '../src/blocks/assets/flo-fb.js',
			['jquery'],
			'3.5.7',
			TRUE
		);

		wp_register_script(
			'flo-frontend-scripts',
			plugins_url('../build/frontend.js', __FILE__),
			['jquery'],
			$this->version,
			TRUE
		);

		wp_register_script(
			'flo-slider-gallery-block-editor',
			plugins_url('../' . $index_js, __FILE__),
			$script_asset['dependencies'],
			$script_asset['version']
		);

		$editor_css = 'build/index.css';
		wp_register_style(
			'flo-slider-gallery-block-editor',
			plugins_url('../' . $editor_css, __FILE__),
			[],
			$this->version
		);

		$style_css = 'build/style-index.css';
		wp_register_style(
			'flo-gutenberg-blocks-style',
			plugins_url('../' . $style_css, __FILE__),
			[],
			$this->version
		);

		/*========== GALLERY ==========*/
		include_once 'partials/gallery-block/default-gallery-attributes.php';
		include_once 'partials/gallery-block/block-gallery-frontend-render.php'; // makes $default_attributes available

		register_block_type('flo-block/gallery', [
			'editor_script' => 'flo-slider-gallery-block-editor',
			'editor_style' => 'flo-slider-gallery-block-editor',

			// some attributes are not being passed properly, therefore we have to redeclare them here (:
			'attributes' => $default_gallery_attributes,
			'render_callback' => 'flo_gallery_render_frontend',
		]);

		/*========== RELATED ITEMS ==========*/
		include_once 'partials/related-items-block/default-related-items-attributes.php';
		include_once 'partials/related-items-block/block-related-items-frontend-render.php'; // makes $default_attributes available
		register_block_type('flo-block/related-items', [
			// some attributes are not being passed properly, therefore we have to redeclare them here (:
			'attributes' => $default_related_items_atributes,
			'render_callback' => 'flo_related_items_frontend',
		]);

		/*========== CATEGORY SWITCHER ==========*/
		include_once 'partials/category-switcher/default-categories-attributes.php';
		include_once 'partials/category-switcher/block-categories-frontend-render.php'; // makes $default_attributes available

		register_block_type('flo-block/category-switcher', [
			// some attributes are not being passed properly, therefore we have to redeclare them here (:
			'attributes' => $default_categories_attributes,
			'render_callback' => 'flo_categories_render_frontend_block',
		]);

		/*========== BLOCK TITLE ==========*/
		include_once 'partials/title-block/default-title-attributes.php';
		include_once 'partials/title-block/block-title-frontend-render.php'; // makes $default_attributes available

		register_block_type('flo-block/title-block', [
			// some attributes are not being passed properly, therefore we have to redeclare them here (:
			'attributes' => $default_title_attributes,
			'render_callback' => 'flo_title_render_frontend_block',
		]);

		/*========== BLOCK COMMENTS ==========*/
		include_once 'partials/comments/default-comments-attributes.php';
		include_once 'partials/comments/block-comments-frontend-render.php'; // makes $default_attributes available

		register_block_type('flo-block/comments', [
			// some attributes are not being passed properly, therefore we have to redeclare them here (:
			'attributes' => $default_comments_attributes,
			'render_callback' => 'flo_comments_render_frontend_block',
		]);

		/*========== BLOCK FORM ==========*/
		include_once 'partials/form-block/default-form-attributes.php';
		include_once 'partials/form-block/block-form-frontend-render.php'; // makes $default_attributes available

		register_block_type('flo-block/form-block', [
			// some attributes are not being passed properly, therefore we have to redeclare them here (:
			'attributes' => $default_form_attributes,
			'render_callback' => 'flo_form_render_frontend_block',
		]);

		/*========== SLIDER ==========*/
		include_once 'partials/slider-block/default-slider-attributes.php';
		include_once 'partials/slider-block/block-slider-frontend-render.php';

		register_block_type('flo-block/slider', [
			'editor_script' => 'flo-slider-gallery-block-editor',
			'editor_style' => 'flo-slider-gallery-block-editor',

			'attributes' => $default_slider_attributes,
			'render_callback' => 'flo_slider_block_render_frontend_block',
		]);

		/*========== BLOCK button ==========*/
		include_once 'partials/button-block/button-block-frontend-render.php';
		include_once 'partials/button-block/default-button-block-attributes.php'; // makes $default_attributes available

		register_block_type('flo-block/button-block', [
			// some attributes are not being passed properly, therefore we have to redeclare them here (:
			'attributes' => $default_button_attributes,
			'render_callback' => 'flo_button_block_frontend_render',
		]);

		/*========== ITEM PAGINATION  ==========*/
		include_once 'partials/item-pagination/default-items-pagination-attributes.php';
		include_once 'partials/item-pagination/block-items-pagination-frontend-render.php'; // makes $default_attributes available
		register_block_type('flo-block/item-pagination', [
					// some attributes are not being passed properly, therefore we have to redeclare them here (:
					'attributes' => $default_item_pagination_attributes,
					'render_callback' => 'flo_items_pagination_frontend',
				]);
	}

	/**
	 * calculate the mobile crop position to be applied in the front end
	 * @param float - the numeric percentage value which  represents the left hand side displacement from the middle of the crop (focus) area
	 * @return string - the percentage  value to be used in CSS to arrange the  image using 'object-position'
	 */
	public static function get_mobile_crop_position($imagePositionMobile)
	{
		if ($imagePositionMobile) {
			// the background position is calculated using the following formula:
			// y = 1.8x - 40
			// http://www.wolframalpha.com/input/?i=interpolate+%5B(22.22,+0),(77.77,100)+%5D

			$result = 1.8 * $imagePositionMobile;
			if ($result < 40) {
				$mobile_crop_position = $result < 40 ? '0%' : $result - 40 . '%';
			} else {
				$mobile_crop_position = $result > 140 ? '100%' : $result - 40 . '%';
			}
		} else {
			$mobile_crop_position = '50%';
		}

		return $mobile_crop_position;
	}

	/**
	 * build the overlay gradient styles based on the slide settings or general settings
	 * @param string $slideMediaOverlay
	 * @param string $generalMediaOverlay
	 * @return string - overlay gradient styles
	 */
	public static function get_overlay_gradient(
		$slideMediaOverlay,
		$generalMediaOverlay
	) {
		$overlayColor = '';

		// if the  individual slide has the overlay color set, it will have priority
		if (
			$slideMediaOverlay !== '' &&
			isset($slideMediaOverlay['custom']) &&
			strlen($slideMediaOverlay['custom'])
		) {
			$overlayColor = $slideMediaOverlay['custom'];
		} elseif (
			isset($generalMediaOverlay['custom']) &&
			strlen($generalMediaOverlay['custom'])
		) {
			$overlayColor = $generalMediaOverlay['custom'];
		}

		return 'linear-gradient(0deg,' .
			$overlayColor .
			' 0%, rgba(0, 0, 0, 0) 100%)';
	}

	public function the_content($content)
	{
		$blocks = parse_blocks($content);

		$depts = [];

		$depts = $this->check_block($content, $blocks, $depts);
		$depts = $this->check_reusable_block($content, $depts);

		if (is_array($depts) && !empty($depts)) {
			if (in_array('fancybox-js', $depts)) {
				wp_enqueue_script('fancybox-js');
				wp_enqueue_style(
					'flo-fancyb',
					plugin_dir_url(__FILE__) .
						'../src/blocks/assets/jquery.fancybox.min.css',
					[],
					FALSE
				);
			}

			if (in_array('comment-reply', $depts)) {
				wp_enqueue_script('comment-reply');
			}

			if (in_array('flo-slick-js', $depts)) {
				wp_enqueue_script('flo-slick-js');
			}
			if (in_array('jquery', $depts) && !is_admin()) {
				wp_enqueue_script('flo-frontend-scripts', $depts);
			}
		}

		return $content;
	}

	public function check_block($content, $blocks, $depts)
	{
		$flo_all_blocks_array = [
			'flo-block/slider',
			'flo-block/gallery',
			'flo-block/faq2',
			'flo-block/faq1',
			'flo-block/post-list',
			'flo-block/post-grid',
			'flo-block/post-cards',
			'flo-block/related-items',
			'flo-block/testimonials',
			'flo-block/title-block',
			'flo-block/comments',
			'flo-block/form-block',
			'flo-block/category-switcher',
			'gutenberg-block/child-content',
			'flo-block/button-block',
		];
		//$flo_fancy_blocks_array = ['flo-block/slider', 'flo-block/gallery'];
		$flo_slick_blocks_array = [
			'flo-block/slider',
			'flo-block/gallery',
			'flo-block/faq2',
			'flo-block/testimonials',
		];

		if (
			strpos($content, 'wp:flo-block/slider') &&
			strpos($content, '"addVideo":true')
		) {
			$depts[] = 'fancybox-js';
			$depts[] = 'jquery';
		}

		if (strpos($content, 'wp:flo-block/comments')) {
			$depts[] = 'comment-reply';
		}

		if (
			strpos($content, 'wp:flo-block/gallery') &&
			strpos($content, '"galleryType":"grid"')
		) {
			$depts[] = 'fancybox-js';
			$depts[] = 'jquery';
		}


		foreach ($blocks as $block) {

			// sometimes we need to parse the inner block which comes from Pronto child-content block
			if ($block['blockName'] == 'gutenberg-block/child-content') {
				$depts[] = 'jquery';

				$child_content = render_block($block);

				if (strpos($child_content, 'slick-slider-block-slide')) {
					// slider OR gallery block
					$depts[] = 'flo-slick-js';
				}

				if (strpos($child_content, 'flo-video-button') || strpos($child_content, 'flo-gallery-grid__image_wrap_inner')) {
					$depts[] = 'fancybox-js';
				}
			}
			if (in_array($block['blockName'], $flo_all_blocks_array)) {
				$depts[] = 'jquery';
			}

			if (in_array($block['blockName'], $flo_slick_blocks_array)) {
				if ($block['blockName'] == 'flo-block/gallery') {
					if (
						!isset($block['attrs']['galleryType']) ||
						$block['attrs']['galleryType'] != 'grid'
					) {
						$depts[] = 'flo-slick-js';
					}
				} else {
					$depts[] = 'flo-slick-js';
				}
			}
		}

		return $depts;
	}

	public function check_reusable_block($content, $depts)
	{
		$blocks = parse_blocks($content);
		if (!is_array($blocks) || empty($blocks)) {
			return;
		} else {
			foreach ($blocks as $block) {
				if (
					$block['blockName'] === 'core/block' &&
					!empty($block['attrs']['ref'])
				) {
					$content = get_post_field('post_content', $block['attrs']['ref']);
					$blocks = parse_blocks($content);
					$depts = $this->check_block($content, $blocks, $depts);
					if (is_array($blocks) || !empty($blocks)) {
						return $this->check_reusable_block($content, $depts);
					}
				}
			}
			return $depts;
		}
	}
}
