<?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;
}

/**
 * Section Heading
 */
class Archive_Title extends Block_Base {


	/**
	 * Set_block_properties
	 *
	 * @return void
	 */
	protected function set_block_properties() {
		$this->block_name = 'archive-title';
		$this->styles     = array( 'sp_smart_post_blocks_css', 'sp_smart_post_blocks_style', 'sp_smart_post_blocks_google_fonts' );
	}

	/**
	 * Render_block
	 *
	 * @param  array  $attributes attributes.
	 * @param  string $content  Content to be rendered.
	 * @param  array  $blocks   Array of block list.
	 * @return string Rendered HTML content.
	 */
	public function render_block( $attributes, $content = '', $blocks = array() ) {
		if ( \SmartPostShow\Blocks\Helper::is_editor_page() ) {
			return $content;
		}
		$is_license_activated = $this->is_license_activated();
		if ( 'valid' !== $is_license_activated ) {
			return $is_license_activated;
		}

		// Extract attributes with defaults.
		$unique_id                 = $attributes['uniqueId'] ?? '';
		$layout_style              = $attributes['layoutStyle'] ?? 'layout-one';
		$advanced_additional_class = $attributes['advancedAdditionalClass'] ?? '';
		$advanced_additional_id    = $attributes['advancedAdditionalID'] ?? '';
		$align_class               = $attributes['align'] ?? '';
		$post_breadcrumb           = $attributes['postBreadcrumb'] ?? true;
		$layout_two_img_overlay    = $attributes['layoutTwoImgOverlay'] ?? false;
		$show_archive_type         = $attributes['showArchiveType'] ?? false;
		$archive_img_lazy          = $attributes['archiveImgLazy'] ?? false;

		$overlay_class = ( $layout_two_img_overlay && 'layout-two' === $layout_style ) ? 'sp-image-overlay' : '';

		// Get actual archive data.
		$archive_title       = $this->get_archive_title( $show_archive_type );
		$archive_description = $this->get_archive_description();
		$category_thumbnail  = $this->get_category_thumbnail();
		if ( empty( $category_thumbnail ) ) {
			$category_thumbnail = SP_PCP_URL . 'public/assets/img/placeholder.png';
		}
		$category_thumbnail_alt = $this->get_category_thumbnail_alt() ?? 'Archive banner';

		$thumbnail_id   = attachment_url_to_postid( $category_thumbnail ) ?? 0;
		$thumbnail_data = $thumbnail_id ? wp_get_attachment_image_src( $thumbnail_id, 'full' ) : '';

		$thumbnail_attr = ! empty( $thumbnail_data ) ? ( 'width="' . $thumbnail_data[1] . '" height="' . $thumbnail_data[2] . '"' ) : '';

		if ( ! $post_breadcrumb ) {
			$content = '';
		}

		ob_start();
		?>


		<div class="sp-smart-post-archive-header-block <?php echo 'align' . esc_attr( $align_class ); ?>" <?php echo ( ! empty( $advanced_additional_id ) ? 'id="' . esc_attr( $advanced_additional_id ) . '"' : '' ); ?>>

			<div class="sp-smart-post-archive-header sp-smart-post-wrapper <?php echo esc_attr( $advanced_additional_class . ' ' . $layout_style ); ?>"
				id="<?php echo esc_attr( $unique_id ); ?>">

				<?php if ( 'layout-one' === $layout_style ) : ?>
					<div class="sp-smart-post-archive-banner">
						<?php if ( ! empty( $category_thumbnail ) ) : ?>
							<img src="<?php echo esc_url( $category_thumbnail ); ?>" alt="<?php echo esc_attr( $category_thumbnail_alt ); ?>" loading="<?php echo $archive_img_lazy ? 'lazy' : 'eager'; ?>" <?php echo $thumbnail_attr; // phpcs:ignore ?> />
						<?php endif; ?>


					</div>
					<?php
						//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						echo $content; // No need for escaping it's has our svg icons.
					?>
					<?php
						//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						echo $this->get_archive_content( $attributes, $archive_title, $archive_description ); // No need for escaping as it's coming from our own function.
					?>


				<?php elseif ( 'layout-two' === $layout_style && ! empty( $category_thumbnail ) ) : ?>
					<div class="sp-smart-post-archive-overlay <?php echo esc_attr( $overlay_class ); ?>">

						<img src="<?php echo esc_url( $category_thumbnail ); ?>" alt="<?php echo esc_attr( $category_thumbnail_alt ); ?>" loading="<?php echo $archive_img_lazy ? 'lazy' : 'eager'; ?>" <?php echo $thumbnail_attr; // phpcs:ignore ?> />


						<div class="sp-smart-post-archive-overlay-content">
							<?php
								//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
								echo $content; // No need for escaping it's has our svg icons.
							?>
							<?php
							//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
							echo $this->get_archive_content( $attributes, $archive_title, $archive_description ); // No need for escaping as it's coming from our own function.
							?>
						</div>
					</div>

				<?php elseif ( 'layout-two' === $layout_style && empty( $category_thumbnail ) ) : ?>
					<?php
						//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						echo $content; // No need for escaping it's has our svg icons.
					?>
					<?php
						//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						echo $this->get_archive_content( $attributes, $archive_title, $archive_description ); // No need for escaping as it's coming from our own function.
					?>



				<?php elseif ( 'layout-three' === $layout_style ) : ?>
					<?php
						//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						echo $content; // No need for escaping it's has our svg icons.
					?>
					<?php
						//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						echo $this->get_archive_content( $attributes, $archive_title, $archive_description ); // No need for escaping as it's coming from our own function.
					?>
					<div class="sp-smart-post-archive-banner">
						<?php if ( ! empty( $category_thumbnail ) ) : ?>
							<img src="<?php echo esc_url( $category_thumbnail ); ?>" alt="<?php echo esc_attr( $category_thumbnail_alt ); ?>" loading="<?php echo $archive_img_lazy ? 'lazy' : 'eager'; ?>" <?php echo $thumbnail_attr; // phpcs:ignore ?> />
						<?php endif; ?>
					</div>
				<?php endif; ?>

			</div>
		</div>

		<?php
		return ob_get_clean();
	}


	/**
	 * Get archive content HTML.
	 *
	 * @param array  $attributes .
	 * @param string $title .
	 * @param string $description .
	 */
	private function get_archive_content( $attributes, $title, $description ) {
		$show_title               = $attributes['showTitle'] ?? true;
		$html_tag                 = $attributes['htmlTag'] ?? 'h2';
		$prefix                   = $attributes['prefix'] ?? false;
		$prefix_text              = $attributes['prefixText'] ?? '';
		$prefix_position          = $attributes['prefixPosition'] ?? 'above-title';
		$image_content_aliment    = $attributes['imageContentAliment'] ?? '';
		$specific_color           = $attributes['specificColor'] ?? true;
		$category_color           = $this->get_category_color();
		$prefix_global_typography = $attributes['prefixGlobalTypography'] ?? '';
		$prefix_global_class      = $prefix_global_typography['class'] ?? '';
		$title_global_typography  = $attributes['titleGlobalTypography'] ?? '';
		$title_global_class       = $title_global_typography['class'] ?? '';
		$des_global_typography    = $attributes['descriptionGlobalTypography'] ?? '';
		$des_global_class         = $des_global_typography['class'] ?? '';

		$title_color = null;

		if ( $specific_color && ! empty( $category_color ) ) {
			$title_color = $category_color;
		}

		ob_start();
		?>
		<div class="sp-smart-post-archive-content <?php echo esc_attr( $image_content_aliment ); ?>">
			<div class="sp-smart-post-archive-content-wrapper">
				<div class="sp-smart-post-title-prefix-wrapper">

					<?php if ( 'above-title' === $prefix_position && $prefix ) : ?>
						<p class="sp-smart-post-prefix-text"><?php echo esc_html( $prefix_text ); ?></p>
					<?php endif; ?>

				
						<div class="sp-smart-post-title-wrapper">
							<?php if ( 'before-title' === $prefix_position && $prefix ) : ?>
								<p class="sp-smart-post-prefix-text <?php echo esc_attr( $prefix_global_class ); ?>  "><?php echo esc_html( $prefix_text ); ?></p>
							<?php endif; ?>
							<?php if ( $show_title ) : ?>
							<<?php echo esc_attr( $html_tag ); ?>
								class="sp-smart-post-archive-title <?php echo esc_attr( $title_global_class ); ?> "
								<?php echo ( ! empty( $title_color ) ) ? 'style="color:' . esc_attr( $title_color ) . ';"' : ''; ?>
								>
								<?php echo wp_kses_post( $title ); ?>
							</<?php echo esc_attr( $html_tag ); ?>>
							<?php endif; ?>

						</div>
					

					<?php if ( 'below-title' === $prefix_position && $prefix ) : ?>
						<p class="sp-smart-post-prefix-text"><?php echo esc_html( $prefix_text ); ?></p>
					<?php endif; ?>

				</div>

				<?php if ( ! empty( $description ) ) : ?>
					<div class="sp-smart-post-archive-description  <?php echo esc_attr( $des_global_class ); ?> ">
						<?php echo wp_kses_post( $description ); ?>
					</div>
				<?php endif; ?>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}

	/**
	 * Get dynamic archive title.
	 *
	 * @param boolean $show_archive_type show/hide archive type.
	 * @return html archive title.
	 */
	private function get_archive_title( $show_archive_type ) {
		if ( ! is_archive() ) {
			return '';
		}
		$archive_title = '';
		if ( $show_archive_type ) {
			$archive_title = get_the_archive_title();
		} else {
			// Removes prefixes like "Category:", "Tag:", and "Author:".
			add_filter( 'get_the_archive_title_prefix', '__return_empty_string' );
			$archive_title = get_the_archive_title();
			remove_filter( 'get_the_archive_title_prefix', '__return_empty_string' );
		}

		return $archive_title;
	}

	/**
	 * Get dynamic archive description
	 */
	private function get_archive_description() {
		if ( is_archive() ) {
			return get_the_archive_description();
		}
		return '';
	}

	/**
	 * Get the category thumbnail URL if set.
	 *
	 * Checks if the current archive is a category archive and
	 * retrieves the 'category_thumbnail' term meta. Returns false if not found.
	 *
	 * @return string|false The URL of the category thumbnail or false if not set.
	 */
	private function get_category_thumbnail() {
		if ( is_category() ) {
			$term_id = get_queried_object_id();

			// If using term meta (ACF or custom field).
			$thumbnail = get_term_meta( $term_id, 'category_thumbnail', true );

			if ( $thumbnail ) {
				return esc_url( $thumbnail ); // return thumbnail URL only.
			}
		}

		return false;
	}

	/**
	 * Get the category color if set.
	 *
	 * Checks if the current archive is a category archive and
	 * retrieves the 'category_color' term meta. Returns false if not found.
	 *
	 * @return string|false The URL of the category thumbnail or false if not set.
	 */
	private function get_category_color() {
		if ( is_category() ) {
			$term_id = get_queried_object_id();

			// Fetch term meta (ACF or custom meta).
			$color = get_term_meta( $term_id, 'category_color', true );

			if ( $color ) {
				return sanitize_hex_color( $color );
			}
		}

		return false;
	}

	/**
	 * Get the category thumbnail Alt text if set.
	 *
	 * Checks if the current archive is a category archive and
	 * retrieves the 'category_thumbnail' term meta. Returns false if not found.
	 *
	 * @return string|false The Alt text of the category thumbnail or false if not set.
	 */
	private function get_category_thumbnail_alt() {
		global $wpdb;
		if ( is_category() ) {
			$term_id = get_queried_object_id();

			// If using term meta (ACF or custom field).
			$thumbnail = get_term_meta( $term_id, 'category_thumbnail', true );

			$attachment_id = attachment_url_to_postid( $thumbnail );

			if ( $attachment_id ) {
				// The alt text is stored in the post meta with the key '_wp_attachment_image_alt'.
				$alt_text = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
				return $alt_text;
			}
		}

		return false;
	}
}
