<?php
/**
 * Page Content — embed a WordPress page (or post) body inside the builder.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

use AuraBuilder\Document\Node;
use AuraBuilder\Renderer\DocumentRenderer;
use AuraBuilder\Storage\DocumentRepository;
use AuraBuilder\Widgets\WidgetBase;

final class PageContentWidget extends WidgetBase {

	public function get_type(): string {
		return 'page_content';
	}

	public function get_title(): string {
		return 'Conteúdo de página';
	}

	public function get_category(): string {
		return 'dynamic';
	}

	public function get_icon(): string {
		return 'page';
	}

	public function get_defaults(): array {
		return array(
			'page_id'    => '',
			'source_type'=> 'page', // page | post
			'show_title' => '0',
		);
	}

	public function sanitize_settings( array $settings ): array {
		$type = sanitize_key( (string) ( $settings['source_type'] ?? 'page' ) );
		if ( ! in_array( $type, array( 'page', 'post' ), true ) ) {
			$type = 'page';
		}
		$flag = static function ( $v, string $d = '0' ): string {
			if ( $v === null || $v === '' ) {
				return $d;
			}
			return ( $v === true || $v === 1 || $v === '1' || $v === 'true' || $v === 'yes' ) ? '1' : '0';
		};
		return array(
			'page_id'     => (string) max( 0, (int) ( $settings['page_id'] ?? 0 ) ),
			'source_type' => $type,
			'show_title'  => $flag( $settings['show_title'] ?? null, '0' ),
		);
	}

	public function render( Node $node, array $context = array() ): string {
		$s   = $node->settings;
		$id  = (int) ( $s['page_id'] ?? 0 );
		$editor = ! empty( $context['editor'] );

		if ( $id <= 0 ) {
			return $editor
				? '<div class="ab-page-content ab-empty">Conteúdo de página — escolha uma página no painel</div>'
				: '';
		}

		// Avoid infinite recursion if embedding the current Aura page into itself.
		$current = isset( $context['postId'] ) ? (int) $context['postId'] : (int) get_the_ID();
		if ( $id === $current && empty( $context['allow_self_embed'] ) ) {
			return $editor
				? '<div class="ab-page-content ab-empty">Não é possível embutir a mesma página em si mesma.</div>'
				: '';
		}

		$post = get_post( $id );
		if ( ! $post || $post->post_status !== 'publish' ) {
			return $editor
				? '<div class="ab-page-content ab-empty">Página #' . esc_html( (string) $id ) . ' não encontrada ou não publicada.</div>'
				: '';
		}

		$html = '<div class="ab-page-content" data-ab-page-content="' . esc_attr( (string) $id ) . '">';
		if ( ( $s['show_title'] ?? '0' ) === '1' ) {
			$html .= '<h2 class="ab-page-content__title">' . esc_html( get_the_title( $post ) ) . '</h2>';
		}

		$repo = new DocumentRepository();
		if ( $repo->is_enabled( $id ) ) {
			// Render Aura document without re-entering ContentFilter recursion loops.
			$doc = $repo->get( $id );
			$doc->metadata['postId'] = $id;
			$out = ( new DocumentRenderer() )->render(
				$doc,
				array(
					'editor'  => false,
					'postId'  => $id,
					'nested'  => true,
				)
			);
			// Nested doc CSS is enqueued on the front via ContentFilter/ThemeBuilder handles when possible.
			// Avoid raw <style> echo; inline via Assets when in front request.
			if ( ! empty( $out['css'] ) && function_exists( 'wp_add_inline_style' ) ) {
				\AuraBuilder\Support\Assets::inline_style(
					'auranet-ptb-page-content-' . $id,
					(string) $out['css'],
					array( 'aura-builder-front' )
				);
			}
			$html .= \AuraBuilder\Support\Assets::kses_builder( (string) ( $out['html'] ?? '' ) );
		} else {
			// Classic page content.
			$content = (string) $post->post_content;
			// Temporarily set global post for shortcodes/blocks.
			$prev = $GLOBALS['post'] ?? null;
			// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
			$GLOBALS['post'] = $post;
			setup_postdata( $post );
			$rendered = apply_filters( 'the_content', $content );
			wp_reset_postdata();
			if ( $prev ) {
				// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
				$GLOBALS['post'] = $prev;
			}
			$html .= '<div class="ab-page-content__body entry-content">' . $rendered . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		}

		$html .= '</div>';
		return $html;
	}
}
