<?php
/**
 * PixiGo functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package pixigo
 */

if ( ! function_exists( 'pixigo_fs' ) ) {
	/**
	 * Create a helper function for easy SDK access.
	 */
	function pixigo_fs() {
		global $pixigo_fs;

		if ( ! isset( $pixigo_fs ) ) {
			// Include Freemius SDK.
			require_once dirname( __FILE__ ) . '/freemius/start.php';

			$pixigo_fs = fs_dynamic_init( array(
				'id'                  => '4050',
				'slug'                => 'pixigo',
				'type'                => 'theme',
				'public_key'          => 'pk_54f771e523ad8fa8f15c45c52bdd1',
				'is_premium'          => false,
				'has_addons'          => false,
				'has_paid_plans'      => false,
				'menu'                => array(),
			) );
		}

		return $pixigo_fs;
	}

	// Init Freemius.
	pixigo_fs();
	// Signal that SDK was initiated.
	do_action( 'pixigo_fs_loaded' );
}

/**
 * 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 pixigo_setup() {

	define( 'PIXIGO_VERSION', '1.0.16' );

	/*
		* Make theme available for translation.
		* Translations can be filed in the /languages/ directory.
		* If you're building a theme based on pixigo, use a find and replace
		* to change 'pixigo' to the name of your theme in all the template files.
		*/
	load_theme_textdomain( 'pixigo', 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(
			'header' => esc_html__( 'Header', 'pixigo' ),
			'footer' => esc_html__( 'Footer', 'pixigo' ),
		)
	);

	/*
		* 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',
		)
	);

	// Set up the WordPress core custom background feature.
	add_theme_support(
		'custom-background', apply_filters(
			'pixigo_custom_background_args', array(
				'default-color' => 'F5F7FA',
				'default-image' => '',
			)
		)
	);

	// Add theme support for selective refresh for widgets.
	add_theme_support( 'customize-selective-refresh-widgets' );

	/**
	 * Add support for core custom logo.
	 *
	 * @link https://codex.wordpress.org/Theme_Logo
	 */
	add_theme_support(
		'custom-logo', array(
			'height'      => 30,
			'width'       => 150,
			'flex-width'  => true,
			'flex-height' => true,
		)
	);

	/**
	 * PixiGo metabox
	 */
	add_action( 'add_meta_boxes', 'add_pixigo_metabox' );
	add_action( 'save_post', 'save_pixigo_metabox', 10, 2 );

	/**
	 * Add support for default block styles.
	 *
	 * @link https://wordpress.org/gutenberg/handbook/extensibility/theme-support/#default-block-styles
	 */
	add_theme_support( 'wp-block-styles' );
	/**
	 * Add support for wide aligments.
	 *
	 * @link https://wordpress.org/gutenberg/handbook/extensibility/theme-support/#wide-alignment
	 */
	add_theme_support( 'align-wide' );

	/**
	 * Add support for block color palettes.
	 *
	 * @link https://wordpress.org/gutenberg/handbook/extensibility/theme-support/#block-color-palettes
	 */
	add_theme_support( 'editor-color-palette', array(
		array(
			'name'  => __( 'PixiGo Green', 'pixigo' ),
			'slug'  => 'pixigo-green',
			'color' => '#31B237',
		),
	) );

	/**
	 * Add support for font sizes.
	 *
	 * @link https://wordpress.org/gutenberg/handbook/extensibility/theme-support/#block-font-sizes
	 */
	add_theme_support( 'editor-font-sizes', array(
		array(
			'name'      => __( 'small', 'pixigo' ),
			'shortName' => __( 'S', 'pixigo' ),
			'size'      => 16,
			'slug'      => 'small',
		),
		array(
			'name'      => __( 'regular', 'pixigo' ),
			'shortName' => __( 'M', 'pixigo' ),
			'size'      => 20,
			'slug'      => 'regular',
		),
		array(
			'name'      => __( 'large', 'pixigo' ),
			'shortName' => __( 'L', 'pixigo' ),
			'size'      => 36,
			'slug'      => 'large',
		),
		array(
			'name'      => __( 'larger', 'pixigo' ),
			'shortName' => __( 'XL', 'pixigo' ),
			'size'      => 48,
			'slug'      => 'larger',
		),
	) );

	/**
	 * Optional: Add AMP support.
	 *
	 * Add built-in support for the AMP plugin and specific AMP features.
	 * Control how the plugin, when activated, impacts the theme.
	 *
	 * @link https://wordpress.org/plugins/amp/
	 */
	add_theme_support( 'amp', array(
		'comments_live_list' => true,
	) );

}
add_action( 'after_setup_theme', 'pixigo_setup' );

/**
 * Adds a timestamp on theme activation.
 */
function pixigo_add_options() {
	add_option( 'pixigo_activation_timestamp', time() );
}
add_action( 'after_switch_theme', 'pixigo_add_options' );

/**
 * Delete options created on theme activation.
 */
function pixigo_delete_options() {
	delete_option( 'pixigo_activation_timestamp' );
}
add_action( 'switch_theme', 'pixigo_delete_options' );

/**
 * Set the embed width in pixels, based on the theme's design and stylesheet.
 *
 * @param array $dimensions An array of embed width and height values in pixels (in that order).
 * @return array
 */
function pixigo_embed_dimensions( array $dimensions ) {
	$dimensions['width'] = 720;
	return $dimensions;
}
add_filter( 'embed_defaults', 'pixigo_embed_dimensions' );

/**
 * Enqueue WordPress theme styles within Gutenberg.
 */
function pixigo_gutenberg_styles() {
	// Enqueue main stylesheet.
	wp_enqueue_style( 'pixigo-base-style', get_theme_file_uri( '/css/editor-styles.css' ), array(), PIXIGO_VERSION );
}
add_action( 'enqueue_block_editor_assets', 'pixigo_gutenberg_styles' );

/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function pixigo_widgets_init() {
	register_sidebar( array(
		'name'          => esc_html__( 'Sidebar', 'pixigo' ),
		'id'            => 'sidebar-1',
		'description'   => esc_html__( 'Add widgets here.', 'pixigo' ),
		'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', 'pixigo_widgets_init' );

/**
 * Register a Recent Posts Widget
 */
function pixigo_register_recent_posts_widget() {
	register_widget( 'PixiGo_Recent_Posts' );
}
add_action( 'widgets_init', 'pixigo_register_recent_posts_widget' );

/**
 * Enqueue styles.
 */
function pixigo_styles() {
	// Enqueue main stylesheet.
	wp_enqueue_style( 'pixigo-base-style', get_stylesheet_uri(), array(), PIXIGO_VERSION );

	// Register component styles that are printed as needed.
	wp_register_style( 'pixigo-comments', get_theme_file_uri( '/css/comments.css' ), array(), PIXIGO_VERSION );
	wp_register_style( 'pixigo-content', get_theme_file_uri( '/css/content.css' ), array(), PIXIGO_VERSION );
	wp_register_style( 'pixigo-widgets', get_theme_file_uri( '/css/widgets.css' ), array(), PIXIGO_VERSION );
}
add_action( 'wp_enqueue_scripts', 'pixigo_styles' );

/**
 * Enqueue scripts.
 */
function pixigo_scripts() {

	// If the AMP plugin is active, return early.
	if ( pixigo_is_amp() ) {
		return;
	}

	// Register flying-pages JS.
	wp_register_script(
		'pixigo-flying-pages',
		get_theme_file_uri( '/js/flying-pages.min.js' ),
		[],
		PIXIGO_VERSION,
		true
	);

	// Enqueue the navigation script.
	wp_enqueue_script(
		'pixigo-navigation',
		get_theme_file_uri( '/js/navigation.js' ),
		[],
		PIXIGO_VERSION,
		false
	);
	wp_script_add_data( 'pixigo-navigation', 'defer', true );
	wp_localize_script( 'pixigo-navigation', 'pixigoScreenReaderText', array(
		'expand'   => __( 'Expand child menu', 'pixigo' ),
		'collapse' => __( 'Collapse child menu', 'pixigo' ),
	));

	if ( ! pixigo_is_flying_pages_active() && 'yes' === get_theme_mod( 'pixigo_prefetch' ) ) {

		// Enqueue Flying Pages JS.
		wp_enqueue_script( 'pixigo-flying-pages' );
		wp_script_add_data( 'pixigo-flying-pages', 'async', true );

		$pixigo_flying_pages_options = array(
			// Array of regex strings that further determines if a URL should be prefetched. These execute _after_ origin matching.
			'ignoreKeywords' => array(
				'/wp-admin',
				'/wp-content',
				'/wp-login.php',
				'/cart',
				'add-to-cart',
				'feed',
				'logout',
				'#',
				'?',
				'.png',
				'.jpeg',
				'.jpg',
				'.gif',
				'.svg'
			),
		);

		wp_add_inline_script(
			'pixigo-flying-pages',
			sprintf( 'window.FPConfig = %s;', wp_json_encode( $pixigo_flying_pages_options ) ),
			'before'
		);
	}

	// Enqueue comment script on singular post/page views only.
	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
}
add_action( 'wp_enqueue_scripts', 'pixigo_scripts' );

/**
 * Asks user to add a review after a week of theme use.
 */
function pixigo_add_review_notice() {
	$theme_activation_timestamp = get_option( 'pixigo_activation_timestamp' );

	// If the timestamp does not exist or clicked on "show later" in notice, update the timestamp.
	if ( ! $theme_activation_timestamp || isset( $_GET['pixigo-review-notice-show-later'] ) ) {
		update_option( 'pixigo_activation_timestamp', time() );
		return;
	}

	global $current_user;
	if ( get_user_meta( $current_user->ID, 'pixigo_review_notice_dismissed' ) ) {
		// If the user has dismissed the notice, don't process.
		return;
	}

	if ( $theme_activation_timestamp >= time() - ( 7 * 24 * 60 * 60 ) ) {
		// Don't process if it hasn't been less than a week after activation.
		return;
	}

	// Enqueue notice.css.
	wp_enqueue_style(
		'pixigo-notice',
		get_template_directory_uri() . '/css/notice.css',
		[],
		PIXIGO_VERSION
	);

	printf(
		'<div class="notice notice-success notice-pixigo-review">
			<div class="pixigo-review-logo">
				<img src="%1$s" alt="%2$s">
			</div>
			<div class="pixigo-review-content">
				<p>
					%3$s %4$s, %5$s
					<br>
					<b>%6$s</b>
					%7$s
				</p>
				<p>
					%8$s,
					<br>
					%9$s
				</p>
				<a href="%10$s" target="_blank">
					%11$s
					<span class="dashicons dashicons-external"></span>
				</a>
				<a href="%12$s">
					%13$s
				</a>
				<a href="%14$s">
					%15$s
				</a>
			</div>
		</div>',
		get_template_directory_uri() . '/images/pixigo-logo-coloured.svg',
		__( 'PixiGo Logo', 'pixigo' ),
		__( 'Hey', 'pixigo' ),
		$current_user->display_name,
		__( 'you\'ve been using PixiGo theme from more than a week - that\'s awesome!', 'pixigo' ),
		__( 'Could you please do me a BIG favor and give it a 5-star rating on WordPress?', 'pixigo' ),
		__( 'Just to help us spread the word and boost our motivation.', 'pixigo' ),
		__( '~ Paras Shah', 'pixigo' ),
		__( 'Full-Stack Magician', 'pixigo' ),
		'https://wordpress.org/support/theme/pixigo/reviews/?filter=5#new-post',
		__( 'Ok, you deserve it', 'pixigo' ),
		'?pixigo-review-notice-show-later',
		__( 'Nope, maybe later', 'pixigo' ),
		'?pixigo-review-notice-dismissed',
		__( 'I already did', 'pixigo' )
	);
}
add_action( 'admin_notices', 'pixigo_add_review_notice' );

/**
 * Function to register admin notice dismissal
 */
function pixigo_review_notice_dismissed() {
	$user_id = get_current_user_id();
	if ( isset( $_GET['pixigo-review-notice-dismissed'] ) ) {
		add_user_meta( $user_id, 'pixigo_review_notice_dismissed', 'true', true );
	}
}
add_action( 'admin_init', 'pixigo_review_notice_dismissed' );

/**
 * Custom responsive image sizes.
 */
require get_template_directory() . '/inc/image-sizes.php';

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

/**
 * Recent Posts Widget
 */
require get_template_directory() . '/inc/widget-recent-posts.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';

/**
 * Customizer CSS Output.
 */
require get_template_directory() . '/inc/dynamic-css.php';

/**
 * Add theme support for lazyloading images.
 *
 * @link https://developers.google.com/web/fundamentals/performance/lazy-loading-guidance/images-and-video/
 */
require get_template_directory() . '/pluggable/lazyload/lazyload.php';
