<?php
/**
 * Total Raised Block
 *
 * @package AmbassadorHub\Fundraisers\Blocks\TotalRaised
 */

namespace AmbassadorHub\Fundraisers\Blocks\TotalRaised;

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

use AmbassadorHub\Fundraisers\Admin\Settings\SettingsManager;
use AmbassadorHub\Fundraisers\Blocks\Stats\Block as StatsBlock;

final class Block {
	public static function init(): void {
		add_action( 'init', array( self::class, 'register_block' ) );
	}

	public static function register_block(): void {
		$handle    = 'ambh-total-raised-block';
		$block_dir = AMBASSADOR_HUB_PATH . 'src/Fundraisers/Blocks/TotalRaised/';
		$block_url = AMBASSADOR_HUB_URL . 'src/Fundraisers/Blocks/TotalRaised/';

		$script_file = $block_dir . 'index.js';
		if ( file_exists( $script_file ) ) {
			wp_register_script(
				$handle,
				$block_url . 'index.js',
				array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-server-side-render', 'wp-block-editor' ),
				filemtime( $script_file ),
				true
			);
		}

		wp_register_style(
			'ambh-total-raised',
			$block_url . 'style.css',
			array(),
			file_exists( $block_dir . 'style.css' ) ? (string) filemtime( $block_dir . 'style.css' ) : AMBASSADOR_HUB_VERSION
		);

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

		if ( file_exists( $script_file ) ) {
			$block_args['editor_script'] = $handle;
		}

		register_block_type( $block_dir, $block_args );
	}

	public static function render_block( array $attributes = array() ): string {
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return '<div style="padding: 20px; background: #f0f0f1; border: 1px solid #ddd; text-align: center;">'
				. esc_html__( 'Total raised.', 'ambassadorhub' )
				. '</div>';
		}

		$stats = StatsBlock::resolve_stats( $attributes );
		if ( array() === $stats ) {
			return '';
		}

		$wrapper_attrs = get_block_wrapper_attributes( array( 'class' => 'ambh-total-raised-block' ) );

		ob_start();
		?>
		<div <?php echo $wrapper_attrs; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- sanitized by get_block_wrapper_attributes(). ?>>
			<div class="ambh-total-raised-block__value"><?php echo esc_html( SettingsManager::format_currency( $stats['total_raised'] ) ); ?></div>
			<div class="ambh-total-raised-block__label"><?php esc_html_e( 'Total raised', 'ambassadorhub' ); ?></div>
		</div>
		<?php
		return (string) ob_get_clean();
	}
}