<?php
/**
 * Widget Name: Blog Listing
 * Description: A vertical list of posts — thumbnail, category, title,
 *              excerpt and meta in scannable rows, with optional numbered
 *              pagination. The query supports category filtering, ordering
 *              and offset. Ships with selectable visual styles — classic
 *              rows, boxed cards, minimal dividers, date blocks and a zebra
 *              compact list. Only the selected style CSS file is loaded on
 *              the frontend.
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes
 * @since      1.7.0
 */

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

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;

/**
 * Class Captwiki_Blog_Listing
 *
 * @since 1.7.0
 */
class Captwiki_Blog_Listing extends Widget_Base {

	/**
	 * Get widget name.
	 *
	 * @since 1.7.0
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-blog-listing';
	}

	/**
	 * Get widget title.
	 *
	 * @since 1.7.0
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'Blog Listing', 'captain-widgets-kit' );
	}

	/**
	 * Get widget icon.
	 *
	 * @since 1.7.0
	 * @return string
	 */
	public function get_icon(): string {
		return 'eicon-post-list captwiki-el-logo';
	}

	/**
	 * Get widget categories.
	 *
	 * @since 1.7.0
	 * @return array
	 */
	public function get_categories(): array {
		return array( 'captwiki-essential' );
	}

	/**
	 * Get widget keywords.
	 *
	 * @since 1.7.0
	 * @return array
	 */
	public function get_keywords(): array {
		return array( 'blog', 'listing', 'posts', 'list', 'archive', 'captain-widgets-kit' );
	}

	/**
	 * Common stylesheet dependency.
	 *
	 * @since 1.7.0
	 * @return array
	 */
	public function get_style_depends(): array {
		return array( 'captwiki_blog_listing' );
	}

	/**
	 * Disable Elementor's default inner wrapper.
	 *
	 * @since 1.7.0
	 * @return bool
	 */
	public function has_widget_inner_wrapper(): bool {
		return ! \Elementor\Plugin::$instance->experiments->is_feature_active( 'e_optimized_markup' );
	}

	/**
	 * Selectable visual styles.
	 *
	 * @since 1.7.0
	 * @return array
	 */
	private function captwiki_style_options(): array {
		return array(
			'style-1' => esc_html__( 'Style 1 – Classic Rows', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Boxed Cards', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Minimal Divider', 'captain-widgets-kit' ),
			'style-4' => esc_html__( 'Style 4 – Date Block', 'captain-widgets-kit' ),
			'style-5' => esc_html__( 'Style 5 – Zebra Compact', 'captain-widgets-kit' ),
		);
	}

	/**
	 * Category options for the query filter.
	 *
	 * @since 1.7.0
	 * @return array
	 */
	private function captwiki_category_options(): array {

		$options = array();
		$terms   = get_terms(
			array(
				'taxonomy'   => 'category',
				'hide_empty' => false,
				'number'     => 200,
			)
		);

		if ( is_array( $terms ) ) {
			foreach ( $terms as $term ) {
				$options[ $term->term_id ] = $term->name;
			}
		}

		return $options;
	}

	/**
	 * Register widget controls.
	 *
	 * @since 1.7.0
	 * @return void
	 */
	protected function register_controls(): void {
		$this->register_query_controls();
		$this->register_display_controls();

		$this->register_row_style_controls();
		$this->register_content_style_controls();
	}

	/**
	 * Content tab — query.
	 *
	 * @since 1.7.0
	 * @return void
	 */
	private function register_query_controls(): void {

		$this->start_controls_section(
			'section_query',
			array(
				'label' => esc_html__( 'Query', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'widget_style',
			array(
				'label'   => esc_html__( 'Style', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'style-1',
				'options' => $this->captwiki_style_options(),
			)
		);

		$this->add_control(
			'posts_per_page',
			array(
				'label'   => esc_html__( 'Posts Per Page', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::NUMBER,
				'min'     => 1,
				'max'     => 50,
				'step'    => 1,
				'default' => 5,
			)
		);

		$this->add_control(
			'categories',
			array(
				'label'       => esc_html__( 'Categories', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::SELECT2,
				'multiple'    => true,
				'options'     => $this->captwiki_category_options(),
				'default'     => array(),
				'label_block' => true,
			)
		);

		$this->add_control(
			'orderby',
			array(
				'label'   => esc_html__( 'Order By', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'date',
				'options' => array(
					'date'          => esc_html__( 'Date', 'captain-widgets-kit' ),
					'title'         => esc_html__( 'Title', 'captain-widgets-kit' ),
					'comment_count' => esc_html__( 'Comment Count', 'captain-widgets-kit' ),
					'rand'          => esc_html__( 'Random', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_control(
			'order',
			array(
				'label'   => esc_html__( 'Order', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'DESC',
				'options' => array(
					'DESC' => esc_html__( 'Descending', 'captain-widgets-kit' ),
					'ASC'  => esc_html__( 'Ascending', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_control(
			'show_pagination',
			array(
				'label'        => esc_html__( 'Pagination', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => '',
				'description'  => esc_html__( 'Numbered page links below the list.', 'captain-widgets-kit' ),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Content tab — display toggles.
	 *
	 * @since 1.7.0
	 * @return void
	 */
	private function register_display_controls(): void {

		$this->start_controls_section(
			'section_display',
			array(
				'label' => esc_html__( 'Display', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'show_image',
			array(
				'label'        => esc_html__( 'Thumbnail', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'show_category',
			array(
				'label'        => esc_html__( 'Category', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'show_excerpt',
			array(
				'label'        => esc_html__( 'Excerpt', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'excerpt_length',
			array(
				'label'     => esc_html__( 'Excerpt Length (words)', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::NUMBER,
				'min'       => 5,
				'max'       => 100,
				'step'      => 1,
				'default'   => 24,
				'condition' => array( 'show_excerpt' => 'yes' ),
			)
		);

		$this->add_control(
			'show_author',
			array(
				'label'        => esc_html__( 'Author', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'show_date',
			array(
				'label'        => esc_html__( 'Date', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'title_tag',
			array(
				'label'   => esc_html__( 'Title HTML Tag', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'h3',
				'options' => array(
					'h2'  => 'H2',
					'h3'  => 'H3',
					'h4'  => 'H4',
					'h5'  => 'H5',
					'h6'  => 'H6',
					'div' => 'div',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Style tab — rows.
	 *
	 * @since 1.7.0
	 * @return void
	 */
	private function register_row_style_controls(): void {

		$this->start_controls_section(
			'section_row_style',
			array(
				'label' => esc_html__( 'Rows', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'accent_color',
			array(
				'label'     => esc_html__( 'Accent Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-blog-listing' => '--captwiki-bl-accent: {{VALUE}};',
				),
			)
		);

		$this->add_responsive_control(
			'rows_gap',
			array(
				'label'      => esc_html__( 'Gap Between Rows', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array(
					'px' => array(
						'min' => 0,
						'max' => 80,
					),
				),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-blog-listing' => '--captwiki-bl-gap: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'thumb_width',
			array(
				'label'      => esc_html__( 'Thumbnail Width', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', '%' ),
				'range'      => array(
					'px' => array(
						'min' => 80,
						'max' => 500,
					),
					'%'  => array(
						'min' => 15,
						'max' => 60,
					),
				),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-blog-listing' => '--captwiki-bl-thumb-w: {{SIZE}}{{UNIT}};',
				),
				'condition'  => array( 'show_image' => 'yes' ),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Style tab — content.
	 *
	 * @since 1.7.0
	 * @return void
	 */
	private function register_content_style_controls(): void {

		$this->start_controls_section(
			'section_content_style',
			array(
				'label' => esc_html__( 'Content', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'title_color',
			array(
				'label'     => esc_html__( 'Title Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-blog-listing__title a' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'title_typography',
				'label'    => esc_html__( 'Title Typography', 'captain-widgets-kit' ),
				'selector' => '{{WRAPPER}} .captwiki-blog-listing__title',
			)
		);

		$this->add_control(
			'excerpt_color',
			array(
				'label'     => esc_html__( 'Excerpt Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-blog-listing__excerpt' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'excerpt_typography',
				'label'    => esc_html__( 'Excerpt Typography', 'captain-widgets-kit' ),
				'selector' => '{{WRAPPER}} .captwiki-blog-listing__excerpt',
			)
		);

		$this->add_control(
			'meta_color',
			array(
				'label'     => esc_html__( 'Meta Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-blog-listing__meta' => 'color: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Build the posts query from the widget settings.
	 *
	 * @since 1.7.0
	 * @param array $settings Widget settings.
	 * @param int   $paged    Current page number.
	 * @return \WP_Query
	 */
	private function captwiki_build_query( array $settings, int $paged ): \WP_Query {

		$args = array(
			'post_type'           => 'post',
			'post_status'         => 'publish',
			'ignore_sticky_posts' => true,
			'posts_per_page'      => max( 1, (int) $settings['posts_per_page'] ),
			'orderby'             => in_array( $settings['orderby'], array( 'date', 'title', 'comment_count', 'rand' ), true ) ? $settings['orderby'] : 'date',
			'order'               => 'ASC' === $settings['order'] ? 'ASC' : 'DESC',
			'paged'               => max( 1, $paged ),
		);

		if ( ! empty( $settings['categories'] ) && is_array( $settings['categories'] ) ) {
			$args['category__in'] = array_map( 'absint', $settings['categories'] );
		}

		return new \WP_Query( $args );
	}

	/**
	 * Render one listing row.
	 *
	 * @since 1.7.0
	 * @param array  $settings  Widget settings.
	 * @param string $title_tag Sanitised heading tag.
	 * @return void
	 */
	private function captwiki_render_row( array $settings, string $title_tag ): void {

		$permalink = get_permalink();
		$title     = get_the_title();
		$title     = '' !== $title ? $title : esc_html__( '(no title)', 'captain-widgets-kit' );

		echo '<article class="captwiki-blog-listing__item">';

		// Date block used by the Date Block style; hidden elsewhere.
		echo '<div class="captwiki-blog-listing__date-block" aria-hidden="true">';
		echo '<span class="captwiki-blog-listing__date-day">' . esc_html( get_the_date( 'd' ) ) . '</span>';
		echo '<span class="captwiki-blog-listing__date-month">' . esc_html( get_the_date( 'M' ) ) . '</span>';
		echo '</div>';

		if ( 'yes' === $settings['show_image'] ) {
			echo '<div class="captwiki-blog-listing__media">';
			echo '<a class="captwiki-blog-listing__media-link" href="' . esc_url( $permalink ) . '" tabindex="-1" aria-hidden="true">';

			if ( has_post_thumbnail() ) {
				the_post_thumbnail( 'medium_large', array( 'class' => 'captwiki-blog-listing__img' ) );
			} else {
				echo '<span class="captwiki-blog-listing__img captwiki-blog-listing__img--empty"></span>';
			}

			echo '</a>';
			echo '</div>';
		}

		echo '<div class="captwiki-blog-listing__body">';

		if ( 'yes' === $settings['show_category'] ) {
			$category = get_the_category();
			if ( ! empty( $category[0] ) ) {
				echo '<a class="captwiki-blog-listing__category" href="' . esc_url( get_category_link( $category[0] ) ) . '">' . esc_html( $category[0]->name ) . '</a>';
			}
		}

		echo '<' . esc_attr( $title_tag ) . ' class="captwiki-blog-listing__title">';
		echo '<a href="' . esc_url( $permalink ) . '">' . esc_html( $title ) . '</a>';
		echo '</' . esc_attr( $title_tag ) . '>';

		if ( 'yes' === $settings['show_excerpt'] ) {
			$length  = max( 5, (int) $settings['excerpt_length'] );
			$excerpt = wp_trim_words( get_the_excerpt(), $length, '…' );

			if ( '' !== $excerpt ) {
				echo '<p class="captwiki-blog-listing__excerpt">' . esc_html( $excerpt ) . '</p>';
			}
		}

		$show_author = 'yes' === $settings['show_author'];
		$show_date   = 'yes' === $settings['show_date'];

		if ( $show_author || $show_date ) {
			echo '<div class="captwiki-blog-listing__meta">';

			if ( $show_author ) {
				echo '<span class="captwiki-blog-listing__author">' . esc_html( get_the_author() ) . '</span>';
			}

			if ( $show_date ) {
				echo '<time class="captwiki-blog-listing__date" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( get_the_date() ) . '</time>';
			}

			echo '</div>';
		}

		echo '</div>'; // body.
		echo '</article>';
	}

	/**
	 * Render the numbered pagination.
	 *
	 * @since 1.7.0
	 * @param \WP_Query $query Posts query.
	 * @param int       $paged Current page.
	 * @return void
	 */
	private function captwiki_render_pagination( \WP_Query $query, int $paged ): void {

		$links = paginate_links(
			array(
				'total'     => (int) $query->max_num_pages,
				'current'   => max( 1, $paged ),
				'type'      => 'array',
				'prev_text' => esc_html__( '« Prev', 'captain-widgets-kit' ),
				'next_text' => esc_html__( 'Next »', 'captain-widgets-kit' ),
			)
		);

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

		echo '<nav class="captwiki-blog-listing__pagination" aria-label="' . esc_attr__( 'Posts pagination', 'captain-widgets-kit' ) . '">';

		foreach ( $links as $link ) {
			echo wp_kses_post( $link );
		}

		echo '</nav>';
	}

	/**
	 * Render widget output on the frontend.
	 *
	 * @since 1.7.0
	 * @return void
	 */
	protected function render(): void {
		$settings = $this->get_settings_for_display();

		$allowed_styles = array_keys( $this->captwiki_style_options() );
		$style          = in_array( $settings['widget_style'], $allowed_styles, true ) ? $settings['widget_style'] : 'style-1';
		$title_tag      = in_array( $settings['title_tag'], array( 'h2', 'h3', 'h4', 'h5', 'h6', 'div' ), true ) ? $settings['title_tag'] : 'h3';
		$paged          = max( 1, (int) get_query_var( 'paged' ), (int) get_query_var( 'page' ) );

		// Load only the active style stylesheet, depending on the common one.
		wp_enqueue_style(
			'captwiki-blog-listing-' . $style,
			CAPTWIKI_URL . 'assets/css/widgets/blog-listing/captwiki-blog-listing-' . $style . '.css',
			array( 'captwiki_blog_listing' ),
			CAPTWIKI_VERSION
		);

		$query = $this->captwiki_build_query( $settings, $paged );

		if ( ! $query->have_posts() ) {
			echo '<div class="captwiki-blog-listing__empty">' . esc_html__( 'No posts found.', 'captain-widgets-kit' ) . '</div>';
			return;
		}

		echo '<div class="captwiki-blog-listing captwiki-' . esc_attr( $style ) . '">';

		while ( $query->have_posts() ) {
			$query->the_post();
			$this->captwiki_render_row( $settings, $title_tag );
		}

		wp_reset_postdata();

		if ( 'yes' === $settings['show_pagination'] ) {
			$this->captwiki_render_pagination( $query, $paged );
		}

		echo '</div>';
	}
}
