<?php
/**
 * Campaign Countdown Block
 *
 * Renders a visual countdown (days / hours / minutes) to the campaign end date
 * stored in the _ambh_end_date post meta. Applies an is-urgent modifier class
 * when the deadline is within the configurable urgencyDays threshold.
 *
 * Returns an empty string when:
 *  - No campaign context can be resolved.
 *  - The campaign has no end date set.
 *
 * @package AmbassadorHub\Campaigns\Blocks\CampaignCountdown
 */

namespace AmbassadorHub\Campaigns\Blocks\CampaignCountdown;

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

use AmbassadorHub\Fundraisers\FundraisersModule;

/**
 * Campaign Countdown block registration and server-side rendering.
 */
final class Block {

	// -------------------------------------------------------------------------
	// Boot
	// -------------------------------------------------------------------------

	/**
	 * Initialize the block.
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'init', array( self::class, 'register_block' ) );
	}

	// -------------------------------------------------------------------------
	// Registration
	// -------------------------------------------------------------------------

	/**
	 * Register block type, editor script, and styles.
	 *
	 * @return void
	 */
	public static function register_block(): void {
		$block_dir = AMBASSADOR_HUB_PATH . 'src/Campaigns/Blocks/CampaignCountdown/';
		$block_url = AMBASSADOR_HUB_URL . 'src/Campaigns/Blocks/CampaignCountdown/';

		$editor_handle = 'ambh-campaign-countdown-editor';
		$editor_file   = $block_dir . 'index.js';
		if ( file_exists( $editor_file ) ) {
			wp_register_script(
				$editor_handle,
				$block_url . 'index.js',
				array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-server-side-render' ),
				(string) filemtime( $editor_file ),
				true
			);
		}

		$style_file = $block_dir . 'style.css';
		wp_register_style(
			'ambh-campaign-countdown',
			$block_url . 'style.css',
			array(),
			file_exists( $style_file ) ? (string) filemtime( $style_file ) : AMBASSADOR_HUB_VERSION
		);

		$block_args = array(
			'style'           => 'ambh-campaign-countdown',
			'render_callback' => array( self::class, 'render_block' ),
		);

		if ( file_exists( $editor_file ) ) {
			$block_args['editor_script'] = $editor_handle;
		}

		register_block_type( $block_dir, $block_args );
	}

	// -------------------------------------------------------------------------
	// Rendering
	// -------------------------------------------------------------------------

	/**
	 * Server-side render callback.
	 *
	 * @param array $attributes Block attributes.
	 *
	 * @return string Rendered HTML or empty string.
	 */
	public static function render_block( array $attributes = array() ): string {

		// Lightweight editor placeholder.
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return '<div class="ambh-campaign-countdown ambh-block-preview">'
				. '<p class="ambh-block-preview__label">' . esc_html__( 'Campaign Countdown', 'ambassadorhub' ) . '</p>'
				. '<p class="ambh-block-preview__meta">' . esc_html__( 'Displays time remaining to the campaign end date.', 'ambassadorhub' ) . '</p>'
				. '</div>';
		}

		// Resolve campaign ID: explicit attribute > current page context.
		$campaign_id = isset( $attributes['campaignId'] ) && $attributes['campaignId'] > 0
			? (int) $attributes['campaignId']
			: 0;

		if ( ! $campaign_id ) {
			$current_id = (int) get_the_ID();
			if ( FundraisersModule::POST_TYPE === get_post_type( $current_id ) ) {
				$campaign_id = $current_id;
			}
		}

		if ( ! $campaign_id ) {
			return '';
		}

		$end_date_raw = get_post_meta( $campaign_id, FundraisersModule::META_END_DATE, true );
		if ( ! $end_date_raw ) {
			return '';
		}

		$urgency_days = max( 0, (int) ( $attributes['urgencyDays'] ?? 7 ) );
		$show_label   = $attributes['showLabel'] ?? true;
		$ended_label  = ! empty( $attributes['endedLabel'] )
			? $attributes['endedLabel']
			: __( 'This campaign has ended', 'ambassadorhub' );

		$end_ts   = strtotime( $end_date_raw );
		$now      = time();
		$status   = get_post_status( $campaign_id );
		$is_ended = ( 'ended' === $status ) || ( $end_ts && $end_ts <= $now );

		if ( $is_ended ) {
			return '<div class="ambh-campaign-countdown is-ended">'
				. '<p class="ambh-countdown__ended-label">' . esc_html( $ended_label ) . '</p>'
				. '</div>';
		}

		$diff_seconds = $end_ts - $now;
		$days         = (int) floor( $diff_seconds / DAY_IN_SECONDS );
		$hours        = (int) floor( ( $diff_seconds % DAY_IN_SECONDS ) / HOUR_IN_SECONDS );
		$minutes      = (int) floor( ( $diff_seconds % HOUR_IN_SECONDS ) / MINUTE_IN_SECONDS );

		$is_urgent = $urgency_days > 0 && $days < $urgency_days;
		$classes   = 'ambh-campaign-countdown' . ( $is_urgent ? ' is-urgent' : '' );

		ob_start();
		?>
		<div class="<?php echo esc_attr( $classes ); ?>">
			<?php if ( $show_label ) : ?>
				<p class="ambh-countdown__label">
					<?php esc_html_e( 'Time remaining', 'ambassadorhub' ); ?>
				</p>
			<?php endif; ?>

			<div class="ambh-countdown__units">
				<div class="ambh-countdown__unit">
					<span class="ambh-countdown__value"><?php echo esc_html( (string) $days ); ?></span>
					<span class="ambh-countdown__unit-label">
						<?php echo esc_html( _n( 'day', 'days', $days, 'ambassadorhub' ) ); ?>
					</span>
				</div>
				<div class="ambh-countdown__separator" aria-hidden="true">:</div>
				<div class="ambh-countdown__unit">
					<span class="ambh-countdown__value"><?php echo esc_html( str_pad( (string) $hours, 2, '0', STR_PAD_LEFT ) ); ?></span>
					<span class="ambh-countdown__unit-label">
						<?php echo esc_html( _n( 'hour', 'hours', $hours, 'ambassadorhub' ) ); ?>
					</span>
				</div>
				<div class="ambh-countdown__separator" aria-hidden="true">:</div>
				<div class="ambh-countdown__unit">
					<span class="ambh-countdown__value"><?php echo esc_html( str_pad( (string) $minutes, 2, '0', STR_PAD_LEFT ) ); ?></span>
					<span class="ambh-countdown__unit-label">
						<?php echo esc_html( _n( 'min', 'mins', $minutes, 'ambassadorhub' ) ); ?>
					</span>
				</div>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}
}
