<?php
/**
 * Abstract base class for Smart Post Show Blocks.
 *
 * @package Smart_Post_Show_Pro
 * @subpackage Smart_Post_Show_Pro/blocks/includes
 */

namespace SmartPostShow\Blocks;

use SmartPostShow\Blocks\Block_Base;

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

/**
 * Post Content.
 */
class Post_Content extends Block_Base {

	/**
	 * Block properties
	 */
	protected function set_block_properties() {
		$this->block_name = 'post-content';
		$this->styles     = array(
			'sp_smart_post_blocks_css',
			'sp_smart_post_blocks_style',
			'sp_smart_post_blocks_google_fonts',
		);
	}

	/**
	 * Render block
	 *
	 * @param array  $attributes of blocks.
	 * @param string $content of blocks.
	 * @param array  $blocks of the plugin.
	 * @return string Rendered HTML.
	 */
	public function render_block( $attributes, $content = '', $blocks = array() ) {

		// Show placeholder inside editor.
		if ( \SmartPostShow\Blocks\Helper::is_editor_page() ) {
			return '<p style="opacity:0.5;">Post content will appear here.</p>';
		}

		// if ( ! is_singular() ) {
		// return '';
		// }

		$is_license_activated = $this->is_license_activated();
		if ( 'valid' !== $is_license_activated ) {
			return $is_license_activated;
		}

		$unique_id                 = $attributes['uniqueId'] ?? '';
		$layout_style              = $attributes['layoutStyle'] ?? 'layout-one';
		$advanced_additional_class = $attributes['advancedAdditionalClass'] ?? '';
		$advanced_additional_id    = $attributes['advancedAdditionalID'] ?? '';
		$content_link_color        = $attributes['contentLinkColor'] ?? '';
		$drop_cap                  = $attributes['dropCap'] ?? '';
		$align_class               = ! empty( $attributes['align'] ) ? 'align' . $attributes['align'] : '';

		// Get post content.
		global $post;

		if ( ! $post ) {
			return '';
		}

		$content = apply_filters( 'the_content', $post->post_content );

		if ( ! empty( $drop_cap ) ) {

			$content = preg_replace_callback(
				'/<p([^>]*)>\s*([^\s<])(.*)<\/p>/isu',
				function ( $matches ) {

					$p_attrs   = $matches[1];
					$firstChar = $matches[2];
					$restText  = $matches[3];

					return sprintf(
						'<p%1$s><span class="sp-smart-post-dropcap">%2$s</span><span class="sp-smart-post-rest">%3$s</span></p>',
						$p_attrs,
						$firstChar,
						trim( $restText )
					);
				},
				$content,
				1
			);

			// ALL OTHER PARAGRAPHS → add class.
			$content = preg_replace_callback(
				'/<p([^>]*)>(.*?)<\/p>/isu',
				function ( $m ) {

					$p_attrs = $m[1];
					$inner   = $m[2];

					// If it's the already modified dropcap paragraph → skip.
					if ( strpos( $inner, 'sp-smart-post-dropcap' ) !== false ) {
						return $m[0];
					}

					// Add class.
					if ( preg_match( '/class=["\']([^"\']*)["\']/', $p_attrs, $c ) ) {
						// Merge with existing class.
						$new_attrs = preg_replace(
							'/class=["\']([^"\']*)["\']/',
							'class="' . $c[1] . ' sp-smart-post-rest"',
							$p_attrs
						);
					} else {
						$new_attrs = $p_attrs . ' class="sp-smart-post-rest"';
					}

					return "<p$new_attrs>$inner</p>";
				},
				$content
			);
		}

		$content = preg_replace_callback(
			'/<a\b([^>]*)>/i',
			function ( $matches ) use ( $content_link_color ) {

				$attrs = $matches[1];

				// Add or update class.
				if ( preg_match( '/class=["\']([^"\']*)["\']/', $attrs, $class_match ) ) {
					$new_class = $class_match[1] . ' sp-smart-post-link';
					$attrs     = preg_replace(
						'/class=["\']([^"\']*)["\']/',
						'class="' . $new_class . '"',
						$attrs
					);
				} else {
					$attrs .= ' class="sp-smart-post-link"';
				}

				// Add inline color.
				if ( preg_match( '/style=["\']([^"\']*)["\']/', $attrs, $style_match ) ) {
					// Append to existing style.
					$new_style = rtrim( $style_match[1], '; ' ) . '; color: ' . $content_link_color . ';';
					$attrs     = preg_replace(
						'/style=["\']([^"\']*)["\']/',
						'style="' . $new_style . '"',
						$attrs
					);
				} else {
					// Add new style.
					$attrs .= ' style="color: ' . $content_link_color . ';"';
				}

				return '<a' . $attrs . '>';
			},
			$content
		);

		ob_start();
		?>

		<div class="sp-smart-post-content-block <?php echo esc_attr( $align_class ); ?>">
			<div id="<?php echo esc_attr( $advanced_additional_id ); ?>">
				<div
					class="smart-post-content-block-wrapper <?php echo esc_attr( $advanced_additional_class ); ?>"
					id="<?php echo esc_attr( $unique_id ); ?>">
					<div class="sp-smart-post-content-wrapper">
						<?php
						// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						echo $content; // Escaping may break our content ( iframe / svg ).
						?>
					</div>
				</div>
			</div>
		</div>

		<?php
		return ob_get_clean();
	}
}
