<?php
/**
 * Custom functions that act independently of the theme templates.
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 * @package Afterlight 2.0
 * @since Afterlight 2.0
 */

/**
 * Add a `screen-reader-text` class to the search form's submit button.
 *
 * @since Afterlight 1.0
 *
 * @param string $html Search form HTML.
 * @return string Modified search form HTML.
 */
function afterlight_2_search_form_modify( $html ) {
	return str_replace( 'class="search-submit"', 'class="search-submit screen-reader-text"', $html );
}
add_filter( 'get_search_form', 'afterlight_2_search_form_modify' );

/**
 * Adds custom classes to the array of body classes.
 *
 * @param array $classes Classes for the body element.
 * @return array
 */
function afterlight_2_body_classes( $classes ) {

	if ( is_singular() ) {
		$classes[] = 'single';
	}

	if ( has_nav_menu( 'primary' ) ) {
		$classes[] = 'header-menu';
	}

	if ( ! is_active_sidebar( 'sidebar-1' ) ) {
		$classes[] = 'no-widgets';
	}

	if ( ! is_active_sidebar( 'sidebar-1' ) && ! has_nav_menu( 'primary' ) && ! has_nav_menu( 'social' ) ) {
		$classes[] = 'no-sidebar';
	}

	if ( get_background_image() && '1' == get_theme_mod( 'afterlight_2_full_page_background', '1' ) ) {
		$classes[] = 'full-page-background';
	}

	if ( '1' == get_theme_mod( 'afterlight_2_background_overlay', '1' ) ) {
		$classes[] = 'has-overlay';
	}

	return $classes;
}
add_filter( 'body_class', 'afterlight_2_body_classes' );

/**
 * Apply full-page background image to the pseudo element so that it also works on mobile Safari.
 *
 * @since Afterlight 1.0
 *
 * @see wp_add_inline_style()
 */
function afterlight_2_full_page_background_image() {
	$image                = get_background_image();
	$full_page_background = get_theme_mod( 'afterlight_2_full_page_background', '1' );
	$css                  = '';

	if ( ! empty ( $image ) && '1' == $full_page_background ) {
		$css .= 'body:before { background-image: url("' . esc_url( $image ) . '"); }';
	}

	wp_add_inline_style( 'afterlight-2-style', $css );
}
add_action( 'wp_enqueue_scripts', 'afterlight_2_full_page_background_image' );

/**
 * Add a pingback url auto-discovery header for singularly identifiable articles.
 */
function afterlight_2_pingback_header() {

	if ( is_singular() && pings_open() ) {
		echo '<link rel="pingback" href="', esc_url( get_bloginfo( 'pingback_url' ) ), '">';
	}
}
add_action( 'wp_head', 'afterlight_2_pingback_header' );