<?php

function flatnews_title_to_slug($title = '', $sep = '-') {
	$slug = esc_attr(sanitize_title_with_dashes($title));
	if (!$sep || strlen($sep) > 1) {
		$sep = '-';
	}
	
	if (!((ord($sep) >= ord('A') && ord($sep) <= ord('Z')) || 
		(ord($sep) >= ord('a') && ord($sep) <= ord('z')) || 
		(ord($sep) >= ord('0') && ord($sep) <= ord('9')) ||
		(ord($sep) == ord('_') || ord($sep) == ord($sep))
		)) {
		$sep = '-';
	}
	if (ord($slug[0]) >= ord('0') && ord($slug[0]) <= ord('9')) {
		$slug[0] = $sep;
	}
	for ($i = 0; $i < strlen($slug); $i++) {		
		if ((ord($slug[$i]) >= ord('A') && ord($slug[$i]) <= ord('Z')) || 
			(ord($slug[$i]) >= ord('a') && ord($slug[$i]) <= ord('z')) || 
			(ord($slug[$i]) >= ord('0') && ord($slug[$i]) <= ord('9')) ||
			(ord($slug[$i]) == ord('_') || ord($slug[$i]) == ord($sep))
			) {
			continue;
		}		
		$slug[$i] = $sep;
	}
	return $slug;
}

function flatnews_related_path($path = '') {
	
	if ($path) {
		
	}
	return $path;
}

function flatnews_site_title() {
	if (get_theme_mod('site_logo')) {
		$logo_src = get_theme_mod('site_logo');
		$logo_retina = get_theme_mod('site_logo_retina');
		
		if (wp_is_mobile() && get_theme_mod('mobile_site_logo')) {
			$logo_src = get_theme_mod('mobile_site_logo');
			$logo_retina = get_theme_mod('mobile_site_logo_retina');
		}
		
		$site_title = '<a href="'.esc_url(get_home_url()).'" title="'.esc_attr(get_bloginfo('name')).'">';
		$site_title .= '<img alt="'.esc_attr(get_bloginfo('name')).'" src="'.esc_url($logo_src).'" data-retina="'.esc_url($logo_retina).'"/>';
		$site_title .= '</a>';
	}
	else {
		$site_title = '<a href="'.esc_url(get_home_url()).'" title="'.esc_attr(get_bloginfo( 'name')).'">';
		$site_title .= get_bloginfo('name');
		$site_title .= '</a>';
	}
	
	if (!is_home() && !is_front_page()) : ?>
		<h2 class="fn-site-title"><?php echo $site_title; ?></h2>
	<?php else : ?>
		<h1 class="fn-site-title"><?php echo $site_title; ?></h1>
	<?php endif;
}

/*  ----------------------------------------------------------------------------
    mbstring support
 */

if (!function_exists('mb_strlen')) {
    function mb_strlen ($string) {
        return strlen($string);
    }
}

if (!function_exists('mb_strpos')) {
    function mb_strpos($haystack,$needle,$offset=0) {
        return strpos($haystack,$needle,$offset);
    }
}
if (!function_exists('mb_strrpos')) {
    function mb_strrpos ($haystack,$needle,$offset=0) {
        return strrpos($haystack,$needle,$offset);
    }
}
if (!function_exists('mb_strtolower')) {
    function mb_strtolower($string) {
        return strtolower($string);
    }
}
if (!function_exists('mb_strtoupper')) {
    function mb_strtoupper($string){
        return strtoupper($string);
    }
}
if (!function_exists('mb_substr')) {
    function mb_substr($string,$start,$length = false) {
	    if ($length) {
		    return substr($string,$start, $length);
	    }
	    return substr($string,$start);
    }
}
if (!function_exists('mb_internal_encoding')) {
    function mb_internal_encoding($string) {
        return $string;
    }
}
if (!function_exists('mb_http_output')) {
    function mb_http_output($string) {
        return $string;
    }
}
if (!function_exists('mb_http_output')) {
    function mb_http_output($string) {
        return $string;
    }
}
if (!function_exists('mb_http_input')) {
    function mb_http_input($string) {
        return $string;
    }
}
if (!function_exists('mb_language')) {
    function mb_language($string) {
        return $string;
    }
}
if (!function_exists('mb_regex_encoding')) {
    function mb_regex_encoding($string) {
        return $string;
    }
}

function flatnews_substring($string, $start, $length = 150) {	
	mb_internal_encoding('UTF-8');
	mb_http_output('UTF-8');
	mb_http_input('UTF-8');
	mb_language('uni');
	mb_regex_encoding('UTF-8');
	
	return mb_substr($string, $start, $length);
	
}

/*Use this function inside loop
 * wrap = true mean wrap content by p tag
 * one_line = true mean remove all html tags in content
 */
function flatnews_get_the_snippet($length = 150, $hellip = true) {
	$html = '';
	global $post;
	
	if ( is_object( $post ) ) {
		if ( property_exists( $post, 'post_excerpt' ) && $post->post_excerpt ) {
			$html = $post->post_excerpt;
		} else if ( property_exists ($post, 'post_content') && $post->post_content ){
			$html = $post->post_content;
		}
	}
	
	if ( ( !$html ) && get_the_content( '', false) ) {
		$html = get_the_content( '', false );
	}
	
	if ((!$html) && get_the_excerpt()) {
		$html = get_the_excerpt();
	}
	
	if ($html) {
		$html = do_shortcode( $html );
		$html = strip_tags( $html );
		if ( strlen( $html ) > $length ) {			
			$html = flatnews_substring( $html, 0, $length );
		}
	}
	
	if ( $hellip ) {
		if ( is_string( $hellip ) ) {
			$html .= ' ' . $hellip . ' ';
		} else {
			$html .= ' ... ';
		}
	}
	
	return $html;
}
function flatnews_remove_html_slashes($content) {
	return filter_var(stripslashes($content), FILTER_SANITIZE_SPECIAL_CHARS);
}
function flatnews_safe_array_get($arr, $element, $default = '') {
	$value = $default;
	
	if (is_array($arr) && array_key_exists($element, $arr)) {
		$value = $arr[$element];
	}
	return $value;
}
function flatnews_pagenav_index($position = 'top'){
	global $wp_query;
	$current = max( 1, get_query_var('paged') );	
	$big = 999999999; // need an unlikely integer
	
	if ( 'bottom' == $position ) {
		echo '<div class="clear"></div>';
	}
	
	echo '<div class="archive-page-pagination archive-page-pagination-'.$position.'">';
	echo paginate_links( array(
		'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
		'format' => '?paged=%#%',
		'current' => $current,
		'total' => $wp_query->max_num_pages,
		'prev_text'    => wp_kses(__('<i class="fa fa-angle-left"></i>', 'flatnews'),array('i'=>array('class'=>array()))),
		'next_text'    => wp_kses(__('<i class="fa fa-angle-right"></i>', 'flatnews'),array('i'=>array('class'=>array())))
	) );
	
	$listed = $current * $wp_query->query_vars['posts_per_page'];
	if ($listed > $wp_query->found_posts) {
		$listed = $wp_query->found_posts;
	}
	if ( $wp_query->max_num_pages > 1 || 'bottom' == $position ) {
		echo '<span class="archive-page-pagination-info">'.	wp_kses(sprintf(__('<span class="value">%1$s</span> / %2$s POSTS', 'flatnews'), $listed, $wp_query->found_posts).'</span>', array('span'=>array('class'=>array())));
	}
	echo '<div class="clear"></div></div>';
}
function flatnews_has_form_controls($str = '') {
	if (!$str) {
		return false;
	}
	if (strpos($str, '<form') !== false) {
		return true;
	}
	if (strpos($str, '<input') !== false) {
		return true;
	}
	if (strpos($str, '<textarea') !== false) {
		return true;
	}
	if (strpos($str, '<select') !== false) {
		return true;
	}
	if (strpos($str, '<option') !== false) {
		return true;
	}
	
	return false;
}

function flatnews_get_server_request($key) {
	$value = '';
	if ($key) {
		if (isset($_GET[$key])) {
			$value = sanitize_text_field($_GET[$key]);
		} else if (isset($_POST[$key])) {
			if (is_array($_POST[$key])) {
				$value = array_map('sanitize_text_field', $_POST[$key]);
			} else {
				$value = sanitize_text_field($_POST[$key]);
			}
		}
	}
	return $value;
}

function flatnews_is_IE() {
	return preg_match('/(?i)msie [5-8]/',$_SERVER['HTTP_USER_AGENT']);
}


function flatnews_get_attachment_id_from_src($src = '') {
	if (!$src) {
		return false;
	}
	
	global $wpdb;
	$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $src )); 
	if (!$attachment || !is_array($attachment)) {
		return false;
	}
    return $attachment[0]; 	
}

function flatnews_get_attachment_from_src($src = '') {
	$attachment_id = flatnews_get_attachment_id_from_src($src); 
	
	if (!$attachment_id) {
		return false;
	}
	
	return wp_get_attachment_metadata($attachment_id);
}

function fn_display_sidebar($sidebar_id = '') {
	if (!$sidebar_id) {
		return;
	}
	$prefix = '';
	$sidebar = '';
	$layout = '';
	$sticky = false;
	
	// if user set sidebar on post
	// we must priority use that sidebar
	if ( is_singular() ) {
		$sidebar = get_post_meta(get_the_ID(), 'singular-'.$sidebar_id, true);
		if ('disable' == $sidebar) {			
			return;
		}
	}

	// but if they leave it as default
	// we will get from global options
	if (!$sidebar) {	
		// in case this is not item page or item sidebar layout is default
		if (function_exists( 'is_woocommerce' ) && is_woocommerce() ) {
			if ( is_shop() ){
				// always check just in case this is not item or item sidebar name is default
				$prefix = 'shop';
			}	
			elseif ( is_product() ) {
				$prefix = 'product';
			}
			else {
				$prefix = 'archive-product';
			}
		}
		// or process with normal pages
		else {
			if ( is_home() || is_front_page() ) {
				$prefix = 'home';
			} 
			elseif ( is_page() ) {
				$prefix = 'page';
			} 
			elseif ( is_single() ) {
				$prefix = 'single';
			}
			else {
				$prefix = 'archive';
			}
		}
		if ($prefix) {
			$sidebar = get_theme_mod($prefix.'-'.$sidebar_id, $sidebar_id);
		}		
	}	

	// if did not set, just use the default
	if ( !$sidebar ) {
		$sidebar = $sidebar_id;
	}
	
	
	
	// get layout and sticky for MAIN SIDEBAR
	if ('fn-main-sidebar' == $sidebar_id) {
		// SIDEBAR LAYOUT
		// check if users set a specific sidebar layout 
		// then we must use the thing they set
		if ( is_singular() ) {
			$layout = get_post_meta(get_the_ID(), 'singular-sidebar-layout', true);			
		}
		
		// if they leave as default
		// we need to check global options
		if (!$layout && $prefix) {
			$layout = get_theme_mod($prefix.'-sidebar-layout', '');
		}
		// if global option is disable
		if ('full' == $layout) {			
			return;
		}

		// SIDEBAR STICKY
		if ($prefix) {
			$sticky = get_theme_mod($prefix.'-sidebar-sticky', false);
		}		
	}
	
	
	if ( ! function_exists( 'sneeit_framework' ) && is_active_sidebar( $sidebar ) ) {	
		dynamic_sidebar( $sidebar );	
	} 
	else {
		do_action( 'sneeit_display_sidebar', array(
			'id'    => $sidebar,
			'class' => $sidebar_id . ' fn-sidebar' . ($sticky?' fn-sticky-col':''),
		) );
	}
}

