<?php

/**
 * The file that defines typography post check methods
 *
 * A class definition that includes attributes and functions used across both the
 * public-facing side of the site and the admin area.
 *
 * @link       https://flothemes.com/
 * @since      1.0.0
 *
 * @package    Flo_Flex_Builder
 * @subpackage Flo_Flex_Builder/includes
 */

/**
 * The core plugin class.
 *
 * This is used to define internationalization, admin-specific hooks, and
 * public-facing site hooks.
 *
 * Also maintains the unique identifier of this plugin as well as the current
 * version of the plugin.
 *
 * @since      1.0.0
 * @package    Flo_Flex_Builder
 * @subpackage Flo_Flex_Builder/includes
 * @author     Flothemes <alexb@flothemes.com>
 */
class Flo_Flex_Builder_Typography_Post_Check
{
	/**
	 * The unique identifier of this plugin.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      string    $plugin_name    The string used to uniquely identify this plugin.
	 */
	protected $css_name;

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

	/**
	 * Array with all stylekits.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      array    $stylekits_obj
	 */
	protected $enqueue_bases = ['post', 'flotheme_page_acf-options'];

	/**
	 * Default Stylekit id.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      array    $default_stylekit_id
	 */
	protected $default_stylekit_id;

	/**
	 * Load class Flo_Flex_Builder_Typography_Post_Check
	 *
	 */
	public function __construct()
	{
		if (defined('Flo_Flex_Builder_Version')) {
			$this->version = Flo_Flex_Builder_Version;
		} else {
			$this->version = '0.1';
		}
		$this->css_name = 'flo-flex-stylekits';

		//set stylekits class vars
		$this->default_stylekit_id = get_option('flex_active_stylekit_name');

		//add css file if page have custom stylekit
		add_action('wp_enqueue_scripts', [$this, 'getPostStylekit']);
		add_action('wp_enqueue_scripts', [$this, 'checkPageStylekit'], 9); // 9 because with 10 there is a dependency in the theme
		add_action('wp_head', array($this, 'viewport_render_typography'), 5); //"5" because at "4" are injected main CSS file

		//check screens and enqueue scripts
		add_action('current_screen', [$this, 'enqueue_admin_scripts']);
	}

	/**
	 * Enqueue admin scripts
	 *
	 */
	public function enqueue_admin_scripts()
	{
		$current_screen = get_current_screen();

		foreach ($this->enqueue_bases as $enqueue_base) {
			if (preg_match("/\b$enqueue_base\b/", $current_screen->base)) {
				add_action('admin_enqueue_scripts', [$this, 'getPostStylekit']);
				add_action('admin_enqueue_scripts', [$this, 'checkPageStylekit']);
			}
		}
	}

	/**
	 * Check post id stylekit
	 *
	 * @param null $post_id
	 * @return string
	 */
	public function getPostStylekit($post_id = NULL)
	{
		//variables
		if ($post_id === NULL) {
			$post_id = get_the_ID();
		}

		$installed_stylekits = get_option('flex_active_stylekits_names');
		$stylekit_pages = is_array(get_option('flex_stylekits_pages')) ? get_option('flex_stylekits_pages') : [];

		if (isset($_GET['demo_stylekit']) && array_key_exists($_GET['demo_stylekit'], $installed_stylekits)) {
			$stylekit_id = $_GET['demo_stylekit'];
			return $stylekit_id;
		} elseif ($post_id && array_key_exists($post_id, $stylekit_pages)) {
			$stylekit_id = $stylekit_pages[$post_id]['stylekit_value'];
			if (array_key_exists($stylekit_id, $installed_stylekits)) {
				return $stylekit_id;
			}
		}

		return $this->default_stylekit_id;
	}

	/**
	 * Check what stylekit have page
	 */
	public function checkPageStylekit()
	{
		$flexTheme = defined('FLEX_THEME') ? FLEX_THEME : FALSE;
		$stylekit_id = $this->getPostStylekit();
		$uploads_dir = wp_get_upload_dir();
		$uploads_dir_path = isset($uploads_dir['basedir']) ? $uploads_dir['basedir'] : FALSE;
		$uploads_dir_url = isset($uploads_dir['baseurl']) ? $uploads_dir['baseurl'] : FALSE;
		$is_admin = is_admin();

		if (!$uploads_dir_path || !$uploads_dir_url) {
			return FALSE;
		}

		$style_version = $is_admin ? mt_rand(0, 99999) : Flo_Flex_Builder_Version;

		$gfontUrl = Flo_Flex_Builder_Typography::getGfontsUrl($stylekit_id);
		$customGFontsUrl = Flo_Flex_Builder_Typography::getCustomGfontsUrl();
		$deps = [];
		if (defined('FLEX_THEME') && FLEX_THEME === TRUE || (isset($author) && $author == 'Flothemes')) {
			$deps =  $is_admin ? [] : ['theme-css', 'vendor-css', 'default_stylesheet'];
		}

		if ($gfontUrl) {
			wp_enqueue_style($this->css_name . "-google-fonts", "{$gfontUrl}&display=swap", [], NULL, 'all');
		}

		if ($customGFontsUrl) {
			wp_enqueue_style($this->css_name . "-custom-google-fonts", "{$customGFontsUrl}&display=swap", [], NULL, 'all');
		}

		if ($is_admin) {
			if (file_exists("{$uploads_dir_path}/flex/stylekits/{$stylekit_id}.css")) {
				wp_enqueue_style($this->css_name, "{$uploads_dir_url}/flex/stylekits/{$stylekit_id}.css", $deps, $style_version, 'all');
			} else {
				if (file_exists("{$uploads_dir_path}/flex/stylekits/{$this->default_stylekit_id}.css")) {
					wp_enqueue_style($this->css_name, "{$uploads_dir_url}/flex/stylekits/{$this->default_stylekit_id}.css", $deps, $style_version, 'all');
				}
			}
		} else {
			wp_register_style($this->css_name, FALSE);
		}
	}

	/**
	 * Print inline the stylekit CSS file
	 */
	public function viewport_render_typography()
	{
		$uploads_dir = wp_get_upload_dir();
		$uploads_dir_path = isset($uploads_dir['basedir']) ? $uploads_dir['basedir'] : FALSE;
		$stylekit_id = $this->getPostStylekit();

		if (file_exists("{$uploads_dir_path}/flex/stylekits/{$stylekit_id}.css")) {
			$preload = get_post_meta(get_the_ID(), 'stylekit-metabox__preload', TRUE);

			if ($preload) {
				add_action('wp_head', function () use ($preload, $stylekit_id) {
					$preloaded_fonts = is_array($preload) ? $preload : [];
					$all_stylekits = get_option('flex_all_stylekits_obj');
					$stylekit_obj = isset($all_stylekits[$stylekit_id]) ? $all_stylekits[$stylekit_id] : [];
					$fonts_list = isset($stylekit_obj['generalInfo']['customFonts']) ? $stylekit_obj['generalInfo']['customFonts'] : [];

					foreach ($fonts_list as $key => $font) {
						if (in_array($font['name'], $preloaded_fonts)) {
							echo '<link rel="preload" href="' . str_replace('http://', '//', $font['files'][0]['url']) . '" as="font" type="font/' . $font['files'][0]['format'] . '" crossorigin="anonymous">';
						}
					}
				});
			}

			echo '<style class="' . $this->css_name . '-css">';
			require "{$uploads_dir_path}/flex/stylekits/{$stylekit_id}.css";
			echo '</style>';
			wp_enqueue_style($this->css_name);
		} else {
			if (file_exists("{$uploads_dir_path}/flex/stylekits/{$this->default_stylekit_id}.css")) {
				echo '<style class="' . $this->css_name . '-css">';
				require "{$uploads_dir_path}/flex/stylekits/{$this->default_stylekit_id}.css";
				echo '</style>';
				wp_enqueue_style($this->css_name);
			}
		}
	}

	public function getStylekitStyleLinks($post_id = NULL)
	{
		$stylekit_id = $this->getPostStylekit($post_id);
		$uploads_dir = wp_get_upload_dir();
		$uploads_dir_path = isset($uploads_dir['basedir']) ? $uploads_dir['basedir'] : FALSE;
		$uploads_dir_url = isset($uploads_dir['baseurl']) ? $uploads_dir['baseurl'] : FALSE;

		if (!$uploads_dir_path || !$uploads_dir_url) {
			return FALSE;
		}

		$gfontUrl = Flo_Flex_Builder_Typography::getGfontsUrl($stylekit_id);
		if ($gfontUrl) {
			$gfontUrl .= "&display=swap";
		}

		$stylekitCss = FALSE;
		if (file_exists("{$uploads_dir_path}/flex/stylekits/{$stylekit_id}.css")) {
			$stylekitCss = "{$uploads_dir_url}/flex/stylekits/{$stylekit_id}.css";
		} elseif (file_exists("{$uploads_dir_path}/flex/stylekits/{$this->default_stylekit_id}.css")) {
			$stylekitCss = "{$uploads_dir_url}/flex/stylekits/{$this->default_stylekit_id}.css";
		}

		if ($stylekitCss) {
			$stylekitCss .= "?ver=" . uniqid();
		}

		$customGFontsUrl = Flo_Flex_Builder_Typography::getCustomGfontsUrl();

		if ($gfontUrl || $stylekitCss || $customGFontsUrl) {
			$links = [];
			if ($gfontUrl) {
				$links['gFonts'] = $gfontUrl;
			}
			if ($stylekitCss) {
				$links['css'] = $stylekitCss;
			}
			if ($customGFontsUrl) {
				$links['customGFonts'] = $customGFontsUrl;
			}

			return $links;
		}

		return FALSE;
	}
}
