<?php
/**
 * Fundraiser Info Block — Template
 *
 * Displays the root fundraiser's title, dates, and description.
 * On a root fundraiser page the root IS the current post.
 * On a child/ambassador fundraiser page the root is resolved via get_root_fundraiser_id().
 *
 * @var array{fundraiser: WP_Post} $context
 * @var array                      $block_attrs
 *
 * @package AmbassadorHub\Fundraisers\Blocks\CampaignInfo
 */

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

require_once __DIR__ . '/../utils.php';
use function AmbassadorHub\Fundraisers\Blocks\CampaignInfo\truncate_html;

$ambh_fundraiser     = $context['fundraiser'];
$ambh_content_limit  = isset( $block_attrs['contentLimit'] ) ? (int) $block_attrs['contentLimit'] : 0;
$ambh_show_read_more = ! empty( $block_attrs['showReadMore'] );

$ambh_raw_content  = $ambh_fundraiser->post_excerpt ? $ambh_fundraiser->post_excerpt : $ambh_fundraiser->post_content;
$ambh_is_truncated = false;
if ( $ambh_content_limit > 0 && mb_strlen( wp_strip_all_tags( $ambh_raw_content ) ) > $ambh_content_limit ) {
	$ambh_display_content = truncate_html( $ambh_raw_content, $ambh_content_limit );
	$ambh_is_truncated    = true;
} else {
	$ambh_display_content = wpautop( $ambh_raw_content );
}
?>
<div class="ambh-fundraiser-info">
	<h3 class="ambh-fundraiser-info__title"><?php echo esc_html( get_the_title( $ambh_fundraiser ) ); ?></h3>
	<div class="ambh-fundraiser-info__meta">
		<span class="ambh-fundraiser-info__label"><?php esc_html_e( 'Start:', 'ambassadorhub' ); ?></span>
		<span class="ambh-fundraiser-info__value"><?php echo esc_html( get_date_from_gmt( $ambh_fundraiser->post_date_gmt, get_option( 'date_format' ) ) ); ?></span>
		<?php
		$ambh_end_date = get_post_meta( $ambh_fundraiser->ID, '_ambh_end_date', true );
		if ( $ambh_end_date ) :
			?>
			<span class="ambh-fundraiser-info__label"><?php esc_html_e( 'End:', 'ambassadorhub' ); ?></span>
			<span class="ambh-fundraiser-info__value"><?php echo esc_html( get_date_from_gmt( $ambh_end_date, get_option( 'date_format' ) ) ); ?></span>
		<?php endif; ?>
	</div>
	<div class="ambh-fundraiser-info__desc"><?php echo wp_kses_post( $ambh_display_content ); ?></div>
	<?php if ( $ambh_is_truncated && $ambh_show_read_more ) : ?>
		<a class="ambh-fundraiser-info__link" href="<?php echo esc_url( get_permalink( $ambh_fundraiser ) ); ?>">
			<?php esc_html_e( 'Read more about this fundraiser', 'ambassadorhub' ); ?>
		</a>
	<?php elseif ( get_the_ID() !== $ambh_fundraiser->ID ) : ?>
		<a class="ambh-fundraiser-info__link" href="<?php echo esc_url( get_permalink( $ambh_fundraiser ) ); ?>">
			<?php esc_html_e( 'View fundraiser', 'ambassadorhub' ); ?>
		</a>
	<?php endif; ?>
</div>
