<?php
/**
 * Add dynamic css to frontend.
 *
 * This file is loaded at 'after_setup_theme' hook with 10 priority.
 */

/* Add CSS vars built from options to the dynamic CSS vars array */
add_action( 'hoot_dynamic_cssrules', 'magboost_dynamic_cssvars', 2 );

/* Enqueue Google Fonts */
add_action( 'hoot_dynamic_cssrules', 'magboost_enqueue_google_fonts', 99 );
/**
 * Enqueue Google Fonts
 */
function magboost_enqueue_google_fonts() {
	/* Load Google Fonts if any google font is active. */
	$style_uri = hootfontography()->gfonts_style_uri();
	if ( $style_uri )
		wp_enqueue_style( 'magboost-googlefont', $style_uri, array(), null );
}

/**
 * Modify google font enqueue weights
 */
function magboost_enqueue_gfonts_weights( $fonts ) {
	$bodyfont = hoot_get_mod( 'body_font' );
	$bodyfont = json_decode($bodyfont, true);
	$bodyfont = is_array( $bodyfont ) ? $bodyfont : array();
	$bodyfont = !empty( $bodyfont['face'] ) ? $bodyfont['face'] : '';
	if ( !empty( $fonts[ $bodyfont ] ) && is_array( $fonts[ $bodyfont ] ) && !empty( $fonts[ $bodyfont ]['weight'] ) && is_array( $fonts[ $bodyfont ]['weight'] ) ) {
		if ( !in_array( '500', $fonts[ $bodyfont ]['weight'] ) )
			$fonts[ $bodyfont ]['weight'][] = '500';
		if ( !in_array( '700', $fonts[ $bodyfont ]['weight'] ) )
			$fonts[ $bodyfont ]['weight'][] = '700';
	}
	return $fonts;
}
add_filter( 'hoot_enqueue_gfonts_array', 'magboost_enqueue_gfonts_weights', 999 );

/**
 * Frontpage custom font color css selector
 * @param bool
 * @param string
 * @return string
 */
if ( ! function_exists( 'hoot_fp_customfontcolor_selector' ) ):
function hoot_fp_customfontcolor_selector( $force = false, $selector = 'selector-place' ) {
	$sym = $force ? '#' : '.';
	return "{$sym}{$selector} *:not(.button):not(button):not(.button *):not(button *):not(.social-icons-icon):not(.social-icons-icon *):not([class*='wpcf7']), {$sym}{$selector} .more-link, {$sym}{$selector} .more-link a";
}
endif;

/**
 * Map customizer option background to css properties
 * @param string
 * @return array
 */
function magboost_resolve_background( $idtag, $hasoverlay=false ) {
	$bgarray = array(
		'background-color' => '',
		'background-image' => '',
		'background-repeat' => '',
		'background-position' => '',
		'background-attachment' => '',
		'background-size' => '',
	);
	global $hoot_style_builder;
	$bgvals = $hoot_style_builder->sanitize_background( $idtag, false );
	if ( is_array( $bgvals ) ) {
		foreach ( $bgarray as $key => $value ) {
			if ( !empty( $bgvals[ $key ] ) && is_array( $bgvals[ $key ] ) && !empty( $bgvals[ $key ]['value'] ) ) {
				$bgarray[ $key ] = $bgvals[ $key ]['value'];
			}
		}
	}
	if ( $hasoverlay ) {
		$bg = hoot_get_mod( $idtag . '-overlay' );
		if ( $bg && ! hoot_color_istransparent( $bg ) ) {
			$bgarray['background-overlay'] = $bg;
		}
	}
	return $bgarray;
}

if ( ! function_exists( 'hoot_themeradii' ) ):
function hoot_themeradii( $suffix = true ) {
	$defaults = array(
		'button' => 0,
		'base' => 0,
		'small' => 0,
		'medium' => 0,
		'big' => 0,
		'limit12' => 0,
		'limit20' => 0,
		'limit50' => 0,
	);
	static $radii = array();
	if ( empty( $radii ) && function_exists( 'hoot_get_mod' ) ) {
		$buttonradius     = intval( hoot_get_mod( 'buttonradius' ) );
		$radii['button']  = $buttonradius && $buttonradius >= 0 && $buttonradius <= 250 ? $buttonradius : 0;
		$borderradius     = intval( hoot_get_mod( 'borderradius' ) );
		$borderradius     = $borderradius && $borderradius >= 0 && $borderradius <= 250 ? $borderradius : 0;
		$radii['base']    = $borderradius;
		$radii['small']   = $borderradius >=  2 ? $borderradius - 2 : 0;
		$radii['medium']  = $borderradius !== 0 ? $borderradius + 2 : 0;
		$radii['big']     = $borderradius !== 0 ? $borderradius + 2 : 0;
		$radii['limit12'] = $borderradius <= 12 ? $borderradius     : 12;
		$radii['limit20'] = $borderradius <= 20 ? $borderradius     : 20;
		$radii['limit50'] = $borderradius <= 50 ? $borderradius     : 50;
		$radii = wp_parse_args( $radii, $defaults );
		if ( $suffix ) {
			foreach ( $radii as $key => $value ) {
				$radii[ $key ] = $value . 'px';
			}
		}
	}
	return ( empty( $radii ) ? $defaults : $radii );
}
endif;

/**
 * Custom CSS built from user theme options
 * For proper sanitization, always use functions from library/sanitization.php
 *
 * @since 1.0
 * @access public
 */
function magboost_dynamic_cssvars() {
	$cssvars = array();

	// GRID

	// SPACERS
	$radii = hoot_themeradii();
	if ( !empty( $radii ) && is_array( $radii ) ) {
		foreach ( $radii as $key => $value ) {
			$cssvars["--hoot-radius-{$key}"] = $value;
		}
	}

	$widgetmargin = hoot_get_mod( 'widgetmargin' );
	$widgetmargin = hoot_betterrange_css( $widgetmargin, 'px' );
	$cssvars['--hoot-widget-margin'] = $widgetmargin;

	// FORMS

	/** Typography **/

	// GENERAL

	// LOGO

	$resolvedfont = hootfontography()->resolve_font( 'logo_font', '--hoot-logo-' );
	$cssvars = array_merge( $cssvars, $resolvedfont );
	$cssvars['--hoot-logo-color'] = hoot_get_mod( 'logo_color' );

	$logo_custom = hoot_sortlist( hoot_get_mod( 'logo_custom' ) );
	if ( is_array( $logo_custom ) && !empty( $logo_custom ) ) {
		$lcount = 1;
		foreach ( $logo_custom as $logo_custom_line ) {
			$size = !empty( $logo_custom_line[ 'size' ] ) ? intval( $logo_custom_line[ 'size' ] ) : false;
			$cssvars['--hoot-logo-line'.$lcount.'-size'] = $size ? $size . 'px' : '';
			$lcount++;
		}
	}

	// HEADINGS

	if ( !defined( 'MAGBOOST_PREMIUM_VERSION' ) ) {
		$hsize = hoot_get_mod( 'heading_size' );
		$hsizes = magboost_default_style( 'heading_size_enum' );
		if ( is_array( $hsizes ) && !empty( $hsizes[ $hsize ] ) && is_array( $hsizes[ $hsize ] ) ) {
			foreach( $hsizes[ $hsize ] as $htype => $size ) {
				$cssvars["--hoot-{$htype}-size"] = $size;
			}
		}
	}
	$resolvedfont = hootfontography()->resolve_font( 'heading_font', '--hoot-headings-' );
	$cssvars = array_merge( $cssvars, $resolvedfont );

	$resolvedfont = hootfontography()->resolve_font( 'subheading_font', '--hoot-subheadings-' );
	$cssvars = array_merge( $cssvars, $resolvedfont );

	// LINK
	$cssvars['--hoot-linkcolor']            = hoot_get_mod( 'link_color' );
	$cssvars['--hoot-linkhovercolor']       = hoot_get_mod( 'link_hover_color' );

	// BODY

	$resolvedfont = hootfontography()->resolve_font( 'body_font', '--hoot-basefont-' );
	$cssvars = array_merge( $cssvars, $resolvedfont );

	if ( !empty( $cssvars['--hoot-basefont-color'] ) ) {
		$cssvars['--hoot-basefont-light'] = hoot_color_increase( $cssvars['--hoot-basefont-color'], 50 );
	}

	// TOPBAR

	// MENU

	// FOOTER

	/** Colors and backgrounds **/

	// GENERAL

	$cssvars['--hoot-accentcolor'] = hoot_get_mod( 'accent_color' );
	$cssvars['--hoot-accentfont'] = hoot_get_mod( 'accent_font' );
	$cssvars['--hoot-buttoncolor'] = hoot_get_mod( 'button_color' );
	$cssvars['--hoot-buttonfont'] = hoot_get_mod( 'button_font' );

	// BODY

	$body_background = magboost_resolve_background( 'background', true );
	$cssvars['--hoot-body-bg']               = $body_background['background-color'];
	$cssvars['--hoot-body-bgimg']            = $body_background['background-image'];
	$cssvars['--hoot-body-bgrepeat']         = $body_background['background-repeat'];
	$cssvars['--hoot-body-bgpos']            = $body_background['background-position'];
	$cssvars['--hoot-body-bgatch']           = $body_background['background-attachment'];
	$cssvars['--hoot-body-bgsize']           = $body_background['background-size'];
	if ( !empty( $body_background['background-overlay'] ) ) {
		$cssvars['--hoot-body-bgoverlay'] = $body_background['background-overlay'];
	}

	// TOPBAR

	// LOGO
	$bg = hoot_get_mod( 'logo_background' );
	if ( $bg && ! hoot_color_istransparent( $bg ) ) {
		$cssvars['--hoot-logo-bg'] = $bg;
	}

	// CONTENT

	$cssvars['--hoot-box-bg'] = hoot_get_mod( 'box_background_color' );
	$cssvars['--hoot-article-bg'] = hoot_get_mod( 'article_background_color' );

	// FOOTER

	/** Misc **/

	// MISC

	$goto_top_offset = hoot_get_mod( 'goto_top_offset' );
	$goto_top_offset = hoot_betterrange_css( $goto_top_offset, 'px' );
	$cssvars['--hoot-goto-offset'] = $goto_top_offset;

	$logo_icon_size = intval( hoot_get_mod( 'site_title_icon_size' ) );
	$cssvars['--hoot-logo-iconsize'] = $logo_icon_size ? $logo_icon_size . 'px' : '';

	$logo_image_width = hoot_get_mod( 'logo_image_width' );
	$logo_image_width = hoot_betterrange_css( $logo_image_width, 'px' );
	$cssvars['--hoot-logo-maximgwidth'] = $logo_image_width;

	$logo_stickyzoom = intval( hoot_get_mod( 'sticky_sitehead_dtp_logozoom' ) );
	$logo_stickyzoom = $logo_stickyzoom && $logo_stickyzoom > 0 && $logo_stickyzoom <= 100 ? $logo_stickyzoom : 100;
	$cssvars['--hoot-sticky-dtplogozoom'] = $logo_stickyzoom / 100;
	$logo_stickyzoom = intval( hoot_get_mod( 'sticky_sitehead_mob_logozoom' ) );
	$logo_stickyzoom = $logo_stickyzoom && $logo_stickyzoom > 0 && $logo_stickyzoom <= 100 ? $logo_stickyzoom : 100;
	$cssvars['--hoot-sticky-moblogozoom'] = $logo_stickyzoom / 100;

	// PADDINGS

	$processpad = array(
		'topbar_padding' => '--hoot-topbar-padding',
		'logo_margin' => '--hoot-logo-margin',
		'below_sitehead_padding' => '--hoot-below-sitehead-padding',
		'subfooter_padding' => '--hoot-subfooter-padding',
		'footer_padding' => '--hoot-footer-padding',
		'postfooter_padding' => '--hoot-postfooter-padding',
	);
	foreach ( $processpad as $opt => $cssvar ) {
		$val = hoot_get_mod( $opt );
		$val = hoot_spacings_css( $val );
		$cssvars[ $cssvar ] = $val;
	}

	// TOP ANNOUNCEMENT BAR
		$topannbg = hoot_get_mod( 'topann_content_bg' );
		$cssvars['--hoot-textstyle-topannbg'] = $topannbg ? $topannbg : magboost_default_style('topann_content_bg');
		$topannbg = hoot_get_mod( 'topann_content_color' );
		$cssvars['--hoot-textstyle-topanncol'] = $topannbg ? $topannbg : magboost_default_style('topann_content_color');

	// BELOW SITEHEAD
		$belowshcol = hoot_get_mod( 'belowsh_bg' );
		$cssvars['--hoot-textstyle-belowshbg'] = $belowshcol ? $belowshcol : magboost_default_style('belowsh_bg');
		$belowshcol = hoot_get_mod( 'belowsh_color' );
		$cssvars['--hoot-textstyle-belowshcol'] = $belowshcol ? $belowshcol : magboost_default_style('belowsh_color');

	// SIDEBAR WIDTHS

	$sbwidth = hoot_get_mod( 'sidebar1_width' );
	if ( $sbwidth === 'px' ) {
		$sbval = intval( hoot_get_mod( 'sidebar1_width_px' ) );
		if ( $sbval && $sbval > 0 ) {
			$cssvars['--hoot-sidebar1-width'] = $sbval . 'px';
		}
	} elseif ( $sbwidth === 'pcnt' ) {
		$sbval = intval( hoot_get_mod( 'sidebar1_width_pcnt' ) );
		if ( $sbval && $sbval >= 0 && $sbval <= 100 ) {
			$cssvars['--hoot-sidebar1-width'] = $sbval . '%';
		}
	}
	$sbwidth = hoot_get_mod( 'sidebar2_width' );
	if ( $sbwidth === 'px' ) {
		$sbval = intval( hoot_get_mod( 'sidebar2_width_px' ) );
		if ( $sbval && $sbval > 0 ) {
			$cssvars['--hoot-sidebar2-width'] = $sbval . 'px';
		}
	} elseif ( $sbwidth === 'pcnt' ) {
		$sbval = intval( hoot_get_mod( 'sidebar2_width_pcnt' ) );
		if ( $sbval && $sbval >= 0 && $sbval <= 100 ) {
			$cssvars['--hoot-sidebar2-width'] = $sbval . '%';
		}
	}

	// SINGLE ARTICLE

	$article_maxwidth = intval( hoot_get_mod( 'article_maxwidth' ) );
	$cssvars['--hoot-article-width'] = $article_maxwidth ? $article_maxwidth . 'px' : '';
	$article_maxwidth = intval( hoot_get_mod( 'article_maxwidth_nosidebar' ) );
	$cssvars['--hoot-article-width-nosb'] = $article_maxwidth ? $article_maxwidth . 'px' : '';

	// FRONTPAGE IMAGE
	$rawfpminheight = hoot_get_mod( 'header_image_minheight' );
	$fpminheight = hoot_betterrange_css( $rawfpminheight, 'px' );
	$fpminheight = is_array( $fpminheight ) ? $fpminheight : ( intval( $rawfpminheight ) ? intval( $rawfpminheight ) . 'px' : '' ); // backward compatibility for old single value
	if ( $fpminheight || $fpminheight === 0 ) {
		$cssvars['--hoot-fimg-minheight'] = $fpminheight;
	}
	foreach ( array(
		'conpad',
		'imgpad',
		'headsize',
		'subheadsize',
		'textsize',
		'btnsize',
	) as $key ) {
		$val = hoot_get_mod( "header_image_{$key}" );
		$val = intval( $val );
		if ( $val || $val === 0 ) {
			$cssvars[ "--hoot-fimg-{$key}" ] = $val . 'px';
		}
	}
	foreach ( array(
		'bg',
		'headcolor',
		'subheadcolor',
		'textcolor',
		'btncolor',
		'btnbg',
		'btncolor2',
		'btnbg2',
	) as $key ) {
		$val = hoot_get_mod( "header_image_{$key}" );
		if ( $val ) {
			$cssvars[ "--hoot-fimg-{$key}" ] = $val;
		}
	}
	foreach ( array(
		'conbg',
		'overlay',
	) as $key ) {
		$bg = hoot_get_mod( "header_image_{$key}" );
		if ( $bg && ! hoot_color_istransparent( $bg ) ) {
			$cssvars[ "--hoot-fimg-{$key}" ] = $bg;
		}
	}

	/**
	 * Misc Stuff not covered by css vars
	 */

	/** Frontpage **/
	if ( !is_customize_preview() ) {
		$sections = hoot_sortlist( hoot_get_mod( 'frontpage_sections' ) );
		if ( is_array( $sections ) && !empty( $sections ) ) { foreach ( $sections as $key => $section ) {
			if ( is_array( $section ) && !empty( $section['sortitem_hide'] ) ) continue;
			if ( $key == 'image' ) continue;
			$id = ( $key == 'content' ) ? 'frontpage-page-content' : sanitize_html_class( 'frontpage-' . $key );
			$type = hoot_get_mod( "frontpage_sectionbg_{$key}-font" );
			switch ($type) {
				case 'color': $selector = hoot_fp_customfontcolor_selector( false, $id ); break;
				case 'force': $selector = hoot_fp_customfontcolor_selector( true, $id ); break;
				default: $selector = ''; break;
			}
			if ( $selector ) {
				hoot_add_css_rule( array(
							'selector'  => $selector,
							'property'  => 'color',
							'value'     => hoot_get_mod( "frontpage_sectionbg_{$key}-fontcolor" ),
						) );
			}
		} }
	}

	/**
	 * NOTE: add_cssvars checks if $cssvars is an array.
	 * NOTE: var is added ONLY if its value is not empty.
	 */
	$cssvars = apply_filters( 'magboost_dynamic_cssvars', $cssvars );
	hoot_add_cssvars( $cssvars );

}
