<?php

namespace ElementPack\Modules\PostContent\Widgets;

use ElementPack\Base\Module_Base;
use ElementPack\Includes\Builder\Builder_Template_Helper;
use ElementPack\Includes\Builder\Meta;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Core\Kits\Documents\Tabs\Global_Typography;

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

class Post_Content extends Module_Base {

	public function get_name() {
		return 'bdt-post-content';
	}

	public function get_title() {
		return BDTEP . esc_html__( 'Post Content', 'bdthemes-element-pack' );
	}

	public function get_icon() {
		return 'bdt-wi-post-content';
	}

	public function get_categories() {
		return [ 'bdt-template-builder', 'theme-elements-single' ];
	}

	public function get_keywords() {
		return [ 'post', 'content', 'blog', 'page', 'single' ];
	}

	// public function show_in_panel() {
	// 	if ( ! Builder_Template_Helper::isTemplateEditMode() ) {
	// 		return false;
	// 	}

	// 	$template_type = (string) get_post_meta( get_the_ID(), Meta::TEMPLATE_TYPE, true );

	// 	return false !== strpos( $template_type, Builder_Template_Helper::separator() . 'single' );
	// }

	public function has_widget_inner_wrapper(): bool {
		return ! \Elementor\Plugin::$instance->experiments->is_feature_active( 'e_optimized_markup' );
	}

	public function register_controls() {
		$this->start_controls_section(
			'content_section',
			[
				'label' => esc_html__( 'Layout', 'bdthemes-element-pack' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			]
		);
		$this->add_control(
			'content_type',
			[
				'label'   => esc_html__( 'Content Type', 'bdthemes-element-pack' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'full',
				'options' => [
					'excerpt' => esc_html__( 'Excerpt', 'bdthemes-element-pack' ),
					'full'    => esc_html__( 'Full Content', 'bdthemes-element-pack' ),
				],
			]
		);
		$this->add_control(
			'limit',
			[
				'label'     => esc_html__( 'Excerpt Length', 'bdthemes-element-pack' ),
				'type'      => Controls_Manager::SLIDER,
				'default'   => [
					'size' => 55,
				],
				'range'     => [
					'px' => [
						'min'  => 0,
						'max'  => 100,
						'step' => 1,
					],
				],
				'condition' => [
					'content_type' => 'excerpt',
				],
			]
		);
		$this->add_responsive_control(
			'upk_content_alignment',
			[
				'label'     => esc_html__( 'Alignment', 'bdthemes-element-pack' ),
				'type'      => Controls_Manager::CHOOSE,
				'options'   => [
					'left'    => [
						'title' => esc_html__( 'Left', 'bdthemes-element-pack' ),
						'icon'  => 'eicon-text-align-left',
					],
					'center'  => [
						'title' => esc_html__( 'Center', 'bdthemes-element-pack' ),
						'icon'  => 'eicon-text-align-center',
					],
					'right'   => [
						'title' => esc_html__( 'Right', 'bdthemes-element-pack' ),
						'icon'  => 'eicon-text-align-right',
					],
					'justify' => [
						'title' => esc_html__( 'Justify', 'bdthemes-element-pack' ),
						'icon'  => 'eicon-text-align-justify',
					],
				],
				'selectors' => [
					'{{WRAPPER}}' => 'text-align: {{VALUE}};',
				],
			]
		);
		$this->end_controls_section();

		$this->start_controls_section(
			'section_style',
			[
				'label' => esc_html__( 'Content', 'bdthemes-element-pack' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);
		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'typography',
				'selector' => '{{WRAPPER}} .elementor-post__content, {{WRAPPER}} .bdt-post-content',
				'global'   => [
					'default' => Global_Typography::TYPOGRAPHY_TEXT,
				],
			]
		);
		$this->add_responsive_control(
			'content_margin',
			[
				'label'      => esc_html__( 'Margin', 'bdthemes-element-pack' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', '%', 'em' ],
				'selectors'  => [
					'{{WRAPPER}} .elementor-post__content, {{WRAPPER}} .bdt-post-content' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				],
			]
		);
		$this->add_control(
			'text_color',
			[
				'label'     => esc_html__( 'Text Color', 'bdthemes-element-pack' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .elementor-post__content, {{WRAPPER}} .bdt-post-content' => 'color: {{VALUE}};',
				],
			]
		);
		$this->end_controls_section();
	}

	public function render() {
		$settings = $this->get_settings_for_display();
		$this->bdt_set_single_post_preview_data();

		if ( 'excerpt' === $settings['content_type'] ) {
			$this->render_excerpt_content( $settings );
			return;
		}

		$this->render_post_content( false, false );
	}

	/**
	 * @param array<string, mixed> $settings Widget settings.
	 */
	protected function render_excerpt_content( array $settings ) {
		$post = $this->get_theme_builder_queried_post();
		if ( ! $post instanceof \WP_Post ) {
			return;
		}

		$limit   = isset( $settings['limit']['size'] ) ? (int) $settings['limit']['size'] : 55;
		$excerpt = get_the_excerpt( $post );
		if ( '' === trim( (string) $excerpt ) ) {
			$excerpt = get_post_field( 'post_content', $post->ID );
		}

		echo '<div class="bdt-post-content bdt-post-content--excerpt">';
		echo '<p class="bdt-post-content__excerpt">' . esc_html( wp_trim_words( wp_strip_all_tags( (string) $excerpt ), $limit ) ) . '</p>';
		echo '</div>';
	}

	/**
	 * Elementor Pro theme-post-content render (Skin_Content_Base parity).
	 *
	 * @param bool $with_wrapper Wrap in .elementor-post__content.
	 * @param bool $with_css     Inline CSS with content.
	 */
	protected function render_post_content( $with_wrapper = false, $with_css = false ) {
		static $did_posts = [];
		static $level     = 0;

		$post = $this->get_theme_builder_queried_post();
		if ( ! $post instanceof \WP_Post ) {
			echo '<div class="elementor-theme-builder-content-area">' . esc_html__( 'Content area', 'bdthemes-element-pack' ) . '</div>';
			return;
		}

		if ( post_password_required( $post ) ) {
			echo get_the_password_form( $post ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			return;
		}

		if ( isset( $did_posts[ $post->ID ] ) ) {
			return;
		}

		$level++;
		$did_posts[ $post->ID ] = true;

		if ( ! class_exists( '\Elementor\Plugin' ) ) {
			$this->render_classic_post_content( $post );
			unset( $did_posts[ $post->ID ] );
			$level--;
			return;
		}

		$elementor    = \Elementor\Plugin::instance();
		$is_edit_mode = $elementor->editor->is_edit_mode();

		if ( $elementor->preview->is_preview_mode( $post->ID ) ) {
			$content = $elementor->preview->builder_wrapper( '' );
		} else {
			$elementor->editor->set_edit_mode( false );

			$content = $elementor->frontend->get_builder_content( $post->ID, $with_css );
			$elementor->frontend->remove_content_filter();

			if ( '' === trim( (string) $content ) ) {
				setup_postdata( $post );
				$content = apply_filters( 'the_content', get_the_content( null, false, $post ) );
				wp_link_pages(
					[
						'before'      => '<div class="page-links elementor-page-links"><span class="page-links-title elementor-page-links-title">' . esc_html__( 'Pages:', 'bdthemes-element-pack' ) . '</span>',
						'after'       => '</div>',
						'link_before' => '<span>',
						'link_after'  => '</span>',
					]
				);
				$elementor->frontend->add_content_filter();
			} else {
				$elementor->frontend->remove_content_filters();
				$content = apply_filters( 'the_content', $content );
				$elementor->frontend->restore_content_filters();
			}

			$elementor->editor->set_edit_mode( $is_edit_mode );
		}

		if ( $with_wrapper ) {
			echo '<div class="elementor-post__content">' . $content . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		} else {
			echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		}

		$level--;
		if ( 0 === $level ) {
			$did_posts = [];
		}
	}

	/**
	 * @param \WP_Post $post Queried singular post.
	 */
	protected function render_classic_post_content( \WP_Post $post ) {
		setup_postdata( $post );

		$content = get_post_field( 'post_content', $post->ID );
		if ( '' === trim( (string) $content ) ) {
			echo '<div class="elementor-theme-builder-content-area">' . esc_html__( 'Content area', 'bdthemes-element-pack' ) . '</div>';
			wp_reset_postdata();
			return;
		}

		echo apply_filters( 'the_content', $content ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		wp_reset_postdata();
	}
}
