<?php
if(!class_exists('daneshfileStarRating_plugin')) :

	class daneshfileStarRating_plugin
	{
	public $id;
	public function __construct($id)
	{
	$this->id = $id;		
	}
	protected function enqueue_js($slug, $file, $ver = false, $prerequisite=false, $params=false)
	{
	$json = '';
	if(is_array($params) && $json)
	{
	?>
<script type="text/javascript">
var <?php echo str_replace('-','_',$this->id).'_'.$slug; ?> = <?php echo json_encode( $params ); ?>;
</script>
<?php
	}	
	if(is_single()):
	wp_enqueue_script($this->id.($slug?('_'.$slug):''), $file, is_array($prerequisite)?$prerequisite:array('jquery'), $ver ? $ver : $this->ver, true);
			
	if(is_array($params) && !$json) 
	wp_localize_script($this->id.($slug?('_'.$slug):''), str_replace('-','_',$this->id).'_'.$slug, $params);
	endif;
	}
	}
endif;	

if(!class_exists('daneshfile_framework_dfStarRatings')) :

	class daneshfile_framework_dfStarRatings extends daneshfileStarRating_plugin
	{
//////////////////////////////////////////////////////////////////////////////////
// @ ADD params & js 
//////////////////////////////////////////////////////////////////////////////////	

	public function js()
	{
	$nonce = wp_create_nonce($this->id);
	$Params = array();
	$Params['nonce'] = $nonce; //for security
	$Params['ajaxurl'] = admin_url('admin-ajax.php');
	$Params['func'] = 'dffr_ajax';
	$this->enqueue_js('js',get_template_directory_uri() . '/js/star-ratings.js', '1.0', array('jquery'), $Params, false, true);
	}
		
//////////////////////////////////////////////////////////////////////////////////
// @ add meta_key to database
//////////////////////////////////////////////////////////////////////////////////	

	public function PasargadStarRating()
	{
	global $wpdb;
	$table = $wpdb->prefix . 'postmeta';
	$Posts = $wpdb->get_results("SELECT a.ID, b.meta_key, b.meta_value 
								FROM " . $wpdb->posts . " a, $table b 
								WHERE a.ID=b.post_id AND 
								(
									b.meta_key='_kk_ratings_ratings' OR 
									b.meta_key='_kk_ratings_casts' OR 
									b.meta_key='_kk_ratings_ips'
								) ORDER BY a.ID ASC");
	$Wrap = array();
	foreach ($Posts as $post)
	{
	$Wrap[$post->ID]['id'] = $post->ID;
	$Wrap[$post->ID][$post->meta_key] = $post->meta_value;
	}
	foreach($Wrap as $p)
	{
	update_post_meta($p['id'], '_kksr_ratings', $p['_kk_ratings_ratings']);
	update_post_meta($p['id'], '_kksr_casts', $p['_kk_ratings_casts']);
	$Ips = array();
	$Ips = explode('|', $p['_kk_ratings_ips']);
	$ip = base64_encode(serialize($Ips));
	update_post_meta($p['id'], '_kksr_ips', $ip);
	update_post_meta($p['id'], '_kksr_avg', round($p['_kk_ratings_ratings']/$p['_kk_ratings_casts'],1));
	}
	}


//////////////////////////////////////////////////////////////////////////////////
// @ AJAX functions
//////////////////////////////////////////////////////////////////////////////////	
public function dffr_ajax()
		{
			header('Content-type: application/json; charset=utf-8');
			check_ajax_referer($this->id);

			$Response = array();

			$total_stars = 5; 

			$stars = is_numeric($_POST['stars']) && ((int)$_POST['stars']>0) && ((int)$_POST['stars']<=$total_stars)
					? $_POST['stars']:
					0;
			$ip = $_SERVER['REMOTE_ADDR'];

			$Ids = explode(',', $_POST['id']);

			foreach($Ids as $pid) :

			$ratings = get_post_meta($pid, '_kksr_ratings', true) ? get_post_meta($pid, '_kksr_ratings', true) : 0;
			$casts = get_post_meta($pid, '_kksr_casts', true) ? get_post_meta($pid, '_kksr_casts', true) : 0;

			if($stars==0 && $ratings==0)
			{
				$Response[$pid]['legend'] = 'true';
				$Response[$pid]['disable'] = 'false';
				$Response[$pid]['fuel'] = '0';
				do_action('dffr_init', $pid, false, false);
			}
			else
			{
				$nratings = $ratings + ($stars/($total_stars/5));
				$ncasts = $casts + ($stars>0);
				$avg = $nratings ? number_format((float)($nratings/$ncasts), 2, '.', '') : 0;
				$per = $nratings ? number_format((float)((($nratings/$ncasts)/5)*100), 2, '.', '') : 0;
				$Response[$pid]['disable'] = 'false';
				if($stars)
				{
					$Ips = get_post_meta($pid, '_kksr_ips', true) ? unserialize(base64_decode(get_post_meta($pid, '_kksr_ips', true))) : array();
					if(!in_array($ip, $Ips))
					{
						$Ips[] = $ip;
					}
					$ips = base64_encode(serialize($Ips));
					update_post_meta($pid, '_kksr_ratings', $nratings);
					update_post_meta($pid, '_kksr_casts', $ncasts);
					update_post_meta($pid, '_kksr_ips', $ips);
					update_post_meta($pid, '_kksr_avg', $avg);
					$Response[$pid]['disable'] = 'true';
					do_action('kksr_rate', $pid, $stars, $ip);
				}
				else
				{
					do_action('dffr_init', $pid, number_format((float)($avg*($total_stars/5)), 2, '.', '').'/'.$total_stars, $ncasts);
				}
				$legend = '[total]';
				$avrages = number_format((float)($avg*($total_stars/5)), 2, '.', '').'/'.$total_stars;
				$rating_score = number_format((float)($avg*($total_stars/5)), 2, '.', '');
				$user_votes = $ncasts;
				$legend = str_replace('[total]','امتیاز'.$rating_score.' ( '.$user_votes.' رای )', $legend);
				$Response[$pid]['legend'] = str_replace('[per]',$per.'px', $legend);
				$Response[$pid]['fuel'] = $per;
			
			}

			$Response[$pid]['success'] = true;

			endforeach;
			
			echo json_encode($Response);
			die();
		}
		protected function trim_csv_cb($value)
		{
			if(trim($value)!="")
			    return true;
			return false;
		}
		
		public function markup($id=false)
		{
			$id = !$id ? get_the_ID() : $id;

	$disabled = false;
			if(get_post_meta($id, '_kksr_ips', true))
			{
				$Ips = unserialize(base64_decode(get_post_meta($id, '_kksr_ips', true)));
				$ip = $_SERVER['REMOTE_ADDR'];
				if(in_array($ip, $Ips))
				{
					$disabled = true;
				}
			}
			
//////////////////////////////////////////////////////////////////////////////////
// @ output functions
//////////////////////////////////////////////////////////////////////////////////	

$score = get_post_meta($id, '_kksr_ratings', true) ? get_post_meta($id, '_kksr_ratings', true) : 0;
$votes = get_post_meta($id, '_kksr_casts', true) ? get_post_meta($id, '_kksr_casts', true) : 0;
$avg = $score ? number_format((float)($score/$votes), 2, '.', '') : 0;
$title = get_the_title($id);
$postid = get_the_ID($id);
$markup = '
<div class="df-star-ratings '.($disabled ? 'disabled':'').'" data-id="'.$id.'">
<div class="stars-wrap">
<div class="dffr-stars dffr-star gray">
<div class="dffr-fuel dffr-star '.($disabled ? 'orange' : 'yellow').'" style="width:0%;"></div>
';
$total_stars = 5;
for($ts = 1; $ts <= $total_stars; $ts++)
{
$markup .= '<a href="#'.$ts.'" rel="nofollow"></a>';
}
$markup .='
</div></div>
<div class="dffr-legend">
<div id="post-ratings-'.$postid.'" class="post-ratings">
';
$markup .= apply_filters('dffr_legend', '[total]', $id);
$markup .='
</div>
</div>
</div>
';
return $markup;
}
	
	public function df_star_rating($pid=false)
	{
		return $this->markup($pid);
		return '';
	}
	public function df_star_ratings_get($total=5)
	{
	global $wpdb;
	$table = $wpdb->prefix . 'postmeta';
	if(!$cat)
	$rated_posts_to_db = $wpdb->get_results("SELECT a.ID, a.post_title, b.meta_value AS 'ratings' FROM " . $wpdb->posts . " a, $table b, $table c WHERE a.post_status='publish' AND a.ID=b.post_id AND a.ID=c.post_id AND b.meta_key='_kksr_avg' AND c.meta_key='_kksr_casts' ORDER BY b.meta_value DESC, c.meta_value DESC LIMIT $total");
	else
	{
	$table2 = $wpdb->prefix . 'term_taxonomy';
	$table3 = $wpdb->prefix . 'term_relationships';
	$rated_posts_to_db = $wpdb->get_results("SELECT a.ID, a.post_title, b.meta_value AS 'ratings' FROM " . $wpdb->posts . " a, $table b, $table2 c, $table3 d, $table e WHERE c.term_taxonomy_id=d.term_taxonomy_id AND c.term_id=$cat AND d.object_id=a.ID AND a.post_status='publish' AND a.ID=b.post_id AND a.ID=e.post_id AND b.meta_key='_kksr_avg' AND e.meta_key='_kksr_casts' ORDER BY b.meta_value DESC, e.meta_value DESC LIMIT $total");
	}
	return $rated_posts_to_db;
	}
		
//////////////////////////////////////////////////////////////////////////////////
// @ Updates And order meta_key
//////////////////////////////////////////////////////////////////////////////////

	public function sort_columns($Args)
	{
	$Args = array_merge($Args,
	array('df_star_ratings' => 'df_star_ratings')
	);
	return wp_parse_args($Args);
	}

	public function sort_columns_helper($Query)
	{
	$orderby = $Query->get( 'orderby');  
	if($orderby=='df_star_ratings')
	{  
	$Query->set('meta_key','_kksr_avg');
	$Query->set('orderby','meta_value_num');  
	}
	}
	
	

//////////////////////////////////////////////////////////////////////////////////
// @ Google schema.org for posts rating
//////////////////////////////////////////////////////////////////////////////////	\

public function google_schema_legend($legend, $id){
$post_type = get_post_type($id);
$title = get_the_title($id);
$exp = get_the_excerpt($id);
$url = get_permalink($id);
$best = 5;
$score = get_post_meta($id, '_kksr_ratings', true) ? get_post_meta($id, '_kksr_ratings', true) : 0;
$snippet = '';
if($score){
$votes = get_post_meta($id, '_kksr_casts', true) ? get_post_meta($id, '_kksr_casts', true) : 0;
$avg = $score ? number_format((float)($score/$votes), 2, '.', '') : 0;
$per = $score ? number_format((float)((($score/$votes)/5)*100), 2, '.', '') : 0;
$leg = str_replace('[total]', 'امتیاز '.$avg.' ( <span class="ratenumber">'.$votes.'</span> رای )', $legend);
$snippet .=  $leg;
$snippet .= '
<meta itemprop="name" content="'. $title .'">
<meta itemprop="description" content="'. $exp .'">
<meta itemprop="url" content="'. $url .'">
';
if($post_type != 'post'){
$snippet .= '
<div style="display: none;" itemprop="aggregateRating" itemscope="" itemtype="http://schema.org/AggregateRating">
<meta itemprop="bestRating" content="5">
<meta itemprop="ratingValue" content="'.$avg.'">
<meta itemprop="ratingCount" content="'.$votes.'">
</div>
';
}
}
return $snippet;
return $legend;
}	
}
$dfStarRatings_obj = new daneshfile_framework_dfStarRatings('Ajax_send_dffr', 'df Star Ratings', '2.4');
add_filter('dffr_legend', array($dfStarRatings_obj, 'google_schema_legend'), 1, 2);

//////////////////////////////////////////////////////////////////////////////////
// @ Register scripts
//////////////////////////////////////////////////////////////////////////////////	

add_action('wp_enqueue_scripts', array($dfStarRatings_obj, 'js'));

// AJAX
add_action('wp_ajax_dffr_ajax', array($dfStarRatings_obj, 'dffr_ajax'));
add_action('wp_ajax_nopriv_dffr_ajax', array($dfStarRatings_obj, 'dffr_ajax'));	

/////////////////////////////////////////////////////////////////////////////////
// @ Add to theme
/////////////////////////////////////////////////////////////////////////////////
if(!function_exists('df_star_ratings')){
function df_star_ratings($pid=false)
{
global $dfStarRatings_obj;
return $dfStarRatings_obj->df_star_rating($pid);
}
}
endif;
?>