<?php
/**
 * Widget Name: Post Author
 * Description: Displays the post author's avatar, name, and bio.
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes
 *
 * @since      1.1.0
 */

use Elementor\Widget_Base;
use Elementor\Controls_Manager;

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

/**
 * Class Captwiki_Grid_Listing
 *
 * @since 1.1.0
 */
class Captwiki_Grid_Listing extends Widget_Base {

	/**
	 * Set Attributes.
	 *
	 * @since 1.1.0
	 * @var array
	 */
	public $widget_attr = array();

	/**
	 * Get Widget Name.
	 *
	 * @since 1.1.0
	 */
	public function get_name() {
		return 'captwiki-grid-listing';
	}

	/**
	 * Get Widget Title.
	 *
	 * @since 1.1.0
	 */
	public function get_title() {
		return esc_html__( 'Grid listing', 'captain-widgets-kit' );
	}

	/**
	 * Get Widget Icon.
	 *
	 * @since 1.1.0
	 */
	public function get_icon() {
		return 'eicon-person captwiki-el-logo';
	}

	/**
	 * Get Widget Categories.
	 *
	 * @since 1.1.0
	 */
	public function get_categories() {
		return array( 'captwiki-essential' );
	}

	/**
	 * Get Widget Keywords.
	 *
	 * @since 1.1.0
	 */
	public function get_keywords() {
		return array( 'post', 'author' );
	}

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

	/**
	 * Update is_reload_preview_required.
	 *
	 * @since 1.1.0
	 */
	public function is_reload_preview_required() {
		return true;
	}

	/**
	 * Register controls.
	 *
	 * @since 1.1.0
	 */
	protected function register_controls() {

		$this->start_controls_section(
			'layout_section',
			array(
				'label' => esc_html__( 'Layout', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);
		$this->add_control(
			'post_type',
			array(
				'label'   => esc_html__( 'Post Type', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'post',
				'options' => $this->captwiki_get_post_type(),
			)
		);
		$this->end_controls_section();

		$this->start_controls_section(
			'section_content',
			array(
				'label' => esc_html__( 'Content', 'captain-widgets-kit' ),
			)
		);
		$this->add_control(
			'display_number',
			array(
				'label'   => esc_html__( 'Maximum Posts Display', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::NUMBER,
				'min'     => 1,
				'max'     => 200,
				'step'    => 1,
				'default' => 8,
			)
		);
		$this->add_control(
			'offset',
			array(
				'label'   => esc_html__( 'Offset', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::NUMBER,
				'min'     => 0,
				'max'     => 200,
				'step'    => 1,
				'default' => 0,
			)
		);
		$this->add_control(
			'orderby',
			array(
				'label'   => esc_html__( 'Order By', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'date',
				'options' => $this->captwiki_orderby_arr(),
			)
		);
		$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->end_controls_section();

		$this->start_controls_section(
			'columns_section',
			array(
				'label' => esc_html__( 'Columns Manage', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);
		$this->add_control(
			'column_desktop',
			array(
				'label'   => esc_html__( 'Desktop Column', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => '3',
				'options' => $this->captwiki_get_columns_list(),
			)
		);
		$this->add_control(
			'column_tablet',
			array(
				'label'   => esc_html__( 'Tablet Column', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => '4',
				'options' => $this->captwiki_get_columns_list(),
			)
		);
		$this->add_control(
			'column_mobile',
			array(
				'label'   => esc_html__( 'Mobile Column', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => '6',
				'options' => $this->captwiki_get_columns_list(),
			)
		);
		$this->add_responsive_control(
			'columns_gap',
			array(
				'label'      => esc_html__( 'Columns Gap/Space Between', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%', 'em' ),
				'default'    => array(
					'top'    => '15',
					'right'  => '15',
					'bottom' => '15',
					'left'   => '15',
				),
				'separator'  => 'before',
				'condition'  => array(
					'layout!' => array( 'carousel' ),
				),
				'selectors'  => array(
					'{{WRAPPER}} .blog-list .post-inner-loop .grid-item' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);
		$this->end_controls_section();

		$this->start_controls_section(
			'extra_option_section',
			array(
				'label' => esc_html__( 'Extra Option', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);
		$this->add_control(
			'connection_id',
			array(
				'label'       => esc_html__( 'Connection ID', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => '',
				'placeholder' => esc_html__( 'Type your uniq ID here', 'captain-widgets-kit' ),
				'ai'          => array(
					'active' => false,
				),
			)
		);
		$this->end_controls_section();

		// ── Text Limit Section ──────────────────────────────────────────────
		$this->start_controls_section(
			'text_limit_section',
			array(
				'label' => esc_html__( 'Text Limit', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);
		$this->add_control(
			'text_limit',
			array(
				'label'        => esc_html__( 'Text Limit', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Show', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'Hide', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => '',
			)
		);
		$this->add_control(
			'limit_on',
			array(
				'label'     => esc_html__( 'Limit On', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::SELECT,
				'default'   => 'character',
				'options'   => array(
					'character' => esc_html__( 'Character', 'captain-widgets-kit' ),
					'word'      => esc_html__( 'Word', 'captain-widgets-kit' ),
				),
				'condition' => array(
					'text_limit' => 'yes',
				),
			)
		);
		$this->add_control(
			'more_text',
			array(
				'label'       => esc_html__( 'More Text', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Show More', 'captain-widgets-kit' ),
				'ai'          => array( 'active' => false ),
				'condition'   => array(
					'text_limit' => 'yes',
				),
			)
		);
		$this->add_control(
			'less_text',
			array(
				'label'       => esc_html__( 'Less Text', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Show Less', 'captain-widgets-kit' ),
				'ai'          => array( 'active' => false ),
				'condition'   => array(
					'text_limit' => 'yes',
				),
			)
		);
		$this->add_control(
			'limit_count',
			array(
				'label'     => esc_html__( 'Limit Count', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::NUMBER,
				'min'       => 1,
				'max'       => 1000,
				'step'      => 1,
				'default'   => 100,
				'condition' => array(
					'text_limit' => 'yes',
				),
			)
		);
		$this->end_controls_section();
	}

	/**
	 * Render Widget Output.
	 *
	 * @since 1.1.0
	 */
	protected function render() {
		$settings = $this->get_settings_for_display();
		$query    = $this->captwiki_query_args();

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

		$column_desktop = ! empty( $settings['column_desktop'] ) ? $settings['column_desktop'] : 3;
		$column_tablet  = ! empty( $settings['column_tablet'] ) ? $settings['column_tablet'] : 4;
		$column_mobile  = ! empty( $settings['column_mobile'] ) ? $settings['column_mobile'] : 6;

		$connection_id = ! empty( $settings['connection_id'] ) ? $settings['connection_id'] : '';

		$this->widget_attr['ajax_url'] = admin_url( 'admin-ajax.php' );
		$this->widget_attr['nonce']    = wp_create_nonce( 'captwiki_widegt_nonce' );

		if ( ! empty( $connection_id ) ) {
			$this->widget_attr['connection_id'] = $connection_id;
		}

		$this->widget_attr['column_desktop'] = $column_desktop;
		$this->widget_attr['column_tablet']  = $column_tablet;
		$this->widget_attr['column_mobile']  = $column_mobile;

		// Text Limit settings — passed to JS via data-widget-settings
		$text_limit  = ! empty( $settings['text_limit'] ) ? $settings['text_limit'] : '';
		$limit_on    = ! empty( $settings['limit_on'] ) ? $settings['limit_on'] : 'character';
		$more_text   = ! empty( $settings['more_text'] ) ? $settings['more_text'] : esc_html__( 'Show More', 'captain-widgets-kit' );
		$less_text   = ! empty( $settings['less_text'] ) ? $settings['less_text'] : esc_html__( 'Show Less', 'captain-widgets-kit' );
		$limit_count = ! empty( $settings['limit_count'] ) ? intval( $settings['limit_count'] ) : 100;

		$this->widget_attr['text_limit']  = ( 'yes' === $text_limit );
		$this->widget_attr['limit_on']    = $limit_on;
		$this->widget_attr['more_text']   = $more_text;
		$this->widget_attr['less_text']   = $less_text;
		$this->widget_attr['limit_count'] = $limit_count;

		// Tell the Search Filter AJAX handler which widget + style template to use.
		$this->widget_attr['widget_type']  = 'grid-listing';
		$this->widget_attr['widget_style'] = 'style-1';

		$widget_settings = 'data-widget-settings="' . htmlspecialchars( wp_json_encode( $this->widget_attr, true ), ENT_QUOTES, 'UTF-8' ) . '"';

		$desktop_class = 'dp-col-lg-' . esc_attr( $column_desktop );
		$tablet_class  = 'dp-col-md-' . esc_attr( $column_tablet );
		$mobile_class  = 'dp-col-sm-' . esc_attr( $column_mobile );
		$mobile_class .= ' dp-col-' . esc_attr( $column_mobile );

		echo '<div id="' . esc_attr( $connection_id ) . '" class="captwiki-grid-listing" ' . $widget_settings . '>';
			echo '<div class="dp-row">';

		while ( $query->have_posts() ) {

			$query->the_post();

			$title   = get_the_title();
			$excerpt = get_the_excerpt();

			$post_image = wp_get_attachment_url( get_post_thumbnail_id( get_the_ID() ) );

			include CAPTWIKI_PATH . 'includes/elementor/widget-style/grid-listing/style-1.php';

		}

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

	/**
	 * Query.
	 *
	 * @since 1.1.0
	 */
	public function captwiki_query_args() {
		$settings = $this->get_settings_for_display();

		$display_number = ! empty( $settings['display_number'] ) ? $settings['display_number'] : 8;
		$orderby        = ! empty( $settings['orderby'] ) ? $settings['orderby'] : 'date';
		$order          = ! empty( $settings['order'] ) ? $settings['order'] : 'DESC';
		$post_type      = ! empty( $settings['post_type'] ) ? $settings['post_type'] : 'post';
		$offset         = ! empty( $settings['offset'] ) ? $settings['offset'] : 0;

		$this->widget_attr['display_number'] = intval( $display_number );
		$this->widget_attr['orderby']        = $orderby;
		$this->widget_attr['order']          = $order;
		$this->widget_attr['post_type']      = $post_type;
		$this->widget_attr['offset']         = intval( $offset );

		$query_args = array(
			'post_type'           => $post_type,
			'post_status'         => 'publish',
			'ignore_sticky_posts' => true,
			'posts_per_page'      => intval( $display_number ),
			'orderby'             => $orderby,
			'order'               => $order,
			'offset'              => intval( $offset ),
		);

		return new \WP_Query( $query_args );
	}

	/**
	 * Render Widget Output.
	 *
	 * @since 1.1.0
	 */
	public function captwiki_get_columns_list() {
		return array(
			'2'  => esc_html__( 'Column 6', 'captain-widgets-kit' ),
			'3'  => esc_html__( 'Column 4', 'captain-widgets-kit' ),
			'4'  => esc_html__( 'Column 3', 'captain-widgets-kit' ),
			'5'  => esc_html__( 'Column 5', 'captain-widgets-kit' ),
			'6'  => esc_html__( 'Column 2', 'captain-widgets-kit' ),
			'12' => esc_html__( 'Column 1', 'captain-widgets-kit' ),
		);
	}

	/**
	 * Render Widget Output.
	 *
	 * @since 1.1.0
	 */
	public function captwiki_orderby_arr() {
		return array(
			'none'          => esc_html__( 'None', 'captain-widgets-kit' ),
			'ID'            => esc_html__( 'ID', 'captain-widgets-kit' ),
			'author'        => esc_html__( 'Author', 'captain-widgets-kit' ),
			'title'         => esc_html__( 'Title', 'captain-widgets-kit' ),
			'name'          => esc_html__( 'Name (slug)', 'captain-widgets-kit' ),
			'date'          => esc_html__( 'Date', 'captain-widgets-kit' ),
			'modified'      => esc_html__( 'Modified', 'captain-widgets-kit' ),
			'rand'          => esc_html__( 'Random', 'captain-widgets-kit' ),
			'comment_count' => esc_html__( 'Comment Count', 'captain-widgets-kit' ),
			'menu_order'    => esc_html__( 'Default Menu Order', 'captain-widgets-kit' ),
		);
	}

	/**
	 * Custom Post Type.
	 *
	 * @since 1.1.0
	 */
	public function captwiki_get_post_type() {
		$args       = array(
			'public'  => true,
			'show_ui' => true,
		);
		$post_types = get_post_types( $args, 'objects' );

		foreach ( $post_types  as $post_type ) {
			$exclude = array( 'elementor_library', 'attachment' );

			if ( true === in_array( $post_type->name, $exclude, true ) ) {
				continue;
			}

			$options[ $post_type->name ] = $post_type->label;
		}
		return $options;
	}
}
