<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly


class TH90_P_Postsselective extends \Elementor\Widget_Base {

	public function get_script_depends() {
		return [ 'th90-front' ];
	}

	public function get_name() {
		return 'p-postsselective';
	}

	public function get_title() {
		return __( 'Post Selective', 'atlas-core' );
	}

	public function get_icon() {
		return 'eicon-image-box th90-widget-icon';
	}

	public function get_categories() {
		return [ sanitize_key( wp_get_theme()->name ) . '-posts' ];
	}

	public function controls_general() {

		$this->start_controls_section(
			'section_general',
			[
				'label' => __( 'General', 'atlas-core' ),
			]
		);
		$this->add_control(
            'posts',
            [
                'label' => __('Select Post', 'atlas-core'),
                'type' => 'selectajax',
                'options' => th90_get_query_post_list('post'),
                'label_block' => true,
                'multiple'    => false,
                'source_name' => 'post_type',
                'source_type' => 'post',
            ]
        );

		/* Default Post Options */
		$controls = new TH90_Controls();
		$controls->post_default( $this );

		$this->end_controls_section();
	}

	public function style_controls_posts() {

		$this->start_controls_section(
			'_section_style_post',
			[
				'label' => __( 'Post', 'atlas-core' ),
                'tab' => \Elementor\Controls_Manager::TAB_STYLE,
			]
		);
		$controls = new TH90_Controls();
		$controls->post_style_default( $this );

		$this->end_controls_section();
	}

	protected function register_controls() {

		$this->controls_general();

		$this->style_controls_posts();
	}

	/**
	 * Render the widget output on the frontend.
	 *
	 * Written in PHP and used to generate the final HTML.
	 */
	protected function render() {
		global $block_id;
		$block_id++;
		$atts = $this->get_settings_for_display();
		$atts['image_size'] = !$atts['image_size'] ? 'post-thumbnail' : $atts['image_size'];

		/* Module Classes */
		$wrapper_classes = array(
			'th90-block',
			'posts-selective',
		);

		$atts = th90_blog_atts_convert( $atts );

		/* Render HTML */
		if ( $atts['posts'] ) {
		?>
			<div class="<?php echo esc_attr( implode( ' ', array_filter( $wrapper_classes ) ) ); ?>">
				<?php
					$block_query = th90_query( $atts );
					if ( $block_query->have_posts() ) {
						while ( $block_query->have_posts() ) {
							$block_query->the_post();
							get_template_part( 'template-parts/posts/post', $atts['post_style'], array(
								'block'     => $atts,
								'count'     => null,
							) );
						} wp_reset_postdata();
					}
				?>
			</div>
		<?php
		}
	}

	/**
	 * Render the widget output in the editor.
	 *
	 * Written as a Backbone JavaScript template and used to generate the live preview.
	 */
	protected function content_template() {}
}
