<?php
/**
 * KIS custom functions and definitions.
 *
 * @package KIS
 */

/**
 * Prevent theme activation if WordPress version is less than 5.0 !
 *
 * @param object $old_theme_name Old Theme Name.
 * @param string $old_theme Switch to Old Theme.
 */
function kis_check_wp_version( $old_theme_name, $old_theme ) {

	global $wp_version;
	if ( $wp_version < 5.0 && current_user_can( 'edit_theme_options' ) ) :

		/** Info message: Theme not activated */
		function kis_not_activated_admin_notice() {
			echo '<div class="error notice">';
			echo '<h2>';
				esc_html_e( 'Theme not activated: this theme requires at least WordPress Version 5.0 !', 'kis' );
			echo '</h2>';
			echo '</div>';
		}
		add_action( 'admin_notices', 'kis_not_activated_admin_notice' );

		// Switch back to previous theme.
		switch_theme( $old_theme->stylesheet );
		return false;

	endif;

}
add_action( 'after_switch_theme', 'kis_check_wp_version', 10, 2 );

/**
 * Enqueue original scripts and styles.
 */
function kis_original_scripts() {
	wp_enqueue_style( 'kis-default', get_theme_file_uri( '/css/kis-default.css' ), array(), filemtime( get_theme_file_path( '/css/kis-default.css' ) ) );

	wp_enqueue_style( 'kis-layout', get_theme_file_uri( '/css/kis-layout.css' ), array(), filemtime( get_theme_file_path( '/css/kis-layout.css' ) ) );

	wp_enqueue_style( 'kis-media-queries', get_theme_file_uri( '/css/kis-media-queries.css' ), array(), filemtime( get_theme_file_path( '/css/kis-media-queries.css' ) ) );

	wp_enqueue_style( 'kis-merriweather', '//fonts.googleapis.com/css?family=Merriweather:400,400i,700', array( 'kis-default' ), wp_get_theme()->get( 'Version' ) );

	wp_enqueue_style( 'kis-open-sans', '//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700', array( 'kis-default' ), wp_get_theme()->get( 'Version' ) );

	wp_enqueue_script( 'headroom', get_theme_file_uri( '/js/headroom.min.js' ), array(), filemtime( get_theme_file_path( '/js/headroom.min.js' ) ), true );

	wp_enqueue_script( 'kis-main', get_theme_file_uri( '/js/kis-main.js' ), array( 'jquery' ), filemtime( get_theme_file_path( '/js/kis-main.js' ) ), true );
}
add_action( 'wp_enqueue_scripts', 'kis_original_scripts' );

/**
 * Disable output of kirki styles if the plugin is disabled or removed.
 */
if ( ! class_exists( 'Kirki' ) ) {
	/**
	 * Function to remove Kirki styles.
	 */
	function kis_remove_kirki_styles() {
		wp_dequeue_style( 'kis_no-kirki' );
		wp_deregister_style( 'kis_no-kirki' );
	}
	add_action( 'wp_enqueue_scripts', 'kis_remove_kirki_styles', 20 );
}

/**
 * Add an admin notice if Kirki is disabled or removed.
 */
if ( ! class_exists( 'Kirki' ) ) {
	/**
	 * Function to display admin notice.
	 */
	function kis_admin_notice__info() {
		$class   = 'notice notice-info is-dismissible';
		$message = __( 'To take full advantage of this theme\'s features in the Customizer, install the Kirki plugin and activate it !', 'kis' );

		printf( '<div class="%1$s"><h1>%2$s</h1></div>', esc_attr( $class ), esc_html( $message ) );
	}
	add_action( 'admin_notices', 'kis_admin_notice__info' );
}

/**
 * Give #wpadminbar a fixed position from 600px and under, using inline style since we can't use #wpadminbar in CSS.
 */
function kis_wp_adminbar() {
	$wp_adminbar = '
		@media screen and (max-width: 600px) {
			#wpadminbar {
				position: fixed;
			}
		}';
	wp_add_inline_style( 'kis-layout', $wp_adminbar );
}
add_action( 'wp_enqueue_scripts', 'kis_wp_adminbar' );

/**
 * Generate custom search form
 *
 * @param string $form Form HTML.
 * @return string Modified form HTML.
 *
 * @link https://developer.wordpress.org/reference/functions/get_search_form/#comment-369
 */
function kis_search_form( $form ) {
	$form =
		'<form role="search" method="get" class="search-form" action="' . home_url( '/' ) . '" >
			<label>
				<span class="screen-reader-text">' . esc_attr__( 'Search for:', 'kis' ) . '</span>
				<input type="search" class="search-field text-search"
					   placeholder="' . esc_attr__( 'Search here &hellip;', 'kis' ) . '" '
					. 'value="' . get_search_query() . '" name="s" id="s" required '
					. 'title="' . esc_attr__( 'Search for:', 'kis' ) . '" />
			</label>
			<button type="submit" class="search-submit"
					value="' . esc_attr__( 'Search', 'kis' ) . '" />
				<i class="icon-search"></i>
			</button>
		</form>';

	return $form;
}
add_filter( 'get_search_form', 'kis_search_form' );

/**
 * Allow to upload and use SVG.
 *
 * @see https://themeisle.com/blog/add-svg-to-wordpress/
 * @param string $file_types SVG.
 */
function kis_add_file_types_to_uploads( $file_types ) {
	$new_filetypes        = array();
	$new_filetypes['svg'] = 'image/svg+xml';
	$file_types           = array_merge( $file_types, $new_filetypes );
	return $file_types;
}
add_action( 'upload_mimes', 'kis_add_file_types_to_uploads' );

/**
 * Modify The Read More Link Text.
 *
 * @see https://codex.wordpress.org/Customizing_the_Read_More
 */
function kis_read_more_link() {
	return '<a class="more-link" href="' . get_permalink() . '"> [ Read more ] </a>';
}
add_filter( 'the_content_more_link', 'kis_read_more_link' );

/**
 * Filter the excerpt length to 20 words.
 *
 * @see https://developer.wordpress.org/reference/functions/the_excerpt/#comment-325
 * @param int $length Excerpt length.
 * @return int (Maybe) modified excerpt length.
 */
function wpdocs_custom_excerpt_length( $length ) {
	return 20;
}
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );

/**
 * Replaces the excerpt "Read More" text by a link.
 *
 * @see https://codex.wordpress.org/Customizing_the_Read_More
 * @param string $more Link to the article.
 */
function kis_excerpt_more( $more ) {
	global $post;
	return '<a class="moretag" href="' . get_permalink( $post->ID ) . '"> [ Read more ] </a>';
}
add_filter( 'excerpt_more', 'kis_excerpt_more' );

/**
 * Change the HTML5 output of comments.
 *
 * @see wp_list_comments()
 *
 * @param WP_Comment $comment Comment to display.
 * @param array      $args    An array of arguments.
 * @param int        $depth   Depth of the current comment.
 */
function kis_comments_callback( $comment, $args, $depth ) {
	$tag = ( 'div' === $args['style'] ) ? 'div' : 'li';
	?>
	<<?php echo esc_html( $tag ); ?> id="comment-<?php comment_ID(); ?>" <?php comment_class( $args['has_children'] ? 'parent' : '', $comment ); ?>>
		<article id="div-comment-<?php comment_ID(); ?>" class="comment-body">
			<footer class="comment-meta">
				<div class="comment-author vcard">
					<?php
					// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
					if ( 0 != $args['avatar_size'] ) {
						echo get_avatar( $comment, $args['avatar_size'] );}
					?>
					<?php
						printf(
							/* translators: %s: comment author link */
							esc_html( '%1$s, %2$s' ),
							sprintf( '<b class="fn">%s</b>', get_comment_author_link( $comment ) ),
							sprintf( '<span class="says">says:</span>' )
						);
					?>
				</div><!-- .comment-author -->

				<div class="comment-metadata">
					<a href="<?php echo esc_url( get_comment_link( $comment, $args ) ); ?>">
						<time datetime="<?php comment_time( 'c' ); ?>">
							<?php
								printf(
									/* translators: 1: comment date, 2: comment time */
									esc_html( '%1$s @ %2$s' ),
									esc_html( get_comment_date( '', $comment ) ),
									esc_html( get_comment_time() )
								);
							?>
						</time>
					</a>
					<?php
					comment_reply_link(
						array_merge(
							$args,
							array(
								'add_below' => 'div-comment',
								'depth'     => $depth,
								'max_depth' => $args['max_depth'],
								'before'    => '<span class="sep">/</span><div class="reply">',
								'after'     => '</div>',
							)
						)
					);
					?>
					<?php edit_comment_link( __( 'Edit', 'kis' ), '<span class="edit-link">', '</span>' ); ?>
				</div><!-- .comment-metadata -->

				<?php // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison ?>
				<?php if ( '0' == $comment->comment_approved ) : ?>
				<p class="comment-awaiting-moderation"><?php esc_html_e( 'Your comment is awaiting moderation.', 'kis' ); ?></p>
				<?php endif; ?>
			</footer><!-- .comment-meta -->

			<div class="comment-content">
				<?php comment_text(); ?>
			</div><!-- .comment-content -->

		</article><!-- .comment-body -->
	<?php
}

/**
 * Change comment form textarea to use placeholder.
 *
 * @see https://www.billerickson.net/code/use-placeholders-instead-of-labels-in-comment-form/
 * @param string $args Comment Form Textarea.
 */
function kis_comment_textarea_placeholder( $args ) {
	$args['comment_field'] = str_replace( 'textarea', 'textarea placeholder="' . esc_attr__( 'Comment *', 'kis' ) . '" class="form-control"', $args['comment_field'] );
	return $args;
}
add_filter( 'comment_form_defaults', 'kis_comment_textarea_placeholder' );

/**
 * Comment Form Fields Placeholder.
 *
 * @param string $fields Comment Form Author, Email and Website.
 */
function kis_comment_form_fields( $fields ) {
	foreach ( $fields as &$field ) {
		$field = str_replace( 'id="author"', 'id="author" class="form-control" placeholder="' . esc_attr__( 'Name *', 'kis' ) . '"', $field );
		$field = str_replace( 'id="email"', 'id="email" class="form-control" placeholder="' . esc_attr__( 'Email *', 'kis' ) . '"', $field );
		$field = str_replace( 'id="url"', 'id="url" class="form-control" placeholder="' . esc_attr__( 'Website', 'kis' ) . '"', $field );
	}
	return $fields;
}
add_filter( 'comment_form_default_fields', 'kis_comment_form_fields' );

/**
 * Move the Comment Text Field to Bottom.
 *
 * @param string $fields Comment Text Field.
 */
function kis_move_comment_field_to_bottom( $fields ) {
	$comment_field = $fields['comment'];
	unset( $fields['comment'] );
	$fields['comment'] = $comment_field;
	return $fields;
}
add_filter( 'comment_form_fields', 'kis_move_comment_field_to_bottom' );

/**
 * Use Dashicons on frontend in WordPress.
 */
function load_dashicons_front_end() {
	wp_enqueue_style( 'dashicons' );
}
add_action( 'wp_enqueue_scripts', 'load_dashicons_front_end' );

/**
 * Create and return an array containing the names of the social sites.
 */
function kis_social_sites() {
	/* store social sites names in array */
	$social_sites = array(
		'facebook'   => '',
		'twitter'    => '',
		'googleplus' => '',
		'wordpress'  => '',
		'email'      => '',
	);

	// Filtering the function, allowing user(s) to add more social sites in child theme.
	return apply_filters( 'kis_social_sites', $social_sites );
}

/**
 * Get user input from the Customizer and output the linked social media site icon.
 */
function kis_social_media_icons() {
	$social_sites = kis_social_sites();

	/* any inputs that aren't empty are stored in $active_sites array */
	foreach ( $social_sites as $social_site => $profile ) {
		if ( strlen( get_theme_mod( $social_site ) ) > 0 ) {
			$active_sites[] = $social_site;
		}
	}

	/* for each active social site, add it as a list item */
	if ( ! empty( $active_sites ) ) {

		foreach ( $active_sites as $key => $active_site ) {

			/* setup the class */
			$class = 'dashicons dashicons-' . $active_site;

			if ( 'email' === $active_site ) {
				?>
				<li>
					<a class="email" target="_blank" href="mailto:<?php echo esc_attr( antispambot( is_email( get_theme_mod( $active_site ) ) ) ); ?>">
						<span class="dashicons dashicons-email-alt">
						</span>
					</a>
				</li>
				<?php

			} else {
				?>
				<li>
					<a class="<?php echo esc_attr( $active_site ); ?>" target="_blank" href="<?php echo esc_url( get_theme_mod( $active_site ) ); ?>">
						<span class="<?php echo esc_attr( $class ); ?>">
						</span>
					</a>
				</li>
				<?php

			}
		}
	}
}

/**
 * Function to display the site info, copyrigth.
 */
function kis_site_info() {
	$credits          = get_theme_mod( 'display_credits', true );
	$custom_copyright = get_theme_mod( 'custom_copyright', '' );
	if ( ( ! empty( $credits ) && empty( $custom_copyright ) ) || ( ! empty( $credits && $custom_copyright ) ) ) {
		?>
		<a href="<?php echo esc_url( __( 'https://wordpress.org/', 'kis' ) ); ?>">
			<?php
			/* translators: %s: CMS name, i.e. WordPress. */
			printf( esc_html__( 'Proudly powered by %s', 'kis' ), 'WordPress' );
			?>
		</a>
		<span class="sep"> | </span>
			<?php
			/* translators: 1: Theme name, 2: Theme author. */
			printf( esc_html__( 'Theme: %1$s by %2$s', 'kis' ), 'kis', '<a href="https://lebcit.tk">LebCit</a>' );
			?>
		<span class="sep"> | </span>
			<?php
			/* translators: %s: Template Designer. */
			printf( esc_html__( 'Design by %s.', 'kis' ), '<a href="http://www.styleshout.com/">Styleshout</a>' );
			?>
			<?php
	} else {
		echo esc_html( $custom_copyright );
	}
}
