<?php
/*
	User rating aggregate functions
 
	WARNING: This file is part of the core WPRichSnippets plugin. DO NOT edit
	this file under any circumstances.
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
	
	//add_action('get_header', 'wprs_comment_reply_script');
	/*
		Load comment reply script
		*/
	function wprs_comment_reply_script() {
		if (is_admin()) return;
    	if ( is_singular() AND comments_open() AND (get_option('thread_comments') == 1)) wp_enqueue_script( 'comment-reply' );
		return;
	}
	
	/*
		Get user reviews
		to be used on aggregate templates
		@since 1.0.0
		*/
	function wprs_get_user_reviews(){
		
		$options = get_option('wprs_options');
		
		$post_id = get_the_ID();
		
		// Get filtered reviews number
		$number = intval(get_query_var( 'filter' )) != 0 ? intval(get_query_var( 'filter' )) : '';
		
		$orderby = isset($options['wprs_drp_aggregate_pagination_order_by']) ? $options['wprs_drp_aggregate_pagination_order_by'] : '';
		
		$content = '';

		$args = array(
			'post_id'		=> get_the_ID(),	// Use post_id, not post_ID
			'type'			=> 'comment',
			'status'		=> 'approve',
			'number'		=> '',				// Number of comments, leave blank to return all
			'offset'		=> 0,
			'meta_key'		=> 'rating',		// (string) - Custom field key.
			'meta_value'	=> $number,
			'orderby'		=> $orderby,
			'order'			=> 'DESC',
		);
		
		$comments = get_comments($args);
		
		$content .= apply_filters( 'wprs_user_reviews_top', '' );
		
		$content .= '<div class="wprs_container">'; // open container-fluid
		
		$content .= '<div id="wprs_square" class="wprs_user_reviews_wrap">'; // open div 
		
		$content .= '<div id="reviews"></div>'; // to jump #
		
		// If user review is submitted, display a callout
		// @since 1.3.4
		if ( isset($_GET['updated']) && $_GET['updated'] == 'approved' ) {
			$content .= '<div class="bs-callout bs-callout-success" role="alert">';
			$content .= '<h4>'.__('Thank You!','wprs').'</h3>';
			$content .= '<p>'.__('Your review has been submitted.', 'wprs').'</p>';
			$content .= '</div>';
		}
		
		if ( isset($_GET['updated']) && $_GET['updated'] == 'pending' ) {
			$content .= '<div class="bs-callout bs-callout-warning" role="alert">';
			$content .= '<h4>'.__('Thank You!','wprs').'</h3>';
			$content .= '<p>'.__('Your review has been submitted and is pending approval.', 'wprs').'</p>';
			$content .= '</div>';
		}
		
		$content .= apply_filters( 'wprs_user_reviews_before', '' );
		
		// If there is no comment, return message!
		if (empty($comments)) {
			
			if (!empty($number)) {
				$content .= '<p><center>';
				$content .= '<span class="sr-only">' . __('No one has rated this', 'wprs') . ' ('.$number.') ' . __('stars', 'wprs').'</span>';
				$content .= '<span class="fa fa-info-circle"></span> ' . __('No one has rated this', 'wprs') . ' ('.$number.') ' . __('stars', 'wprs');
				$content .= '</center></p>';
			} else {
				$content .= '<p><center>';
				$content .= '<span class="sr-only">' . __('No one has rated this yet, be the first!', 'wprs') . '</span>';
				$content .= '<span class="fa fa-info-circle"></span> ' . __('No one has rated this yet, be the first!', 'wprs');
				$content .= '</center></p>';
				$content .= '<br />';
				$content .= wprs_get_add_your_review_button();
			}
			
			$content .= '<hr />';
			
			$content .= '</div>'; // close div
			
			$content .= '</div>'; // close container-fluid
		
			$content .= apply_filters( 'wprs_user_reviews_after', '' );
			
			return apply_filters( 'wprs_user_reviews', $content );	
		
		}
		
		// Get add your review button
		$content .= wprs_get_add_your_review_button();
		
		$content .= '</div>'; // close div
			
		$content .= '</div>'; // close container-fluid
		
		$content .= apply_filters( 'wprs_user_reviews_after', '' );
		
		//** Display user reviews
		// Get variables
		$per_page = ( isset($options['wprs_drp_aggregate_pagination_per_page']) && $options['wprs_drp_aggregate_pagination_per_page'] != '' ) ? intval($options['wprs_drp_aggregate_pagination_per_page']) : -1;
		
		// Avoid value of 0
		// @since 1.3.6 
		If ($per_page == 0 ) $per_page = -1; 
		
		$reverse_top_level = isset($options['wprs_drp_aggregate_pagination_per_page']) ? intval($options['wprs_drp_aggregate_pagination_per_page']) : '';
		
		// For pagination
		// @since 1.3.5
		$page = (int) (!isset($_REQUEST["pageNumber"]) ? 1 : $_REQUEST["pageNumber"]);
		$offset = ($page * $per_page) - $per_page;
		$pages = ceil(count($comments) / $per_page);
		// Dirty
		ob_start();
		// Display comments list
		wp_list_comments( array(
					'type' => 'comment',
					'callback' => 'wprs_list_comment',
					'reverse_top_level' => false,
					'per_page' => $per_page,
					'page' => $page
					),
					$comments );
		
		// Display pagination
		if ( get_option( 'page_comments' ) && isset($options['wprs_chk_aggregate_pagination_enable']) ) {
		
			echo '<div class="wprs_pagination-wrap">';
		
				// @since 1.3.5
				paginate_comments_links( array(
					'base'			=> @add_query_arg('pageNumber','%#%'),
					'format'		=> '?pageNumber=%#%',
					'add_fragment'	=> '#reviews',
					'total'			=> $pages,
					'current'		=> $page, 
					'show_all'		=> false,
					'end_size'		=> 1,
					'mid_size'		=> 2,
					'prev_next'		=> true,
					'prev_text'		=> __('&laquo; Previous'),
					'next_text'		=> __('Next &raquo;'),
					'type'			=> 'list', // plain
					'class'			=> 'page_reviews',
					'echo'			=> true
				));
		
			echo '</div>';
			// I think there is a missing div, but still can not find it
			// thid div below just fix the issue, till then!
			// @since 1.3.5
			//echo '</div>';
			
		}
			
		$content .= ob_get_clean();
		
		return apply_filters( 'wprs_user_reviews', $content );
	}

	
	/*
		Get user reviews, example: wprs_get_user_aggregate_reviews_details()
		to be used on aggregate templates
		@since 1.0.0
		*/	
	function wprs_get_user_aggregate_reviews_details() {
		
		global $post, $wprs_prefix;
		
		$meta = wprs_get_meta();
		
		if (! isset($meta[$wprs_prefix.'userrating_average'])) {
			// If 0, return 0 percentage!
			$percentage = '<p>'.wprs_get_rating_percentage(0, 'user').'</p>';
		} else {
			$percentage = wprs_get_rating_percentage($meta[$wprs_prefix.'userrating_average'], 'user') !='' ? '<p>'.wprs_get_rating_percentage($meta[$wprs_prefix.'userrating_average'], 'user').'</p>' : '';
		}
		
		$num_reviews = get_comments_number(); // get_comments_number returns only a numeric value
		
		$write_review = '';
		
		if ( comments_open() ) {
			
			if ( $num_reviews == 0 ) {
				$reviews = __('No reviews yet!', 'wprs');
			} elseif ( $num_reviews > 1 ) {
				$reviews = $num_reviews . __(' Reviews', 'wprs');
			} else {
				$reviews = __('1 Review', 'wprs');
			}
			$write_review = apply_filters( 'wprs_box_aggregate_before', '' );
			$write_review .= '<div class="col-xs-6"><p>' . wprs_get_userrating_stars($post->ID) . wprs_get_add_your_review() . '</p></div>';
			$write_review .= '<div class="col-xs-6 text_right"><p class="text_right">' . $percentage . '</p></div>';
			if (wprs_get_userrating_array($post->ID)) {
				$write_review .= '<div class="clr"><br /></div>';
				$write_review .= '<div class="col-sm-6 wprs_progress_array">'.wprs_get_userrating_array($post->ID).'</div>';
			}
			$write_review .= '<div class="col-sm-6">'.wprs_get_criteria($post->ID, 'user').'</div>';
		} else {
			$write_review = apply_filters( 'wprs_box_aggregate_before', '' );
			$write_review .= '<p>'.__('User Reviews are disabled for this review!', 'wprs').'</p>';
		}
		
		
		$write_review .= '<div class="col-md-12"><hr /><br /></div>';
		
		$write_review .= '<div class="clr"></div>';
		
		$write_review .= apply_filters( 'wprs_box_reviews_before', '' );

		return apply_filters( 'wprs_user_reviews_details', $write_review );
	}
	
		
	/*
    	Update user rating array
		@since 1.0.0
    	*/
	function wprs_update_post_userrating_array($postid, $userrating) {
		
		global $wprs_prefix;
		
		if (get_post_meta($postid, $wprs_prefix.'userrating_array', true)) {
			$ratings = get_post_meta($postid, $wprs_prefix.'userrating_array', true);
		} else {
			$ratings = array();
			$ratings = array(
						5	=>	0,
						4	=>	0,
						3	=>	0,
						2	=>	0,
						1	=>	0
					);
		}
	
		$ratings[$userrating] = $ratings[$userrating] + 1;
		
		update_post_meta($postid, $wprs_prefix.'userrating_array', $ratings);
		
		// Debug
		// echo '<pre>';
		// var_dump($ratings);
		// echo '</pre>';
		
	}


	/*
    	Display user rating array
		@since 1.0.0
    	*/
	function wprs_get_userrating_array($postid) {
		
		global $wprs_prefix;
		
		if (get_post_meta($postid, $wprs_prefix.'userrating_array', true)) {
			$ratings = get_post_meta($postid, $wprs_prefix.'userrating_array', true);
		} else {
			$ratings = '';
		}
		
		if (!$ratings) return;
		
		$count = get_post_meta($postid, $wprs_prefix.'userrating_count', true);
		
		$permalink = get_permalink( $postid ) . '#reviews';
		
		$content = '';
		
		if ($count == 0) return;
		
		foreach(  $ratings as $k => $v ) {
			
			$p = ($v / $count) * 100;
			$p = round($p * 2) / 2 ;
						
			$content .= '<div class="row">';
			$content .= '<a href="' . add_query_arg( 'filter', $k, $permalink ).'">';
			
			$content .= '<div class="col-xs-4">';
			$content .= '<span>' . $k . ' ' . __( 'stars', 'wprs' ) . '</span>';
			$content .= '</div>';
			
			$content .= '<div class="col-xs-6">';
			$content .= '<div class="progress">';
			$content .= '<div class="progress-bar progress-bar-info" role="progressbar" title="'.$p.'%" aria-valuenow="'.$p.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$p.'%">';
			$content .= '<span class="sr-only">User: '.$p.'%</span>';
			$content .= '<div class="bar" style="width: '.$p.'%;"></div>';
			$content .= '</div>';
			$content .= '</div>';
			$content .= '</div>';
			
			$content .= '<div class="col-xs-2">';
			$content .= '<span class="wprs_ml_5">' . $v . '</span>';
			$content .= '</div>';
			
			$content .= '</a>';
			$content .= '</div>';
			
		}
		
		return $content;
	}

	
	add_filter('query_vars', 'wprs_userrating_add_query_vars');
	/*
    	Hook wprs_userrating_add_query_vars function into query_vars
		@since 1.0.0
    	*/
	function wprs_userrating_add_query_vars($aVars) {
		$aVars[] = "filter"; // Represents the name of the product category as shown in the URL
		return $aVars;
	}
 
	
	add_filter('comment_form_defaults', 'wprs_userrating_customize_comment_form_text_area', 99);	
	/*
    	Hook wprs_userrating_customize_comment_form_text_area function into comment_form_defaults
		@since 1.0.0
    	*/
	function wprs_userrating_customize_comment_form_text_area($arg) {
		global $post;
		if (!wprs_is_enabled($post->ID)) return $arg;
		if (wprs_get_type() != 'aggregate') return $arg;
		
		$arg['comment_field'] = '<p class="comment-form-comment"><label for="comment">' . __( 'Your Review', 'wprs' ) . '</label><textarea id="comment" name="comment" placeholder="" cols="45" rows="4" aria-required="true"></textarea></p>';
		return $arg;
	}
 
	
	add_filter( 'comments_open', 'wprs_is_comments_open', 10, 2 );
	/*
    	Open comments by default if review type agregate enabled
		@since 1.0.0
		*/
	function wprs_is_comments_open( $open, $post_id ) {
		
		if (!wprs_is_enabled($post_id)) return $open;
		if (wprs_get_type() != 'aggregate') return $open;
	
		$open = true;

		return $open;
	}
	

	/*
		Return user website or author page link for registered user,
		or return comment author name only for guests
		@since 1.0.0
		*/
	function wprs_comment_author_profile_link($comment_ID, $user_ID = 0){

    	$authorName = get_comment_author( $comment_ID );
    	$authorURL = get_comment_author_url( $comment_ID );

		// Return the default WordPress comment author link if comment author is not a registered user
		if ($user_ID == 0){
        	if ( empty( $authorURL ) || 'http://' == $authorURL )
				$return = $authorName;
			else
				$return = "<a href='$authorURL' rel='' class='author-url'>$authorName</a>";
		} else {

    		// Return the link to the comment author's profile page if otherwise
        	$return = '<a href="'.home_url().'/?author='.$user_ID.'">'.$authorName.'</a>';
    
		}

    	return $return;
	}


	add_filter( 'comment_post_redirect', 'wprs_redirect_after_comment', 10, 2 );
	/*
		Redirect after user submit a review
		@since 1.3.3
		*/

	function wprs_redirect_after_comment( $location, $comment ){
    
		$post_id = $comment->comment_post_ID;

    	// product-only comment redirects
    	if( wprs_get_type_by_id($post_id) == 'aggregate' ){
			
			if ( !$comment->comment_approved ) {
				
				$location = $_SERVER["HTTP_REFERER"].'?updated=pending#reviews';
				
			} else {
			
    	    	$location = $_SERVER["HTTP_REFERER"].'?updated=approved#reviews';
			}
		}
	
		return $location;
	}
	
	