<?php
/**
 *
 * Let's Review Widget
 *
 * @since      1.0.0
 *
 * @package    Let's Review
 * @subpackage lets-review/inc
 */

class Lets_Review_Widget extends WP_Widget {

	/**
	 * Constructor
	 *
	 * @since 1.0.0
	 *
	*/
	public function __construct() {
		$widget_ops = array(
			'classname' => 'lets_review_widget',
			'description' => esc_html__( 'Powerful widget to show off your reviews.', 'lets-review' ),
		);
		parent::__construct( 'lets-review-widget', esc_html__( 'Let\'s Review Widget', 'lets-review' ) , $widget_ops );
	}

	/**
	 * Let's Review Final Scores
	 *
	 * @since 1.0.0
	 * @see WP_Widget::widget()
	 *
	 * @param array $args     Widget arguments.
	 * @param array $instance Saved values from database.
	 */
	public function lets_review_box( $pid = '', $size = 'bar', $type_live = 1, $instance ) {
		$final_score = get_post_meta( $pid, '_lets_review_final_score', true );
		$type = get_post_meta( $pid, '_lets_review_type', true );
		$format = get_post_meta( $pid, '_lets_review_format', true );
		$subtitle = get_post_meta( $pid, '_lets_review_subtitle', true );
		$color = get_post_meta( $pid, '_lets_review_color', true ) == '' ? '#f8d92f' : get_post_meta( $pid, '_lets_review_color', true );

		if ( $type == 3 || $type_live == 2 ) {
			$final_score_per = get_post_meta( $pid, '_lets_review_user_rating', true ) ? get_post_meta( $pid, '_lets_review_user_rating', true ) : '0';
			switch ( $format ) {
				case 1:
					$final_score = $final_score_per;
					break;
				case 2:
					$final_score = $final_score_per / 10;
					break;
				default:
					$final_score = number_format( ( $final_score_per /  20 ), 1 ) + 0;
					break;
			}
		} else {
			switch ( $format ) {
				case 1:
					$final_score_per = $final_score;
					break;
				case 2:
					$final_score_per = $final_score * 10;
					break;
				default:
					$final_score_per = $final_score * 20;
					break;
			}
		}
		if ( $size == 'big' ) {
		?>
		<div class="score-box<?php if ( empty( $subtitle ) ) { ?> cb-no-sub<?php } ?>">
			<div class="score-bg" style="background: <?php echo esc_attr( $color ); ?>;"></div>
			<div class="score cb-format-<?php echo esc_attr( $format ); ?>"><?php echo floatval( $final_score ); ?></div>
		</div>
		<?php
		} elseif ( $size == 'small' ) {
		?>
		<div class="score-box">
			<div class="score-bg" style="background-color:<?php echo esc_attr( $color ); ?>; "></div>
			<div class="score cb-format-<?php echo esc_attr( $format ); ?>"><?php echo floatval( $final_score ); ?></div>
		</div>
		<?php
		} elseif ( $size == 'bar' ) {
		?>
		<div class="score cb-format-<?php echo esc_attr( $format ); ?>"><?php echo floatval( $final_score ); ?></div>
		<div class="score-bar"><div class="score-overlay" style="width: <?php echo floatval( $final_score_per ); ?>%; background-color:<?php echo esc_attr( $color ); ?>;"></div></div>
		<?php
		} elseif ( $size == 'stars' ) {
		?>
		<span class="cb-overlay" style="color: <?php echo esc_attr( $color ); ?>;"><?php echo str_repeat( '<i class="' . esc_attr( apply_filters( 'lets_review_stars', 'fa fa-star' ) ) . '"></i>', 5 ); ?><span style="width: <?php echo 100 - (int) $final_score_per; ?>%; <?php if ( ! empty( $instance['overlay_color'] ) ) { echo 'background: ' . esc_attr( $instance['overlay_color'] ) . ';'; } ?>"></span></span>
		<?php
		}
	}

	/**
	 * Front-end display of widget.
	 *
	 * @since 1.0.0
	 * @see WP_Widget::widget()
	 *
	 * @param array $args     Widget arguments.
	 * @param array $instance Saved values from database.
	 */
	public function widget( $args, $instance ) {
		switch ( $instance['order'] ) {
			case 2:
				$order = 'ASC';
				$orderby = 'meta_value_num';
				break;
			case 3:
				$order = 'DESC';
				$orderby = 'date';
				break;
			default:
				$order = 'DESC';
				$orderby = 'meta_value_num';
				break;
		}
		switch ( $instance['pubdate'] ) {
			case 2:
				$week = date( 'W' );
				$month = '';
				$year = date( 'Y' );
				break;
			case 3:
				$week = '';
				$month = date( 'm', strtotime( '-30 days' ) );
				$year = date( 'Y', strtotime( '-30 days' ) );
				break;
			default:
				$week = '';
				$year = '';
				$month = '';
				break;
		}

		if ( $instance['type'] == 1 ) {
			$type_filter = '_lets_review_final_score_100';
			$type_live = 1;
		} else {
			$type_filter = '_lets_review_user_rating';
			$type_live = 2;
		}

		$source = empty( $instance['source'] ) ? 1 : $instance['source'];
		$current_posts = empty( $instance['all_posts'] ) ? '' : $instance['all_posts'];
		$post__in = '';
		$tag__in = '';
		$cat = '';
		$cpt = '';
		switch ( $source ) {
			case 2:
				$tag__in = is_array( $instance['tag'] ) ? $instance['tag'] : explode( ',', $instance['tag'] );
				break;
			case 3:
				$post__in = is_array( $current_posts ) ? $current_posts : explode( ',', $current_posts );
				break;
			case 4:
				$cpt = $instance['cpt'];
				break;
			default:
				$cat = $instance['category'];
				break;
		}

		if ( empty( $cpt ) ) {
			$cpt = Lets_Review_Helpers::lets_review_get_post_types();
		}
		$qry = new WP_Query( array(
			'post_type' => $cpt,
			'posts_per_page' => $instance['count'] + 5,
			'cat' => $cat,
			'tag__in' => $tag__in,
			'post__in' => $post__in,
			'w' => $week,
			'monthnum' => $month,
			'year' => $year,
			'meta_key' => $type_filter,
			'orderby' => $orderby,
			'order' => $order,
			'post_status' => 'publish',
			'ignore_sticky_posts' => true
		) );

		if ( $qry->have_posts() ) :
			echo lets_review_sanitize_wp_kses( $args['before_widget'] );
			if ( ! empty( $instance['title'] ) ) {
				echo lets_review_sanitize_wp_kses( $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ). $args['after_title'] );
			}
			?>
			<div class="lets-review__widget cb-lets-review-widget lr-cf cb-widget-design-base">
			<?php
				$i = 1;
				switch ( $instance['design'] ) {
					case 2:
						$width = 360;
						$height = 240;
						break;
					case 3:
						$width = 90;
						$height = 60;
						break;
					 case 4:
						$width = 90;
						$height = 60;
						break;
					default:
						$width = $height = '';
						break;
				}

				while ( $qry->have_posts() ) :
					$qry->the_post();
					global $post;
					$pid = $post->ID;

					if ( get_post_meta( $pid, '_lets_review_onoff', true ) != 1 ) {
						continue;
					}
					if ( $instance['design'] != 1 ) {
						$fi_url = aq_resize( wp_get_attachment_url( get_post_thumbnail_id( $pid ) ), $width, $height, true ) ? aq_resize( wp_get_attachment_url( get_post_thumbnail_id( $pid ) ), $width, $height, true ) : wp_get_attachment_url( get_post_thumbnail_id( $pid ) );
						$fi_exist = $fi_url ? ' cb-fi-on' : ' cb-fi-off';
					} else {
						$fi_exist = ' cb-fi-off';
					}

					?>
					<article class="cb-widget-post lr-cf lr-font-p<?php echo esc_attr( $fi_exist ); ?> lets-review__widget__design-<?php echo (int) $instance['design']; ?> cb-widget-design-<?php echo (int) $instance['design']; ?>">
						<?php if ( $instance['design'] == 1 ) { ?>
							<h4 class="cb-title lr-font-h"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
							<?php $this->lets_review_box( $pid, 'bar', $type_live, $instance );?>
						<?php } elseif ( $instance['design'] == 2 ) { ?>
							<div class="mask">
								<a href="<?php the_permalink(); ?>">
									<img src="<?php echo esc_url( $fi_url ); ?>" alt="">
								</a>
							</div>
							<div class="meta">
								<h4 class="cb-title lr-font-h"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
							</div>
							<?php $this->lets_review_box( $pid, 'big', $type_live, $instance );?>
							<a href="<?php the_permalink(); ?>" class="lr-overlay"></a>
							<div class="cb-countdown"><?php echo (int) $i; ?></div>
						<?php } elseif ( $instance['design'] == 3 ) { ?>
							<div class="mask">
								<?php $this->lets_review_box( $pid, 'small', $type_live, $instance );?>
								<a href="<?php the_permalink(); ?>">
									<img src="<?php echo esc_url( $fi_url ); ?>" alt="">
								</a>
							</div>
							<div class="meta">
								<h4 class="cb-title lr-font-h"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
							</div>

						<?php } elseif ( $instance['design'] == 4 ) { ?>
							<div class="mask">
								<a href="<?php the_permalink(); ?>">
									<img src="<?php echo esc_url( $fi_url ); ?>" alt="">
								</a>
							</div>
							<div class="meta">
								<h4 class="cb-title lr-font-h"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
								<?php $this->lets_review_box( $pid, 'stars', $type_live, $instance );?>
							</div>
						<?php } ?>

						<?php if ( $instance['design'] > 4 ) { ?>
							<?php echo apply_filters( 'lets_review_widget_add_design_html_' . (int) ( $instance['design'] - 4 ), '' ); ?>
						<?php } ?>
					</article>
					<?php
					if ( $i == $instance['count'] ) {
						break;
					}
					$i++;
					?>

				<?php endwhile; ?>
			</div>

			<?php
			echo lets_review_sanitize_wp_kses( $args['after_widget'] );
			wp_reset_postdata();
		endif;
	}

	/**
	 * Back-end widget form.
	 *
	 * @since 1.0.0
	 * @see WP_Widget::form()
	 *
	 * @param array $instance Previously saved values from database.
	 */
	public function form( $instance ) {

		$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
		$count = ! empty( $instance['count'] ) ? $instance['count'] : 4;
		$pubdate = ! empty( $instance['pubdate'] ) ? $instance['pubdate'] : 1;
		$source = ! empty( $instance['source'] ) ? $instance['source'] : 1;
		$category = ! empty( $instance['category'] ) ? $instance['category'] : array( 0 );
		$instance['tag'] = empty( $instance['tag'] ) ? '' : $instance['tag'] ;
		$tag = is_array( $instance['tag'] ) ? implode( ',', $instance['tag'] ) : $instance['tag'];
		$instance['all_posts'] = empty( $instance['all_posts'] ) ? '' : $instance['all_posts'] ;
		$current_posts = is_array( $instance['all_posts'] ) ? implode( ',', $instance['all_posts'] ) : $instance['all_posts'];
		$cpt = ! empty( $instance['cpt'] ) ? $instance['cpt'] : array( 0 );
		$order = ! empty( $instance['order'] ) ? $instance['order'] : 1;
		$skin = ! empty( $instance['skin'] ) ? $instance['skin'] : 1;
		$design = ! empty( $instance['design'] ) ? $instance['design'] : 1;
		$overlay_color = ! empty( $instance['overlay_color'] ) ? $instance['overlay_color'] : '';
		$type = ! empty( $instance['type'] ) ? $instance['type'] : 1;
		$cpts = get_post_types( array( 'public' => true, '_builtin' => false ) );
		$cpts_list = $cpts;
		$cpts[] = 'post';
		$cpts[] = 'page';
		$post_qry = new WP_Query( array (
			'posts_per_page' => -1,
			'post_type' => $cpts,
			'fields' => 'ids'
		));
		?>
		<p>
		<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Title:', 'lets-review' ); ?></label>
		<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
		</p>
		<p>
		<label for="<?php echo esc_attr( $this->get_field_id( 'count' ) ); ?>"><?php esc_html_e( 'Amount Reviews:', 'lets-review' ); ?></label>
		<input class="tiny-text" id="<?php echo esc_attr( $this->get_field_id( 'count' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'count' ) ); ?>" min="1" max="100" size="3" type="number" value="<?php echo esc_attr( $count ); ?>">
		</p>
		<p>
		<label for="<?php echo esc_attr( $this->get_field_id( 'source' ) ); ?>"><?php esc_html_e( 'Review source:', 'lets-review' ); ?></label>
		<select id="<?php echo esc_attr( $this->get_field_id( 'source' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'source' ) ); ?>"  class="lets-review-source-choice">
			<option value="1" <?php selected( $source, '1' ); ?>><?php esc_html_e( 'Categories', 'lets-review' ); ?></option>
			<option value="2" <?php selected( $source, '2' ); ?>><?php esc_html_e( 'Tags', 'lets-review' ); ?></option>
			<option value="3" <?php selected( $source, '3' ); ?>><?php esc_html_e( 'Posts', 'lets-review' ); ?></option>
			<option value="4" <?php selected( $source, '4' ); ?>><?php esc_html_e( 'Custom Post Types', 'lets-review' ); ?></option>
		</select>
		</p>
		<p class="source-cats" <?php if ( $source != 1 ) { ?>style="display:none;"<?php } ?>>
		<label for="<?php echo esc_attr( $this->get_field_id( 'category' ) ); ?>"><?php esc_html_e( 'Category(s):', 'lets-review' ); ?></label>
		<select multiple="multiple" name="<?php echo esc_attr( $this->get_field_name( 'category' ) ); ?>[]" id="cb-cat-<?php echo esc_attr( $this->get_field_id( 'category' ) ); ?>">
			<option value="0" <?php if ( in_array( 0, $category ) == true ) {?>selected="selected"<?php } ?>>
				<?php esc_html_e( 'All Categories', 'lets-review' ); ?>
			</option>
			<?php foreach ( get_categories() as $key ) { ?>
				<option value="<?php echo esc_attr( $key->term_id ); ?>" <?php if ( in_array( $key->term_id, $category ) ) { ?>selected="selected"<?php } ?>> <?php echo ( $key->name ) . ' ( ' . $key->count . ' )'; ?> </option>
			<?php } ?>
		</select>
		</p>
		<p class="source-tags" <?php if ( $source != 2 ) { ?>style="display:none;"<?php } ?>>
		<label for="<?php echo esc_attr( $this->get_field_id( 'tag' ) ); ?>"><?php esc_html_e( 'Tag(s):', 'lets-review' ); ?></label>
		<span class="howto" id="new-tag-post_tag-desc"><?php esc_attr_e( 'Separate tags with commas', 'lets-review' ); ?></span>
		<input class="widefat tipi-tag-suggest" id="<?php echo esc_attr( $this->get_field_id( 'tag' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'tag' ) ); ?>" type="text" value="<?php echo esc_attr( $tag ); ?>" />
		</p>
		<p class="source-posts" <?php if ( $source != 3 ) { ?>style="display:none;"<?php } ?>>
		<label for="<?php echo esc_attr( $this->get_field_id( 'all_posts' ) ); ?>"><?php esc_html_e( 'Post(s):', 'lets-review' ); ?></label>
		<span class="howto" id="new-post-desc"><?php esc_attr_e( 'Separate post ids with commas', 'lets-review' ); ?></span>
		<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'all_posts' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'all_posts' ) ); ?>" type="text" value="<?php echo esc_attr( $current_posts ); ?>" />
		</p>
		<p class="source-cpt" <?php if ( $source != 4 ) { ?><?php } ?>>
		<label for="<?php echo esc_attr( $this->get_field_id( 'cpt' ) ); ?>"><?php esc_html_e( 'Custom Post Type:', 'lets-review' ); ?></label>
		<select multiple="multiple" name="<?php echo esc_attr( $this->get_field_name( 'cpt' ) ); ?>[]" id="cb-cat-<?php echo esc_attr( $this->get_field_id( 'cpt' ) ); ?>">
			<?php foreach ( $cpts_list  as $post_type ) { ?>
				<option value="<?php echo esc_attr( $post_type ); ?>" <?php if ( in_array( $post_type, $cpt ) ) { ?>selected="selected"<?php } ?>><?php echo esc_attr( $post_type ); ?> </option>
			<?php } ?>
		</select>
		</p>

		<p>
		<label for="<?php echo esc_attr( $this->get_field_id( 'pubdate' ) ); ?>"><?php esc_html_e( 'Review Date:', 'lets-review' ); ?></label>
		<select id="<?php echo esc_attr( $this->get_field_id( 'pubdate' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'pubdate' ) ); ?>">
			<option value="1" <?php selected( $pubdate, '1' ); ?>><?php esc_html_e( 'All-time', 'lets-review' ); ?></option>
			<option value="2" <?php selected( $pubdate, '2' ); ?>><?php esc_html_e( 'Past 7 Days', 'lets-review' ); ?></option>
			<option value="3" <?php selected( $pubdate, '3' ); ?>><?php esc_html_e( 'Last Month', 'lets-review' ); ?></option>
		</select>
		</p>
		<p>
		<label for="<?php echo esc_attr( $this->get_field_id( 'order' ) ); ?>"><?php esc_html_e( 'Order:', 'lets-review' ); ?></label>
		<select id="<?php echo esc_attr( $this->get_field_id( 'order' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'order' ) ); ?>">
			<option value="1" <?php selected( $order, '1' ); ?>><?php esc_html_e( 'Top Scores', 'lets-review' ); ?></option>
			<option value="2" <?php selected( $order, '2' ); ?>><?php esc_html_e( 'Lowest Scores', 'lets-review' ); ?></option>
			<option value="3" <?php selected( $order, '3' ); ?>><?php esc_html_e( 'Newest Reviews', 'lets-review' ); ?></option>
		</select>
		</p>
		<p>
		<label for="<?php echo esc_attr( $this->get_field_id( 'design' ) ); ?>"><?php esc_html_e( 'Design:', 'lets-review' ); ?></label>
		<select id="<?php echo esc_attr( $this->get_field_id( 'design' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'design' ) ); ?>" class="lets-review-design-choice">
			<?php $this->lets_review_widget_add_design( $design ); ?>
		</select>
		</p>
		<p<?php if ( $design != 4 ) { echo ' style="display:none;"'; }?>>
		<label for="<?php echo esc_attr( $this->get_field_id( 'overlay_color' ) ); ?>"><?php esc_html_e( 'Color (Refer to documentation for info):', 'lets-review' ); ?></label>
		<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'overlay_color' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'overlay_color' ) ); ?>" type="text" value="<?php echo esc_attr( $overlay_color ); ?>">
		</p>
		<p>
		<label for="<?php echo esc_attr( $this->get_field_id( 'type' ) ); ?>"><?php esc_html_e( 'Score Type:', 'lets-review' ); ?></label>
		<select id="<?php echo esc_attr( $this->get_field_id( 'type' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'type' ) ); ?>">
			<option value="1" <?php selected( $type, '1' ); ?>><?php esc_html_e( 'Editor Scores', 'lets-review' ); ?></option>
			<option value="2" <?php selected( $type, '2' ); ?>><?php esc_html_e( 'Visitor Scores', 'lets-review' ); ?></option>
		</select>
		</p>
		<?php
	}

	/**
	 * Sanitize widget form values as they are saved.
	 *
	 * @see WP_Widget::update()
	 *
	 * @param array $new_instance Values just sent to be saved.
	 * @param array $old_instance Previously saved values from database.
	 *
	 * @return array Updated safe values to be saved.
	 */
	public function lets_review_widget_add_design( $design ) {
		?>
		<option value="1" <?php selected( $design, '1' ); ?>><?php esc_html_e( 'Minimal', 'lets-review' ); ?></option>
		<option value="2" <?php selected( $design, '2' ); ?>><?php esc_html_e( 'Bold', 'lets-review' ); ?></option>
		<option value="3" <?php selected( $design, '3' ); ?>><?php esc_html_e( 'Simple', 'lets-review' ); ?></option>
		<option value="4" <?php selected( $design, '4' ); ?>><?php esc_html_e( 'Simple + Stars', 'lets-review' ); ?></option>
		<?php
		$check = apply_filters( 'lets_review_widget_add_design', '' );
		if ( ! empty( $check ) ) {
			if ( is_array( $check ) ) {
				$i = 5;
				foreach ( $check as $design ) {
					 ?>
					<option value="<?php echo (int) $i; ?>" <?php selected( $design, '1' ); ?>><?php echo esc_html( $design ); ?></option>
					<?php
					$i++;
				}
			} else {
				?>
				<option value="5" <?php selected( $design, '5' ); ?>><?php echo esc_html( $check ); ?></option>
				<?php
			}
		}
	}

	/**
	 * Sanitize widget form values as they are saved.
	 *
	 * @see WP_Widget::update()
	 *
	 * @param array $new_instance Values just sent to be saved.
	 * @param array $old_instance Previously saved values from database.
	 *
	 * @return array Updated safe values to be saved.
	 */
	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['title'] = ! empty( $new_instance['title'] ) ? strip_tags( $new_instance['title'] ) : '';
		$instance['count'] = ! empty( $new_instance['count'] ) ? (int) $new_instance['count'] : 4;
		$instance['design'] = ! empty( $new_instance['design'] ) ? (int) $new_instance['design'] : 1;
		$instance['overlay_color'] = ! empty( $new_instance['overlay_color'] ) ? esc_attr( $new_instance['overlay_color'] ) : '';
		$instance['order'] = ! empty( $new_instance['order'] ) ? (int) $new_instance['order'] : 1;
		$instance['skin'] = ! empty( $new_instance['skin'] ) ? (int) $new_instance['skin'] : 1;
		$instance['pubdate'] = ! empty( $new_instance['pubdate'] ) ? (int) $new_instance['pubdate'] : 1;
		$instance['source'] = ! empty( $new_instance['source'] ) ? (int) $new_instance['source'] : 1;
		$instance['category'] = ! empty( $new_instance['category'] ) ? $new_instance['category'] : array( 0 );
		$instance['tag'] = ! empty( $new_instance['tag'] ) ? $new_instance['tag'] : '';
		$instance['cpt'] = ! empty( $new_instance['cpt'] ) ? $new_instance['cpt'] : array();
		$instance['all_posts'] = ! empty( $new_instance['all_posts'] ) ? $new_instance['all_posts'] : array();
		$instance['type'] = ! empty( $new_instance['type'] ) ? $new_instance['type'] : 1;
		return $instance;
	}
}
