<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class Vista_Blog_Widget extends \Elementor\Widget_Base {

	public function get_name() { return 'vista-blog'; }
	public function get_title() { return esc_html__( 'مقالات', 'vista' ); }
	public function get_icon() { return 'eicon-post-list'; }
	public function get_categories() { return [ 'vista-widgets' ]; }
	public function is_dynamic_content(): bool { return true; }
	public function get_keywords() { return [ 'blog', 'posts', 'articles', 'وبلاگ', 'مطالب', 'نوشته' ]; }

	protected function register_controls() {

		$this->start_controls_section( 'section_query', [
			'label' => esc_html__( 'کوئری', 'vista' ),
			'tab'   => \Elementor\Controls_Manager::TAB_CONTENT,
		] );

		$this->add_control( 'show_pagination', [
			'label'        => esc_html__( 'نمایش صفحه‌بندی', 'vista' ),
			'type'         => \Elementor\Controls_Manager::SWITCHER,
			'label_on'     => esc_html__( 'بله', 'vista' ),
			'label_off'    => esc_html__( 'خیر', 'vista' ),
			'return_value' => 'yes',
			'default'      => 'no',
		] );

		$this->add_control( 'posts_per_page', [
			'label'       => esc_html__( 'تعداد نمایش', 'vista' ),
			'type'        => \Elementor\Controls_Manager::NUMBER,
			'default'     => 3,
			'min'         => 0,
			'max'         => 999,
			'description' => esc_html__( 'عدد ۰ = نمایش همه موارد', 'vista' ),
			'condition'   => [ 'show_pagination!' => 'yes' ],
		] );

		$this->add_control( 'posts_per_page_paged', [
			'label'       => esc_html__( 'تعداد در هر صفحه', 'vista' ),
			'type'        => \Elementor\Controls_Manager::NUMBER,
			'default'     => 6,
			'min'         => 1,
			'max'         => 99,
			'description' => esc_html__( 'تعداد مطالب نمایش داده شده در هر صفحه', 'vista' ),
			'condition'   => [ 'show_pagination' => 'yes' ],
		] );

		$this->add_control( 'total_posts', [
			'label'       => esc_html__( 'تعداد کل مطالب', 'vista' ),
			'type'        => \Elementor\Controls_Manager::NUMBER,
			'default'     => 0,
			'min'         => 0,
			'max'         => 999,
			'description' => esc_html__( 'عدد ۰ = نمایش همه موارد (بدون محدودیت)', 'vista' ),
			'condition'   => [ 'show_pagination' => 'yes' ],
		] );

		$this->add_control( 'columns', [
			'label'   => esc_html__( 'تعداد ستون‌ها', 'vista' ),
			'type'    => \Elementor\Controls_Manager::SELECT,
			'default' => '3',
			'options' => [
				'1' => esc_html__( '۱ ستون', 'vista' ),
				'2' => esc_html__( '۲ ستون', 'vista' ),
				'3' => esc_html__( '۳ ستون', 'vista' ),
			],
		] );

		$blog_cats = [];
		$cats = get_categories( [ 'hide_empty' => false ] );
		if ( $cats ) {
			foreach ( $cats as $cat ) {
				$blog_cats[ $cat->term_id ] = $cat->name;
			}
		}

		$this->add_control( 'category', [
			'label'    => esc_html__( 'دسته‌بندی', 'vista' ),
			'type'     => \Elementor\Controls_Manager::SELECT2,
			'options'  => $blog_cats,
			'multiple' => true,
			'default'  => [],
		] );

		$this->add_control( 'orderby', [
			'label'   => esc_html__( 'مرتب‌سازی بر اساس', 'vista' ),
			'type'    => \Elementor\Controls_Manager::SELECT,
			'default' => 'date',
			'options' => [
				'date'          => esc_html__( 'تاریخ', 'vista' ),
				'title'         => esc_html__( 'عنوان', 'vista' ),
				'comment_count' => esc_html__( 'تعداد نظرات', 'vista' ),
				'rand'          => esc_html__( 'تصادفی', 'vista' ),
			],
		] );

		$this->add_control( 'order', [
			'label'   => esc_html__( 'ترتیب', 'vista' ),
			'type'    => \Elementor\Controls_Manager::SELECT,
			'default' => 'DESC',
			'options' => [
				'DESC' => esc_html__( 'نزولی', 'vista' ),
				'ASC'  => esc_html__( 'صعودی', 'vista' ),
			],
		] );

		$this->add_control( 'read_more_text', [
			'label'       => esc_html__( 'متن دکمه ادامه', 'vista' ),
			'type'        => \Elementor\Controls_Manager::TEXT,
			'default'     => esc_html__( 'ادامه', 'vista' ),
			'label_block' => false,
		] );

		$this->add_control( 'show_read_time', [
			'label'        => esc_html__( 'نمایش زمان مطالعه', 'vista' ),
			'type'         => \Elementor\Controls_Manager::SWITCHER,
			'label_on'     => esc_html__( 'بله', 'vista' ),
			'label_off'    => esc_html__( 'خیر', 'vista' ),
			'return_value' => 'yes',
			'default'      => 'yes',
		] );

		$this->end_controls_section();
	}

	protected function render() {
		$settings        = $this->get_settings_for_display();
		$show_pagination = 'yes' === $settings['show_pagination'];
		$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
		if ( is_front_page() ) {
			$paged = get_query_var( 'page' ) ? get_query_var( 'page' ) : 1;
		}

		if ( $show_pagination ) {
			$ppp   = intval( $settings['posts_per_page_paged'] );
			if ( $ppp < 1 ) $ppp = 6;
			$total = intval( $settings['total_posts'] ); 
		} else {
			$ppp   = intval( $settings['posts_per_page'] );
			$total = 0;
		}

		$args = [
			'post_type'      => 'post',
			'posts_per_page' => ( ! $show_pagination && $ppp === 0 ) ? -1 : $ppp,
			'orderby'        => $settings['orderby'],
			'order'          => $settings['order'],
			'post_status'    => 'publish',
		];

		if ( $show_pagination ) {
			$args['paged'] = $paged;
			if ( $total > 0 ) {
				$offset = ( $paged - 1 ) * $ppp;
				if ( $offset >= $total ) {
					$args['posts_per_page'] = 0;
				} else {
					$remaining              = $total - $offset;
					$args['posts_per_page'] = min( $ppp, $remaining );
					$args['offset']         = $offset;
				}
			}
		}

		if ( ! empty( $settings['category'] ) ) {
			$args['cat'] = implode( ',', array_map( 'intval', (array) $settings['category'] ) );
		}

		$query     = new WP_Query( $args );
		$read_more = ! empty( $settings['read_more_text'] ) ? $settings['read_more_text'] : __( 'ادامه', 'vista' );
		$show_time = 'yes' === $settings['show_read_time'];
		$arrow_dir = is_rtl() ? 'left' : 'right';
		$cols      = intval( $settings['columns'] );

		if ( ! $query->have_posts() ) {
			if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
				echo '<p style="text-align:center;padding:40px;color:var(--t2,#666);">' . esc_html__( 'هیچ مطلبی یافت نشد. لطفاً چند پست منتشر کنید.', 'vista' ) . '</p>';
			}
			wp_reset_postdata();
			return;
		}
		?>
		<div class="blog-grid" style="grid-template-columns:repeat(<?php echo esc_attr( $cols ); ?>,1fr)">
			<?php
			$post_count = 0;
			while ( $query->have_posts() ) : $query->the_post();
				$post_count++;
				$delay_class = 'd' . min( $post_count, 4 );
				$categories  = get_the_category();
			?>
			<article id="post-<?php the_ID(); ?>" <?php post_class( 'blog-card rv ' . $delay_class ); ?> aria-label="<?php the_title_attribute(); ?>">

				<div class="blog-card-thumb">
					<?php if ( has_post_thumbnail() ) : ?>
						<a href="<?php the_permalink(); ?>" tabindex="-1" aria-hidden="true">
							<?php the_post_thumbnail( 'vista-blog-card', [
								'loading' => 'lazy',
								'alt'     => the_title_attribute( [ 'echo' => false ] ),
							] ); ?>
						</a>
					<?php else : ?>
						<a href="<?php the_permalink(); ?>" tabindex="-1" aria-hidden="true">
							<i class="fa-solid fa-newspaper" style="font-size:36px;color:var(--t3);" aria-hidden="true"></i>
						</a>
					<?php endif; ?>

					<?php if ( $categories ) : ?>
						<a href="<?php echo esc_url( get_category_link( $categories[0]->term_id ) ); ?>" class="blog-card-cat">
							<?php echo esc_html( $categories[0]->name ); ?>
						</a>
					<?php endif; ?>
				</div>

				<div class="blog-card-body">
					<div class="blog-card-meta">
						<time datetime="<?php echo esc_attr( get_the_date( 'c' ) ); ?>">
							<?php echo esc_html( get_the_date() ); ?>
						</time>
						<span class="blog-card-meta-sep" aria-hidden="true"></span>
						<a href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>">
							<?php the_author(); ?>
						</a>
					</div>

					<h2 class="blog-card-title">
						<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
					</h2>

					<div class="blog-card-excerpt">
						<?php echo esc_html( get_the_excerpt() ); ?>
					</div>

					<div class="blog-card-footer">
						<a href="<?php the_permalink(); ?>" class="blog-card-more">
							<?php echo esc_html( $read_more ); ?>
							<i class="fa-solid fa-arrow-<?php echo esc_attr( $arrow_dir ); ?>" aria-hidden="true"></i>
						</a>

						<?php if ( $show_time && function_exists( 'vista_reading_time' ) ) : ?>
							<div class="blog-card-read-time">
								<?php vista_reading_time( get_the_ID(), true ); ?>
							</div>
						<?php elseif ( $show_time ) : ?>
							<div class="blog-card-read-time">
								<?php
								$words   = str_word_count( strip_tags( get_the_content() ) );
								$minutes = max( 1, ceil( $words / 200 ) );
								printf( esc_html__( '%d دقیقه مطالعه', 'vista' ), $minutes );
								?>
							</div>
						<?php endif; ?>
					</div>
				</div>

			</article>
			<?php endwhile; wp_reset_postdata(); ?>
		</div>

		<?php if ( $show_pagination ) : ?>
		<div class="pagination-wrap">
			<?php
			
			$max_pages = ( $total > 0 )
				? ceil( $total / $ppp )
				: $query->max_num_pages;

			$paginate_args = [
				'total'     => $max_pages,
				'current'   => $paged,
				'type'      => 'list',
				'prev_text' => is_rtl()
					? '<i class="fa-solid fa-chevron-right"></i>'
					: '<i class="fa-solid fa-chevron-left"></i>',
				'next_text' => is_rtl()
					? '<i class="fa-solid fa-chevron-left"></i>'
					: '<i class="fa-solid fa-chevron-right"></i>',
			];
			$pagination = paginate_links( $paginate_args );
			if ( $pagination ) {
				echo wp_kses_post( $pagination );
			}
			?>
		</div>
		<?php endif; ?>
		<?php
	}

	protected function content_template() {
		?>
		<#
		var cols    = settings.columns || '3';
		var isPaged = settings.show_pagination === 'yes';
		var cnt     = isPaged
		              ? ( parseInt( settings.posts_per_page_paged ) || 6 )
		              : ( parseInt( settings.posts_per_page ) || 3 );
		if ( cnt === 0 ) cnt = 3;
		#>
		<div class="blog-grid" style="grid-template-columns:repeat({{ cols }},1fr)">
			<# for(var i=0;i<cnt;i++){ #>
			<article class="blog-card on">
				<div class="blog-card-thumb" style="display:flex;align-items:center;justify-content:center;min-height:180px;background:var(--card2,#f4f7fb)">
					<i class="fa-solid fa-newspaper" style="font-size:36px;color:var(--t3,#7d95b0)"></i>
				</div>
				<div class="blog-card-body">
					<div class="blog-card-meta" style="display:flex;align-items:center;gap:8px;font-size:11px;color:var(--t3)">
						<span>۱ فروردین ۱۴۰۴</span>
					</div>
					<h2 class="blog-card-title" style="font-size:15px"><a href="#">عنوان مطلب {{ i+1 }}</a></h2>
					<div class="blog-card-excerpt" style="font-size:13px;color:var(--t2)">خلاصه مطلب اینجا نمایش داده می‌شود...</div>
					<div class="blog-card-footer">
						<a href="#" class="blog-card-more">{{ settings.read_more_text || 'ادامه' }} <i class="fa-solid fa-arrow-left"></i></a>
					</div>
				</div>
			</article>
			<# } #>
		</div>
		<# if ( settings.show_pagination === 'yes' ) { #>
		<div class="pagination-wrap">
			<ul>
				<li><a href="#" class="page-numbers">«</a></li>
				<li><a href="#" class="page-numbers current">1</a></li>
				<li><a href="#" class="page-numbers">2</a></li>
				<li><a href="#" class="page-numbers">3</a></li>
				<li><a href="#" class="page-numbers">»</a></li>
			</ul>
		</div>
		<# } #>
		<?php
	}
}