<?php
/**
 * Countdown Block Markup
 *
 * @package StrategyBlocks
 */

use StrategyBlocks\Utility;

$id = $attributes['anchor'] ?? '';
$timer_type = $attributes['timerType'] ?? 'due';
$due_date = $attributes['dueDate'] ?? '';
$units_allowed = $attributes['unitsShown'] ?? [];
$evergreen_hours = isset( $attributes['evergreenHours'] ) ? (int) $attributes['evergreenHours'] : 0;
$evergreen_minutes = isset( $attributes['evergreenMinutes'] ) ? (int) $attributes['evergreenMinutes'] : 0;
$show_labels = isset( $attributes['showLabels'] ) ? (bool) $attributes['showLabels'] : true;
$expire_message = $attributes['expireMessage'] ?? '';
$redirect_url = $attributes['redirectUrl'] ?? '';
$actions_after_expire = $attributes['actionsAfterExpire'] ?? [];
$custom_labels = $attributes['customLabels'] ?? [
	'days' => 'Days',
	'hours' => 'Hours',
	'minutes' => 'Minutes',
	'seconds' => 'Seconds',
];

$class_name = implode(
	' ',
	array_filter(
		[
			'lg-block',
			'lg-block__countdown',
			Utility\get_block_style_classes( $attributes ),
			Utility\get_native_wp_classes( $attributes ),
			Utility\get_visibility_classes( $attributes ),
		]
	)
);

if ( 'evergreen' === $timer_type ) {
	$evergreen_seconds = ( $evergreen_hours * 3600 ) + ( $evergreen_minutes * 60 );
	$target_timestamp = time() + $evergreen_seconds;
	$due_date = gmdate( 'c', $target_timestamp );
}

$animations = Utility\get_animation_data( $attributes );

do_action( 'lg_block_countdown_before' );
?>

<div
	<?php echo $id ? 'id="' . esc_attr( $id ) . '"' : ''; ?>
	class="<?php echo esc_attr( $class_name ); ?>"
	<?php echo ! empty( $animations ) ? 'data-animation="' . esc_attr( $animations ) . '"' : ''; ?>
>
	<time
		class="countdown__timer"
		role="timer"
		aria-atomic="true"
		aria-live="off"
		aria-label="<?php echo esc_attr__( 'Countdown timer:', 'lead-gen' ); ?>"
		datetime="<?php echo esc_attr( $due_date ); ?>"
		data-mode="<?php echo esc_attr( $timer_type ); ?>"
		data-units="<?php echo esc_attr( wp_json_encode( $units_allowed ) ); ?>"
		data-show-label="<?php echo $show_labels ? 'true' : 'false'; ?>"
		data-label-days="<?php echo esc_attr( $custom_labels['days'] ?? 'Days' ); ?>"
		data-label-hours="<?php echo esc_attr( $custom_labels['hours'] ?? 'Hours' ); ?>"
		data-label-minutes="<?php echo esc_attr( $custom_labels['minutes'] ?? 'Minutes' ); ?>"
		data-label-seconds="<?php echo esc_attr( $custom_labels['seconds'] ?? 'Seconds' ); ?>"
		data-after-type="<?php echo esc_attr( wp_json_encode( $actions_after_expire ) ); ?>"
		data-after-message="<?php echo esc_attr( $expire_message ); ?>"
		data-after-redirect="<?php echo esc_attr( $redirect_url ); ?>"
	>
		<?php echo esc_html( $due_date ); ?>
	</time>
	<p class="countdown__message"></p>
</div>
<?php do_action( 'lg_block_countdown_after' ); ?>
