<?php
/**
 * Widget Name: Blog Card
 * Description: A responsive grid of post cards with featured image, category
 *              badge, title, excerpt, author / date meta and a read-more
 *              link. The query supports category filtering, ordering and
 *              offset. Ships with selectable visual styles — classic card,
 *              image overlay, horizontal split, minimal borderless and
 *              editorial. 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;
use Elementor\Group_Control_Box_Shadow;

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

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

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

	/**
	 * Get widget icon.
	 *
	 * @since 1.7.0
	 * @return string
	 */
	public function get_icon(): string {
		return 'eicon-posts-grid 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', 'card', 'posts', 'grid', 'recent posts', 'captain-widgets-kit' );
	}

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

	/**
	 * 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 Card', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Image Overlay', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Horizontal Split', 'captain-widgets-kit' ),
			'style-4' => esc_html__( 'Style 4 – Minimal Borderless', 'captain-widgets-kit' ),
			'style-5' => esc_html__( 'Style 5 – Editorial', '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_layout_controls();
		$this->register_query_controls();
		$this->register_display_controls();

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

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

		$this->start_controls_section(
			'section_layout',
			array(
				'label' => esc_html__( 'Layout', '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_responsive_control(
			'columns',
			array(
				'label'           => esc_html__( 'Columns', 'captain-widgets-kit' ),
				'type'            => Controls_Manager::SELECT,
				'default'         => '3',
				'tablet_default'  => '2',
				'mobile_default'  => '1',
				'options'         => array(
					'1' => '1',
					'2' => '2',
					'3' => '3',
					'4' => '4',
				),
				'selectors'       => array(
					'{{WRAPPER}} .captwiki-blog-card' => '--captwiki-bc-cols: {{VALUE}};',
				),
			)
		);

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

		$this->end_controls_section();
	}

	/**
	 * 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(
			'posts_per_page',
			array(
				'label'   => esc_html__( 'Number of Posts', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::NUMBER,
				'min'     => 1,
				'max'     => 50,
				'step'    => 1,
				'default' => 6,
			)
		);

		$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(
			'offset',
			array(
				'label'   => esc_html__( 'Offset', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::NUMBER,
				'min'     => 0,
				'max'     => 50,
				'step'    => 1,
				'default' => 0,
			)
		);

		$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__( 'Featured Image', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'show_category',
			array(
				'label'        => esc_html__( 'Category Badge', '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'       => 80,
				'step'      => 1,
				'default'   => 18,
				'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(
			'read_more_text',
			array(
				'label'   => esc_html__( 'Read More Text', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::TEXT,
				'default' => esc_html__( 'Read More', 'captain-widgets-kit' ),
			)
		);

		$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 — card.
	 *
	 * @since 1.7.0
	 * @return void
	 */
	private function register_card_style_controls(): void {

		$this->start_controls_section(
			'section_card_style',
			array(
				'label' => esc_html__( 'Card', '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-card' => '--captwiki-bc-accent: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'card_bg_color',
			array(
				'label'     => esc_html__( 'Card Background', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-blog-card' => '--captwiki-bc-card-bg: {{VALUE}};',
				),
			)
		);

		$this->add_responsive_control(
			'card_border_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%' ),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-blog-card__item' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}}; overflow: hidden;',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'card_box_shadow',
				'label'    => esc_html__( 'Box Shadow', 'captain-widgets-kit' ),
				'selector' => '{{WRAPPER}} .captwiki-blog-card__item',
			)
		);

		$this->add_responsive_control(
			'image_height',
			array(
				'label'      => esc_html__( 'Image Height', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array(
					'px' => array(
						'min' => 120,
						'max' => 600,
					),
				),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-blog-card' => '--captwiki-bc-img-h: {{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-card__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-card__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-card__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-card__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-card__meta' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_responsive_control(
			'content_padding',
			array(
				'label'      => esc_html__( 'Content Padding', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em' ),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-blog-card__body' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Build the posts query from the widget settings.
	 *
	 * @since 1.7.0
	 * @param array $settings Widget settings.
	 * @return \WP_Query
	 */
	private function captwiki_build_query( array $settings ): \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',
			'offset'              => max( 0, (int) $settings['offset'] ),
		);

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

		return new \WP_Query( $args );
	}

	/**
	 * Render one post card.
	 *
	 * @since 1.7.0
	 * @param array  $settings  Widget settings.
	 * @param string $title_tag Sanitised heading tag.
	 * @return void
	 */
	private function captwiki_render_card( 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-card__item">';

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

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

			echo '</a>';

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

			echo '</div>';
		}

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

		echo '<' . esc_attr( $title_tag ) . ' class="captwiki-blog-card__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-card__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-card__meta">';

			if ( $show_author ) {
				echo '<span class="captwiki-blog-card__author">';
				echo get_avatar( get_the_author_meta( 'ID' ), 24, '', '', array( 'class' => 'captwiki-blog-card__avatar' ) );
				echo '<span>' . esc_html( get_the_author() ) . '</span>';
				echo '</span>';
			}

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

			echo '</div>';
		}

		$read_more = trim( (string) $settings['read_more_text'] );

		if ( '' !== $read_more ) {
			echo '<a class="captwiki-blog-card__more" href="' . esc_url( $permalink ) . '">' . esc_html( $read_more )
				. '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="4" y1="12" x2="20" y2="12"></line><polyline points="14 6 20 12 14 18"></polyline></svg></a>';
		}

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

	/**
	 * 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';

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

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

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

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

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

		wp_reset_postdata();

		echo '</div>';
	}
}
