<?php
/**
 * Implementation of slider feature.
 *
 * @package Trade_Line
 */

// Check slider status.
add_filter( 'trade_line_filter_slider_status', 'trade_line_check_slider_status' );

// Add slider to the theme.
add_action( 'trade_line_action_before_content', 'trade_line_add_featured_slider', 5 );

// Slider details.
add_filter( 'trade_line_filter_slider_details', 'trade_line_get_slider_details' );


if ( ! function_exists( 'trade_line_get_slider_details' ) ) :
	/**
	 * Slider details.
	 *
	 * @since 1.0.0
	 *
	 * @param array $input Slider details.
	 */
	function trade_line_get_slider_details( $input ) {

		$featured_slider_type   = trade_line_get_option( 'featured_slider_type' );
		$featured_slider_number = trade_line_get_option( 'featured_slider_number' );

		switch ( $featured_slider_type ) {

			case 'demo-slider':
				$slides = array();
				for( $i = 0; $i <= 1 ; $i++ ) {
					$img_arr = array(
						0 => get_template_directory_uri() . '/images/slide'. ( $i + 1 ) . '.jpg',
						1 => 1420,
						2 => 440,
						3 => 0,
					);
					$slides[ $i ]['images']  = $img_arr;
					$slides[ $i ]['title']   = __( 'Slide Title ','trade-line-pro' ) . ( $i + 1 );
					$slides[ $i ]['url']     = esc_url( home_url( '/' ) );
					$slides[ $i ]['excerpt'] = __( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam quis metus scelerisque, faucibus risus eu, luctus est.', 'trade-line-pro' );

				}
				if ( ! empty( $slides ) ) {
					$input = $slides;
				}

			break;

			case 'featured-page':

				$ids = array();

				for ( $i = 1; $i <= $featured_slider_number ; $i++ ) {
					$id = trade_line_get_option( 'featured_slider_page_' . $i );
					if ( ! empty( $id ) ) {
						$ids[] = absint( $id );
					}
				}
				// Bail if no valid pages are selected.
				if ( empty( $ids ) ) {
					return $input;
				}

				$qargs = array(
					'posts_per_page' => esc_attr( $featured_slider_number ),
					'no_found_rows'  => true,
					'orderby'        => 'post__in',
					'post_type'      => 'page',
					'post__in'       => $ids,
					'meta_query'     => array(
						array( 'key' => '_thumbnail_id' ), // Show only posts with featured images.
					),
				);

				// Fetch posts.
				$all_posts = get_posts( $qargs );
				$slides = array();

				if ( ! empty( $all_posts ) ) {

					$cnt = 0;
					foreach ( $all_posts as $key => $post ) {

						if ( has_post_thumbnail( $post->ID ) ) {
							$image_array = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'trade-line-slider' );
							$slides[ $cnt ]['images']  = $image_array;
							$slides[ $cnt ]['title']   = esc_html( $post->post_title );
							$slides[ $cnt ]['url']     = esc_url( get_permalink( $post->ID ) );
							$slides[ $cnt ]['excerpt'] = trade_line_the_excerpt( apply_filters( 'trade_line_filter_slider_caption_length', 30 ), $post );

							$cnt++;
						}
					}
				}
				if ( ! empty( $slides ) ) {
					$input = $slides;
				}

			break;
			case 'featured-post':

				$ids = array();

				for ( $i = 1; $i <= $featured_slider_number ; $i++ ) {
					$id = trade_line_get_option( 'featured_slider_post_' . $i );
					if ( ! empty( $id ) ) {
						$ids[] = absint( $id );
					}
				}
				// Bail if no valid pages are selected.
				if ( empty( $ids ) ) {
					return $input;
				}

				$qargs = array(
					'posts_per_page' => esc_attr( $featured_slider_number ),
					'no_found_rows'  => true,
					'orderby'        => 'post__in',
					'post_type'      => 'post',
					'post__in'       => $ids,
					'meta_query'     => array(
						array( 'key' => '_thumbnail_id' ), // Show only posts with featured images.
					),
				);

				// Fetch posts.
				$all_posts = get_posts( $qargs );
				$slides = array();

				if ( ! empty( $all_posts ) ) {

					$cnt = 0;
					foreach ( $all_posts as $key => $post ) {

						if ( has_post_thumbnail( $post->ID ) ) {
							$image_array = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'trade-line-slider' );
							$slides[ $cnt ]['images']  = $image_array;
							$slides[ $cnt ]['title']   = esc_html( $post->post_title );
							$slides[ $cnt ]['url']     = esc_url( get_permalink( $post->ID ) );
							$slides[ $cnt ]['excerpt'] = trade_line_the_excerpt( apply_filters( 'trade_line_filter_slider_caption_length', 30 ), $post );

							$cnt++;
						}
					}
				}
				if ( ! empty( $slides ) ) {
					$input = $slides;
				}

			break;
			case 'featured-category':

				$featured_slider_category = trade_line_get_option( 'featured_slider_category' );

				$qargs = array(
					'posts_per_page' => esc_attr( $featured_slider_number ),
					'no_found_rows'  => true,
					'post_type'      => 'post',
					'meta_query'     => array(
						array( 'key' => '_thumbnail_id' ), // Show only posts with featured images.
					),
				);
				if ( absint( $featured_slider_category ) > 0  ) {
					$qargs['cat'] = esc_attr( $featured_slider_category );
				}

				// Fetch posts.
				$all_posts = get_posts( $qargs );
				$slides = array();

				if ( ! empty( $all_posts ) ) {

					$cnt = 0;
					foreach ( $all_posts as $key => $post ) {

						if ( has_post_thumbnail( $post->ID ) ) {
							$image_array = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'trade-line-slider' );
							$slides[ $cnt ]['images']  = $image_array;
							$slides[ $cnt ]['title']   = esc_html( $post->post_title );
							$slides[ $cnt ]['url']     = esc_url( get_permalink( $post->ID ) );
							$slides[ $cnt ]['excerpt'] = trade_line_the_excerpt( apply_filters( 'trade_line_filter_slider_caption_length', 30 ), $post );

							$cnt++;
						}
					}
				}
				if ( ! empty( $slides ) ) {
					$input = $slides;
				}

			break;

			case 'featured-tag':

				$featured_slider_tag = trade_line_get_option( 'featured_slider_tag' );

				$qargs = array(
					'posts_per_page' => esc_attr( $featured_slider_number ),
					'no_found_rows'  => true,
					'post_type'      => 'post',
					'meta_query'     => array(
						array( 'key' => '_thumbnail_id' ), // Show only posts with featured images.
					),
				);
				if ( absint( $featured_slider_tag ) > 0  ) {
					$qargs['tag_id'] = esc_attr( $featured_slider_tag );
				}

				// Fetch posts.
				$all_posts = get_posts( $qargs );
				$slides = array();

				if ( ! empty( $all_posts ) ) {

					$cnt = 0;
					foreach ( $all_posts as $key => $post ) {

						if ( has_post_thumbnail( $post->ID ) ) {
							$image_array = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'trade-line-slider' );
							$slides[ $cnt ]['images']  = $image_array;
							$slides[ $cnt ]['title']   = esc_html( $post->post_title );
							$slides[ $cnt ]['url']     = esc_url( get_permalink( $post->ID ) );
							$slides[ $cnt ]['excerpt'] = trade_line_the_excerpt( apply_filters( 'trade_line_filter_slider_caption_length', 30 ), $post );

							$cnt++;
						}
					}
				}
				if ( ! empty( $slides ) ) {
					$input = $slides;
				}

			break;

			case 'featured-image':
				$slides = array();

				for ( $i = 1; $i <= $featured_slider_number; $i++ ) {
					$photo = trade_line_get_option( 'featured_slider_image_photo_' . $i );
					if ( ! empty( $photo  ) ) {
						$item = array();
						$item['images'][0] = esc_url( $photo );

						$title      = trade_line_get_option( 'featured_slider_image_title_' . $i );
						$url        = trade_line_get_option( 'featured_slider_image_url_' . $i );
						$caption    = trade_line_get_option( 'featured_slider_image_caption_' . $i );
						$new_window = trade_line_get_option( 'featured_slider_image_new_window_' . $i );

						$item['title']      = esc_html( $title );
						$item['url']        = esc_url( $url );
						$item['excerpt']    = esc_html( $caption );
						$item['new_window'] = esc_attr( $new_window );

						$slides[] = $item;
					}
				}
				if ( ! empty( $slides ) ) {
					$input = $slides;
				}

			break;

			default:
			break;
		}
		return $input;

	}
endif;

if ( ! function_exists( 'trade_line_add_featured_slider' ) ) :
	/**
	 * Add featured slider.
	 *
	 * @since 1.0.0
	 */
	function trade_line_add_featured_slider() {

		$flag_apply_slider = apply_filters( 'trade_line_filter_slider_status', true );
		if ( true !== $flag_apply_slider ) {
			return false;
		}

		$slider_details = array();
		$slider_details = apply_filters( 'trade_line_filter_slider_details', $slider_details );

		if ( empty( $slider_details ) ) {
			return;
		}

		// Render slider now.
		trade_line_render_featured_slider( $slider_details );

	}
endif;


if ( ! function_exists( 'trade_line_render_featured_slider' ) ) :
	/**
	 * Render featured slider.
	 *
	 * @since 1.0.0
	 *
	 * @param array $slider_details Details of slider content.
	 */
	function trade_line_render_featured_slider( $slider_details = array() ) {

		if ( empty( $slider_details ) ) {
			return;
		}
		$featured_slider_transition_effect      = trade_line_get_option( 'featured_slider_transition_effect' );
		$featured_slider_enable_caption         = trade_line_get_option( 'featured_slider_enable_caption' );
		$featured_slider_enable_arrow           = trade_line_get_option( 'featured_slider_enable_arrow' );
		$featured_slider_enable_pager           = trade_line_get_option( 'featured_slider_enable_pager' );
		$featured_slider_enable_autoplay        = trade_line_get_option( 'featured_slider_enable_autoplay' );
		$featured_slider_transition_duration    = trade_line_get_option( 'featured_slider_transition_duration' );
		$featured_slider_transition_delay       = trade_line_get_option( 'featured_slider_transition_delay' );

		// Cycle data.
		$slide_data = array(
		'fx'             => esc_attr( $featured_slider_transition_effect ),
		'speed'          => esc_attr( $featured_slider_transition_duration ) * 1000,
		'pause-on-hover' => 'true',
		'loader'         => 'true',
		'log'            => 'false',
		'swipe'          => 'true',
		'auto-height'    => 'container',
		);
		if ( $featured_slider_enable_caption ) {
			$slide_data['caption-template'] = '<h3><a href="{{url}}" target="{{target}}">{{title}}</a></h3><p>{{excerpt}}</p>';
		}

		if ( $featured_slider_enable_pager ) {
			$slide_data['pager-template'] = '<span class="pager-box"></span>';
		}
		if ( $featured_slider_enable_autoplay ) {
			$slide_data['timeout'] = esc_attr( $featured_slider_transition_delay ) * 1000;
		} else {
			$slide_data['timeout'] = 0;
		}

		$slide_data['slides'] = 'article';

		$slide_attributes_text = '';
		foreach ( $slide_data as $key => $item ) {

			$slide_attributes_text .= ' ';
			$slide_attributes_text .= ' data-cycle-'.esc_attr( $key );
			$slide_attributes_text .= '="'.esc_attr( $item ).'"';

		}

	?>
    <div id="featured-slider">

        <div class="cycle-slideshow" id="main-slider" <?php echo $slide_attributes_text; ?>>

			<?php if ( $featured_slider_enable_arrow ) :  ?>
            <!-- prev/next links -->
            <div class="cycle-prev"></div>
            <div class="cycle-next"></div>
			<?php endif ?>

			<?php if ( $featured_slider_enable_caption ) :  ?>
            <!-- empty element for caption -->
            <div class="cycle-caption"></div>
			<?php endif ?>

            <?php $cnt = 1; ?>
            <?php foreach ( $slider_details as $key => $slide ) : ?>

				<?php $class_text = ( 1 === $cnt ) ? 'first' : ''; ?>
				<?php
				$target = '_self';
				if ( isset( $slide['new_window'] ) && 1 === $slide['new_window'] && ! empty( $slide['url'] ) ) {
					$target = '_blank';
				}
				$url = 'javascript:void(0);';
				if ( ! empty( $slide['url'] ) ) {
					$url = esc_url( $slide['url'] );
				}

				?>
              <article class="<?php echo esc_attr( $class_text ); ?>" data-cycle-title="<?php echo esc_attr( $slide['title'] ); ?>"  data-cycle-url="<?php echo esc_url( $url ); ?>"  data-cycle-excerpt="<?php echo esc_attr( $slide['excerpt'] ); ?>" data-cycle-target="<?php echo esc_attr( $target ); ?>" >

                <?php if ( ! empty( $slide['url'] ) ) :  ?>
                  <a href="<?php echo esc_url( $slide['url'] ); ?>" target="<?php echo esc_attr( $target ); ?>" >
                <?php endif; ?>

                  <img src="<?php echo esc_url( $slide['images'][0]); ?>" alt="<?php echo esc_attr( $slide['title'] ); ?>"  />
                <?php if ( ! empty( $slide['url'] ) ) :  ?>
                  </a>
                <?php endif ?>

              </article>

				<?php $cnt++; ?>

            <?php endforeach ?>


            <?php if ( $featured_slider_enable_pager ) :  ?>
              <!-- pager -->
              <div class="cycle-pager"></div>
            <?php endif ?>


        </div> <!-- #main-slider -->

    </div><!-- #featured-slider -->

    <?php

	}

endif;

if( ! function_exists( 'trade_line_check_slider_status' ) ):

	/**
	 * Check status of slider.
	 *
	 * @since 1.0.0
	 */
	function trade_line_check_slider_status( $input ){

		global $post, $wp_query;

		// Slider status.
		$featured_slider_status = trade_line_get_option( 'featured_slider_status' );

		// Get Page ID outside Loop.
		$page_id = $wp_query->get_queried_object_id();

		// Front page displays in Reading Settings.
		$page_on_front  = get_option( 'page_on_front' ) ;
		$page_for_posts = get_option( 'page_for_posts' );

		if ( 'entire-site' == $featured_slider_status || ( ( is_front_page() || ( is_home() && $page_for_posts !== $page_id ) ) && 'home-page' === $featured_slider_status ) ){
			$input = true;
		}
		else{
			$input = false;
		}
		return $input;

	}

endif;
