<?php
/**
* This template containing functions of the theme.
*
* @package Interserver Mommy Blog
*/

if ( ! function_exists( 'interserver_mommy_blog_setup' ) ) :
function interserver_mommy_blog_setup() {
    global $interserver_mommy_blog_default;
     /*
     * Make theme available for translation.
     * Translations can be filed in the /languages/ directory.
     * If you're building a theme based on twentyfifteen, use a find and replace
     * to change 'interserver-mommy-blog' to the name of your theme in all the template files
     */
    load_theme_textdomain( 'interserver-mommy-blog', get_template_directory() . '/languages' );
 
    // Add default posts and comments RSS feed links to head.
    add_theme_support( 'automatic-feed-links' );

    // Content width
    global $content_width;
    if ( ! isset( $content_width ) ) {
      $content_width = 1170; /* pixels */
    }
 
    /*
     * Let WordPress manage the document title.
     * By adding theme support, we declare that this theme does not use a
     * hard-coded  tag in the document head, and expect WordPress to
     * provide it for us.
     */
    add_theme_support( 'title-tag' );

    // Setup the WordPress core custom background feature.
    $defaults = array(
	    'default-image'          => '',
	    'default-preset'         => 'default', // 'default', 'fill', 'fit', 'repeat', 'custom'
	    'default-position-x'     => 'left',    // 'left', 'center', 'right'
	    'default-position-y'     => 'top',     // 'top', 'center', 'bottom'
	    'default-size'           => 'cover',    // 'auto', 'contain', 'cover'
	    'default-repeat'         => 'repeat',  // 'repeat-x', 'repeat-y', 'repeat', 'no-repeat'
	    'default-attachment'     => 'scroll',  // 'scroll', 'fixed'
	    'default-color'          => '',
	    'wp-head-callback'       => '_custom_background_cb',
	    'admin-head-callback'    => '',
	    'admin-preview-callback' => '',
    );
	add_theme_support( 'custom-background', $defaults );

 	// Setup the WordPress Custom header
	$defaults = array(
	    'default-image'          => '',
	    'random-default'         => false,
	    'width'                  => 0,
	    'height'                 => 0,
	    'flex-height'            => false,
	    'flex-width'             => false,
	    'header-text'            => false,
	    'uploads'                => true,
	    'wp-head-callback'       => '',
	    'admin-head-callback'    => '',
	    'admin-preview-callback' => '',
	    'video'                  => false,
	    'video-active-callback'  => 'is_front_page',
	);
	add_theme_support( 'custom-header', $defaults );

	// Setup the WordPress Custom Logo
	add_theme_support( 'custom-logo', array(
    'height'      => 100,
    'width'       => 400,
    'flex-height' => true,
    'flex-width'  => true,
    'header-text' => array( 'site-title', 'site-desc' ),
	) );
  
    /*
     * Enable support for Post Thumbnails on posts and pages.
     *
     * See: https://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails
     */
    add_theme_support( 'post-thumbnails' );
      
    // This theme uses wp_nav_menu() in two locations.
    register_nav_menus( array(
        'primary' => __( 'Primary Menu', 'interserver-mommy-blog' ),
        'social'  => __( 'Social Menu', 'interserver-mommy-blog' ),
    ) );
 
    /*
     * Switch default core markup for search form, comment form, and comments
     * to output valid HTML5.
     */
    add_theme_support( 'html5', array(
        'search-form', 'comment-form', 'comment-list', 'gallery', 'caption'
    ) );
 
    /*
     * Enable support for Post Formats.
     *
     * See: https://codex.wordpress.org/Post_Formats
     */
    add_theme_support( 'post-formats', array(
        'aside', 'image', 'video', 'quote', 'link', 'gallery', 'status', 'audio', 'chat'
    ) );

    // Set up the WordPress core custom background feature.
    add_theme_support( 'custom-background', apply_filters( 'interserver_mommy_blog_custom_background_args', array(
        'default-color' => 'ffffff',
        'default-image' => '',
    ) ) );

    // Adds support for editor color palette.
    add_theme_support( 'editor-color-palette', array(
    array(
        'name'  => __( 'Primary color', 'interserver-mommy-blog' ),
        'slug'  => 'primary_color',
        'color' => $interserver_mommy_blog_default['primary_color'],
    ),
    array(
        'name'  => __( 'Secondary color', 'interserver-mommy-blog' ),
        'slug'  => 'secondary_color',
        'color' => $interserver_mommy_blog_default['secondary_color'],
    ),
    array(
        'name'  => __( 'Body Text Color', 'interserver-mommy-blog' ),
        'slug'  => 'body_color',
        'color' => $interserver_mommy_blog_default['body_color'],
    ),
    array(
        'name'  => __( 'Title Color', 'interserver-mommy-blog' ),
        'slug'  => 'title_color',
        'color' => $interserver_mommy_blog_default['sw_title_color'],
    ),
    array(
        'name'  => __( 'White Color', 'interserver-mommy-blog' ),
        'slug'  => 'white_color',
        'color' => '#ffffff',
    ),
    array(
        'name'  => __( 'Black Color', 'interserver-mommy-blog' ),
        'slug'  => 'black_color',
        'color' => '#000000',
    )
    ));


    // Add support for responsive embedded content.
    add_theme_support( 'responsive-embeds' );

    add_theme_support( 'align-wide' );

    add_theme_support( "wp-block-styles" );

    /*
     * This theme styles the visual editor to resemble the theme style,
     * specifically font, colors, icons, and column width.
     */
    add_editor_style('css/editor-style.css');

    add_theme_support( 'customize-selective-refresh-widgets' );
}
endif; // interserver_mommy_blog_setup
add_action( 'after_setup_theme', 'interserver_mommy_blog_setup' );


function interserver_mommy_blog_init(){
    register_block_style(
            'core/quote',
            array(
                'name'         => 'blue-quote',
                'label'        => __( 'Blue Quote', 'interserver-mommy-blog' ),
                'is_default'   => true,
                'inline_style' => '.wp-block-quote.is-style-blue-quote { color: blue; }',
            )
    );

    register_block_pattern(
        'imb-awesome-pattern',
        array(
            'title'       => __( 'Two buttons', 'interserver-mommy-blog' ),
            'description' => _x( 'Two horizontal buttons, the left button is filled in, and the right button is outlined.', 'Block pattern description', 'interserver-mommy-blog' ),
            'content'     => "<!-- wp:buttons {\"align\":\"center\"} -->\n<div class=\"wp-block-buttons aligncenter\"><!-- wp:button {\"backgroundColor\":\"very-dark-gray\",\"borderRadius\":0} -->\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link has-background has-very-dark-gray-background-color no-border-radius\">" . esc_html__( 'Button One', 'interserver-mommy-blog' ) . "</a></div>\n<!-- /wp:button -->\n\n<!-- wp:button {\"textColor\":\"very-dark-gray\",\"borderRadius\":0,\"className\":\"is-style-outline\"} -->\n<div class=\"wp-block-button is-style-outline\"><a class=\"wp-block-button__link has-text-color has-very-dark-gray-color no-border-radius\">" . esc_html__( 'Button Two', 'interserver-mommy-blog' ) . "</a></div>\n<!-- /wp:button --></div>\n<!-- /wp:buttons -->",
        )
    );
}
add_action('init', 'interserver_mommy_blog_init');

// Fonts
if ( !function_exists('interserver_mommy_blog_google_fonts') ) :
function interserver_mommy_blog_google_fonts() {
    global $interserver_mommy_blog_default;
    $logo_font      = get_theme_mod('logo_font_name', $interserver_mommy_blog_default['logo_font_name']);
    $headings_font  = get_theme_mod('headings_font_name', $interserver_mommy_blog_default['headings_font_name']);
    $body_font      = get_theme_mod('body_font_name', $interserver_mommy_blog_default['body_font_name']);

    $fonts = array();
    $fonts[] = esc_attr( str_replace( '+', ' ', $logo_font ) );
    $fonts[] = esc_attr( str_replace( '+', ' ', $body_font ) );
    $fonts[] = esc_attr( str_replace( '+', ' ', $headings_font ) );

    $query_args = array(
        'family' => urlencode( implode( '|', $fonts ) )
    );
    
    if ( $fonts ) {
        $fonts_url = add_query_arg($query_args, 'https://fonts.googleapis.com/css' );
    }
    return $fonts_url;  
}
endif;

function interserver_mommy_blog_enqueue_scripts() {
    wp_enqueue_style( 'style', get_stylesheet_uri() );
    wp_register_style( 'interserver-mommy-blog-google-fonts', esc_url( interserver_mommy_blog_google_fonts() ), array(),null );
    wp_enqueue_style( 'interserver-mommy-blog-google-fonts' );

    wp_enqueue_style( 'interserver-mommy-blog-fa-all', get_template_directory_uri() . '/fonts/css/all.min.css' );
    wp_enqueue_style( 'interserver-mommy-blog-meanmenu-style', get_template_directory_uri() . '/css/meanmenu.css' );
   
    wp_enqueue_style( 'interserver-mommy-blog-responsive', get_template_directory_uri() . '/css/responsive.css' );

    wp_enqueue_style( 'interserver-mommy-blog-ie9', get_template_directory_uri() . '/css/ie9.css', array( 'interserver-blog-style' ) );
    wp_style_add_data( 'interserver-mommy-blog-ie9', 'conditional', 'lte IE 9' );

    wp_enqueue_style( 'interserver-blog-fontawesome', get_template_directory_uri() . '/fonts/js/all.min.js' );   
    wp_enqueue_script( 'interserver-mommy-blog-meanmenu', get_template_directory_uri() . '/js/jquery.meanmenu.js', array('jquery'), '20160909', true );
     wp_enqueue_script( 'interserver-mommy-blog-custom', get_template_directory_uri() . '/js/custom.js', array(), '20130115', true );
 
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
      wp_enqueue_script( 'comment-reply' );
    }
}
add_action( 'wp_enqueue_scripts', 'interserver_mommy_blog_enqueue_scripts' );


/**
 * Register widget area.
 * @link http://codex.wordpress.org/Function_Reference/register_sidebar
 */
function interserver_mommy_blog_widgets_init() {
    register_sidebar( array(
        'name'          => __( 'Sidebar', 'interserver-mommy-blog' ),
        'id'            => 'sidebar-1',
        'description'   => '',
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget'  => '</aside>',
        'before_title'  => '<h4 class="widget-title">',
        'after_title'   => '</h4>',
    ));
    // Footer Top Widget
    register_sidebar( array(
        'name'          => __( 'Footer Top', 'interserver-mommy-blog' ),
        'id'            => 'footer-top',
        'description'   => '',
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget'  => '</aside>',
        'before_title'  => '<h4 class="widget-title">',
        'after_title'   => '</h4>',
    ));
    //Footer widget areas
    $widget_areas = get_theme_mod('footer_widgets', '1');
    for ($i=1; $i<=$widget_areas; $i++) {
        register_sidebar( array(
            'name'          => __( 'Footer ', 'interserver-mommy-blog' ) . $i,
            'id'            => 'footer-' . $i,
            'description'   => '',
            'before_widget' => '<aside id="%1$s" class="widget %2$s">',
            'after_widget'  => '</aside>',
            'before_title'  => '<h4 class="widget-title">',
            'after_title'   => '</h4>',
        ) );
    }
}
add_action( 'widgets_init', 'interserver_mommy_blog_widgets_init' );

include_once('inc/customizer/customizer.php');

include_once('inc/customizer/customizer.php');

include_once('inc/tgm/tgm.php');

include_once('inc/template-tags.php');

function interserver_mommy_blog_featured_section() {
global $interserver_mommy_blog_default;
global $post;
    $featured_cat_id = get_theme_mod('featured_cat', $interserver_mommy_blog_default['featured_cat']);
    $count = 1;
    $feat_query = new WP_Query(array(
        'cat' => $featured_cat_id,
        'post_status' => 'publish',
        'posts_per_page' => 5,
        'ignore_sticky_posts' => 1
    ));
   
    echo '<div class="featured-section">';
    while ($feat_query->have_posts() ) : ($feat_query->the_post()); 
    if ( has_post_thumbnail() ) {
        $feat_img = get_the_post_thumbnail_url($post->ID, 'full');
    } else {
        $feat_img = get_template_directory_uri().'/images/default-image.jpg';
    }

    get_template_part( 'content', get_post_format() );
    if ($count == 1) {
        echo '<div class="featured-left"><a href="'.esc_url(get_the_permalink()).'" title="'.the_title_attribute( 'echo=0' ).'"><img src="'.$feat_img.'" class="img-responsive"/></a></div><div class="featured-right">';
         $count++;
    } else {
        echo '<div class="featured-block"><a href="'.esc_url(get_the_permalink()).'" title="'.the_title_attribute( 'echo=0' ).'"><img src="'.$feat_img.'" class="img-responsive"/></a></div>';
    }
    endwhile;
    echo "</div></div>";
}

// Custom Excerpt
function interserver_mommy_blog_custom_excerpt() {
  global $interserver_mommy_blog_default;
  $limit = get_theme_mod('excerpt_length', $interserver_mommy_blog_default['excerpt_length']);
  $excerpt = explode(' ', strip_tags(get_the_content()), $limit);
  if ( count( $excerpt ) >= $limit ){
    array_pop($excerpt);
    $excerpt = implode( " ",$excerpt ).'';
  } else {
    $excerpt = implode( " ",$excerpt );
  } 
  $excerpt = preg_replace('`[[^]]*]`','',$excerpt);
  return $excerpt;
}

// Numbered pagination
function interserver_mommy_blog_pagination_nav( $query ) {
  global $wp_query;
  $total_pages = $query->max_num_pages;
  if ($total_pages > 1){
    $current_page = max(1, get_query_var('paged'));
    echo paginate_links(array(
    'base' => get_pagenum_link(1) . '%_%',
    'format' => '/page/%#%',
    'mid_size'  =>2,
    'current'=> $current_page,
    'total' => $total_pages,
    ));
  }
}

/**
 * Filter the term clauses using the arguments, specifically for the wp_dropdown_categories.
 *
 * @see http://wordpress.stackexchange.com/questions/207655/restrict-taxonomy-dropdown-to-post-type
 * @see https://www.dfactory.eu/get_terms-post-type/
 * 
 * @param array $clauses 
 * @param string $taxonomy
 * @param array $args
 * 
 * @return array
 */
add_filter( 'terms_clauses', 'interserver_mommy_blog_post_type_terms_clauses', 10, 3 );
function interserver_mommy_blog_post_type_terms_clauses( $clauses, $taxonomy, $args ) {
// Make sure we have a post_type argument to run with.
if( !isset( $args['post_type'] ) || empty( $args['post_type'] ) )
    return $clauses;
    
  global $wpdb;
  // Setup the post types in an array
  $post_types = array();
  
  // If the argument is an array, check each one and cycle through the post types
  if( is_array( $args['post_type'] ) ) {
    
    // All possible, public post types
    $possible_post_types = get_post_types( array( 'public' => true ) );
    
    // Cycle through the post types, add them to our array if they are public
    foreach( $args['post_type'] as $post_type ) {
      if( in_array( $post_type, $possible_post_types ) )
        $post_types[] = "'" . esc_attr( $post_type ) . "\'";
    }
    
  // If the post type argument is a string, not an array
  } elseif( is_string( $args['post_type'] ) ) {
    $post_types[] = "'" . esc_attr( $args['post_type'] ) . "'";
  }
  // If we have valid post types, build the new sql
  if( !empty( $post_types ) ) {
    $post_types_string = implode( ',', $post_types );
    $fields = str_replace( 'tt.*', 'tt.term_taxonomy_id, tt.term_id, tt.taxonomy, tt.description, tt.parent', $clauses['fields'] );
    
    $clauses['fields'] = 'DISTINCT ' . esc_sql( $fields ) . ', COUNT(t.term_id) AS count';
    $clauses['join'] .= ' INNER JOIN ' . $wpdb->term_relationships . ' AS r ON r.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN ' . $wpdb->posts . ' AS p ON p.ID = r.object_id';
    $clauses['where'] .= ' AND p.post_type IN (' . $post_types_string . ')';
    $clauses['orderby'] = 'GROUP BY t.term_id ' . $clauses['orderby'];
  }
    return $clauses;
}