<?php
/***************************************************/
/*     Customização da área de administração        */
/*  			    TELA DE LOGIN                   */
/****************************************************/

function custom_login() { 
echo '<link rel="stylesheet" type="text/css" href="'.get_bloginfo('template_directory').'/custom-login/custom-login.css" />'; 
}
add_action('login_head', 'custom_login');


// Muda o logotipo na tela de login do painel administrativo
 
function cutom_login_logo() {
		echo "<style type=\"text/css\">
		body.login div#login h1 a {
		background-image: url(".get_bloginfo('template_directory')."/images/logo-login.svg);
		-webkit-background-size: auto;
		background-size: 320px 209px;
		margin: 0;
		width: 320px;
		height: 209px;
}
</style>";
}
add_action( 'login_enqueue_scripts', 'cutom_login_logo' );

/****************************************************/
/*      Customização da COR DE FUNDO da página      */
/****************************************************/
	$defaults = array(
	    'default-color'          => 'ffffff',
	    'default-image'          => '',
	    'default-repeat'         => 'no-repeat',
	    'default-position-x'     => 'center',
	    'default-attachment'     => 'fixed',
	    'background-preset'		 => 'custom',
	    'wp-head-callback'       => '_custom_background_cb',
	    'admin-head-callback'    => '',
	    'admin-preview-callback' => ''
	);
	add_theme_support( 'custom-background', $defaults );

/***************************************************************/
/*   Customização da IMAGEM do cabeçalho com altura flexível   */
/***************************************************************/
	add_theme_support( 'custom-header', array(
	  // Imagem padrão
	  'default-image' => get_template_directory_uri() . '/images/topo.png',
      // Altura da imagem flexível
      'flex-height' => false,
      // Altura recomendada 150px
       'height' => 250,
      // Largura da imagem não é flexível
      'flex-width' => true,
	  // Não esquecer de alterar também a largura da página no Zurb Foundation...
      'width' => 1200
	) );


/****************************************************/
/*        Adiciona suporte a imagem destacada       */
/*                 Post-thumbnails                  */
/****************************************************/
		add_theme_support( 'post-thumbnails' ); 
    	
    	add_image_size( 'noticias-thumb', 175, 98, false); // 16:9    
    	add_image_size( 'eventos-thumb', 75, 57, false); // 16:9    

/****************************************************/
/*           Adiciona  menus personalizados         */
/*            Este tema usa wp_nav_menu()           */
/****************************************************/
	register_nav_menus(
		array(
			'menu_principal' 	=> __( 'Menu Principal Horizontal', 'foundation' ),
            'menu_responsivo' 	=> __('Menu Responsivo', 'foundation'),
			'menu_superior'		=> __( 'Menu Superior', 'foundation' ),
			'mapa_do_site'		=> __('Mapa do Site', 'foundation' )
		)
	);


// Habilitar uso dos Dashicons no frontend
add_action( 'wp_enqueue_scripts', 'load_dashicons_front_end' );
function load_dashicons_front_end() {
wp_enqueue_style( 'dashicons' );
}

/****************************************************/
/*				Adiciona links RSS ao <head>        */
/****************************************************/
//	add_theme_support( 'automatic-feed-links' );


/****************************************************/
/*		Registra áreas de Widget                    */
/****************************************************/

function theme_widgets_init() {
	
/****************************************************/
/*           Registra a SideBar CENTROS             */
/****************************************************/
register_sidebar(array(
			'name' => 'Sidebar Centros',
			'id' => 'sidebar_centros',
			'before_widget' => '<ul class="menu vertical" data-accordion-menu><li>',
			'after_widget' => '</ul></li></ul>',
			'before_title' => '<a href="#"><h5>',
			'after_title' => '</h5></a><ul class="nested is-active">'
    ));
	
	
/****************************************************/
/*           Registra a SideBar NÚCLEOS             */
/****************************************************/
register_sidebar(array(
			'name' => 'Sidebar Núcleos',
			'id' => 'sidebar_nucleos',
			'before_widget' => '<ul class="menu vertical" data-accordion-menu><li>',
			'after_widget' => '</ul></li></ul>',
			'before_title' => '<a href="#"><h5>',
			'after_title' => '</h5></a><ul class="nested is-active">'
    ));		
	
	
/****************************************************/
/*        Registra a SideBar LINKS ÚTEIS            */
/****************************************************/
register_sidebar(array(
			'name' => 'Sidebar Links Úteis',
			'id' => 'sidebar_links_uteis',
			'before_widget' => '<ul class="menu vertical" data-accordion-menu><li>',
			'after_widget' => '</ul></li></ul>',
			'before_title' => '<a href="#"><h5>',
			'after_title' => '</h5></a><ul class="nested is-active">'
    ));	
	
	
/****************************************************/
/*      Registra a SideBar LINKS IMPORTANTES        */
/****************************************************/
register_sidebar(array(
			'name' => 'Sidebar Links Importantes',
			'id' => 'sidebar_links_importantes',
			'before_widget' => '<ul class="menu vertical" data-accordion-menu><li>',
			'after_widget' => '</ul></li></ul>',
			'before_title' => '<a href="#"><h5>',
			'after_title' => '</h5></a><ul class="nested is-active">'
    ));	



/****************************************************/
/*   Registra a Primeira Coluna de Links - Rodapé   */
/****************************************************/
register_sidebar(array(
			'name' => 'Primeira Coluna de Links',
			'id' => 'primeira_coluna',
			'before_widget' => '<div class="colunas_de_links">',
			'after_widget' => '</div>',
			'before_title' => '<h2>',
			'after_title' => '</h2>'
    ));

/****************************************************/
/*   Registra a Segunda Coluna de Links - Rodapé    */
/****************************************************/
register_sidebar(array(
			'name' => 'Segunda Coluna de Links',
			'id' => 'segunda_coluna',
			'before_widget' => '<div class="colunas_de_links">',
			'after_widget' => '</div>',
			'before_title' => '<h2>',
			'after_title' => '</h2>'
    ));

/****************************************************/
/*   Registra a Terceira Coluna de Links - Rodapé   */
/****************************************************/
register_sidebar(array(
			'name' => 'Terceira Coluna de Links',
			'id' => 'terceira_coluna',
			'before_widget' => '<div class="colunas_de_links">',
			'after_widget' => '</div>',
			'before_title' => '<h2>',
			'after_title' => '</h2>'
    ));
	
/****************************************************/
/*   Registra a Quarta Coluna de Links - Rodapé     */
/****************************************************/
register_sidebar(array(
			'name' => 'Quarta Coluna de Links',
			'id' => 'quarta_coluna',
			'before_widget' => '<div class="colunas_de_links">',
			'after_widget' => '</div>',
			'before_title' => '<h2>',
			'after_title' => '</h2>'
    ));

} 
// Inicializa theme_widgets_init
 add_action( 'init', 'theme_widgets_init');

function my_remove_menu_elements()
    {
  		remove_menu_page( 'edit-comments.php' );          //Comments
    }
     add_action('admin_init', 'my_remove_menu_elements');


/************************************************************/
/* Drilldown - menu de navegacao em mobile com Foundation 6 */
/************************************************************/

class F6_DRILL_MENU_WALKER extends Walker_Nav_Menu {
	/*
	 * Add vertical menu class
	 */

	function start_lvl( &$output, $depth = 0, $args = array() ) {
		$indent = str_repeat( "\t", $depth );
		$output .= "\n$indent<ul class=\"vertical menu\">\n";
	}
}

function f6_drill_menu_fallback( $args ) {
	/*
	 * Instantiate new Page Walker class instead of applying a filter to the
	 * "wp_page_menu" function in the event there are multiple active menus in theme.
	 */

	$walker_page = new Walker_Page();
	$fallback    = $walker_page->walk( get_pages(), 0 );
	$fallback    = str_replace( "children", "children vertical menu", $fallback );
	echo '<ul class="vertical medium-horizontal nested menu" data-responsive-menu="drilldown medium-dropdown" style="display: block; width: 100%;">' . $fallback . '</ul>';
}


/****************************************************/
/*         Cria shortcodes para mostrar os posts    */
/*     			    por categorias                  */
/****************************************************/

function listar_categoria($atts) {

	// Pega o nome da categoria e a quantidade de posts a serem exibidos
	 $nome_da_categoria		= $atts['name'];
	 $numero_de_posts		= $atts['nposts'];
	 $editoria 				= 'editoria'.$atts['editoria'];
	 $destaques 			= 'destaques';
	 $cor_da_seta 			= 'wpufpr_'.$editoria.'_header_background_color';

	//setlocale(LC_CTYPE, 'pt_BR'); // Defines para pt-br
	$categoria = iconv("UTF-8", "ISO-8859-1//IGNORE", $nome_da_categoria);


// Inicializa a string..
 	  $string = '';

// Primeiro pesquisa destaques...
	$the_query_destaques = new WP_Query( array( 'category_name' => "$nome_da_categoria+$destaques", 'posts_per_page' => 1, 'orderby' => 'date', 'order' => 'DESC' ) ); 


	if ($the_query_destaques->have_posts()) : while ($the_query_destaques->have_posts()) : $the_query_destaques->the_post(); ?>
	
	<!-- Pega o ID do post atual -->
		<?php $thePostID_destaques = get_the_ID();?>
 
	<!-- Existe imagem de destaque nesta notícia sobre "GESTAO" ? -->
	<?php if ( has_post_thumbnail() ) : ?>


	<!-- Coloca o TÍTULO desta notícia sobre "GESTAO" -->
	<?php
		$string .= '<div id="editorias">';
		$string .= '<a href="' . get_the_permalink() .'" rel="bookmark">';

		$string .= '' . get_the_post_thumbnail($thePostID_destaques, "editorias-thumb") .'</a>';
		$string .= '<div class="titulo_editorias">';
		$string .= '<a href="' . get_the_permalink() . '" rel="bookmark">' . get_the_title() . '</a></div>';
		$string .= '<div class="resumo_editorias">';
		$string .= '<a href="' . get_the_permalink() . '" rel="bookmark">' . get_the_excerpt() . '</a></div>';
		$string .= '</div>';

		else :
	//  Coloca o título... 
		$string .= '<div style="margin-left: 0;"><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></div></div>';// Final da div sem foto" 

		endif; 
		 endwhile; 
		 endif;
	 ?>
 <?php wp_reset_query();?>

<?php
	$the_query = new WP_Query( array( 'category_name' => "$nome_da_categoria", 'posts_per_page' => $numero_de_posts, 'orderby' => 'date', 'order' => 'DESC', 'post__not_in' => array($thePostID_destaques) ) ); 

	 // O Loop
	if ( $the_query->have_posts() ) {
	 $string .= '<ul class="postsbycategory widget_recent_entries">';
		 while ( $the_query->have_posts() ) {

		    $thePostID = get_the_ID();

			 $the_query->the_post();

			 if ( has_post_thumbnail() ) { 
				$string .= '<li>';
				$string .= '<a href="' . get_the_permalink() .'" rel="bookmark">';
				$string .= '<div style="padding: 0; margin: 0; font-size: 1.1em; font-weight: bold;">' . get_the_title() . '</div>';
				$string .= '<div><span style="padding: 0.4em 0; float: left;">' . get_the_post_thumbnail(  $thePostID,"editorias-thumb" ) . '</span><div>' . get_the_excerpt() . '</div>';
				$string .= '</a>';
				$string .= '</li>';
				 
			 } else { 
			 // Se nenhuma imagem de destaque foi cadastrada, exibe apenas o título do post
				 $string .= '<li><i style="font-weight: normal; color:' . get_theme_mod("$cor_da_seta") . '" class="arrow_carrot-2right" aria-hidden="true"></i><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>';
			 }
		 }
	 } else {
	 // Nada será exibido se nenhum Post Relacionado por Categoria foi encontrado
	}
	
	$string .= '<br><span class="ver_mais"><a href="'. get_bloginfo('url') .'/editoria/?cat='
	.$categoria.'?edt='.$editoria.'"> Mais '. $nome_da_categoria . '...</a></span><br>';
	$string .= '</ul>';
	
	  
	return $string;
	 
	/* Restaura os dados originais do post */
	wp_reset_postdata();
	}

// Adiciona um Shortcode
add_shortcode('wpufpr_categoria', 'listar_categoria');
 
 
// Ativa shortcodes em Widgets de Texto
add_filter('widget_text', 'do_shortcode');

// Remove acentos e espaços dos arquivos no upload
function custom_sanitize_file_name ( $filename ) {
	$filename = remove_accents( $filename );
	$filename = strtolower( $filename );
	$file_parts = pathinfo( $filename );
	return sanitize_title( $file_parts['filename'] ) . '.' . $file_parts['extension'];
}
add_filter( 'sanitize_file_name', 'custom_sanitize_file_name' );


/****************************************************/
/*		Habilita uso de shortcodes em Widget        */
/****************************************************/

	add_filter( 'widget_text', 'shortcode_unautop' );
	add_filter( 'widget_text', 'do_shortcode' );
	add_filter( 'widget_title', 'do_shortcode' );

/********************************************************************/
/*	Cria um shortcodes para exibir icone em título em Widget        */
/*			    Icones da fonte Elegant Icons                       */
/********************************************************************/

add_shortcode('icone', 'elegant_icons');


function elegant_icons( $atts, $class ){

	$classe = $atts['classe'];
	$cor = $atts['cor'];
	$tamanho_da_fonte = $atts['tamanho'];
	
	$string = "&lt;i aria-hidden=\"true\" style='margin-top: -0.1em;font-size: ".$tamanho_da_fonte."; color: ".$cor."'  
	class=".$classe."&gt;&lt;/i&gt;";
	$string = str_replace(array("&gt;", "&lt;", "&quot;", "&amp;"), array(">", "<", "\"", "&"), $string);
	return $string;
}

function ld_custom_excerpt_length( $length ) {
    return 25;
}
add_filter( 'excerpt_length', 'ld_custom_excerpt_length', 999 );

/****************************************************/
/*         Carrega o arquivo de customizacao        */
/*     (Wordpress Customizer API) do tema WP_UFPR   */
/****************************************************/
	require_once( get_stylesheet_directory() . '/inc/customizer-wpufpr.php' );

// add_filter('wp_nav_menu_items','add_new_menu_item', 10, 2);

// function add_new_menu_item( $nav, $args ) {
//     if( $args->theme_location == 'menu_principal' )
//     $newmenuitem = "<li class='home-link'><img src='".get_bloginfo('template_url') ."/images/flag_uk.png'/></li>";
//     $nav = $newmenuitem.$nav;
//     return $nav;
// }

/****************************************************/
/*		Numero de views por posts no painel         */
/****************************************************/

function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' Views';
}
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
 
// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); 
// Add to a column in WP-Admin
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
    $defaults['post_views'] = __('Views');
    return $defaults;
}
function posts_custom_column_views($column_name, $id){
    if($column_name === 'post_views'){
        echo getPostViews(get_the_ID());
    }
}

?>