<?php
/**
 * Various utility functions
 *
 * @package Multi
 */

if ( ! defined( 'ABSPATH' ) ) {
	die;
}

/**
 * Replaces empty title with a placeholder
 *
 * @param string $title Title placeholder.
 */
function multimagazine_title( $title ) {
	if ( '' === $title ) {
		$title = __( 'Untitled', 'multimagazine' );
	}
	return $title;
}
add_filter( 'the_title', 'multimagazine_title' );

/**
 * Creates custom excerpt for posts
 *
 * @param integer $limit Max. word count.
 * @param object  $post Post object.
 * @param boolean $show_more_link If true adds a "read more" link to the excerpt.
 */
function multimagazine_custom_excerpt( $limit, $post, $show_more_link = false ) {
	if ( has_excerpt() ) {
		return get_the_excerpt();
	}
	$more = '<!--more-->';
	if ( $post ) {
		$multimagazine_found_posts = strpos( $post->post_content, $more );
	} else {
		$multimagazine_found_posts = false;
	}

	if ( ! $multimagazine_found_posts ) {
		$excerpt = explode( ' ', wp_strip_all_tags( get_the_content() ), $limit );
		if ( count( $excerpt ) >= $limit ) {
			array_pop( $excerpt );
			$excerpt = implode( ' ', $excerpt ) . '...';
		} else {
			$excerpt = implode( ' ', $excerpt );
		}
		$excerpt = preg_replace( '`\[[^\]]*\]`', '', $excerpt );
	} else {
		$excerpt = substr( $post->post_content, 0, $multimagazine_found_posts );
	}

	if ( $show_more_link ) {
		$excerpt .= ' <a href="' . esc_url( get_the_permalink() ) . '" class="more-link"><span class="screen-reader-text">' . get_the_title() . ' - </span>' . esc_html__( 'Read more', 'multimagazine' ) . '</a>';
	}
	return $excerpt;
}

/**
 * Prevents WordPress from adding "more" link to excerpt
 *
 * @param string $more "More" text - ingnore.
 */
function multimagazine_excerpt_more( $more ) {
	global $post;
	return '';
}
add_filter( 'excerpt_more', 'multimagazine_excerpt_more', 11 );

/**
 * Disables comments in new post by default
 *
 * @param array $data Post data.
 */
function multimagazine_default_comments_off( $data ) {
	if ( 'page' === $data['post_type'] && 'auto-draft' === $data['post_status'] ) {
		$data['comment_status'] = 0;
	}

	return $data;
}
add_filter( 'wp_insert_post_data', 'multimagazine_default_comments_off' );

/**
 * Customizes pagination
 */
function multimagazine_post_pagination() {
	return array(
		'link_before'      => '<span class="pagination-link">',
		'link_after'       => '</span>',
		'next_or_number'   => 'number',
		'before'           => '<p class="pages"><strong>' . __( 'Pages', 'multimagazine' ) . ':</strong> ',
		'after'            => '</p>',
		'previouspagelink' => '',
		'nextpagelink'     => '',
		'echo'             => 1,
		'pagelink'         => '%',
		'separator'        => '',
		'aria_current'     => 'page',
	);
}
add_filter( 'wp_link_pages_args', 'multimagazine_post_pagination' );

/**
 * Generates a slug from a string
 *
 * @param string  $phrase Word or phrase to slugify.
 * @param integer $max_length Max. length of the slug.
 */
function multimagazine_generate_slug( $phrase, $max_length = 200 ) {
	$result = strtolower( $phrase );
	$result = preg_replace( '/[^a-z0-9\s-]/', '', $result );
	$result = trim( preg_replace( '/[\s-]+/', ' ', $result ) );
	$result = trim( substr( $result, 0, $max_length ) );
	$result = preg_replace( '/\s/', '-', $result );

	return $result;
}

/**
 * Checks if a post is in any of the descendants of the chosen categories
 *
 * @param array          $parent_categories Category data array.
 * @param integer|object $search_post Post to check for.
 */
function multimagazine_post_is_in_descendant_category( $parent_categories, $search_post = null ) {
	foreach ( (array) $parent_categories as $cat ) {
		$descendants = get_term_children( (int) $cat, 'category' );
		if ( $descendants && in_category( $descendants, $search_post ) ) {
			return true;
		}
	}
	return false;
}

/**
 * Converts hexdec color string to rgb(a) string
 *
 * @param string $hex Hexadecimal color code.
 */
function multimagazine_hex2rgb( $hex ) {
	$hex = str_replace( '#', '', $hex );

	if ( strlen( $hex ) === 3 ) {
		$r = hexdec( substr( $hex, 0, 1 ) . substr( $hex, 0, 1 ) );
		$g = hexdec( substr( $hex, 1, 1 ) . substr( $hex, 1, 1 ) );
		$b = hexdec( substr( $hex, 2, 1 ) . substr( $hex, 2, 1 ) );
	} else {
		$r = hexdec( substr( $hex, 0, 2 ) );
		$g = hexdec( substr( $hex, 2, 2 ) );
		$b = hexdec( substr( $hex, 4, 2 ) );
	}
	$rgb = array( $r, $g, $b );
	return $rgb;
}

/**
 * Remover autopatic <p> tags from CF7 code
 *
 * @param string $form Contact Form 7 shortcode.
 */
function multimagazine_cf7_shortcodes( $form ) {
	$form = shortcode_unautop( do_shortcode( $form ) );
	return $form;
}
add_filter( 'wpcf7_form_elements', 'multimagazine_cf7_shortcodes' );

/**
 * Adds automatic <p> tags to Contact Form 7 form
 *
 * @param string $output CF7 markup.
 */
function multimagazine_wpcf7_response_output( $output ) {
	return wpautop( $output );
}
add_filter( 'wpcf7_form_response_output', 'multimagazine_wpcf7_response_output', 10, 1 );

/**
 * Retrieves the right CSS class for special headings based on settings
 *
 * @param integer $style Special heading style number.
 */
function multimagazine_heading_style( $style = 0 ) {
	$style = absint( $style );
	if ( empty( $style ) ) {
		$style = get_theme_mod( 'multi_underlined_heading_style', MULTIMAGAZINE_UNDERLINED_HEADING_STYLE );
	}
	$class = 't';
	if ( $style < 10 ) {
		$class .= '0';
	}
	$class .= $style;

	return $class;
}

/**
 * Checks if array contains any non-empty values
 *
 * @param array $arr Array to check.
 */
function multimagazine_any_value_exists( $arr ) {
	foreach ( $arr as $k => $v ) {
		if ( ! empty( $v ) ) {
			return true;
		}
	}
	return false;
}

/**
 * Retrieves classes needed by the "load while scrolling" feature
 */
function multimagazine_get_post_loading_classes() {
	$option_value = is_post_type_archive( 'project' ) ? get_theme_mod( 'multi_builder_load_projects', 'off' ) : get_theme_mod( 'multi_load_postlist', MULTIMAGAZINE_LOAD_POSTLIST );
	switch ( $option_value ) {
		case 'auto':
			return 'load-posts load-posts-auto';
		case 'button':
			return 'load-posts';
		default:
			return '';
	}
}

/**
 * Prepares custom attributes for an element
 *
 * @param string $custom_attributes Key-value pairs separated by new line character.
 */
function multimagazine_prepare_custom_attributes( $custom_attributes ) {
	$attributes = explode( "\n", $custom_attributes );
	$output     = '';
	foreach ( $attributes as $attr ) {
		$key   = substr( $attr, 0, strpos( $attr, ':' ) );
		$value = substr( $attr, strpos( $attr, ':' ) + 1 );

		$key = str_replace(
			array( ' ', '.', ',', '/', '?', '!', '~', '+', '*', '@', '#', '$', '%', '^', '&', '( ', ' )', '=' ),
			'-',
			strtolower( $key )
		);

		$output .= ' ' . $key . '="' . esc_attr( $value ) . '"';
	}
	return $output;
}

/**
 * Checks if a widget area is active
 *
 * @param string $name Widget area name.
 */
function multimagazine_is_sidebar_active( $name ) {
	global $wp_registered_sidebars;
	$has_widgets = wp_get_sidebars_widgets();
	return ! empty( $has_widgets[ $name ] );
}

/**
 * Checks if breadcrumb path should be displayed in subheader
 */
function multimagazine_breadcrumbs_in_subheader_pos() {
	$bc_pos = get_theme_mod( 'multi_subheader_breadcrumbs', MULTIMAGAZINE_SUBHEADER_BREADCRUMBS );
	if ( is_singular() ) {
		$local_bc = get_post_meta( get_the_id(), 'multi_show_breadcrumbs', true );
		if ( ! in_array( $local_bc, array( '', 'on', 'off' ), true ) ) {
			$bc_pos = $local_bc;
		}

		if ( 'off' === $local_bc || 'on' === $local_bc ) {
			$bc_pos = '';
		}
	}

	return $bc_pos;
}

/**
 * Checks if page title should be displayed in subheader
 */
function multimagazine_title_in_subheader_pos() {
	$title_pos = get_theme_mod( 'multi_subheader_title', MULTIMAGAZINE_SUBHEADER_TITLE );
	if ( is_singular() ) {
		$local_title = get_post_meta( get_the_id(), 'multi_show_title', true );
		if ( ! in_array( $local_title, array( '', 'on', 'off' ), true ) ) {
			$title_pos = $local_title;
		}

		if ( 'off' === $local_title || 'on' === $local_title ) {
			$title_pos = '';
		}
	}

	return $title_pos;
}

/**
 * Checks if page title should be displayed in page/post header
 */
function multimagazine_title_pos_default() {
	$show_title = get_post_meta( get_the_id(), 'multi_show_title', true );
	if ( strpos( $show_title, 'subheader' ) !== false ) {
		$type       = get_post_type( get_the_id() );
		$show_title = 'off';
	} elseif ( empty( $show_title ) ) {
		$title_in_subheader = get_theme_mod( 'multi_subheader_title', MULTIMAGAZINE_SUBHEADER_TITLE );
		if ( ! empty( $title_in_subheader ) ) {
			$show_title = 'off';
		}
	}

	return $show_title;
}

/**
 * Gets the title of current page
 */
function multimagazine_page_title() {
	$shop_page_id = class_exists( 'Woocommerce' ) ? wc_get_page_id( 'shop' ) : 0;

	$title = '';

	if ( is_home() ) {
		$id    = get_option( 'page_for_posts' );
		$title = get_the_title( $id );

	} elseif ( is_singular() ) {
		global $post;
		if ( class_exists( 'Woocommerce' ) && 'product' === get_post_type( $post->ID ) ) {
			$title = get_the_title( $shop_page_id );
		} elseif ( 'post' === get_post_type( $post->ID ) ) {
			$local_title = get_post_meta( get_the_id(), 'multi_show_title', true );
			if ( empty( $local_title ) ) {
				$local_title = get_theme_mod( 'multi_subheader_title', MULTIMAGAZINE_SUBHEADER_TITLE );
			}
			if ( false !== strpos( $local_title, 'subheader' ) ) {
				$title = get_the_title();
			} else {
				$page_for_posts = get_option( 'page_for_posts' );
				if ( empty( $page_for_posts ) ) {
					$title = __( 'Blog', 'multimagazine' );
				} else {
					$title = get_the_title( $page_for_posts );
				}
			}
		} else {
			$title = get_the_title( $post->ID );
		}
	} elseif ( is_404() ) {
		$title = esc_html__( 'Error 404 - Not Found.', 'multimagazine' );

	} elseif ( is_search() ) {
		$title = esc_attr__( 'Search results for', 'multimagazine' ) . ': "' . get_search_query() . '"';

	} elseif ( is_author() ) {
		global $author;
		$user_info = get_userdata( $author );
		$title     = __( 'Articles by', 'multimagazine' ) . ': ' . esc_html( $user_info->display_name );

	} elseif ( is_category() ) {
		global $cat;
		$current_cat = get_term( $cat, 'category' );
		$title       = $current_cat->name;

	} elseif ( is_tag() ) {
		$title .= esc_attr__( 'Posts tagged', 'multimagazine' ) . ': ' . single_tag_title( '', false );

	} elseif ( is_tax( 'product_cat' ) ) {
		$current_term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
		$title        = $current_term->name;

	} elseif ( is_tax( 'project-categories' ) ) {
		$current_term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
		$title        = $current_term->name;

	} elseif ( is_tax( 'product_tag' ) ) {
		global $wp_query;
		$queried_object = $wp_query->get_queried_object();
		$title          = __( 'Products tagged &ldquo;', 'multimagazine' ) . $queried_object->name . '&rdquo;';

	} elseif ( is_post_type_archive() && ! is_post_type_archive( 'product' ) ) {
		global $wp_query;
		$queried_object = $wp_query->get_queried_object();
		$labels         = $queried_object->labels;
		$title          = $labels->name;

	} elseif ( class_exists( 'Woocommerce' ) && ( ! is_home() && ! is_front_page() && ! ( is_post_type_archive() && get_option( 'page_on_front' ) === $shop_page_id ) ) ) {
		$shop_page_id = wc_get_page_id( 'shop' );
		$shop_page    = get_post( $shop_page_id );
		$title        = $shop_page->post_title;

	} elseif ( is_archive() ) {
		$title = get_the_archive_title();

	}

	return $title;
}

/**
 * Renders post title, or seo title if available
 */
function multimagazine_the_title() {
	if ( function_exists( 'seo_friendly_the_title' ) ) {
		seo_friendly_the_title();
	} else {
		the_title();
	}
}

/**
 * Prepares numbers to be included in css
 *
 * @param Float $number Number to sanitize.
 */
function multimagazine_css_number( $number ) {
	$number = str_replace( ',', '.', $number );

	return $number;
}

/**
 * Gets contents of file
 *
 * @param String $url URL of file to read.
 */
function multimagazine_remote_get( $url ) {
	$response = wp_remote_get( $url );
	$content  = wp_remote_retrieve_body( $response );
	return $content;
}

/**
 * Ensures a url has a trailing slash
 *
 * @param String $url URL.
 */
function multimagazine_slash_link( $url ) {
	$permalink_structure = get_option( 'permalink_structure' );
	$last_char           = substr( $permalink_structure, -1 );
	if ( '/' !== $last_char ) {
		return trailingslashit( $url );
	}
	return $url;
}
add_filter( 'paginate_links', 'trailingslashit' );
add_filter( 'get_pagenum_link', 'trailingslashit' );
