<?php
	if(!isset($content_width)) $content_width = 1440;

	// Remove admin bar from site when user is logged in.
	function remove_admin_bar(){
		show_admin_bar(false);
	}
	add_action('after_setup_theme', 'remove_admin_bar');

	// Disable RSS
	remove_action('do_feed_rdf', 'do_feed_rdf', 10, 1);
	remove_action('do_feed_rss', 'do_feed_rss', 10, 1);
	remove_action('do_feed_rss2', 'do_feed_rss2', 10, 1);
	remove_action('do_feed_atom', 'do_feed_atom', 10, 1);

	// Remove RSS links from wp_head.
	function remove_rss_from_wp_head(){
		remove_action('wp_head', 'feed_links', 2);
		remove_action('wp_head', 'feed_links_extra', 3);
	}
	add_action('wp_head', 'remove_rss_from_wp_head', 1);

	// Remove XMLRPC
	remove_action('wp_head', 'rsd_link');
	remove_action('wp_head', 'wlwmanifest_link');
	add_filter('xmlrpc_enabled', '__return_false');

	// Remove REST API (wp-json)
	remove_action('wp_head', 'rest_output_link_wp_head', 10);
	remove_action('wp_head', 'wp_oembed_add_discovery_links', 10);

	// Remove WP Emoji
	remove_action('wp_head', 'print_emoji_detection_script', 7);
	remove_action('wp_print_styles', 'print_emoji_styles');
	remove_action('admin_print_scripts', 'print_emoji_detection_script');
	remove_action('admin_print_styles', 'print_emoji_styles');

	// Turn off oEmbed auto discovery.
	remove_filter('oembed_dataparse', 'wp_filter_oembed_result', 10); // Don't filter oEmbed results.
	remove_action('wp_head', 'wp_oembed_add_discovery_links'); // Remove oEmbed discovery links.
	remove_action('wp_head', 'wp_oembed_add_host_js'); // Remove oEmbed-specific JavaScript from the front-end and back-end.

	// Change the text at the of the excerpt
	function new_excerpt_more($more){
		global $post;
		return '...';
	}
	add_filter('excerpt_more', 'new_excerpt_more');
	add_filter('excerpt_length', 'my_excerpt_length');
	function my_excerpt_length($len){return 40;}

	// Remove posts and pages
	add_action('admin_menu', 'my_remove_menu_pages');
	function my_remove_menu_pages(){
		//remove_menu_page('edit.php');
		//remove_menu_page('edit.php?post_type=page');
		remove_menu_page('edit-comments.php');
	}

	// Add thumbs
	if(function_exists('add_theme_support')){
		add_theme_support('post-thumbnails');
		set_post_thumbnail_size(1060, 655, true);
		//add_image_size('##nomeaqui', 1120, 810, true);
	}

	// Get the first image from a post
	function catch_that_image(){
		global $post, $posts;
		$first_img = '';
		ob_start();
		ob_end_clean();
		$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
		$first_img = $matches [1] [0];
		if(empty($first_img)) $first_img = ''; //Defines a default image
		return $first_img;
	}

	// Se a busca só retornar um resultado, ir direto para o post
	function single_result(){  
		if(is_search()){  
			global $wp_query;  
			if($wp_query->post_count == 1){  
				wp_redirect(get_permalink($wp_query->posts['0']->ID));  
			}
		}
	}
	add_action('template_redirect', 'single_result');

	// Mostrar apenas posts no resultado da busca
	function searchfilter($query){
		if ($query->is_search && !is_admin()){
			$query->set('post_type',array('post'));
		}
		return $query;
	}
	add_filter('pre_get_posts','searchfilter');

	// Compressing JPEG Files to 80% quality
	// add_filter('jpeg_quality', create_function('', 'return 80;'));

	// Redirecionamentos, caso os custom post types não tenham internas
	/*function custom_redirects() {
		if(is_post_type_archive(array('banner')) || is_singular(array('banner'))){
			wp_redirect(home_url());
			exit;
		}
	}
	add_action('template_redirect', 'custom_redirects');*/
	
	/* ADD Options Page */
	if( function_exists('acf_add_options_page') ) {

		acf_add_options_page();

	}

	/**
	 *
	 * Upload SVG in wp admin
	 *
	 */

	function 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', 'add_file_types_to_uploads');

	/**
	 * Register our sidebars and widgetized areas.
	 *
	 */
	function arphabet_widgets_init() {

		register_sidebar( array(
			'name'          => 'Help Widgets',
			'id'            => 'help_widgets',
			'before_widget' => '<div>',
			'after_widget'  => '</div>',
			'before_title'  => '<h2 class="rounded">',
			'after_title'   => '</h2>',
		) );

	}
	add_action( 'widgets_init', 'arphabet_widgets_init' );

	add_theme_support( 'thumb-post' );
	add_image_size( 'thumb-post', 1344, 400, true);

	add_theme_support( 'thumb-post-tablet' );
	add_image_size( 'thumb-post-tablet', 1024, 338, true);

	add_theme_support( 'thumb-post-mobile' );
	add_image_size( 'thumb-post-mobile', 768, 304, true);

	add_theme_support( 'thumb-post-card' );
	add_image_size( 'thumb-post-card', 286, 336, true);

	add_theme_support( 'thumb-post-card-large' );
	add_image_size( 'thumb-post-card-large', 596, 336, true);

	add_theme_support( 'thumb-post-supersmall' );
	add_image_size( 'thumb-post-supersmall', 56, 56, true);

	add_theme_support( 'thumb-post-small' );
	add_image_size( 'thumb-post-small', 102, 102, true);

	add_theme_support( 'thumb-post-medium' );
	add_image_size( 'thumb-post-medium', 390, 354, true);

	add_theme_support( 'thumb-post-featured' );
	add_image_size( 'thumb-post-featured', 803, 480, true);

	add_theme_support( 'thumb-offers-single' );
	add_image_size( 'thumb-offers-single', 701, 575, true);

	add_theme_support( 'thumb-offers' );
	add_image_size( 'thumb-offers', 287, 260, true);

	/**
	 * Filter the except length to 20 words.
	 *
	 * @param int $length Excerpt length.
	 * @return int (Maybe) modified excerpt length.
	 */
	function wpdocs_custom_excerpt_length( $length ) {
		return 30;
	}
	add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );

	
	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);
		}
	}

	//hook into the init action and call create_topics_nonhierarchical_taxonomy when it fires
 
	add_action( 'init', 'create_countries_nonhierarchical_taxonomy', 0 );
	
	function create_countries_nonhierarchical_taxonomy() {
	
	// Labels part for the GUI
	
	$labels = array(
		'name' => _x( 'Countries', 'taxonomy general name' ),
		'singular_name' => _x( 'Country', 'taxonomy singular name' ),
		'search_items' =>  __( 'Search Countries' ),
		'popular_items' => __( 'Popular Countries' ),
		'all_items' => __( 'All Countries' ),
		'parent_item' => null,
		'parent_item_colon' => null,
		'edit_item' => __( 'Edit Country' ), 
		'update_item' => __( 'Update Country' ),
		'add_new_item' => __( 'Add New Country' ),
		'new_item_name' => __( 'New Country Name' ),
		'separate_items_with_commas' => __( 'Separate countries with commas' ),
		'add_or_remove_items' => __( 'Add or remove countries' ),
		'choose_from_most_used' => __( 'Choose from the most used countries' ),
		'menu_name' => __( 'Countries' ),
	); 
	
	// Now register the non-hierarchical taxonomy like tag
	
	register_taxonomy('countries','post',array(
		'hierarchical' => false,
		'labels' => $labels,
		'show_ui' => true,
		'show_admin_column' => true,
		'update_count_callback' => '_update_post_term_count',
		'query_var' => true,
		'rewrite' => array( 'slug' => 'country' ),
	));
	}

	/**
	* Convert a hexa decimal color code to its RGB equivalent
	*
	* @param string $hexStr (hexadecimal color value)
	* @param boolean $returnAsString (if set true, returns the value separated by the separator character. Otherwise returns associative array)
	* @param string $seperator (to separate RGB values. Applicable only if second parameter is true.)
	* @return array or string (depending on second parameter. Returns False if invalid hex color value)
	*/                                                                                                
	function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
		$hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
		$rgbArray = array();
		if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
			$colorVal = hexdec($hexStr);
			$rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
			$rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
			$rgbArray['blue'] = 0xFF & $colorVal;
		} elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
			$rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
			$rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
			$rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
		} else {
			return false; //Invalid hex color code
		}
		return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
	}

	if( function_exists('acf_add_local_field') ):

		acf_add_local_field_group(array(
			'key' => 'selectoffers',
			'title' => 'Select Offer',
			'fields' => array (),
			'location' => array (
				array (
					array (
						'param' => 'post_type',
						'operator' => '==',
						'value' => 'offer',
					),
				),
			),
		));
		
		$arrLIsts = listasNewsletter();

		acf_add_local_field(array(
			'key' => 'seloffers',
			'label' => 'Offer',
			'name' => 'select_offer',
			'type' => 'select',
			'parent' => 'selectoffers',
			'choices' => $arrLIsts,
			
			/* (bool) Allow a null (blank) value to be selected. Defaults to 0 */
			'allow_null' => 0,
			
			/* (bool) Allow mulitple choices to be selected. Defaults to 0 */
			'multiple' => 0,
			
			/* (bool) Use the select2 interfacte. Defaults to 0 */
			'ui' => 0,
			
			/* (bool) Load choices via AJAX. The ui setting must also be true for this to work. Defaults to 0 */
			'ajax' => 0,
			
			/* (string) Appears within the select2 input. Defaults to '' */
			'placeholder' => '',
		));
		
		
		
	endif;
	
	// Load more posts
	function load_more_scripts(){
		wp_register_script('loadmore', get_template_directory_uri() . '/functions/load-more/load-more.js', array('jquery'));
		wp_localize_script('loadmore', 'loadmore_params', array('ajaxurl' => site_url() . '/wp-admin/admin-ajax.php'));
		wp_enqueue_script('loadmore');
	}
	add_action('wp_enqueue_scripts', 'load_more_scripts');
	require_once('functions/load-more/load-more.php');

	// Loop functions
	require_once('functions/loop-content/loop-content.php');

	// Filter search results
	function filter_results_scripts(){
		wp_register_script('filter_results', get_template_directory_uri() . '/functions/filter-results/filter-results.js', array('jquery'));
		wp_localize_script('filter_results', 'filter_results_params', array('ajaxurl' => site_url() . '/wp-admin/admin-ajax.php'));
		wp_enqueue_script('filter_results');
	}
	add_action('wp_enqueue_scripts', 'filter_results_scripts');
	require_once('functions/filter-results/filter-results.php');

	function countText($text, $limite){
		$len=strlen($text);
		$final = ($len>$limite)? substr($text,0,$limite).'...' : $text ;
		
		return $final;
	}

	function listasNewsletter(){
		global $wpdb;

		$allListas = $wpdb->get_results('SELECT option_value FROM wp_options WHERE option_name = "newsletter_subscription_lists" ');
		$arr = unserialize($allListas[0]->option_value);
		
		$arrLista = null;
		for($i=1; $i <= 40; $i++) { 
			if ($arr['list_'.$i] != '') { 
				$arrLista[$i] =  $arr['list_'.$i];
			}
		}

		return $arrLista;

	}

	//remove_action('template_redirect', 'redirect_canonical');

	// function wpb_filter_query( $query, $error = true ) {
	// 	if ( is_search() ) {
	// 	$query->is_search = false;
	// 	$query->query_vars[s] = false;
	// 	$query->query[s] = false;
	// 	if ( $error == true )
	// 	$query->is_404 = true;
	// 	}
	// 	}
	// 	add_action( 'parse_query', 'wpb_filter_query' );
	// 	add_filter( 'get_search_form', create_function( '$a', "return null;" ) );
	// 	function remove_search_widget() {
	// 		unregister_widget('WP_Widget_Search');
	// 	}
	// 	add_action( 'widgets_init', 'remove_search_widget' );
?>
