<?php
/**
 * Intangt pages
 *
 * @author        Webcraftic <wordpress.webraftic@gmail.com>
 * @copyright (c) 28.05.2021, Webcraftic
 * @version       1.0
 */

// Exit if accessed directly
if( !defined('ABSPATH') ) {
	exit;
}

// Embed the scripts we need for this plugin
add_action('wp_enqueue_scripts', function () {

	if( !WCL_Plugin::app()->getPopulateOption('enable_intant_pages') ) {
		return;
	}

	// Disable for logged admins
	if( WCL_Plugin::app()->getPopulateOption('instant_pages_disable_for_logged_users') && is_user_logged_in() ) {
		return;
	}

	// Abort if the response is AMP since custom JavaScript isn't allowed
	if( function_exists('is_amp_endpoint') && is_amp_endpoint() ) {
		return;
	}

	wp_enqueue_script('instant-pages', WCLP_PLUGIN_URL . '/assets/js/instant-pages.min.js', array(), WCL_Plugin::app()->getPluginVersion(), true);
	wp_add_inline_script('instant-pages', 'window.FPConfig= {
	delay: ' . esc_html(WCL_Plugin::app()->getPopulateOption('instant_pages_delay_start_preloading', 0)) . ',
	ignoreKeywords: ' . json_encode(explode("\n", WCL_Plugin::app()->getPopulateOption('instant_pages_ignore_keywords')), true) . ',
	maxRPS: ' . esc_html(WCL_Plugin::app()->getPopulateOption('instant_pages_max_requests_per_second', 0)) . ',
    hoverDelay: ' . esc_html(WCL_Plugin::app()->getPopulateOption('instant_pages_mouse_hover_delay', 50)) . '
};', "before");
});

// Add defer attribute to Intant Pages script tag
add_filter('script_loader_tag', function ($tag, $handle) {
	if( 'instant-pages' === $handle && false === strpos($tag, 'defer') ) {
		$tag = preg_replace(':(?=></script>):', ' defer', $tag);
	}

	return $tag;
}, 10, 2);
