<?php
/**
 * Event Countdown Section — server-side render.
 *
 * Computes the UTC Unix timestamp from the user-configured
 * targetDate + timezone so the frontend timer 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_target_date = isset( $attributes['content']['targetDate'] )
	? sanitize_text_field( $attributes['content']['targetDate'] )
	: '2027-01-01T00:00:00';

$bpsc_timezone_string = isset( $attributes['content']['timezone'] )
	? sanitize_text_field( $attributes['content']['timezone'] )
	: 'UTC';

$bpsc_target_ts = 0;

try {
	// DateTimeZone will throw InvalidArgumentException for unknown timezones.
	$bpsc_tz = new DateTimeZone( $bpsc_timezone_string );
	$bpsc_dt = new DateTime( $bpsc_target_date, $bpsc_tz );
	// Convert to UTC timestamp.
	$bpsc_target_ts = $bpsc_dt->getTimestamp();
} catch ( Exception $e ) {
	// Fallback: parse the date string as UTC.
	$bpsc_target_ts = (int) strtotime( $bpsc_target_date . ' UTC' );
	if ( ! $bpsc_target_ts ) {
		$bpsc_target_ts = 0;
	}
}

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

$id = wp_unique_id( 'bpscEventCountdownSection-' );
?>
<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_runtime_attributes ) ); ?>"
></div>
