<?php

/**
 * FLEX_GUTENBERG_THEME functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package FLEX_GUTENBERG_THEME
 */

if (!defined('FLEX_GUTENBERG_THEME_VERSION')) {
	// Replace the version number of the theme on each release.

	$theme_version = wp_get_theme()->get('Version');
	define('FLEX_GUTENBERG_THEME_VERSION', $theme_version);
}

if (!defined('FLEX_GUTENBERG_THEME_NAME')) {
	define('FLEX_GUTENBERG_THEME_NAME', 'FLEX_GUTENBERG_THEME_NAME');
}
define('FLEX_THEME', TRUE);
//define('FGT_WOO_SUPPORT', true);
if (defined('FGT_WOO_SUPPORT') && FGT_WOO_SUPPORT) {
	function activate_gutenberg_product($can_edit, $post_type)
	{
		if ($post_type == 'product') {
			$can_edit = TRUE;
		}
		return $can_edit;
	}
	add_filter('use_block_editor_for_post_type', 'activate_gutenberg_product', 10, 2);
}

if (!function_exists('flex_gutenberg_theme_setup')) :
	/**
	 * Sets up theme defaults and registers support for various WordPress features.
	 *
	 * Note that this function is hooked into the after_setup_theme hook, which
	 * runs before the init hook. The init hook is too late for some features, such
	 * as indicating support for post thumbnails.
	 */
	function flex_gutenberg_theme_setup()
	{
		/*
		 * Make theme available for translation.
		 * Translations can be filed in the /languages/ directory.
		 * If you're building a theme based on FLEX_GUTENBERG_THEME, use a find and replace
		 * to change 'flex_gutenberg_theme' to the name of your theme in all the template files.
		 */
		load_theme_textdomain('flex_gutenberg_theme', get_template_directory() . '/languages');

		// Add default posts and comments RSS feed links to head.
		add_theme_support('automatic-feed-links');

		/*
		 * Let WordPress manage the document title.
		 * By adding theme support, we declare that this theme does not use a
		 * hard-coded <title> tag in the document head, and expect WordPress to
		 * provide it for us.
		 */
		add_theme_support('title-tag');

		/*
		 * Enable support for Post Thumbnails on posts and pages.
		 *
		 * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
		 */
		add_theme_support('post-thumbnails');

		// This theme uses wp_nav_menu() in one location.
		register_nav_menus(
			array(
				'menu-1' => esc_html__('Primary', 'flex_gutenberg_theme'),
			)
		);

		/*
		 * Switch default core markup for search form, comment form, and comments
		 * to output valid HTML5.
		 */
		add_theme_support(
			'html5',
			array(
				'search-form',
				'comment-form',
				'comment-list',
				'gallery',
				'caption',
				'style',
				'script',
			)
		);

		// Add theme support for selective refresh for widgets.
		add_theme_support('customize-selective-refresh-widgets');
	}
endif;
add_action('after_setup_theme', 'flex_gutenberg_theme_setup');

/**
 * Main options, served for both frontend and JS backend
 */
include dirname(__FILE__) . '/flo-app/configuration-files/configs/global-options-config.php';

/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 *
 * Priority 0 to make it available to lower priority callbacks.
 *
 * @global int $content_width
 */
function flex_gutenberg_theme_content_width()
{
	$GLOBALS['content_width'] = apply_filters('flex_gutenberg_theme_content_width', 640);
}
add_action('after_setup_theme', 'flex_gutenberg_theme_content_width', 0);

/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function flex_gutenberg_theme_widgets_init()
{
	register_sidebar(
		array(
			'name'          => esc_html__('Sidebar', 'flex_gutenberg_theme'),
			'id'            => 'sidebar-1',
			'description'   => esc_html__('Add widgets here.', 'flex_gutenberg_theme'),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		)
	);
}
add_action('widgets_init', 'flex_gutenberg_theme_widgets_init');

/**
 * Custom template tags for this theme.
 */
require get_template_directory() . '/inc/template-tags.php';

/**
 * Functions which enhance the theme by hooking into WordPress.
 */
require get_template_directory() . '/inc/template-functions.php';

/**
 * Customizer additions.
 */
require get_template_directory() . '/inc/customizer.php';

/**
 * Load Jetpack compatibility file.
 */
if (defined('JETPACK__VERSION')) {
	require get_template_directory() . '/inc/jetpack.php';
}

/**
 * Load Flo Dependency
 */
require get_template_directory() . '/flo-app/class-flo-app-loader.php';

/**
 * Load Flo Filters
 */
require get_template_directory() . '/flo-app/flo-app-filters.php';

/**
 * Load Flo Functions
 */
require get_template_directory() . '/flo-app/flo-app-functions.php';

/**
 * Uncomment filter to defer jquery. USED ONLY FOR TESTING!
 */
function defer_parsing_of_js($url)
{
	if (is_user_logged_in()) {
		return $url;
	} //don't break WP Admin
	if (FALSE === strpos($url, '.js')) {
		return $url;
	}
	if (strpos($url, 'jquery.js')) {
		return $url;
	}
	return str_replace(' src', ' defer src', $url);
}
// add_filter('script_loader_tag', 'defer_parsing_of_js', 10);


/*support for wc gallery*/
add_action('after_setup_theme', 'fgt_setup');
function fgt_setup()
{
	add_theme_support('wc-product-gallery-zoom');
	add_theme_support('wc-product-gallery-lightbox');
	add_theme_support('wc-product-gallery-slider');
}


function flo_pronto_activate($old_theme_name, $old_theme = FALSE)
{
	update_option('flo_prev_theme', $old_theme_name);
}
add_action('after_switch_theme', 'flo_pronto_activate', 10, 2);

//add_theme_support('block-templates');

/**
 * This script is used on demo.flothemes.com for stylekits preview
 * The script is initiated from within the iframe and replaces urls with corespoding ?demo_stylekit=stylekit param
 *
 */
function demo_stylekit_script()
{
	$server_name = get_home_url();

	if (
		strpos($server_name, 'demo.stage.flosites.com') !== FALSE ||
		strpos($server_name, 'demo.flothemes.com') !== FALSE
	) {
		echo '
        <script>
			   if ( window.location !== window.parent.location ) {
                const url = window.parent.location.href;
                const splitByHash = url.split(\'#\');
                if(splitByHash.length > 1) {
                    const stylekit = splitByHash[1];
                    const currentLocation = window.location;
                    if(!currentLocation.search) {
                        const newHref = currentLocation.href + "?demo_stylekit=" + stylekit.toLowerCase().replace(/ /g, \'-\');
                        window.location.replace(newHref);
                    }
                }
            }
        </script>
        ';
	}
}
add_action('wp_head', 'demo_stylekit_script');

/**
 * Function which assists SEO plugins in including images in their Sitemap XMLs
 */

  /*
 * @param string the post content
 * @return string
 */

if (function_exists('is_plugin_active')) {
	if (class_exists('RankMath') || is_plugin_active('wordpress-seo/wp-seo.php')) {
		function prepareImagesForSiteMap($content)
		{
			$blocks = parse_blocks($content);
			foreach ($blocks as $block) {
				if ($block['blockName'] === 'flo/flo-flex-builder') {
					$contentInit = flo_get_render_data_flex($block['attrs']);
					/* We need to strip out script tags, as the images are nested inside them, also, we remove
					 data- prefix as sitemaps cannot read img attributes */
					$contentInit = preg_replace('/<script.*?\>|<\/script.*?>|data\-/', '', $contentInit);
					$content .= htmlspecialchars_decode($contentInit);
				}

				/** Slide and Gallery gutenberg blocks can't be rendered, however we generate some images for Sitemap based
				* on the IMG info we get from the block attrs */

				if ($block['blockName'] === 'flo-block/slider') {
					foreach ($block['attrs']['slides'] as $slide) {
						$content .= '<img src=' . $slide['url'] . ' alt=' . $slide['alt']. ' title=' . $slide['alt'].' > ';
					}
				}
				if ($block['blockName'] === 'flo-block/gallery') {
					foreach ($block['attrs']['images'] as $image) {
						$content .= '<img src=' . $image['url'] . ' alt=' . $image['alt']. ' title=' . $image['caption'].' > ';
					}
				} else {
					// adding an else as XML file tends to get errors with no else statement
				}
			}
			return $content;
		}

		/* For RankMath */
		add_filter('rank_math/sitemap/content_before_parse_html_images', 'prepareImagesForSiteMap');
		/* For Yoast */
		add_filter('wpseo_sitemap_content_before_parse_html_images', 'prepareImagesForSiteMap');
	}
}
