<?php
/**
 * Donors List Block
 *
 * Displays donors who have donated to this fundraiser or any of its children,
 * using a JOIN against the ambh_donors table for name/anonymous data.
 *
 * @package AmbassadorHub\Fundraisers\Blocks\DonorsList
 */

namespace AmbassadorHub\Fundraisers\Blocks\DonorsList;

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

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare

use AmbassadorHub\Donations\DonationsModule;
use AmbassadorHub\Donors\DonorsModule;
use AmbassadorHub\Fundraisers\Admin\Settings\SettingsManager;
use AmbassadorHub\Fundraisers\FundraisersModule;

/**
 * Donors List 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 {
		$handle    = 'ambh-donors-list-block';
		$block_dir = AMBASSADOR_HUB_PATH . 'src/Fundraisers/Blocks/DonorsList/';
		$block_url = AMBASSADOR_HUB_URL . 'src/Fundraisers/Blocks/DonorsList/';

		$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' ),
				filemtime( $script_file ),
				true
			);
		}

		wp_register_style(
			'ambh-donors-list',
			$block_url . 'style.css',
			array(),
			AMBASSADOR_HUB_VERSION
		);

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

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

		register_block_type( $block_dir, $block_args );

		// Register shortcode alias.
		add_shortcode( 'ambh_donors_list', 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 {
		global $post;

		$limit       = isset( $attributes['limit'] ) && $attributes['limit'] > 0 ? intval( $attributes['limit'] ) : 10;
		$show_amount = isset( $attributes['showAmount'] ) ? (bool) $attributes['showAmount'] : true;

		$fundraiser_id = isset( $post->ID ) && FundraisersModule::POST_TYPE === get_post_type( $post ) ? $post->ID : 0;

		if ( 0 === $fundraiser_id ) {
			if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
				return '<div style="padding: 20px; background: #f0f0f1; border: 1px solid #ddd; text-align: center;">'
					. esc_html__( 'Fundraiser Donor lijst.', 'ambassadorhub' )
					. '</div>';
			}
			return '';
		}

		$donors = self::get_donors( $fundraiser_id, $limit );

		if ( empty( $donors ) ) {
			if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
				return '<div style="padding: 20px; background: #f0f0f1; border: 1px solid #ddd; text-align: center;">'
					. esc_html__( 'Geen donors gevonden.', 'ambassadorhub' )
					. '</div>';
			}
			return '';
		}

		ob_start();
		?>
		<div class="donors-list-block">
			<div class="donors-list">
				<?php foreach ( $donors as $donor ) : ?>
					<div class="donor-item">
						<div class="donor-header">
							<span class="donor-name">
								<?php
								$display_name = DonationsModule::get_donor_name_for_display( $donor );
								echo esc_html( $display_name );
								?>
							</span>
							<?php if ( $show_amount ) : ?>
								<span class="donor-amount">
								<?php echo esc_html( SettingsManager::format_currency( (float) $donor->amount ) ); ?>
								</span>
							<?php endif; ?>
						</div>
						<?php if ( ! empty( $donor->message ) ) : ?>
							<div class="donor-message">
								<?php echo esc_html( $donor->message ); ?>
							</div>
						<?php endif; ?>
						<div class="donor-date">
							<?php echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( $donor->created_at ) ) ); ?>
						</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 {
		global $post;

		$atts = shortcode_atts(
			array(
				'limit'       => 10,
				'show_amount' => true,
			),
			$atts
		);

		return self::render_block(
			array(
				'limit'      => intval( $atts['limit'] ),
				'showAmount' => (bool) $atts['show_amount'],
			)
		);
	}

	/**
	 * Get all child fundraiser IDs recursively.
	 *
	 * @param int $parent_id Parent fundraiser ID.
	 * @return array Array of fundraiser IDs including parent.
	 */
	private static function get_all_fundraiser_ids( int $parent_id ): array {
		$ids = array( $parent_id );

		$children = get_posts(
			array(
				'post_type'      => FundraisersModule::POST_TYPE,
				'post_parent'    => $parent_id,
				'posts_per_page' => -1,
				'fields'         => 'ids',
				'post_status'    => 'any',
			)
		);

		foreach ( $children as $child_id ) {
			$ids = array_merge( $ids, self::get_all_fundraiser_ids( $child_id ) );
		}

		return $ids;
	}

	/**
	 * Get donors for display (via completed donations JOIN).
	 *
	 * @param int $fundraiser_id Fundraiser ID.
	 * @param int $limit         Max number of results.
	 * @return array Array of objects with donation + donor fields.
	 */
	private static function get_donors( int $fundraiser_id, int $limit = 10 ): array {
		global $wpdb;
		$donations_table = DonationsModule::get_table_name();
		$donors_table    = DonorsModule::get_table_name();

		$fundraiser_ids = self::get_all_fundraiser_ids( $fundraiser_id );
		$placeholders   = implode( ', ', array_fill( 0, count( $fundraiser_ids ), '%d' ) );

		$sql = "SELECT d.id, d.amount, d.currency, d.message, d.is_anonymous, d.fundraiser_id, d.created_at,
		               dn.name         AS linked_donor_name,
		               dn.email        AS linked_donor_email,
		               dn.is_anonymous AS linked_donor_is_anonymous,
		               d.donor_name    AS donor_name,
		               d.donor_email   AS donor_email
		        FROM {$donations_table} d
		        LEFT JOIN {$donors_table} dn ON dn.id = d.donor_id
		        WHERE d.status = 'completed'
		          AND d.fundraiser_id IN ({$placeholders})
		        ORDER BY d.created_at DESC
		        LIMIT %d";

		$params = array_merge( $fundraiser_ids, array( $limit ) );

		return $wpdb->get_results( $wpdb->prepare( $sql, $params ) );
	}
}
