<?php
/**
 * Announcement Bar Section — server-side render.
 *
 * Computes the UTC Unix timestamp from the user-configured
 * countdownTarget so the frontend CountdownInline can start
 * immediately without any additional HTTP request.
 *
 * @package SectionCollection
 */

// Bail if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/* -------------------------------------------------------
 * Compute target Unix timestamp (UTC) from attributes.
 * ------------------------------------------------------- */
$bpsc_ab_countdown_target = isset( $attributes['content']['countdownTarget'] )
	? sanitize_text_field( $attributes['content']['countdownTarget'] )
	: '';

$bpsc_ab_target_ts = 0;

if ( $bpsc_ab_countdown_target ) {
	try {
		// Treat the datetime string as UTC (no timezone in the bar settings).
		$bpsc_ab_tz = new DateTimeZone( 'UTC' );
		$bpsc_ab_dt = new DateTime( $bpsc_ab_countdown_target, $bpsc_ab_tz );
		$bpsc_ab_target_ts = $bpsc_ab_dt->getTimestamp();
	} catch ( Exception $e ) {
		$bpsc_ab_target_ts = (int) strtotime( $bpsc_ab_countdown_target . ' UTC' );
		if ( ! $bpsc_ab_target_ts ) {
			$bpsc_ab_target_ts = 0;
		}
	}
}

/* -------------------------------------------------------
 * Merge runtime data into attributes passed to JS.
 * ------------------------------------------------------- */
$bpsc_ab_runtime_attributes             = $attributes;
$bpsc_ab_runtime_attributes['_runtime'] = array(
	'targetTs' => $bpsc_ab_target_ts,
);

$id = wp_unique_id( 'bpscAnnouncementBarSection-' );
?>
<div
	<?php echo wp_kses_data( get_block_wrapper_attributes() ); ?>
	id="<?php echo esc_attr( $id ); ?>"
	data-attributes="<?php echo esc_attr( wp_json_encode( $bpsc_ab_runtime_attributes ) ); ?>"
></div>
