<?php
/**
 * Account Block
 *
 * Dynamic block for rendering the ambassador account area.
 *
 * @package AmbassadorHub\Accounts\Blocks\Account
 */

namespace AmbassadorHub\Accounts\Blocks\Account;

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

use AmbassadorHub\Accounts\Roles;
use AmbassadorHub\Api\ApiModule;

use function add_action;
use function register_block_type;
use function add_shortcode;
use function is_user_logged_in;
use function wp_get_current_user;
use function esc_html__;

/**
 * Account block - displays the ambassador account management area.
 *
 * Server-side rendered dynamic block with internal navigation.
 */
final class Block {
	/**
	 * Block name.
	 */
	private const BLOCK_NAME = 'ambassadorhub/account';

	/**
	 * Shortcode name.
	 */
	private const SHORTCODE = 'ambh_ambassador_account';

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

	/**
	 * Enqueue block assets.
	 *
	 * @return void
	 */
	public static function enqueue_assets(): void {
		// Only enqueue on pages with the block/shortcode.
		if ( ! has_block( self::BLOCK_NAME ) && ! self::has_shortcode() ) {
			return;
		}

		wp_enqueue_style(
			'ambassador-account',
			AMBASSADOR_HUB_URL . 'src/Accounts/Blocks/Account/assets/account.css',
			array(),
			AMBASSADOR_HUB_VERSION
		);

		wp_enqueue_script(
			'ambassador-account',
			AMBASSADOR_HUB_URL . 'src/Accounts/Blocks/Account/assets/account.js',
			array(),
			AMBASSADOR_HUB_VERSION,
			true
		);

		wp_localize_script(
			'ambassador-account',
			'ambhConstants',
			array(
				'namespace' => ApiModule::NAMESPACE,
				'restNonce' => wp_create_nonce( 'wp_rest' ),
			)
		);
	}

	/**
	 * Check if current page has the account shortcode.
	 *
	 * @return bool
	 */
	private static function has_shortcode(): bool {
		global $post;
		return is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, self::SHORTCODE );
	}

	/**
	 * Register the block type.
	 *
	 * @return void
	 */
	public static function register_block(): void {
		// Register editor script.
		$handle    = 'ambh-account-block';
		$block_dir = AMBASSADOR_HUB_PATH . 'src/Accounts/Blocks/Account/';
		$block_url = AMBASSADOR_HUB_URL . 'src/Accounts/Blocks/Account/';

		wp_register_script(
			$handle,
			$block_url . 'index.js',
			array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-server-side-render' ),
			filemtime( $block_dir . 'index.js' ),
			true
		);

		register_block_type(
			$block_dir,
			array(
				'editor_script'   => $handle,
				'render_callback' => array( self::class, 'render_block' ),
			)
		);
	}

	/**
	 * Render the block content.
	 *
	 * @param array $attributes Block attributes.
	 *
	 * @return string Block HTML.
	 */
	public static function render_block( array $attributes = array() ): string { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found -- required by block render_callback signature.
		// Compute wrapper attributes once; passed to each render branch so all
		// states (logged-out, denied, dashboard) use the same block-level classes
		// and hook into the theme's layout constraints.
		$wrapper_attrs = get_block_wrapper_attributes( array( 'class' => 'ambassador-account' ) );

		// Check if user is logged in.
		if ( ! is_user_logged_in() ) {
			return self::render_login_prompt( $wrapper_attrs );
		}

		$user = wp_get_current_user();

		// Check if user is an ambassador.
		if ( ! Roles::user_is_ambassador() ) {
			return self::render_access_denied( $wrapper_attrs );
		}

		// Start output buffering.
		ob_start();

		// Get current tab/section.
		$current_tab = Router::get_current_tab();

		?>
		<div <?php echo $wrapper_attrs; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- sanitized by get_block_wrapper_attributes(). ?>>
			<?php if ( isset( $_GET['ambh_joined_team'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only notice, no action taken. ?>
			<div class="ambassador-account__notice ambassador-account__notice--success">
				<p><?php esc_html_e( 'You have successfully joined the team! Your fundraiser has been created.', 'ambassadorhub' ); ?></p>
			</div>
			<?php endif; ?>
			<?php Router::render_navigation( $current_tab ); ?>
			<div class="ambassador-account__content">
				<?php Router::render_content( $current_tab ); ?>
			</div>
		</div>
		<?php

		return ob_get_clean();
	}

	/**
	 * Render shortcode.
	 *
	 * @param array $atts Shortcode attributes.
	 *
	 * @return string Shortcode HTML.
	 */
	public static function render_shortcode( $atts = array() ): string {
		return self::render_block( (array) $atts );
	}

	/**
	 * Render login prompt for non-logged-in users.
	 *
	 * @return string HTML.
	 */
	private static function render_login_prompt( string $wrapper_attrs = '' ): string {
		// wp_login_url() is filtered by AccountsModule to point to the custom
		// login page, so ambassadors stay on the frontend.
		$permalink = get_permalink();
		$login_url = wp_login_url( $permalink ? $permalink : home_url( '/' ) );
		if ( ! $wrapper_attrs ) {
			$wrapper_attrs = 'class="ambassador-account-notice"';
		}
		ob_start();
		?>
		<div <?php echo $wrapper_attrs; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- sanitized by get_block_wrapper_attributes(). ?>>
			<p>
				<?php echo esc_html__( 'Please log in to access your account.', 'ambassadorhub' ); ?>
				<a href="<?php echo esc_url( $login_url ); ?>">
					<?php echo esc_html__( 'Log in', 'ambassadorhub' ); ?>
				</a>
			</p>
		</div>
		<?php
		return ob_get_clean();
	}

	/**
	 * Render access denied message for non-ambassadors.
	 *
	 * @return string HTML.
	 */
	private static function render_access_denied( string $wrapper_attrs = '' ): string {
		if ( ! $wrapper_attrs ) {
			$wrapper_attrs = 'class="ambassador-account-notice ambassador-account-notice--error"';
		}
		ob_start();
		?>
		<div <?php echo $wrapper_attrs; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- sanitized by get_block_wrapper_attributes(). ?>>
			<p><?php echo esc_html__( 'You do not have permission to access this area.', 'ambassadorhub' ); ?></p>
		</div>
		<?php
		return ob_get_clean();
	}
}
