<?php

namespace ThimPress\ThimBlocks\Gutenberg\Blocks\PostCarousel;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use ThimPress\ThimBlocks\Gutenberg\Blocks\AbstractBlockType;
use WP_Query;
use Throwable;

class PostCarouselBlockType extends AbstractBlockType {

	public $block_name = 'post-carousel';

	public function get_supports(): array {
		return array(
			'align'   => array( 'wide', 'full' ),
			'spacing' => array(
				'padding' => true,
				'margin'  => true,
			),
		);
	}

	public function render_content_block_template( array $attributes, $content, $block ): string {
		$handle = 'thim-blocks-view-' . $this->block_name;
		wp_enqueue_script( $handle );

		$defaults   = array(
			'postsPerPage'  => 6,
			'categories'    => array(),
			'order'         => 'DESC',
			'orderBy'       => 'date',
			'showExcerpt'   => false,
			'excerptLength' => 20,
			'showCategory'  => true,
			'showAuthor'    => true,
			'showDate'      => true,
		);
		$attributes = wp_parse_args( $attributes, $defaults );

		$show_category   = $attributes['showCategory'];
		$show_author     = $attributes['showAuthor'];
		$show_date       = $attributes['showDate'];
		$show_nav        = $attributes['showNav'] ?? true;
		$show_Excerpt    = $attributes['showExcerpt'] ?? false;
		$show_pagination = $attributes['showPagination'] ?? true;

		$query_args = array(
			'post_type'           => 'post',
			'posts_per_page'      => $attributes['postsPerPage'],
			'order'               => $attributes['order'],
			'orderby'             => $attributes['orderBy'],
			'ignore_sticky_posts' => true,
		);

		$spaceBetween = ! empty( $attributes['spaceBetween'] ) && is_array( $attributes['spaceBetween'] )
			? $attributes['spaceBetween']
			: array(
				'desktop' => 30,
				'tablet'  => 30,
				'mobile'  => 20,
			);
		$slidesToShow = ! empty( $attributes['slidesToShow'] ) && is_array( $attributes['slidesToShow'] )
			? $attributes['slidesToShow']
			: array(
				'desktop' => 3,
				'tablet'  => 2,
				'mobile'  => 1,
			);

		$swiper_attr = array(
			'slidesToShow' => array(
				'desktop' => (int) ( $slidesToShow['desktop'] ?? 3 ),
				'tablet'  => (int) ( $slidesToShow['tablet'] ?? 2 ),
				'mobile'  => (int) ( $slidesToShow['mobile'] ?? 1 ),
			),
			'spaceBetween' => array(
				'desktop' => (int) ( $spaceBetween['desktop'] ?? 30 ),
				'tablet'  => (int) ( $spaceBetween['tablet'] ?? 30 ),
				'mobile'  => (int) ( $spaceBetween['mobile'] ?? 20 ),
			),
		);

		$swiper_attr = htmlspecialchars( wp_json_encode( $swiper_attr ) );

		if ( ! empty( $attributes['categories'] ) ) {
			$query_args['category__in'] = $attributes['categories'];
		}

		$q = new WP_Query( $query_args );

		if ( ! $q->have_posts() ) {
			return '<p>' . esc_html__( 'No posts found.', 'thim-blocks' ) . '</p>';
		}

		ob_start();
		?>
		<div <?php echo wp_kses_post( get_block_wrapper_attributes( array( 'class' => 'thim-blocks-post-carousel' ) ) ); ?>  data-swiper="<?php echo esc_attr( $swiper_attr ); ?>">
			<div class="swiper">
				<div class="swiper-wrapper">
					<?php
					while ( $q->have_posts() ) :
						$q->the_post();

						$title  = get_the_title();
						$img    = get_the_post_thumbnail_url( null, 'large' );
						$date   = get_the_date();
						$author = get_the_author();

						$categories      = get_the_category();
						$category_output = '';

						if ( ! empty( $categories ) && ! is_wp_error( $categories ) ) {
							$links = array_map(
								function ( $cat ) {
									$url  = esc_url( get_category_link( $cat->term_id ) );
									$name = esc_html( $cat->name );
									return "<a href=\"{$url}\">{$name}</a>";
								},
								$categories
							);

							$category_output = implode( ', ', $links );
						}
						?>
						<div class="swiper-slide">
							<div class="thim-blocks-post-carousel__item">
								<div class="thim-blocks-post-carousel__image">
									<?php if ( $img ) : ?>
									<a href="<?php the_permalink(); ?>">
										<img src="<?php echo esc_url( $img ); ?>" alt="<?php echo esc_attr( $title ); ?>">
									</a>
									<?php endif; ?>
								</div>
								<div class="thim-blocks-post-carousel__content">       
									<?php if ( $show_category && $category_output ) : ?>
										<div class="category"><?php echo wp_kses_post( $category_output ); ?></div>
									<?php endif; ?>

									<h5><a href="<?php the_permalink(); ?>"><?php echo esc_html( $title ); ?></a></h5>


									<?php if ( $show_author || $show_date ) : ?>
										<div class="meta">
											<?php if ( $show_author ) : ?>
												<span class="author"><span class="label"><?php esc_html_e( 'by', 'thim-blocks' ); ?></span><?php echo esc_html( $author ); ?></span>
											<?php endif; ?>
											<?php if ( $show_date ) : ?>
												<span class="date"><?php echo esc_html( $date ); ?></span>
											<?php endif; ?>
										</div>
									<?php endif; ?>

									<?php if ( $show_Excerpt ) : ?>
										<p><?php echo esc_html( wp_trim_words( get_the_excerpt(), $attributes['excerptLength'] ) ); ?></p>
									<?php endif; ?>
								</div>
							</div>
						</div>
						<?php
					endwhile;
					wp_reset_postdata();
					?>
				</div>

				<?php if ( $show_pagination ) : ?>
					<div class="swiper-pagination"></div>
				<?php endif; ?>

				<?php if ( $show_nav ) : ?>
					<div class="swiper-button-prev"></div>
					<div class="swiper-button-next"></div>
				<?php endif; ?>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}

}
