<?php
/**
 * Typer functions and definitions
 *
 * This file must be parseable by PHP 5.2.
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package typer
 */

use function Seventhqueen\Typer\typer;

define( 'TYPER_MINIMUM_WP_VERSION', '4.5' );
define( 'TYPER_MINIMUM_PHP_VERSION', '5.6' );

// Bail if requirements are not met.
if ( version_compare( $GLOBALS['wp_version'], TYPER_MINIMUM_WP_VERSION, '<' ) || version_compare( PHP_VERSION, TYPER_MINIMUM_PHP_VERSION, '<' ) ) {
	require get_template_directory() . '/inc/back-compat.php';

	return;
}

// Setup autoloader (via Composer or custom).
if ( file_exists( get_template_directory() . '/vendor/autoload.php' ) ) {
	require get_template_directory() . '/vendor/autoload.php';
} else {
	/**
	 * Custom autoloader function for theme classes.
	 *
	 * @access private
	 *
	 * @param string $class_name Class name to load.
	 *
	 * @return bool True if the class was loaded, false otherwise.
	 */
	function _typer_autoload( $class_name ) {
		$namespace = 'Seventhqueen\Typer';

		if ( strpos( $class_name, $namespace . '\\' ) !== 0 ) {
			return false;
		}

		$parts = explode( '\\', substr( $class_name, strlen( $namespace . '\\' ) ) );

		$path = get_template_directory() . '/inc';
		foreach ( $parts as $part ) {
			$path .= '/' . $part;
		}
		$path .= '.php';

		if ( ! file_exists( $path ) ) {
			return false;
		}

		require_once $path;

		return true;
	}

	spl_autoload_register( '_typer_autoload' );
}

// Load the `typer()` entry point function.
require get_template_directory() . '/inc/functions.php';

// Initialize the theme.
call_user_func( 'Seventhqueen\Typer\typer' );

if ( ! isset( $content_width ) ) {
	$content_width = 1140;
}

/**
 * Class for managing theme stylesheets and scripts.
 */
class Typer_Assets {

	/**
	 * Stores the class instance
	 *
	 * @var Typer_Assets The single instance of the class
	 * @since 1.0.0
	 */
	protected static $_instance = null;

	/**
	 * @var string
	 */
	protected $min = '';

	/**
	 * Associative array of CSS files, as $handle => $data pairs.
	 * Do not access this property directly, instead use the `get_css_files()` method.
	 *
	 * @var array
	 */
	protected $css_files;

	/**
	 * @var bool
	 */
	protected $fancy_init = false;

	/**
	 * Class Instance
	 *
	 * Ensures only one instance is loaded or can be loaded.
	 *
	 * @return Typer_Assets
	 * @since 1.0.0
	 * @static
	 */
	public static function instance() {
		if ( self::$_instance === null ) {
			self::$_instance = new self();
		}

		return self::$_instance;
	}

	/**
	 * Adds the action and filter hooks to integrate with WordPress.
	 */
	private function __construct() {
		if ( typer()->get_option( 'dev_mode', false ) === false ) {
			$this->min = '.min';
		}

		add_action( 'wp_enqueue_scripts', [ $this, 'action_enqueue_styles' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'action_enqueue_scripts' ], 11 );
		add_action( 'admin_enqueue_scripts', [ $this, 'action_enqueue_admin_styles' ] );

		if ( typer()->get_option( 'css_preload', 1 ) ) {
			add_action( 'wp_head', [ $this, 'action_preload_styles' ] );
		}

		add_action( 'wp_body_open', [ $this, 'enqueue_single_post' ] );

		add_filter( 'the_content', [ $this, 'add_article_tags' ] );
		add_filter( 'the_password_form', [ $this, 'alter_password_form_btn' ] );
		add_filter( 'the_content', [ $this, 'add_fancybox_to_images' ], 10, 1 );
	}

	/**
	 * Enqueue single posts Javascript files
	 */
	public function enqueue_single_post() {
		if ( is_single() || is_singular( 'page' ) ) {

			// When using Gutenberg
			if ( function_exists( 'has_blocks' ) && has_blocks( get_the_ID() ) ) {
				$this->enqueue_prettify();
			}

			$this->enqueue_hc_sticky();
			$this->enqueue_fancybox();
			$this->enqueue_plyr();
		}
	}

	/**
	 * Registers or enqueues scripts.
	 */
	public function action_enqueue_scripts() {
		/* Footer scripts */

		wp_register_script(
			'modernizr',
			get_theme_file_uri( 'assets/js/modernizr-custom' . $this->min . '.js' ),
			[],
			typer()->get_version(),
			true
		);

		wp_register_script(
			'jrespond',
			get_theme_file_uri( 'assets/js/jrespond' . $this->min . '.js' ),
			[ 'jquery' ],
			typer()->get_version(),
			true
		);

		wp_register_script(
			'popper',
			get_theme_file_uri( 'assets/js/popper/popper' . $this->min . '.js' ),
			[ 'jquery' ],
			typer()->get_version(),
			true
		);

		wp_register_script(
			'code-prettify',
			get_theme_file_uri( 'assets/js/code-prettify/prettify' . $this->min . '.js' ),
			[],
			typer()->get_version(),
			true
		);

		wp_register_script(
			'objectfit-pollyfill',
			get_theme_file_uri( 'assets/js/object-fit/objectFitPolyfill.basic' . $this->min . '.js' ),
			[],
			typer()->get_version(),
			true
		);

		wp_register_script(
			'bootstrap',
			get_theme_file_uri( 'assets/js/bootstrap' . $this->min . '.js' ),
			[
				'jquery',
				'popper'
			],
			typer()->get_version(),
			true
		);

		wp_register_script(
			'jquery-parallax-scroll',
			get_theme_file_uri( 'assets/js/jquery.parallax-scroll' . $this->min . '.js' ),
			[ 'jquery' ],
			typer()->get_version(),
			true
		);

		wp_register_script(
			'swiper',
			get_theme_file_uri( 'assets/js/swiper/swiper' . $this->min . '.js' ),
			[],
			typer()->get_version(),
			true
		);

		wp_register_script(
			'jquery-fancybox',
			get_theme_file_uri( 'assets/js/fancybox/jquery.fancybox' . $this->min . '.js' ),
			[ 'jquery', ],
			typer()->get_version(),
			true
		);


		wp_register_script(
			'hc-sticky',
			get_theme_file_uri( 'assets/js/hc-sticky/hc-sticky-all' . $this->min . '.js' ),
			[],
			typer()->get_version(),
			true
		);

		wp_register_script(
			'css-vars-ponyfill',
			get_theme_file_uri( 'assets/js/css-vars/css-vars-ponyfill' . $this->min . '.js' ),
			[],
			typer()->get_version(),
			true
		);

		wp_register_script(
			'plyr-polyfill',
			get_theme_file_uri( 'assets/js/plyr/plyr.polyfilled' . $this->min . '.js' ),
			[ 'jquery' ],
			typer()->get_version(),
			true
		);

		wp_register_script(
			'plyr-init',
			get_theme_file_uri( 'assets/js/plyr-init' . $this->min . '.js' ),
			[ 'jquery', 'plyr-polyfill' ],
			typer()->get_version(),
			true
		);


		wp_register_script(
			'intersection-polyfill',
			get_theme_file_uri( 'assets/js/intersection-observer' . $this->min . '.js' ),
			[],
			typer()->get_version(),
			true
		);

		wp_register_script(
			'typer',
			get_theme_file_uri( 'assets/js/index' . $this->min . '.js' ),
			[
				'jquery',
				'objectfit-pollyfill',
				'intersection-polyfill'
			],
			typer()->get_version(),
			true
		);

		wp_enqueue_script( 'modernizr' );
		wp_enqueue_script( 'css-vars-ponyfill' );
		wp_enqueue_script( 'jrespond' );
		wp_enqueue_script( 'popper' );
		wp_enqueue_script( 'bootstrap' );
		wp_enqueue_script( 'typer' );

		$objectFitData = "jQuery(document).ready(function($) { objectFitPolyfill(); });";

		wp_add_inline_script( 'objectfit-pollyfill', $objectFitData );

		$cssVarsData = "jQuery(document).ready(function($) {cssVars();});";

		wp_add_inline_script( 'css-vars-ponyfill', $cssVarsData );
	}

	/**
	 * Enqueue swiper style & script
	 */
	public function enqueue_swiper() {
		wp_enqueue_style( 'swiper' );
		wp_enqueue_script( 'swiper' );
	}

	/**
	 * Enqueue masonry
	 */
	public function enqueue_masonry() {
		wp_enqueue_script( 'masonry' );
	}

	/**
	 * Enqueue comments reply script
	 */
	public function enqueue_comments_reply() {
		wp_enqueue_script( 'comment-reply', 'wp-includes/js/comment-reply', [], false, true );
	}

	/**
	 * Enqueue fancybox
	 */
	public function enqueue_fancybox() {
		wp_print_styles( [ 'fancybox' ] );
		wp_enqueue_script( 'jquery-fancybox' );

		if ( ! $this->fancy_init ) {
			$fancyBoxInit = "jQuery(document).ready(function($) { $('.svq-fancy-img').filter('[data-elementor-open-lightbox!=\"yes\"]').fancybox(); });";

			wp_add_inline_script( 'jquery-fancybox', $fancyBoxInit );
			$this->fancy_init = true;
		}
	}

	/**
	 * Enqueue code prettify
	 */
	public function enqueue_prettify() {
		wp_enqueue_script( 'code-prettify' );
	}

	/**
	 * Enqueue code hc-sticky
	 */
	public function enqueue_hc_sticky() {
		wp_enqueue_script( 'hc-sticky' );
	}

	/**
	 * Enqueue code plyr
	 */
	public function enqueue_plyr() {
		wp_enqueue_script( 'plyr-polyfill' );
		wp_enqueue_script( 'plyr-init' );
	}

	/**
	 * Enqueue jquery parallax
	 */
	public function enquque_jquery_parallax() {
		wp_enqueue_script( 'jquery-parallax-scroll' );
	}

	/**
	 * Gets all CSS files.
	 *
	 * @return array Associative array of $handle => $data pairs.
	 */
	protected function get_css_files() {
		if ( is_array( $this->css_files ) ) {
			return $this->css_files;
		}

		$css_files = [
			'typer-global'     => [
				'file'             => 'css/index' . $this->min . '.css',
				'global'           => true,
				'preload_callback' => '__return_true',
			],
			'typer-icon-fonts' => [
				'file'   => 'fonts/style.css',
				'global' => true
			],
			'swiper'           => [
				'file' => 'js/swiper/swiper' . $this->min . '.css',
			],
			'fancybox'         => [
				'file' => 'js/fancybox/jquery.fancybox' . $this->min . '.css',
			],
		];

		/**
		 * Filters default CSS files.
		 *
		 * @param array $css_files Associative array of CSS files, as $handle => $data pairs.
		 *                         $data must be an array with keys 'file' (file path relative to 'assets/css'
		 *                         directory), and optionally 'global' (whether the file should immediately be
		 *                         enqueued instead of just being registered) and 'preload_callback' (callback)
		 *                         function determining whether the file should be preloaded for the current request).
		 */
		$css_files = apply_filters( 'typer_css_files', $css_files );

		$this->css_files = [];
		foreach ( $css_files as $handle => $data ) {
			if ( is_string( $data ) ) {
				$data = [ 'file' => $data ];
			}

			if ( empty( $data['file'] ) ) {
				continue;
			}

			$this->css_files[ $handle ] = array_merge(
				[
					'global'           => false,
					'preload_callback' => null,
				],
				$data
			);
		}

		return $this->css_files;
	}

	/**
	 * Registers or enqueues stylesheets.
	 *
	 * Stylesheets that are global are enqueued. All other stylesheets are only registered, to be enqueued later.
	 */
	public function action_enqueue_styles() {

		$css_files = $this->get_css_files();
		foreach ( $css_files as $handle => $data ) {
			$src     = get_theme_file_uri( 'assets/' . $data['file'] );
			$version = Seventhqueen\Typer\typer()->get_asset_version( get_theme_file_path( 'assets/' . $data['file'] ) );

			// Enqueue global stylesheets immediately, register the ones for later use.
			if ( $data['global'] ) {
				wp_enqueue_style( $handle, $src, [], $version );
			} else {
				wp_register_style( $handle, $src, [], $version );
			}

			wp_style_add_data( $handle, 'precache', true );
		}
	}


	/**
	 * Preloads in-body stylesheets depending on what templates are being used.
	 *
	 * Only stylesheets that have a 'preload_callback' provided will be considered. If that callback evaluates to true
	 * for the current request, the stylesheet will be preloaded.
	 *
	 * Preloading is disabled when AMP is active, as AMP injects the stylesheets inline.
	 *
	 * @link https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
	 */
	public function action_preload_styles() {

		// If the AMP plugin is active, return early.
		if ( Seventhqueen\Typer\typer()->is_amp() ) {
			return;
		}

		$wp_styles = wp_styles();

		$css_files = $this->get_css_files();
		foreach ( $css_files as $handle => $data ) {

			// Skip if stylesheet not registered.
			if ( ! isset( $wp_styles->registered[ $handle ] ) ) {
				continue;
			}

			// Skip if no preload callback provided.
			if ( ! is_callable( $data['preload_callback'] ) ) {
				continue;
			}

			// Skip if preloading is not necessary for this request.
			if ( ! call_user_func( $data['preload_callback'] ) ) {
				continue;
			}

			$preload_uri = $wp_styles->registered[ $handle ]->src . '?ver=' . $wp_styles->registered[ $handle ]->ver;

			echo '<link rel="preload" id="' . esc_attr( $handle ) . '-preload" href="' . esc_url( $preload_uri ) . '" as="style">';
			echo "\n";
		}
	}

	/**
	 * Register admin styles
	 */
	public function action_enqueue_admin_styles() {
		wp_enqueue_style(
			'carbon_fields_css',
			get_theme_file_uri( '/assets/admin/css/carbon-fields.css' ),
			false,
			'1.0.0'
		);
	}

	/**
	 * Add tags
	 *
	 * @param $content
	 *
	 * @return mixed
	 */
	public function add_article_tags( $content ) {
		if ( is_single() ) {
			ob_start();
			get_template_part( 'template-parts/content/entry-taxonomies', get_post_type() );
			$tags    = ob_get_clean();
			$content .= $tags;

			remove_filter( 'the_content', [ $this, 'add_article_tags' ], 20 );
		}

		return $content;
	}

	/**
	 * Get the first quote from a post
	 *
	 * @param $content
	 *
	 * @return mixed|string
	 */
	public function get_content_quote( $content ) {
		preg_match( '/<blockquote(.*?)>(.|\n)*?<\/blockquote>/i', $content, $matches );
		if ( isset( $matches[0] ) ) {
			if ( strpos( $matches[0], 'class=' ) !== false ) {
				$matches[0] = str_replace( 'is-style-large', '', $matches[0] );
				$matches[0] = str_replace( 'wp-block-quote', 'wp-block-quote is-style-large', $matches[0] );

				return $matches[0];
			} else {
				return str_replace( '<blockquote', '<blockquote class="wp-block-quote is-style-large"', $matches[0] );
			}

		}

		return '';
	}

	/**
	 * Remove the first quote from single post format quote
	 *
	 * @param $content
	 *
	 * @return mixed
	 */
	public function remove_first_content_quote( $content ) {
		if ( get_post_format() === 'quote' && is_main_query() ) {
			$content = preg_replace( '/<blockquote(.*?)>(.|\n)*?<\/blockquote>/i', '', $content, 1 );
			remove_filter( 'the_content', [ $this, 'remove_first_content_quote' ] );
		}

		return $content;
	}

	/**
	 * Add custom button class to the password form
	 *
	 * @param $form
	 *
	 * @return mixed
	 */
	public function alter_password_form_btn( $form ) {
		$form = str_replace( 'name="Submit"', 'name="Submit" class="btn btn-dark"', $form );

		return $form;
	}

	/**
	 * @param $content
	 *
	 * @return null|string|string[]
	 */
	public function add_fancybox_to_images( $content ) {
		$classes = 'svq-fancy-img';

		$content = preg_replace_callback(
			'/<a(.*?)href=(?:"|\')(?:http(?:s?):)(?:[\/|.|\w|-])*\.(?:jpg|gif|png|jpeg|bmp)(?:"|\')(.*?)>/i',
			function ( array $matches ) use ( $classes ) {
				if ( isset( $matches[0] ) ) {
					if ( strpos( $matches[0], 'svq-gallery__image-link' ) !== false ) {
						return $matches[0];
					} else if ( strpos( $matches[0], 'class=' ) !== false ) {
						$matches[0] = str_replace( 'class="', '<a class="' . esc_attr( $classes ) . ' ', $matches[0] );

						return $matches[0];
					} else {
						$matches[0] = str_replace( '<a', '<a class="' . esc_attr( $classes ) . '"', $matches[0] );

						return $matches[0];
					}
				}
			},
			$content );


		return $content;
	}

}

Typer_Assets::instance();


/**
 * WP 5.2 compatibility
 */
if ( ! function_exists( 'wp_body_open' ) ) {
	function wp_body_open() {
		do_action( 'wp_body_open' );
	}
}

/**
 * Render theme header
 */
function typer_show_header() {
	typer()->get_template_part( 'template-parts/header' );
}

add_action( 'typer_header', 'typer_show_header' );

/**
 * Render theme footer
 */
function typer_show_footer() {
	typer()->get_template_part( 'template-parts/footer/wrapper' );
}

add_action( 'typer_footer', 'typer_show_footer' );

/**
 * Render single main content
 */
function typer_show_single() {
	typer()->get_template_part( 'template-parts/single' );
}

add_action( 'typer_single', 'typer_show_single' );


/**
 * Render archive main content
 */
function typer_show_featured_posts() {
	if ( is_home() && ! is_paged() && typer()->get_option( 'blog_featured_content_status' ) ) {
		typer()->get_template_part( 'template-parts/archive/featured' );
	}
}

add_action( 'typer_archive', 'typer_show_featured_posts', 8 );

/**
 * Render archive main content
 */
function typer_show_archive() {
	// Include archive panel. Except blog home
	if ( ! is_home() ) {
		typer()->get_template_part( 'template-parts/content/panel', 'page' );
	}

	// Include posts loop
	typer()->get_template_part( 'template-parts/archive/index' );
}

add_action( 'typer_archive', 'typer_show_archive' );


/**
 * Displays the classes for the post container element.
 *
 * @param array $class One or more classes to add to the class list.
 * @param int|WP_Post $post_id Optional. Post ID or post object. Defaults to the global `$post`.
 *
 * @since 1.0.0
 *
 */
function typer_post_class( $class = [], $post_id = null ) {
	$post_classes = get_post_class( '', $post_id );

	if ( ( $key = array_search( 'has-post-thumbnail', $post_classes ) ) !== false ) {
		unset( $post_classes[ $key ] );
	}

	if ( ( $key = array_search( 'sticky', $post_classes ) ) === false && is_sticky( $post_id ) ) {
		$post_classes[] = 'sticky';
	}

	$post_classes = array_merge( $post_classes, $class );

	// Separates classes with a single space, collates classes for post DIV
	echo 'class="' . implode( ' ', $post_classes ) . '"';
}

/**
 * @param $classes
 * @param $resolution
 * @param $value
 *
 * @return array
 */
function typer_build_masonry_classes( $classes, $resolution, $value ) {
	$value = 12 / (int) $value;
	switch ( $resolution ) {
		case 'desktop':
			$classes[] = 'svq-masonry-lg-' . $value;
			break;
		case 'tablet':
			$classes[] = 'svq-masonry-md-' . $value;
			break;
		case 'mobile':
			$classes[] = 'svq-masonry-sm-' . $value;
			break;
		default:
	}

	return $classes;
}

/**
 * @param $classes
 * @param $resolution
 * @param $value
 *
 * @return array
 */
function typer_build_grid_classes( $classes, $resolution, $value ) {
	$value = 12 / (int) $value;
	switch ( $resolution ) {
		case 'desktop':
			$classes[] = 'svq-grid-lg-' . $value;
			break;
		case 'tablet':
			$classes[] = 'svq-grid-md-' . $value;
			break;
		case 'mobile':
			$classes[] = 'svq-grid-sm-' . $value;
			break;
		default:
	}

	return $classes;
}


/***************************************************
 * :: MAINTENANCE MODE
 ***************************************************/
if ( ! function_exists( 'typer_maintenance_mode' ) ) {
	function typer_maintenance_mode() {

		if ( typer()->get_option( 'maintenance_mode', 0 ) ) {

			/* Theme My Login compatibility */
			if ( class_exists( 'Theme_My_Login' ) && Theme_My_Login::is_tml_page( 'login' ) ) {
				return;
			}

			if ( ! is_admin() && ! is_user_logged_in() ) {
				wp_die(
					'<div style="text-align:center">'
					. typer()->get_option( 'maintenance_msg' )
					. '</div>',
					get_bloginfo( 'name' )
				);
			}
		}
	}

	add_action( 'get_header', 'typer_maintenance_mode' );
}

/**
 * Disable Google Local fonts
 */
if ( ! typer()->get_option( 'google_font_use_local', 1 ) ) {
	add_filter( 'kirki_webfont_front_method', function () {
		return 'async';
	} );
}
