<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class United_Blog_Posts_Carousel extends United_Blog_Widget_Base {

	public function __construct() {

		$this->widget_cssclass    = 'widget_united_blog_posts_carousel';
		$this->widget_description = __( 'Displays posts in carousel', 'united-blog' );
		$this->widget_id          = 'united_blog_posts_carousel';
		$this->widget_name        = __( 'United Blog: Posts Carousel', 'united-blog' );
		$this->settings           = array(
			'title'                     => array(
				'type'  => 'text',
				'label' => __( 'Title', 'united-blog' ),
			),
			'post_settings_heading'     => array(
				'type'  => 'heading',
				'label' => __( 'Post Settings', 'united-blog' ),
			),
			'category'                  => array(
				'type'  => 'dropdown-taxonomies',
				'label' => __( 'Select Category', 'united-blog' ),
				'desc'  => __( 'Leave empty if you don\'t want the posts to be category specific', 'united-blog' ),
				'args'  => array(
					'taxonomy'        => 'category',
					'class'           => 'widefat',
					'hierarchical'    => true,
					'show_count'      => 1,
					'show_option_all' => __( '&mdash; Select &mdash;', 'united-blog' ),
				),
			),
			'number'                    => array(
				'type'  => 'number',
				'step'  => 1,
				'min'   => 1,
				'max'   => '',
				'std'   => 5,
				'label' => __( 'Number of posts to show', 'united-blog' ),
			),
			'offset'                    => array(
				'type'  => 'number',
				'step'  => 1,
				'min'   => 0,
				'max'   => '',
				'std'   => '',
				'label' => __( 'Offset', 'united-blog' ),
				'desc'  => __( 'Can be useful if you want to skip certain number of posts. Leave as 0 if you do not want to use it.', 'united-blog' ),
			),
			'orderby'                   => array(
				'type'    => 'select',
				'std'     => 'date',
				'label'   => __( 'Order by', 'united-blog' ),
				'options' => array(
					'date'  => __( 'Date', 'united-blog' ),
					'ID'    => __( 'ID', 'united-blog' ),
					'title' => __( 'Title', 'united-blog' ),
					'rand'  => __( 'Random', 'united-blog' ),
				),
			),
			'order'                     => array(
				'type'    => 'select',
				'std'     => 'desc',
				'label'   => __( 'Order', 'united-blog' ),
				'options' => array(
					'asc'  => __( 'ASC', 'united-blog' ),
					'desc' => __( 'DESC', 'united-blog' ),
				),
			),
			'meta_settings_heading'     => array(
				'type'  => 'heading',
				'label' => __( 'Post Meta Settings', 'united-blog' ),
			),
			'post_meta'                 => array(
				'type'    => 'multi-checkbox',
				'label'   => __( 'Post Meta', 'united-blog' ),
				'options' => array(
					'author'    => __( 'Author', 'united-blog' ),
					'date'      => __( 'Date', 'united-blog' ),
					'comment'   => __( 'Comment', 'united-blog' ),
				),
				'std'     => array(),
			),
			'date_format'               => array(
				'type'    => 'select',
				'label'   => __( 'Date Format', 'united-blog' ),
				'desc'    => __( 'Make sure to select Date from above for this to work.', 'united-blog' ),
				'options' => array(
					'format_1' => __( 'Times Ago', 'united-blog' ),
					'format_2' => __( 'Default Format', 'united-blog' ),
				),
				'std'     => 'format_1',
			),
			'author_image'              => array(
				'type'  => 'checkbox',
				'label' => __( 'Show Author Image', 'united-blog' ),
				'desc'  => __( 'Make sure to select Author from above for this to work.', 'united-blog' ),
				'std'   => false,
			),
			'excerpt_settings_heading'  => array(
				'type'  => 'heading',
				'label' => __( 'Excerpt Settings', 'united-blog' ),
			),
			'show_excerpt'              => array(
				'type'  => 'checkbox',
				'label' => __( 'Show Excerpt', 'united-blog' ),
				'std'   => false,
			),
			'excerpt_length'            => array(
				'type'  => 'number',
				'step'  => 1,
				'min'   => 0,
				'max'   => '',
				'std'   => 20,
				'label' => __( 'Excerpt Length', 'united-blog' ),
			),
			'show_read_more'            => array(
				'type'  => 'checkbox',
				'label' => __( 'Show Read More', 'united-blog' ),
				'std'   => false,
			),
			'read_more_text'            => array(
				'type'  => 'text',
				'label' => __( 'Read More Text', 'united-blog' ),
				'desc'  => __( 'Leave Empty if you want to use default text "Continue Reading" ', 'united-blog' ),
			),

			'read_more_icon'            => array(
				'type'    => 'select',
				'label'   => __( 'Read More Icon', 'united-blog' ),
				'options' => united_blog_widget_read_more_icons(),
				'std'     => 'arrow-right',
			),
			'category_settings_heading' => array(
				'type'  => 'heading',
				'label' => __( 'Category Settings', 'united-blog' ),
			),
			'show_category'             => array(
				'type'  => 'checkbox',
				'label' => __( 'Show Category', 'united-blog' ),
				'std'   => true,
			),
			'category_color'            => array(
				'type'    => 'select',
				'label'   => __( 'Categories Display Style', 'united-blog' ),
				'options' => united_blog_get_category_display_styles(),
				'std'     => 'display_as_bg',
			),

			'no_of_category'            => array(
				'type'  => 'number',
				'step'  => 1,
				'min'   => 0,
				'max'   => '',
				'std'   => 1,
				'label' => __( 'Number of Categories to Display', 'united-blog' ),
			),
			'widget_settings_heading'   => array(
				'type'  => 'heading',
				'label' => __( 'Widget Settings', 'united-blog' ),
			),
			'style'                     => array(
				'type'    => 'select',
				'label'   => __( 'Display Style', 'united-blog' ),
				'options' => array(
					'style_1' => __( 'Style 1', 'united-blog' ),
					'style_2' => __( 'Style 2', 'united-blog' ),
				),
				'std'     => 'style_1',
			),
			'title_size' => array(
			    'type' => 'select',
			    'label' => __('Title Size', 'united-blog'),
			    'options' => array(
			        'entry-title-small' => __('Small Size', 'united-blog'),
			        'entry-title-medium' => __('Medium Size', 'united-blog'),
			        'entry-title-big' => __('Big Size', 'united-blog'),
			        'entry-title-large' => __('Large Size', 'united-blog'),
			    ),
			    'std' => 'entry-title-medium',
			),
			'justify_content'           => array(
				'type'  => 'checkbox',
				'label' => __( 'Center Content', 'united-blog' ),
				'std'   => false,
			),
			'margin'                    => array(
				'type'  => 'number',
				'step'  => 1,
				'min'   => 0,
				'max'   => 100,
				'std'   => 24,
				'label' => __( 'Carousel margin', 'united-blog' ),
			),
			'autoplay'                  => array(
				'type'  => 'checkbox',
				'label' => __( 'Autoplay', 'united-blog' ),
				'std'   => false,
			),
			'arrows'                    => array(
				'type'  => 'checkbox',
				'label' => __( 'Enable Arrows', 'united-blog' ),
				'std'   => true,
			),
			'dots'                      => array(
				'type'  => 'checkbox',
				'label' => __( 'Enable Dots', 'united-blog' ),
				'std'   => false,
			),
			'column'                    => array(
				'type'  => 'number',
				'step'  => 1,
				'min'   => 1,
				'max'   => 5,
				'std'   => 3,
				'label' => __( 'Column', 'united-blog' ),
			),
			'enable_post_format_icon'   => array(
				'type'  => 'checkbox',
				'label' => __( 'Display Post Format Icon', 'united-blog' ),
				'std'   => true,
			),
			'title_limit'               => array(
				'type'    => 'select',
				'label'   => __( 'Post Title Limit', 'united-blog' ),
				'options' => united_blog_get_title_line_clamp(),
				'std'     => '',
			),
		);

		parent::__construct();
	}

	/**
	 * Query the posts and return them.
	 *
	 * @param array $args
	 * @param array $instance
	 * @return WP_Query
	 */
	public function united_blog_get_posts( $args, $instance ) {
		$number  = ! empty( $instance['number'] ) ? absint( $instance['number'] ) : $this->settings['number']['std'];
		$orderby = ! empty( $instance['orderby'] ) ? sanitize_title( $instance['orderby'] ) : $this->settings['orderby']['std'];
		$order   = ! empty( $instance['order'] ) ? sanitize_title( $instance['order'] ) : $this->settings['order']['std'];
		$offset  = ! empty( $instance['offset'] ) ? absint( $instance['offset'] ) : $this->settings['offset']['std'];

		$query_args = array(
			'posts_per_page'      => $number,
			'post_status'         => 'publish',
			'no_found_rows'       => true,
			'orderby'             => $orderby,
			'order'               => $order,
			'ignore_sticky_posts' => true,
		);

		if ( $offset ) {
			$query_args['offset'] = $offset;
		}

		if ( ! empty( $instance['category'] ) && $instance['category'] !== '-1' && $instance['category'] !== 0 ) {
			$query_args['tax_query'] = array(
				array(
					'taxonomy' => 'category',
					'field'    => 'term_id',
					'terms'    => absint( $instance['category'] ),
				),
			);
		}

		return new WP_Query( apply_filters( 'united_blog_posts_carousel_query_args', $query_args ) );
	}

	/**
	 * Output widget content.
	 *
	 * @param array $args
	 * @param array $instance
	 */
	public function widget( $args, $instance ) {
		ob_start();

		$posts = $this->united_blog_get_posts( $args, $instance );
		if ( $posts->have_posts() ) {

			// Widget Start
			$this->widget_start( $args, $instance );
			do_action( 'united_blog_before_posts_carousel' );

			$wrapper_class = 'swiper-wrapper consist-' . esc_attr( absint( $instance['column'] ) ) . '-slides';

			$slider_nav = $this->united_blog_get_slider_navigation( $instance );

			$data_slider = $this->united_blog_build_slider_data( $instance );

			?>
			<div class="united-swiper-js as_carousel <?php echo esc_attr( $wrapper_class ); ?>">
				<div class="swiper" data-slider='<?php echo esc_attr( json_encode( $data_slider ) ); ?>'>
					<div class="swiper-wrapper">
						<?php
						while ( $posts->have_posts() ) :
							$posts->the_post();
							$this->unite_blog_render_post( $instance );
						endwhile;
						?>
					</div>
					<?php echo $slider_nav; ?>
				</div>
			</div>
			<?php

			// Widget End
			$this->widget_end( $args, $instance );
			do_action( 'united_blog_after_posts_carousel' );
		}

		wp_reset_postdata();
		ob_end_flush();
	}

	/**
	 * Render individual post in the carousel.
	 *
	 * @param array $instance
	 */
	private function unite_blog_render_post( $instance ) {
        $carousel_post_class = '';
		$show_category = isset( $instance['show_category'] ) ? $instance['show_category'] : $this->settings['show_category']['std'];
		$title_limit   = isset( $instance['title_limit'] ) ? $instance['title_limit'] : $this->settings['title_limit']['std'];
		$title_size   = isset( $instance['title_size'] ) ? $instance['title_size'] : $this->settings['title_size']['std'];
        $show_excerpt = isset($instance['show_excerpt']) ? $instance['show_excerpt'] : $this->settings['show_excerpt']['std'];
        if ($show_excerpt) {
            $excerpt_length = isset($instance['excerpt_length']) ? $instance['excerpt_length'] : $this->settings['excerpt_length']['std'];
        }
        $show_read_more = isset($instance['show_read_more']) ? $instance['show_read_more'] : $this->settings['show_read_more']['std'];
        if ($show_read_more) {
            $read_more_text = isset($instance['read_more_text']) ? $instance['read_more_text'] : '';
            $read_more_icon = isset($instance['read_more_icon']) ? $instance['read_more_icon'] : $this->settings['read_more_icon']['std'];
        }
        $enable_post_format_icon = isset($instance['enable_post_format_icon']) ? $instance['enable_post_format_icon'] : $this->settings['enable_post_format_icon']['std'];

        if ($enable_post_format_icon) {
            $carousel_post_class .= ' has-format-icon';
        }
        ?>
		<div class="swiper-slide">
			<article id="carousel-post-<?php the_ID(); ?>" <?php post_class('united-article united-article-default united-article-carousel' . esc_attr($carousel_post_class)); ?>>

				<?php if ( has_post_thumbnail() ) : ?>
					<div class="entry-image entry-image-medium">
						<a class="post-thumbnail" href="<?php the_permalink(); ?>" aria-hidden="true">
							<?php the_post_thumbnail( 'full', array( 'alt' => esc_attr( get_the_title() ) ) ); ?>
						</a>
					</div>
				<?php endif; ?>

				<div class="entry-details">
					<?php
					if ( $show_category ) {
						united_blog_post_categories( esc_attr( $instance['category_color'] ), absint( $instance['no_of_category'] ) );
					}
					?>
					<header class="entry-header">
						<h3 class="entry-title <?php echo esc_attr( $title_size ); ?> has-line-clamp <?php echo esc_attr( $title_limit ); ?>">
							<a href="<?php the_permalink(); ?>" rel="bookmark">
								<?php echo esc_html( get_the_title() ); ?>
							</a>
						</h3>
					</header>

					<?php united_blog_post_meta_info( $instance['post_meta'], $instance ); ?>


                    <?php
                    if ($show_excerpt && $excerpt_length > 0) {
                        ?>
                        <div class="article-excerpt hide-on-mobile">
                            <?php echo wp_trim_words(get_the_excerpt(), $excerpt_length, '&hellip;'); ?>
                        </div>
                    <?php } ?>
                    <?php
                    if ($show_read_more) {
                        ?>
                        <div class="united-read-more">
                            <a href="<?php the_permalink(); ?>" class="united-button united-button-transparent">
                                <?php
                                if ($read_more_text) {
                                    echo esc_html($read_more_text);
                                } else {
                                    esc_html_e('Continue Reading', 'united-blog');
                                }
                                if ($read_more_icon) {
                                    ?>
                                    <span><?php united_blog_the_theme_svg($read_more_icon); ?></span>
                                    <?php
                                }
                                ?>
                            </a>
                        </div>
                        <?php
                    }
                    ?>

				</div>
			</article>
		</div>
		<?php
	}

	/**
	 * Build the slider data array.
	 *
	 * @param array $instance
	 * @return array
	 */
	private function united_blog_build_slider_data( $instance ) {
		$data_slider = array();
		$data_slider['spaceBetween'] = isset( $instance['margin'] ) ? absint( $instance['margin'] ) : $this->settings['margin']['std'];
		$column = isset( $instance['column'] ) ? absint( $instance['column'] ) : $this->settings['column']['std'];

		if ( isset( $instance['autoplay'] ) && $instance['autoplay'] ) {
			$data_slider['autoplay'] = array( 'delay' => 5000 );
		}

		// Handle responsive breakpoints
		if ( $column == 2 ) {
			$data_slider['breakpoints'] = array( '576' => array( 'slidesPerView' => 2 ) );
		} elseif ( $column == 3 ) {
			$data_slider['breakpoints'] = array( '576' => array( 'slidesPerView' => 2 ), '1025' => array( 'slidesPerView' => 3 ) );
		}
		// Add other breakpoints here as needed

		return $data_slider;
	}

	/**
	 * Get the slider navigation HTML.
	 *
	 * @param array $instance
	 * @return string
	 */
	private function united_blog_get_slider_navigation( $instance ) {
		$slider_nav = '';
		if ( isset( $instance['dots'] ) && $instance['dots'] ) {
			$slider_nav .= '<div class="swiper-pagination"></div>';
		}
		if ( isset( $instance['arrows'] ) && $instance['arrows'] ) {
			$slider_nav .= '<div class="swiper-button-next"></div><div class="swiper-button-prev"></div>';
		}
		return $slider_nav;
	}
}
