<?php
/**
 * Campaign Fundraisers Block
 *
 * Provides a block to display all fundraisers from a campaign (one level deep).
 *
 * @package AmbassadorHub\Campaigns\Blocks\Fundraisers
 */

namespace AmbassadorHub\Campaigns\Blocks\Fundraisers;

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

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

/**
 * Campaign Fundraisers block registration and rendering.
 */
final class Block {
	/**
	 * Initialize the block.
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'init', array( self::class, 'register_block' ) );
	}

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

		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 frontend styles.
		wp_register_style(
			'ambh-campaign-fundraisers',
			$block_url . 'style.css',
			array(),
			AMBASSADOR_HUB_VERSION
		);

		register_block_type(
			$block_dir,
			array(
				'editor_script'   => $handle,
				'style'           => 'ambh-campaign-fundraisers',
				'render_callback' => array( self::class, 'render_block' ),
			)
		);

		// Register shortcode alias.
		add_shortcode( 'ambh_campaign_fundraisers', array( self::class, 'render_shortcode' ) );
	}

	/**
	 * Render the block.
	 *
	 * @param array $attributes Block attributes.
	 *
	 * @return string Block HTML.
	 */
	public static function render_block( array $attributes = array() ): string {
		// Get the campaign ID from attributes or current post.
		$campaign_id = isset( $attributes['campaignId'] ) && $attributes['campaignId'] > 0
			? $attributes['campaignId']
			: 0;

		// If no ID provided, try to get from current post context.
		if ( ! $campaign_id ) {
			$campaign_id = get_the_ID();
		}

		// Validate campaign ID.
		if ( ! $campaign_id ) {
			if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
				return '<div style="padding: 20px; background: #fff3cd; border: 1px solid #ffc107; text-align: center;">'
					. esc_html__( 'Could not determine campaign ID.', 'ambassadorhub' )
					. '</div>';
			}
			return '';
		}

		// Check if it's a valid fundraiser post.
		$post_type = get_post_type( $campaign_id );
		if ( FundraisersModule::POST_TYPE !== $post_type ) {
			if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
				return '<div style="padding: 20px; background: #fff3cd; border: 1px solid #ffc107; text-align: center;">'
					. sprintf(
						// translators: %s: the current post type slug.
						esc_html__( 'This block only works on fundraiser posts. Current post type: %s', 'ambassadorhub' ),
						esc_html( $post_type )
					)
					. '</div>';
			}
			return '';
		}

		// Get all fundraisers for this campaign (one level deep only).
		$fundraisers = self::get_campaign_fundraisers( $campaign_id );

		if ( empty( $fundraisers ) ) {
			// Return a message if in editor context, empty if on frontend.
			if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
				return '<div style="padding: 20px; background: #f0f0f1; border: 1px solid #ddd; text-align: center;">'
					. esc_html__( 'No fundraisers found for this campaign.', 'ambassadorhub' )
					. '</div>';
			}
			return '';
		}

		ob_start();
		?>
		<div class="campaign-fundraisers-block">
			<div class="fundraisers-grid">
				<?php
				foreach ( $fundraisers as $fundraiser_data ) :
					$fundraiser = $fundraiser_data['fundraiser'];
					$owner      = $fundraiser_data['owner'];
					$raised     = $fundraiser_data['raised'];
					$target     = $fundraiser_data['target'];
					$progress   = $fundraiser_data['progress'];

					// Get owner avatar.
					$avatar_url = '';
					if ( $owner ) {
						$avatar_url = get_user_meta( $owner->ID, 'ambh_profile_picture_url', true );
						if ( ! $avatar_url ) {
							// External service call (Gravatar) — see readme.txt's
							// "External Services" section: sends the owner's email
							// (hashed by get_avatar_url()) only when no custom
							// picture is set.
							$avatar_url = get_avatar_url( $owner->ID, array( 'size' => 150 ) );
						}
					}
					?>
					<div class="fundraiser-card">
						<div class="fundraiser-content">
							<h3 class="fundraiser-title">
								<a href="<?php echo esc_url( get_permalink( $fundraiser->ID ) ); ?>">
									<?php echo esc_html( $fundraiser->post_title ); ?>
								</a>
							</h3>
							
							<?php if ( $owner ) : ?>
								<div class="fundraiser-owner">
									<?php if ( $avatar_url ) : ?>
										<img src="<?php echo esc_url( $avatar_url ); ?>" 
											alt="<?php echo esc_attr( $owner->display_name ); ?>" 
											class="owner-avatar">
									<?php endif; ?>
									<span class="owner-name"><?php echo esc_html( $owner->display_name ); ?></span>
								</div>
							<?php endif; ?>
							
							<div class="fundraiser-stats">
								<div class="stat-row">
									<span class="stat-label"><?php esc_html_e( 'Raised:', 'ambassadorhub' ); ?></span>
									<span class="stat-value"><?php echo esc_html( SettingsManager::format_currency( $raised ) ); ?></span>
								</div>
								<?php if ( $target > 0 ) : ?>
									<div class="stat-row">
										<span class="stat-label"><?php esc_html_e( 'Goal:', 'ambassadorhub' ); ?></span>
										<span class="stat-value"><?php echo esc_html( SettingsManager::format_currency( $target ) ); ?></span>
									</div>
									<div class="progress-bar">
										<div class="progress-fill" style="width: <?php echo esc_attr( min( $progress, 100 ) ); ?>%;"></div>
									</div>
									<div class="progress-text"><?php echo number_format( $progress, 1, ',', '.' ); ?>%</div>
								<?php endif; ?>
							</div>
						</div>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}

	/**
	 * Render shortcode.
	 *
	 * @param array $atts Shortcode attributes.
	 *
	 * @return string
	 */
	public static function render_shortcode( $atts ): string {
		$atts = shortcode_atts( array( 'id' => get_the_ID() ), $atts );
		return self::render_block( array( 'campaignId' => intval( $atts['id'] ) ) );
	}

	/**
	 * Get all fundraisers for a campaign (one level deep only).
	 *
	 * @param int $campaign_id Campaign ID.
	 * @return array Array of fundraiser data.
	 */
	private static function get_campaign_fundraisers( $campaign_id ) {
		global $wpdb;
		$table_name       = $wpdb->prefix . 'ambh_donations';
		$fundraisers_data = array();

		// Get direct children of this fundraiser (one level deep).
		$fundraisers = get_posts(
			array(
				'post_type'      => FundraisersModule::POST_TYPE,
				'posts_per_page' => -1,
				'post_status'    => 'publish',
				'post_parent'    => $campaign_id,
				'orderby'        => 'title',
				'order'          => 'ASC',
			)
		);

		foreach ( $fundraisers as $fundraiser ) {
			// Get owner.
			$owner_id = (int) $fundraiser->post_author;
			$owner    = $owner_id ? get_user_by( 'ID', $owner_id ) : null;

			// Get target amount.
			$target = (float) get_post_meta( $fundraiser->ID, '_ambh_target_amount', true );

			// Get raised amount for this fundraiser.
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- table name is $wpdb->prefix constant; fundraiser_id is absint via WP_Post->ID.
			$raised = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COALESCE(SUM(amount), 0) FROM $table_name 
					WHERE fundraiser_id = %d AND status = 'completed'",
					$fundraiser->ID
				)
			);
			// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
			$raised = (float) $raised;

			// Calculate progress.
			$progress = 0;
			if ( $target > 0 ) {
				$progress = ( $raised / $target ) * 100;
			}

			$fundraisers_data[] = array(
				'fundraiser' => $fundraiser,
				'owner'      => $owner,
				'raised'     => $raised,
				'target'     => $target,
				'progress'   => $progress,
			);
		}

		return $fundraisers_data;
	}
}
