<?php
/**
 * Widget API: Majalahpro_RecentPosts_Wgt class
 *
 * Author: Gian MR - http://www.gianmr.com
 *
 * @package Majalahpro Core
 * @subpackage Widgets
 * @since 1.0.0
 */

/* Exit if accessed directly */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Add the RPSL widget.
 *
 * @since 1.0.0
 *
 * @see WP_Widget
 */
class Majalahpro_RecentPosts_Wgt extends WP_Widget {
	/**
	 * Sets up a Recent Posts widget instance.
	 *
	 * @since 1.0.0
	 * @access public
	 */
	public function __construct() {
		$widget_ops = array(
			'classname'   => 'majalahpro-core-form',
			'description' => __( 'Recent posts with thumbnails widget.', 'majalahpro-core' ),
		);
		parent::__construct( 'majalahpro-core-rp', __( 'Recent Posts (Majalahpro Core)', 'majalahpro-core' ), $widget_ops );

		// add action for admin_register_scripts.
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_register_scripts' ) );
		add_action( 'admin_footer-widgets.php', array( $this, 'admin_print_scripts' ), 9999 );
	}

	/**
	 * Enqueue scripts.
	 *
	 * @since 1.0
	 *
	 * @param string $hook_suffix Hook Suffix.
	 */
	public function admin_register_scripts( $hook_suffix ) {
		if ( 'widgets.php' !== $hook_suffix ) {
			return;
		}

		wp_enqueue_style( 'wp-color-picker' );
		wp_enqueue_script( 'wp-color-picker' );
		wp_enqueue_script( 'suggest' );
		wp_enqueue_script( 'underscore' );
	}

	/**
	 * Print scripts.
	 *
	 * @since 1.0
	 */
	public function admin_print_scripts() {
		?>
		<script>
			function setSuggest_cat_recent(id) {
				jQuery('#' + id).suggest("<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>?action=ajax-tag-search&tax=category", {multiple:true, multipleSep: ","});
			}
			( function( $ ){
				function initColorPicker( widget ) {
					widget.find( '.color-picker' ).wpColorPicker( {
						change: _.throttle( function() { // For Customizer
							$(this).trigger( 'change' );
						}, 3000 )
					});
				}

				function onFormUpdate( event, widget ) {
					initColorPicker( widget );
				}

				$( document ).on( 'widget-added widget-updated', onFormUpdate );

				$( document ).ready( function() {
					$( '#widgets-right .widget:has(.color-picker)' ).each( function () {
						initColorPicker( $( this ) );
					} );
				} );
			}( jQuery ) );
		</script>
		<?php
	}

	/**
	 * Outputs the content for Mailchimp Form.
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @param array $args     Display arguments including 'before_title', 'after_title',
	 *                        'before_widget', and 'after_widget'.
	 * @param array $instance Settings for Mailchimp Form.
	 */
	public function widget( $args, $instance ) {

		// Title.
		$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base );

		echo $args['before_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		if ( $title ) {
			echo $args['before_title'] . $title . $args['after_title']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		}
		// Base Id Widget.
		$majpro_widget_id = $this->id_base . '-' . $this->number;
		// Category ID.
		$majpro_category = ( ! empty( $instance['majpro_category'] ) ) ? wp_strip_all_tags( $instance['majpro_category'] ) : '';
		// Excerpt Length.
		$majpro_number_posts = ( ! empty( $instance['majpro_number_posts'] ) ) ? absint( $instance['majpro_number_posts'] ) : absint( 5 );
		// Title Length.
		$majpro_title_length = ( ! empty( $instance['majpro_title_length'] ) ) ? absint( $instance['majpro_title_length'] ) : absint( 80 );
		// Hide current post.
		$majpro_hide_current_post = ( isset( $instance['majpro_hide_current_post'] ) ) ? (bool) $instance['majpro_hide_current_post'] : false;
		$majpro_show_categories   = ( isset( $instance['majpro_show_categories'] ) ) ? (bool) $instance['majpro_show_categories'] : false;
		$majpro_show_date         = ( isset( $instance['majpro_show_date'] ) ) ? (bool) $instance['majpro_show_date'] : false;
		$majpro_show_thumb        = ( isset( $instance['majpro_show_thumb'] ) ) ? (bool) $instance['majpro_show_thumb'] : false;

		// Style.
		$bgcolor    = ( ! empty( $instance['bgcolor'] ) ) ? wp_strip_all_tags( $instance['bgcolor'] ) : '';
		$color_text = ( ! empty( $instance['color_text'] ) ) ? wp_strip_all_tags( $instance['color_text'] ) : '';
		$color_link = ( ! empty( $instance['color_link'] ) ) ? wp_strip_all_tags( $instance['color_link'] ) : '';
		$color_meta = ( ! empty( $instance['color_meta'] ) ) ? wp_strip_all_tags( $instance['color_meta'] ) : '';

		// standard params.
		$query_args = array(
			'posts_per_page'         => $majpro_number_posts,
			'no_found_rows'          => true,
			'post_status'            => 'publish',
			// make it fast withour update term cache and cache results.
			// https://thomasgriffin.io/optimize-wordpress-queries/.
			'update_post_term_cache' => false,
			'update_post_meta_cache' => false,
		);

		$query_args['ignore_sticky_posts'] = true;

		// set order of posts in widget.
		$query_args['orderby'] = 'date';
		$query_args['order']   = 'DESC';

		// add categories param only if 'all categories' was not selected.
		$cat_id_array = $this->generate_cat_id_from_name( $majpro_category );
		if ( count( $cat_id_array ) > 0 ) {
			$query_args['category__in'] = $cat_id_array;
		}

		// exclude current displayed post.
		if ( $majpro_hide_current_post ) {
			global $post;
			if ( isset( $post->ID ) && is_singular() ) {
				$query_args['post__not_in'] = array( $post->ID );
			}
		}

		// run the query: get the latest posts.
		$rp = new WP_Query( apply_filters( 'majpro_rp_widget_posts_args', $query_args ) );
		if ( $bgcolor ) {
			$color = ' style="border: 1px solid rgba(0,0,0,0.1) !important;padding:15px;background-color:' . esc_html( $bgcolor ) . '"';
		} else {
			$color = '';
		}
		if ( $color_link ) {
			$colorlink = ' style="color:' . esc_html( $color_link ) . '"';
		} else {
			$colorlink = '';
		}
		if ( $color_meta ) {
			$colormeta = ' style="color:' . esc_html( $color_meta ) . '"';
		} else {
			$colormeta = '';
		}
		?>

			<div class="majalahpro-core-rp-widget"<?php echo $color; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
				<div class="majalahpro-core-rp">
					<ul>
						<?php
						while ( $rp->have_posts() ) :
							$rp->the_post();
							echo '<li';
							if ( is_sticky() ) {
								echo ' class="majalahpro-core-rp-sticky"';
							}
							echo '>';
							?>
								<div class="majalahpro-core-rp-link clearfix">
									<a href="<?php the_permalink(); ?>"<?php echo $colorlink; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?> itemprop="url" title="<?php the_title_attribute( array( 'before' => __( 'Permalink to: ', 'majalahpro-core' ), 'after' => '' ) ); ?>">
										<?php
										if ( $majpro_show_thumb ) :
											// look for featured image.
											if ( has_post_thumbnail() ) {
												the_post_thumbnail( 'medium' );

											}
										endif;
										?>

										<span class="majalahpro-core-rp-title">
											<?php
											if ( $post_title = $this->get_the_trimmed_post_title( $majpro_title_length ) ) {
												echo esc_html( $post_title );
											} else {
												the_title();
											}
											if ( has_post_format( 'gallery' ) ) {
												echo ' <span class="icon_image"></span>';
											} elseif ( has_post_format( 'video' ) ) {
												echo ' <span class="arrow_triangle-right_alt2"></span>';
											}
											?>
										</span>
									</a>
									<?php
									if ( $majpro_show_date ) :
										?>
										<div class="majalahpro-core-rp-meta majalahpro-core-rp-date"<?php echo $colormeta; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
											<?php echo get_the_date(); ?>
										</div>
										<?php
									endif;

									if ( $majpro_show_categories ) :
										?>
										<div class="majalahpro-core-rp-meta majalahpro-core-rp-categories"<?php echo $colormeta; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
											<?php echo $this->get_the_categories( $rp->post->ID ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
										</div>
									<?php endif; ?>
								</div>
								<?php
								echo '</li>';
						endwhile;
						wp_reset_postdata();
						?>
					</ul>
				</div>
			</div>

		<?php
		echo $args['after_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	}

	/**
	 * Handles updating settings for the current Mailchimp widget instance.
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @param array $new_instance New settings for this instance as input by the user via
	 *                           Majalahpro_Mailchimp_form::form().
	 * @param array $old_instance Old settings for this instance.
	 * @return array Updated settings to save.
	 */
	public function update( $new_instance, $old_instance ) {
		$instance     = $old_instance;
		$new_instance = wp_parse_args(
			(array) $new_instance,
			array(
				'title'                    => '',
				'majpro_category'          => '',
				'majpro_number_posts'      => 5,
				'majpro_title_length'      => 80,
				'majpro_hide_current_post' => false,
				'majpro_show_categories'   => false,
				'majpro_show_date'         => false,
				'majpro_show_thumb'        => false,
				'bgcolor'                  => '',
				'color_text'               => '',
				'color_link'               => '',
				'color_meta'               => '',
			)
		);
		// Title.
		$instance['title'] = sanitize_text_field( $new_instance['title'] );
		// Category IDs.
		$instance['majpro_category'] = wp_strip_all_tags( $new_instance['majpro_category'] );
		// Number posts.
		$instance['majpro_number_posts'] = absint( $new_instance['majpro_number_posts'] );
		// Title Length.
		$instance['majpro_title_length'] = absint( $new_instance['majpro_title_length'] );
		// Hide current post.
		$instance['majpro_hide_current_post'] = (bool) $new_instance['majpro_hide_current_post'];
		// Show element.
		$instance['majpro_show_categories'] = (bool) $new_instance['majpro_show_categories'];
		$instance['majpro_show_date']       = (bool) $new_instance['majpro_show_date'];
		$instance['majpro_show_thumb']      = (bool) $new_instance['majpro_show_thumb'];
		// Style.
		$instance['bgcolor']    = wp_strip_all_tags( $new_instance['bgcolor'] );
		$instance['color_text'] = wp_strip_all_tags( $new_instance['color_text'] );
		$instance['color_link'] = wp_strip_all_tags( $new_instance['color_link'] );
		$instance['color_meta'] = wp_strip_all_tags( $new_instance['color_meta'] );
		return $instance;
	}

	/**
	 * Outputs the settings form for the Mailchimp widget.
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @param array $instance Current settings.
	 */
	public function form( $instance ) {
		$instance = wp_parse_args(
			(array) $instance,
			array(
				'title'                    => 'Recent Post',
				'majpro_category'          => '',
				'majpro_number_posts'      => 5,
				'majpro_title_length'      => 80,
				'majpro_hide_current_post' => false,
				'majpro_show_categories'   => false,
				'majpro_show_date'         => false,
				'majpro_show_thumb'        => true,
				'bgcolor'                  => '',
				'color_text'               => '',
				'color_link'               => '',
				'color_meta'               => '',
			)
		);
		// Title.
		$title = sanitize_text_field( $instance['title'] );
		// Category ID.
		$majpro_category = wp_strip_all_tags( $instance['majpro_category'] );
		// Number posts.
		$majpro_number_posts = absint( $instance['majpro_number_posts'] );
		// Title Length.
		$majpro_title_length = absint( $instance['majpro_title_length'] );
		// Hide current post.
		$majpro_hide_current_post = (bool) $instance['majpro_hide_current_post'];
		// Show element.
		$majpro_show_categories = (bool) $instance['majpro_show_categories'];
		$majpro_show_date       = (bool) $instance['majpro_show_date'];
		$majpro_show_thumb      = (bool) $instance['majpro_show_thumb'];
		// Style.
		$bgcolor    = wp_strip_all_tags( $instance['bgcolor'] );
		$color_text = wp_strip_all_tags( $instance['color_text'] );
		$color_link = wp_strip_all_tags( $instance['color_link'] );
		$color_meta = wp_strip_all_tags( $instance['color_meta'] );

		?>

		<p>
			<label for="<?php echo esc_html( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Title:', 'majalahpro-core' ); ?></label>
			<input class="widefat" id="<?php echo esc_html( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
		</p>
		<p>
			<label for="<?php echo esc_html( $this->get_field_id( 'majpro_category' ) ); ?>"><?php esc_html_e( 'Selected categories', 'majalahpro' ); ?></label>
			<input class="widefat" id="<?php echo esc_html( $this->get_field_id( 'majpro_category' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'majpro_category' ) ); ?>" type="text" value="<?php echo esc_html( $majpro_category ); ?>" onfocus ="setSuggest_cat_view('<?php echo esc_html( $this->get_field_id( 'majpro_category' ) ); ?>');" />
			<br />
			<small><?php esc_html_e( 'Category Names, separated by commas. Eg: News, Home Design, Technology.', 'majalahpro-core' ); ?></small>
		</p>
		<p>
			<label for="<?php echo esc_html( $this->get_field_id( 'majpro_number_posts' ) ); ?>"><?php esc_html_e( 'Number post', 'majalahpro-core' ); ?></label>
			<input class="widefat" id="<?php echo esc_html( $this->get_field_id( 'majpro_number_posts' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'majpro_number_posts' ) ); ?>" type="number" value="<?php echo esc_attr( $majpro_number_posts ); ?>" />
		</p>
		<p>
			<label for="<?php echo esc_html( $this->get_field_id( 'majpro_title_length' ) ); ?>"><?php esc_html_e( 'Maximum length of title', 'majalahpro-core' ); ?></label>
			<input class="widefat" id="<?php echo esc_html( $this->get_field_id( 'majpro_title_length' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'majpro_title_length' ) ); ?>" type="number" value="<?php echo esc_attr( $majpro_title_length ); ?>" />
		</p>
		<p>
			<input class="checkbox" type="checkbox" <?php checked( $majpro_hide_current_post ); ?> id="<?php echo esc_html( $this->get_field_id( 'majpro_hide_current_post' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'majpro_hide_current_post' ) ); ?>" />
			<label for="<?php echo esc_html( $this->get_field_id( 'majpro_hide_current_post' ) ); ?>"><?php esc_html_e( 'Do not list the current post?', 'majalahpro-core' ); ?></label>
		</p>
		<p>
			<input class="checkbox" type="checkbox" <?php checked( $majpro_show_categories ); ?> id="<?php echo esc_html( $this->get_field_id( 'majpro_show_categories' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'majpro_show_categories' ) ); ?>" />
			<label for="<?php echo esc_html( $this->get_field_id( 'majpro_show_categories' ) ); ?>"><?php esc_html_e( 'Show Categories?', 'majalahpro-core' ); ?></label>
		</p>
		<p>
			<input class="checkbox" type="checkbox" <?php checked( $majpro_show_date ); ?> id="<?php echo esc_html( $this->get_field_id( 'majpro_show_date' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'majpro_show_date' ) ); ?>" />
			<label for="<?php echo esc_html( $this->get_field_id( 'majpro_show_date' ) ); ?>"><?php esc_html_e( 'Show Date?', 'majalahpro-core' ); ?></label>
		</p>
		<p>
			<input class="checkbox" type="checkbox" <?php checked( $majpro_show_thumb ); ?> id="<?php echo esc_html( $this->get_field_id( 'majpro_show_thumb' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'majpro_show_thumb' ) ); ?>" />
			<label for="<?php echo esc_html( $this->get_field_id( 'majpro_show_thumb' ) ); ?>"><?php esc_html_e( 'Show Thumbnail?', 'majalahpro-core' ); ?></label>
		</p>
		<p>
			<label for="<?php echo esc_html( $this->get_field_id( 'bgcolor' ) ); ?>"><?php esc_html_e( 'Background Color', 'majalahpro-core' ); ?></label><br />
			<input class="widefat color-picker" id="<?php echo esc_html( $this->get_field_id( 'bgcolor' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'bgcolor' ) ); ?>" type="text" value="<?php echo esc_attr( $bgcolor ); ?>" data-default-color="" />
		</p>
		<p>
			<label for="<?php echo esc_html( $this->get_field_id( 'color_text' ) ); ?>"><?php esc_html_e( 'Text Color', 'majalahpro-core' ); ?></label><br />
			<input class="widefat color-picker" id="<?php echo esc_html( $this->get_field_id( 'color_text' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'color_text' ) ); ?>" type="text" value="<?php echo esc_attr( $color_text ); ?>" data-default-color="" />
		</p>
		<p>
			<label for="<?php echo esc_html( $this->get_field_id( 'color_link' ) ); ?>"><?php esc_html_e( 'Link Color', 'majalahpro-core' ); ?></label><br />
			<input class="widefat color-picker" id="<?php echo esc_html( $this->get_field_id( 'color_link' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'color_link' ) ); ?>" type="text" value="<?php echo esc_attr( $color_link ); ?>" data-default-color="" />
		</p>
		<p>
			<label for="<?php echo esc_html( $this->get_field_id( 'color_meta' ) ); ?>"><?php esc_html_e( 'Meta Color', 'majalahpro-core' ); ?></label><br />
			<input class="widefat color-picker" id="<?php echo esc_html( $this->get_field_id( 'color_meta' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'color_meta' ) ); ?>" type="text" value="<?php echo esc_attr( $color_meta ); ?>" data-default-color="" />
		</p>
		<?php
	}

	/**
	 * Return the array index of a given ID
	 *
	 * @param Array  $arr Arr.
	 * @param Number $id Post ID.
	 *
	 * @since 1.0.0
	 * @access private
	 */
	private function get_cat_parent_index( $arr, $id ) {
		$len = count( $arr );
		if ( 0 === $len ) {
			return false;
		}
		$id = absint( $id );
		for ( $i = 0; $i < $len; $i++ ) {
			if ( $id === $arr[ $i ]['id'] ) {
				return $i;
			}
		}
		return false;
	}

	/**
	 * Returns the assigned categories of a post in a string
	 *
	 * @param Number $id Post ID.
	 * @access   private
	 * @since     1.0.0
	 */
	private function get_the_categories( $id ) {
		$terms = get_the_terms( $id, 'category' );

		if ( is_wp_error( $terms ) ) {
			return __( 'Error on listing categories', 'majalahpro-core' );
		}

		if ( empty( $terms ) ) {
			$text = __( 'No categories', 'majalahpro-core' );
			return $text;
		}

		$categories = array();

		foreach ( $terms as $term ) {
			$categories[] = $term->name;
		}

		$string  = __( 'In', 'majalahpro-core' ) . ' ';
		$string .= join( ', ', $categories );

		return $string;
	}

	/**
	 * Returns the shortened post title, must use in a loop.
	 *
	 * @param Number $len Number text to show.
	 * @param String $more Text.
	 * @since 1.0.0
	 */
	private function get_the_trimmed_post_title( $len = 80, $more = '&hellip;' ) {

		// get current post's post_title.
		$post_title = get_the_title();

		// if post_title is longer than desired.
		if ( mb_strlen( $post_title ) > $len ) {
			// get post_title in desired length.
			$post_title = mb_substr( $post_title, 0, $len );
			// append ellipses.
			$post_title .= $more;
		}
		// return text.
		return $post_title;
	}

	/**
	 * Generate Cat id from Cat name
	 *
	 * @param Array $cats Array ID Cat.
	 * @since 1.0.1
	 * @static
	 * @access public
	 *
	 * @return array List of cat ids
	 */
	private function generate_cat_id_from_name( $cats ) {
		global $post;

		$cat_id_array = array();

		if ( ! empty( $cats ) ) {
			$cat_array = explode( ',', $cats );

			foreach ( $cat_array as $cat ) {
				$cat_id_array[] = $this->get_cat_ID( trim( $cat ) );
			}
		}

		return $cat_id_array;
	}

	/**
	 * Get cat id from cat name or slug
	 *
	 * @since 1.0.1
	 * @static
	 * @access public
	 *
	 * @param string $cat_name cat name or slug.
	 * @return int Term id. 0 if not found
	 */
	private function get_Cat_ID( $cat_name ) {
		// Try cat name first.
		$cat = get_term_by( 'name', $cat_name, 'category' );
		if ( $cat ) {
			return $cat->term_id;
		} else {
			// if cat name is not found, try cat slug.
			$cat = get_term_by( 'slug', $cat_name, 'category' );
			if ( $cat ) {
				return $cat->term_id;
			}
			return 0;
		}
	}

}

add_action(
	'widgets_init',
	function() {
		register_widget( 'Majalahpro_RecentPosts_Wgt' );
	}
);
