<?php
/**
 * Create Team Button Block
 *
 * Renders a button that links to the configured create-fundraiser page with
 * `?type=team` pre-appended so the form skips the type-selection step and
 * opens directly in team-creation mode.
 *
 * @package AmbassadorHub\Fundraisers\Blocks\CreateTeamButton
 */

namespace AmbassadorHub\Fundraisers\Blocks\CreateTeamButton;

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

use AmbassadorHub\Fundraisers\Admin\Settings\SettingsManager;
use AmbassadorHub\Fundraisers\FundraisersHelpers;
use AmbassadorHub\Fundraisers\FundraisersModule;

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

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

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

		$editor_handle = 'ambh-create-team-button-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-api-fetch' ),
				(string) filemtime( $editor_file ),
				true
			);
		}

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

		$block_args = array(
			'style'           => 'ambh-create-team-button',
			'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 );
	}

	/**
	 * Server-side render callback.
	 *
	 * @param array $attributes Block attributes.
	 *
	 * @return string Rendered HTML.
	 */
	public static function render_block( array $attributes = array() ): string {
		$label = sanitize_text_field( $attributes['buttonLabel'] ?? '' );
		if ( '' === $label ) {
			$label = __( 'Create a team', 'ambassadorhub' );
		}

		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return '<div class="ambh-create-team-button ambh-block-preview">'
				. '<a class="ambh-ctb-btn ambh-ctb-btn--preview">'
				. esc_html( $label )
				. '</a>'
				. '</div>';
		}

		$context   = self::resolve_context( $attributes );
		$root_id   = $context['root_id'];
		$parent_id = $context['parent_id'];

		// Hide if the root fundraiser is closed.
		if ( $root_id > 0 && ! FundraisersHelpers::fundraiser_is_open( $root_id ) ) {
			return '';
		}

		// Hide if the direct parent fundraiser is closed.
		if ( $parent_id > 0 && ! FundraisersHelpers::fundraiser_is_open( $parent_id ) ) {
			return '';
		}

		if ( self::is_hidden( $attributes ) ) {
			return '';
		}

		$page_url = SettingsManager::get_create_fundraiser_page_url();

		$query_params = self::build_query_params( $attributes );
		if ( ! empty( $query_params ) ) {
			$page_url = add_query_arg( $query_params, $page_url );
		}

		$link_classes  = 'ambh-ctb-btn wp-block-button__link wp-element-button';
		$inline_styles = array();
		$style_attr    = $attributes['style'] ?? array();

		$has_block_bg   = ! empty( $attributes['backgroundColor'] ) || ! empty( $style_attr['color']['background'] );
		$has_block_text = ! empty( $attributes['textColor'] ) || ! empty( $style_attr['color']['text'] );

		if ( ! empty( $attributes['backgroundColor'] ) ) {
			$link_classes .= ' has-' . sanitize_html_class( $attributes['backgroundColor'] ) . '-background-color has-background';
		}
		if ( ! empty( $attributes['textColor'] ) ) {
			$link_classes .= ' has-' . sanitize_html_class( $attributes['textColor'] ) . '-color has-text-color';
		}
		if ( ! empty( $style_attr['color']['background'] ) ) {
			$inline_styles[] = 'background-color:' . esc_attr( $style_attr['color']['background'] );
		}
		if ( ! empty( $style_attr['color']['text'] ) ) {
			$inline_styles[] = 'color:' . esc_attr( $style_attr['color']['text'] );
		}

		if ( ! $has_block_bg ) {
			$inline_styles[] = 'background-color:var(--ambh-color-primary,#2271b1)'; }
		if ( ! $has_block_text ) {
			$inline_styles[] = 'color:#ffffff'; }

		$link_style = ' style="' . implode( ';', $inline_styles ) . '"';

		return '<div class="ambh-create-team-button wp-block-button">'
			. '<a class="' . esc_attr( $link_classes ) . '"' . $link_style . ' href="' . esc_url( $page_url ) . '">' . esc_html( $label ) . '</a>'
			. '</div>';
	}

	/**
	 * Resolve the root and parent fundraiser IDs from block attributes or page context.
	 *
	 * @param array $attributes Block attributes.
	 *
	 * @return array{root_id: int, parent_id: int}
	 */
	private static function resolve_context( array $attributes ): array {
		$root_id      = 0;
		$parent_id    = 0;
		$context_mode = $attributes['contextMode'] ?? 'auto';

		if ( 'preset' === $context_mode ) {
			$root_id   = (int) ( $attributes['presetRootId'] ?? $attributes['presetCampaignId'] ?? 0 );
			$parent_id = (int) ( $attributes['presetParentId'] ?? 0 );
		} else {
			global $post;

			if ( $post && FundraisersModule::POST_TYPE === get_post_type( $post ) ) {
				$parent_id = $post->ID;
				$root_id   = FundraisersHelpers::get_root_fundraiser_id( $post->ID );
			}
		}

		return array(
			'root_id'   => $root_id,
			'parent_id' => $parent_id,
		);
	}

	/**
	 * Determine whether the button should be hidden.
	 *
	 * Hidden when `hideIfNotAllowed` is enabled and teams are not permitted
	 * for the resolved root or parent context.
	 *
	 * @param array $attributes Block attributes.
	 *
	 * @return bool
	 */
	private static function is_hidden( array $attributes ): bool {
		if ( empty( $attributes['hideIfNotAllowed'] ) ) {
			return false;
		}

		$context   = self::resolve_context( $attributes );
		$root_id   = $context['root_id'];
		$parent_id = $context['parent_id'];

		return ! FundraisersHelpers::team_creation_allowed( $root_id, $parent_id );
	}

	/**
	 * Build query parameters from block attributes.
	 *
	 * Always includes `type=team`.
	 *
	 * @param array $attributes Block attributes.
	 *
	 * @return array<string, scalar>
	 */
	private static function build_query_params( array $attributes ): array {
		$params    = array( 'type' => 'team' );
		$context   = self::resolve_context( $attributes );
		$root_id   = $context['root_id'];
		$parent_id = $context['parent_id'];

		if ( $root_id > 0 ) {
			$params['root_id'] = $root_id;
		}
		if ( $parent_id > 0 ) {
			$params['parent_id'] = $parent_id;
		}

		return $params;
	}
}
