<?php
/**
 * Custom functions that act independently of the theme templates
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 * @package yahosein
 */

/**
 * Adds custom classes to the array of body classes.
 *
 * @param array $classes Classes for the body element.
 *
 * @return array
 */
function yahosein_body_classes($classes) {
	// Adds a class of group-blog to blogs with more than 1 published author.
	if (is_multi_author()) {
		$classes[] = 'group-blog';
	}

	// Adds a class of hfeed to non-singular pages.
	if (!is_singular()) {
		$classes[] = 'hfeed';
	}

	return $classes;
}

add_filter('body_class', 'yahosein_body_classes');

/**
 * Add a pingback url auto-discovery header for singularly identifiable articles.
 */
function yahosein_pingback_header() {
	if (is_singular() && pings_open()) {
		echo '<link rel="pingback" href="', esc_url(get_bloginfo('pingback_url')), '">';
	}
}

add_action('wp_head', 'yahosein_pingback_header');

//attach our function to the wp_pagenavi filter
add_filter('wp_pagenavi', 'roman_pagination', 10, 2);

//customize the PageNavi HTML before it is output
function roman_pagination($html) {
	$out = '';

	//wrap a's and span's in li's
	$out = str_replace("<div", "", $html);
	$out = str_replace("class='wp-pagenavi'>", "", $out);
	$out = str_replace("<a", "<li><a", $out);
	$out = str_replace("</a>", "</a></li>", $out);
	$out = str_replace("<span", "<li><span", $out);
	$out = str_replace("</span>", "</span></li>", $out);
	$out = str_replace("</div>", "", $out);

	return '<ul class="pagination pagination-centered">' . $out . '</ul>';
}

function _roman_jdate($format, $time) {
	if (function_exists('jdate')) {
		return jdate($format, $time);
	} elseif (class_exists('bn_parsidate')) {
		$bndate = bn_parsidate::getInstance();

		return $bndate = $bndate->persian_date($format, $time);
	} elseif (class_exists('IntlDateFormatter')) {
		return new IntlDateFormatter('fa@calendar=persian', IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'GMT', IntlDateFormatter::TRADITIONAL, 'EEEE dd MMMM yyyy');

	} else {
		return date($format, $time);
	}

}

/**
 * View Counter
 */
// function to display number of posts.
function roman_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";
	}

	return $count;
}

// function to count views.
function roman_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);
	}
}

// Add it to a column in WP-Admin
add_filter('manage_posts_columns', 'roman_posts_column_views');
add_action('manage_posts_custom_column', 'roman_posts_custom_column_views', 5, 2);
function roman_posts_column_views($defaults) {
	$defaults['post_views'] = __('بازدید');

	return $defaults;
}

function roman_posts_custom_column_views($column_name, $id) {
	if ($column_name === 'post_views') {
		echo roman_getPostViews(get_the_ID());
	}
}

add_action('after_switch_theme', 'roman_after_switch_theme');
function roman_after_switch_theme() {
	if (get_option('yahosein_starpostrating_translated') != '1') {
		update_option('postratings_options', array('richsnippet' => 1)); // 1,0
		update_option('postratings_template_vote', '%RATINGS_IMAGES_VOTE%  %RATINGS_SCORE% امتیاز %RATINGS_TEXT%'); // %RATINGS_IMAGES_VOTE%  %RATINGS_SCORE% امتیاز %RATINGS_TEXT%
		update_option('postratings_template_text', '%RATINGS_IMAGES% %RATINGS_SCORE% امتیاز'); // %RATINGS_IMAGES% %RATINGS_SCORE% امتیاز
		update_option('postratings_template_none', '%RATINGS_IMAGES_VOTE%'); // %RATINGS_IMAGES_VOTE%
		//add
		update_option('yahosein_starpostrating_translated', '1');
	}
}

/**
 * Add custom css to site
 */
add_action('wp_head', 'yahosein_styles_css');
function yahosein_styles_css() {
	global $yahosein;
	$css = '';

	//logo
	if (isset($yahosein['opt-header-img']['url']) && !empty($yahosein['opt-header-img']['url'])) {
		$css .= '.page_index .header_td_lte{background-image:url("' . $yahosein['opt-header-img']['url'] . '");}';
	}

	echo '<style>' . $css . '</style>';

}

/**
 * To fetch roman post meta
 *
 * @param int post_id
 *
 * @return string
 */

function roman_get_meta($post_id, $key) {
	$roman_dll_box = get_post_meta($post_id, '_roman_dll_box_fields', true);
	if ($key == 'genre' && isset($roman_dll_box[$key])) {
		$cat_name = get_cat_name($roman_dll_box[$key]);
		$cat_link = get_category_link($roman_dll_box[$key]);
		if (empty($cat_name) || empty($cat_link)) {
			return false;
		}

		return '<a href="' . $cat_link . '">' . $cat_name . '</a>';
	}
	if (isset($roman_dll_box[$key])) {
		return $roman_dll_box[$key];
	}

	return false;
}

/**
 * Get Categories in html
 * @return string
 */
function roman_get_categories_select_html($name, $selected = false) {
	$teh_cats = get_categories(array('hide_empty' => 0));
	$results = '';
	$results .= '<select name="' . $name . '">';
	$count = count($teh_cats);
	for ($i = 0; $i < $count; $i++) {
		if (isset($teh_cats[$i])) {
			$results .= '<option value="' . $teh_cats[$i]->term_id . '" ';
			if ($selected) {
				if ($selected == $teh_cats[$i]->term_id) {
					$results .= ' selected="selected" ';
				}

			}
			$results .= '>';
			$results .= $teh_cats[$i]->name;
			$results .= '</option>';

		} else {
			$count++;
		}

	}
	$results .= '</select>';

	return $results;
}

/**
 * [roman_get_slideshow_items description]
 *
 * @param  int $cat_id
 *
 * @return array         array of post objects
 */
function roman_get_slideshow_items($cat_id) {
	$services = array();
	$num = 5;

	// The Query
	$the_query = new WP_Query(array(
		'cat' => $cat_id,
		'post_type' => 'post',
		'posts_per_page' => $num,
		'orderby' => 'date',
		'order' => 'DESC',
	));

	// The Loop
	if ($the_query->have_posts()) {
		while ($the_query->have_posts()) {
			$the_query->the_post();
			$services[] = get_post();
		}
		/* Restore original Post Data */
		wp_reset_postdata();
	}

	return $services;
}



function yahosein_edd_product_supports($supports) {
	$supports[] = 'comments';
	return $supports;
}
add_filter('edd_download_supports', 'yahosein_edd_product_supports');

/**
 * Remove the edd contents after post since we own attached is before.
 */
remove_action('edd_after_download_content', 'edd_append_purchase_link');

function yahosein_main_sidebar_class() {
	return 'col-md-12 col-sm-12 col-xs-12';

}
/**
 * https://stackoverflow.com/a/11951022
 * @param  color $hex   #fffddd
 * @param  range $steps  Steps should be between -255 and 255. Negative = darker, positive = lighter
 * @return string        converted color
 */
function yahosein_adjustBrightness($hex, $steps) {
	// Steps should be between -255 and 255. Negative = darker, positive = lighter
	$steps = max(-255, min(255, $steps));

	// Normalize into a six character long hex string
	$hex = str_replace('#', '', $hex);
	if (strlen($hex) == 3) {
		$hex = str_repeat(substr($hex, 0, 1), 2) . str_repeat(substr($hex, 1, 1), 2) . str_repeat(substr($hex, 2, 1), 2);
	}

	// Split into three parts: R, G and B
	$color_parts = str_split($hex, 2);
	$return = '#';

	foreach ($color_parts as $color) {
		$color = hexdec($color); // Convert to decimal
		$color = max(0, min(255, $color + $steps)); // Adjust color
		$return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
	}

	return $return;
}

function yahosein_fix_empty_title_issue($title = false, $instance = false) {

	if (empty($title)) {
		$title = '<span class="widget_hide_me">--خالی--</span>';
	}
	return $title;
}
add_filter('widget_title', 'yahosein_fix_empty_title_issue', 10, 2);


function yahosein_loginlogo_url($url) {
	return 'http://wd7.ir';
}
add_filter('login_headerurl', 'yahosein_loginlogo_url', 99999999);

function yahosein_footer_admin () {
 
echo 'متشکریم که از قالبهای  <a href="http://wd7.ir" target="_blank">وب دیزاین</a> استفاده می کنید.';
 
}
add_filter('admin_footer_text', 'yahosein_footer_admin');


add_action('wp_dashboard_setup', 'yahosein_dashboard_widgets');
function yahosein_dashboard_widgets() {
     wp_add_dashboard_widget( 'dashboard_custom_feed', 'آخرین مطالب وب دیزاین' , 'dashboard_custom_feed_output' );
}
function dashboard_custom_feed_output() {
     echo '<div class="rss-widget">';
     wp_widget_rss_output(array(
          'url' => 'http://wd7.ir/feed',
          'title' => 'آخرین مطالب وب دیزاین',
          'items' => 2,
          'show_summary' => 1,
          'show_author' => 0,
          'show_date' => 1
     ));
     echo '</div>';
}


function yahosein_zekr_hafte() {
	$days = array(
		'thursday' => 'ذکر روز پنجشنبه: ۱۰۰ مرتبه لا اله الا الله الملک الحق المبین  (ذکر روز پنج شنبه موجب رزق و روزی می شود)',
		'friday' => ' ذکر روز جمعه : ۱۰۰ مرتبه اللهم صل علی محمد و ال محمد (ذکر روز جمعه موجب عزیز شدن می شود)',
		'saturday' => ' ذکر روز شنبه : ۱۰۰ مرتبه یا رب العالمین (ذکر روز شنبه موجب بی نیازی می شود)',
		'sunday' => 'ذکر روز یکشنبه: ۱۰۰ مرتبه یا ذالجلال والاکرام (ذکر روز یک شنبه موجب فتح و نصرت می شود)',
		'monday' => 'ذکر روز دوشنبه: ۱۰۰ مرتبه یا قاضی الحاجات  (ذکر روز دو شنبه موجب کثرت مال می شود)',
		'tuesday' => ' ذکر روز سه شنبه: ۱۰۰ مرتبه یا ارحم الراحمین (ذکر روز سه شنبه موجب روا شدن حاجات می شود)',
		'wednesday' => 'ذکر روز چهارشنبه : ۱۰۰ مرتبه یا حی یا قیوم (ذکر روز چهار شنبه موجب عزت دائمی می شود)',
	);

	$current_day = date('l');
	$current_day = strtolower($current_day);

	if (isset($days[$current_day])) {
		echo $days[$current_day];
	}

}


/**
 * Get Categories in html
 * @return string
 */
function yahosein_get_categories_select_html($name, $selected = false) {
	$teh_cats = get_categories(array('hide_empty' => 0));
	$teh_cats[] =(object) array('term_id'=>'_all_','name'=>'همه');
	$results = '';
	$results .= '<select name="' . $name . '">';
	$count = count($teh_cats);
	for ($i = 0; $i < $count; $i++) {
		if (isset($teh_cats[$i])) {
			$results .= '<option value="' . $teh_cats[$i]->term_id . '" ';
			if ($selected) {
				if ($selected == $teh_cats[$i]->term_id) {
					$results .= ' selected="selected" ';
				}

			}
			$results .= '>';
			$results .= $teh_cats[$i]->name;
			$results .= '</option>';

		} else {
			$count++;
		}

	}
	$results .= '</select>';
	return $results;
}
function yahosein_get_fontawesome_select_html($name, $selected = false,$widget_id=false) {
	if(!$widget_id || empty($widget_id))
	{
		$widget_id = mt_rand(1,100);
	}
	$html = '';
	$value = '';
	if($selected)
	{
		$value = $selected;
	}
	$html .= '<i class="catalogmode_icon_placeholder fa '.$selected.'"></i><input name="'.$name.'" class="catalogmode_font_picker catalogmode_font_picker_'.$widget_id.'" target-class="catalogmode_font_picker_'.$widget_id.'" type="text" value="'.$value.'">';
	return $html;
}


/**
 * Get downloads by category
 */
function yahosein_cat_section( $cat_id, $num = 4 ,$class='',$div_id='' ) {

	$cat = get_term( $cat_id, 'category' );
	if(!$cat) return;
//	var_dump($cat);
	$args = array(
	 'post_type' => 'post',
	 'posts_per_page' => $num,
		'tax_query' => array(
			array(
				'taxonomy' => 'category',
				'field'    => 'slug',
				'terms'    => $cat->slug,
			),
		)
	 );
	ob_start();
	$q    = new wp_query( $args );

		?>
    <div id="<?=$div_id?>" class="tab-pane fade in <?php echo $class; ?>">
        <ul>
        	<?php 	if ( $q->have_posts() ) {
        		while ($q->have_posts()) {
        			$q->the_post();
        			echo '<li><a href="'.get_the_permalink().'">'.get_the_title().'</a></li>
';
        		}
					 } 
					?>
            <div class=" clearfix "></div>
        </ul>
    </div>
		<?php
	return ob_get_clean();
}

