<?php
if (!defined('ABSPATH')) {
  exit;
}

/*
  * Blog functions
*/

// Limit characters blog card
function custom_excerpt_length( $length ) {
	return 25;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

// Excerpt readmore change [...] to ...
function excerpt_readmore($more) {
	return '...';
}
add_filter( 'excerpt_more', 'excerpt_readmore' );

// If blog return -> archive, author, category, single, tag and get post
function is_blog () {
  return ( is_archive() || is_author() || is_category() || is_single() || is_tag()) && 'post' == get_post_type();
}

// Blog pagination
function pagination() {
	global $wp_query;
	if ( $wp_query->max_num_pages <= 1 ) return; 
	$big = 999999999; // need an unlikely integer

	$pages = paginate_links( array(
		'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
		'format' => '?paged=%#%',
		'current' => max( 1, get_query_var('paged') ),
		'total' => $wp_query->max_num_pages,
		'type'  => 'array',
	));
  
	if( is_array( $pages ) ) {
		$paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');
		echo '<div class="pagination-wrap"><ul class="pagination">';
		foreach ( $pages as $page ) {
			echo "<li class='pagination-item'>$page</li>";
		}
		echo '</ul></div>';
	}
}

function custom_pre_get_posts($query)
{
 if ($query->is_main_query() && !$query->is_feed() && !is_admin() && is_category()) {
  $query->set('page_val', get_query_var('paged'));
  $query->set('paged', 0);
 }
}
add_action( 'pre_get_posts', 'custom_pre_get_posts' );

// Blog max tittle length
function max_title_length( $title ) {
  $max = 29;
  if( strlen( $title ) > $max ) {
    return substr( $title, 0, $max ). "&hellip;";
  } else {
    return $title;
  }
}

// Share post social media
function get_the_post_thumbnail_src($img)
{
  return (preg_match('~\bsrc="([^"]++)"~', $img, $matches)) ? $matches[1] : '';
}
function sharing_post($content) {
  global $post;
  if(is_single()){
    $sb_url = urlencode(get_permalink());
    $sb_title = str_replace( ' ', '%20', get_the_title());
    $sb_thumb = get_the_post_thumbnail_src(get_the_post_thumbnail());
    
    $facebookURL = 'https://www.facebook.com/sharer/sharer.php?u='.$sb_url;
    $linkedInURL = 'https://www.linkedin.com/shareArticle?mini=true&url='.$sb_url.'&amp;title='.$sb_title;
    $whatsappURL = 'https://api.whatsapp.com/send?text='.$sb_title.' - '.$sb_url.'';
 
    $content .= '<div class="share">';
    $content .= '<h5 class="pull-left">Compartilhe:</h5>';
    $content .= '<ul class="styled-icons">';

    $content .= '<li><a href="'.$facebookURL.'" target="_new" alt="Compartilhar no Facebook"><i class="fa fa-facebook"></i></a></li>';
    $content .= '<li><a href="'. $linkedInURL .'" target="_new" alt="Compartilhar no Facebook"><i class="fa fa-linkedin"></i></a></li>';
    $content .= '<li><a href="'. $whatsappURL .'" target="_new" alt="Compartilhar no Facebook"><i class="fa fa-whatsapp"></i></a></li>';
		$content .= '</ul>';
		$content .= '</div>';
        
    return $content;
    }else{
      return $content;
    }
};
//add_filter( 'the_content', 'sharing_post' );
add_shortcode( 'sharing_post','sharing_post');

// Load more posts listing
function load_more_script() {
  if(!is_front_page()){
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'load-more-posts-list', get_stylesheet_directory_uri() . '/js/load-more-posts-list.js', array('jquery') );
  }
}
add_action( 'wp_enqueue_scripts', 'load_more_script' );

function load_more_posts(){
  $args = unserialize( stripslashes( $_POST['query'] ) );
  $args['paged'] = $_POST['page'] + 1;
  $args['post_status'] = 'publish';
 
  query_posts( $args );
  if( have_posts() ) :
    while( have_posts() ): the_post();
      get_template_part( 'template-parts/blog/list-blog-post', get_post_format() ); 
    endwhile;
  endif;
  die();
}
add_action('wp_ajax_loadmore', 'load_more_posts');
add_action('wp_ajax_nopriv_loadmore', 'load_more_posts');

// Previous and Next Post
function blog_posts_nav(){
  $next_post = get_next_post();
  $prev_post = get_previous_post();
   
  if ( $next_post || $prev_post ) : ?>
   
      <div class="blog-posts-nav">
          <div>
              <?php if (!empty( $prev_post )) : ?>
                  <a href="<?php echo get_permalink( $prev_post ); ?>">
                      <div>
                          <strong>
                              <svg viewBox="0 0 24 24" width="24" height="24">
                                <path d="M13.775,18.707,8.482,13.414a2,2,0,0,1,0-2.828l5.293-5.293,1.414,1.414L9.9,12l5.293,5.293Z"/>
                              </svg>
                              <?php _e( 'Postagem Anterior', 'textdomain' ) ?>
                          </strong>
                          <h4><?php echo get_the_title( $prev_post ); ?></h4>
                      </div>
                  </a>
              <?php endif; ?>
          </div>
          <div>
              <?php if (!empty( $next_post )) : ?>
                  <a href="<?php echo get_permalink( $next_post ); ?>">
                      <div>
                          <strong>
                              <?php _e( 'Próxima postagem', 'textdomain' ) ?>
                              <svg viewBox="0 0 24 24" width="24" height="24">
                                <path d="M10.811,18.707,9.4,17.293,14.689,12,9.4,6.707l1.415-1.414L16.1,10.586a2,2,0,0,1,0,2.828Z"/>
                              </svg>
                          </strong>
                          <h4><?php echo get_the_title( $next_post ); ?></h4>
                      </div>
                  </a>
              <?php endif; ?>
          </div>
      </div>
   
  <?php endif;
}

// Read time
function display_read_time() {
  $content = get_post_field( 'post_content', $post->ID );
  $count_words = str_word_count( strip_tags( $content ) );

  $read_time = ceil($count_words / 250);

  $suffix = " min";
  $read_time_output = $read_time . $suffix;

  return $read_time_output;
}

/*
* Search
*/

// Rewrite url
function search_url_rewrite_rule() {
	if ( is_search() && !empty($_GET['s'])) {
		wp_redirect(home_url("/search/") . urlencode(get_query_var('s')));
		exit();
	}	
}
add_action( 'template_redirect', 'search_url_rewrite_rule' );

// Search only posts
function search_only_posts($query) {
  if ($query->is_search) {
      $query->set('post_type', 'post');
  }
  return $query;
}
add_filter( 'pre_get_posts', 'search_only_posts' );