<?php

/*-----------------------------------------------------------------------------------

	Plugin Name: Tours

-----------------------------------------------------------------------------------*/


// Add function to widgets_init that'll load our widget.
add_action( 'widgets_init', 'datebook_tours_widgets' );

// Tours widget.
function datebook_tours_widgets() {
	register_widget( 'DateBook_Tours_widget' );
}

// Widget class.
class DateBook_Tours_widget extends WP_Widget {


/*-----------------------------------------------------------------------------------*/
/*	Widget Setup
/*-----------------------------------------------------------------------------------*/
	
	function __construct() {
	
		/* Widget settings. */
		$widget_ops = array( 'classname' => 'datebook-tours-widget', 'description' => esc_html__( 'Displays tours.', 'datebook' ) );

		parent::__construct( 'datebook_tours_widget', esc_html__( 'DateBook: Tours', 'datebook' ), $widget_ops );

	}


/*-----------------------------------------------------------------------------------*/
/*	Update Widget
/*-----------------------------------------------------------------------------------*/
	
	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;

		/* Strip tags to remove HTML (important for text inputs). */
		$instance['title'] = strip_tags( $new_instance['title'] );
		$instance['tours_count'] = strip_tags($new_instance['tours_count']);
		$instance['sort_by'] = strip_tags($new_instance['sort_by']);
		$instance['enabled_image'] = !empty($new_instance['enabled_image']) ? 1 : 0;
		$instance['enabled_date'] = !empty($new_instance['enabled_date']) ? 1 : 0;

		return $instance;
	}
	

/*-----------------------------------------------------------------------------------*/
/*	Widget Settings
/*-----------------------------------------------------------------------------------*/
	 
	function form( $instance ) {

		/* Set up some default widget settings. */
		$defaults = array(
		'title' => 'Tours',
		);
		$instance = wp_parse_args( (array) $instance, $defaults );
		
		$title = isset( $instance['title'] ) ? $instance['title'] : '';
		$tours_count = (isset($instance['tours_count']) && (int)$instance['tours_count'] > 0) ? (int)$instance['tours_count'] : 5;
		$sort_by = !empty($instance['sort_by']) ? strip_tags($instance['sort_by']) : 'descending';
		$enabled_image = isset($instance['enabled_image']) ? (bool) $instance['enabled_image'] : false;
		$enabled_date = isset($instance['enabled_date']) ? (bool) $instance['enabled_date'] : false;
		?>

		<p>
			<label for="<?php echo esc_attr($this->get_field_id( 'title' )); ?>"><?php esc_html_e('Title:', 'datebook' ) ?></label>
			<input type="text" class="widefat" id="<?php echo esc_attr($this->get_field_id( 'title' )); ?>" name="<?php echo esc_attr($this->get_field_name( 'title' )); ?>" value="<?php echo esc_attr($title); ?>" />
		</p>
		<p>
			<label for="<?php echo esc_attr($this->get_field_id('tours_count')); ?>"><?php esc_html_e('Number of Tours', 'datebook' ); ?></label>
			<input id="<?php echo esc_attr($this->get_field_id('tours_count')); ?>" name="<?php echo esc_attr($this->get_field_name('tours_count')); ?>" type="text" value="<?php echo esc_attr($tours_count); ?>" class="widefat" />
		</p>
		<p>
			<label for="<?php echo esc_attr($this->get_field_id('sort_by')); ?>"><?php esc_html_e('Sort by date', 'datebook' );?></label>
			<?php $answers = array('DESC' => 'Descending','ASC' => 'Ascending','RAND' => 'Random'); ?>
			<select class="widefat" id="<?php echo esc_attr($this->get_field_id('sort_by')); ?>" name="<?php echo esc_attr($this->get_field_name('sort_by')); ?>">
				<?php foreach ($answers as $key => $answer ): ?>
				<option <?php if ($sort_by == $key ) { echo 'selected="selected"'; } ?> value="<?php echo sanitize_key($key); ?>"><?php echo esc_attr($answer); ?></option>
				<?php endforeach; ?>
			</select>
		</p>
		<p>
			<input type="checkbox" id="<?php echo esc_attr($this->get_field_id('enabled_image')); ?>" name="<?php echo esc_attr($this->get_field_name('enabled_image')); ?>" <?php checked($enabled_image); ?> /> <?php esc_html_e("Show Image", 'datebook' );?>
		</p>
		<p>
			<input type="checkbox" id="<?php echo esc_attr($this->get_field_id('enabled_date')); ?>" name="<?php echo esc_attr($this->get_field_name('enabled_date')); ?>" <?php checked($enabled_date); ?> /> <?php esc_html_e("Show Date", 'datebook' );?>
		</p>
		<?php
	}


/*-----------------------------------------------------------------------------------*/
/*	Display Widget
/*-----------------------------------------------------------------------------------*/
	
	function widget( $args, $instance ) {
		extract( $args );

		/* Our variables from the widget settings. */
		$title = apply_filters('widget_title', $instance['title'] );
		$posts_per_page = ((int)$instance['tours_count'] > 0) ? (int)$instance['tours_count'] : 5;
		$enabled_image = isset($instance['enabled_image']) ? (bool)$instance['enabled_image']:0;
		$enabled_date = isset($instance['enabled_date']) ? (bool)$instance['enabled_date']:0;
		
		$in_country_city = '';
		$tour_country = 0;
		$sort_by = '';
		if (!empty($instance['sort_by']) && is_array($instance['sort_by'])) {
			$sort_by =  array_filter($instance['sort_by']);
		} else if (!empty($instance['sort_by'])) {
			$sort_by = $instance['sort_by'];
		}
		
		
		/* Display Widget */
		global $datebook_gender_titles;
		
		if (isset($_POST['tour_country']) && $_POST['tour_country'] != '') {
			$tour_country = (int)$_POST['tour_country'];
			if ($tour_country == '0') {
				unset($tour_country);
			}
			
			$tour_city = (int)$_POST['tour_city'];
			if ($tour_city == '0') {
				unset($tour_city);
			}
		}
		
		if (isset($_POST['tour_country']) && $_POST['tour_country'] != '' || isset($_POST['tour_city']) && $_POST['tour_city'] != '') {
			$in_country_city .= ' ' . esc_html__( 'in', 'datebook' );
		}

		if(isset($tour_city) && $tour_city > 0){

			$term_data = DateBook_Utilities::datebook_get_term_by( 'id', $tour_city );
			$tour_city_name = isset($term_data->city) ? $term_data->city : '';
			$tour_country_name = isset($term_data->country) ? $term_data->country : '';

			$in_country_city .= ' ' . $tour_city_name;
			
			$in_country_city .= ', ';

			$in_country_city .= ' ' . $tour_country_name;

		}


		$main_tours_cat = $meta_country_array = '';
		if ($tour_country) {
			$main_tours_cat = $tour_country;
			if ($tour_city) {
				$main_tours_cat = $tour_city;
			}
			$posts_per_page = '-1';
			
			$meta_country_array = array( 'key' => 'country', 'value' => $main_tours_cat, 'compare' => '=', 'type' => 'NUMERIC' );
		}
		
		$direction_meta_array = array(
			'key' => 'end',
			'value' => mktime(23, 59, 59, date("m"), date("d"), date("Y")),
			'compare' => '>=',
			'type' => 'NUMERIC'
		);

		$args = array(
			'post_type' => DATEBOOK_TOUR_TYPE,
			'post_status' => 'publish',
			'meta_key' => 'start',
			'meta_query' => array(
				$direction_meta_array,
				$meta_country_array
			),
			'order' => $sort_by,
			'orderby' => 'meta_value_num',
			'posts_per_page' => $posts_per_page
		);
		
		$the_query = new WP_Query( $args );
		
		if ( $the_query->have_posts() ) : 
		
			/* Before widget (defined by themes). */
			echo $before_widget;

			?>

			<!-- sidebar -->
			<div class="card-header">
				<h4 class="mb-0 datebook-title-aside"><?php esc_html_e( 'Tours', 'datebook' ); ?> <?php echo esc_attr($in_country_city); ?></h4>
			</div>

			<?php

			$search_default_thumbnail = of_get_option('search_default_thumbnail') ? 1 : 0;

			$show_age = DateBook_Utilities::datebook_show_field('birthdate', 1) ? 1 : 0;

			$show_sexual_orientation = (DateBook_Utilities::datebook_show_field('sexualorientation', 1) && (of_get_option('sexual_orientation_allowed') != '' || of_get_option('sexual_orientation_allowed_other_' . DATEBOOK_WPLANG) != '')) ? 1 : 0;

			$show_gender = (DateBook_Utilities::datebook_show_field('gender', 1) && (of_get_option('gender_allowed') != '' || of_get_option('gender_allowed_other_' . DATEBOOK_WPLANG) != '')) ? 1 : 0;

			$show_location = DateBook_Utilities::datebook_show_field('countrycity', 1) ? 1 : 0;
			
			// Check if Retina enabled in Theme Options
			$enable_retina_images = of_get_option('enable_retina_images') ? 1 : 0;
	
			?>
		
			<ul class="list-group">
			
			<?php

			while ( $the_query->have_posts() ) : $the_query->the_post();
			
				$profile_id = absint(get_the_ID());
				$tourdescription = get_post($profile_id);
				$tourdescription = $tourdescription->post_content;
				$tourdescription = wp_trim_words(strip_tags($tourdescription),55,'');

				$profile_tour_id = get_post_meta($profile_id, 'profile_tour_id', true);
				$profile_data = get_post($profile_tour_id);

				if (isset($profile_data->ID) && $profile_data->ID > 0 && isset($profile_data->post_status) && $profile_data->post_status == 'publish') {

					$profile_title = $profile_data->post_title;

					$gender = get_post_meta($profile_tour_id, 'gender', true);
					$birthday = get_post_meta($profile_tour_id, 'birthday', true);
					$age = !empty($birthday) ? floor((time() - strtotime($birthday))/31556926) : '';

					$city_id = get_post_meta($profile_id, 'city', true);

					if(isset($city_id)){

						$term_data = DateBook_Utilities::datebook_get_term_by( 'id', $city_id );
						$city = isset($term_data->city) ? $term_data->city : '';
						$country = isset($term_data->country) ? $term_data->country : '';

					}

					if ($gender == 1) {
						$gender_icon = 'fa fa-venus';
					} else if ($gender == 2) {
						$gender_icon = 'fa fa-mars';
					} else {
						$gender_icon = 'fa fa-user';
					}

					if ($profile_tour_id != '') {

						$thumbnail_url = DateBook_Utilities::datebook_profile_thumbnail($profile_tour_id, 'image_mini', $gender, true, '', $search_default_thumbnail);

						?>
						 <li class="list-group-item">
						 	<h5 class="datebook-profile-heading datebook-ellipsis small"><a href="<?php echo esc_url(get_permalink($profile_tour_id)); ?>" title="<?php echo esc_attr($profile_title); ?>"><?php echo esc_attr($profile_data->post_title); ?></a><?php if($show_age == 1){ ?>, <span title="<?php echo esc_attr($age); ?> <?php esc_html_e( 'years old', 'datebook' ); ?>"><?php echo esc_attr($age); ?></span><?php } ?>

							<?php if ($show_gender == 1 && $gender > 0 && isset($datebook_gender_titles[$gender]) && strlen($datebook_gender_titles[$gender]) > 0){ ?>

								<span title="<?php echo esc_html__($datebook_gender_titles[$gender], 'datebook'); ?>"><i class="<?php echo esc_attr($gender_icon); ?>"></i></span>

							<?php } ?>

							</h5>

							<p class="datebook-profile-text">
							<?php if ($enabled_image == 1) { ?>
								<a class="thumbnail float-left" href="<?php echo esc_url(get_permalink($profile_tour_id)); ?>" title="<?php echo esc_attr($profile_title); ?>"><img class="rounded-circle" src="<?php echo esc_url( $thumbnail_url['img_full_url'] ); ?>" alt="" <?php if($enable_retina_images == 1) { ?>data-rjs="2"<?php } ?> /></a>
							<?php } ?>

								<?php esc_html_e( 'is going to', 'datebook' ); ?><br />

								<?php 

								if (isset($city)) {
									echo esc_attr($city);
								}
								if (!empty($city) && !empty($country)) {
									echo ', ';
								}
								if (isset($country)) {
									echo esc_attr($country);
								}

								?>

								<br />
					
								<span class="text-grey"><?php echo date("d.m.y", get_post_meta($profile_id,'start', true)); ?> - <?php echo date("d.m.y", get_post_meta($profile_id,'end', true)); ?></span>
							</p>
						</li>
				
					<?php
					}
				}

				unset($profile_tour_id);

			endwhile;

			?>

		</ul>

		<?php

		/* After widget (defined by themes). */
		echo $after_widget;

		endif;

		wp_reset_postdata();

	}
}