<?php
/**
 * Context Resolver for the Fundraiser Grid block.
 *
 * Detects which fundraisers to display based on the current page context or
 * the admin-configured preset attributes.
 *
 * Resolution priority (auto mode):
 *   1. Any fundraiser page → direct children of that fundraiser
 *   2. No recognised context → empty result (grid will not render)
 *
 * @package AmbassadorHub\Fundraisers\Blocks\FundraiserGrid
 */

namespace AmbassadorHub\Fundraisers\Blocks\FundraiserGrid;

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

use AmbassadorHub\Fundraisers\FundraisersModule;

/**
 * Resolves parent context for the Fundraiser Grid block.
 */
final class ContextResolver {

	/**
	 * Resolve context for the current request.
	 *
	 * @param array $attributes Block attributes from block.json.
	 *
	 * @return array{
	 *     parent_id:   int,
	 *     has_context: bool,
	 * }
	 */
	public static function resolve( array $attributes = array() ): array {
		$context_mode = $attributes['contextMode'] ?? 'auto';

		// 1. Preset mode — use editor-configured values directly.
		if ( 'preset' === $context_mode ) {
			$parent_id = (int) ( $attributes['presetParentId'] ?? 0 );
			return self::build_result( $parent_id );
		}

		// 2. Auto mode — detect from the current page context.
		global $post;
		if ( ! ( $post instanceof \WP_Post ) ) {
			return self::build_result( 0 );
		}

		// Fundraiser page: show direct children of this fundraiser.
		if ( FundraisersModule::POST_TYPE === get_post_type( $post ) ) {
			return self::build_result( (int) $post->ID );
		}

		return self::build_result( 0 );
	}

	/**
	 * Build the final context result array.
	 *
	 * @param int $parent_id Resolved parent fundraiser ID (0 = none).
	 *
	 * @return array{parent_id: int, has_context: bool}
	 */
	private static function build_result( int $parent_id ): array {
		return array(
			'parent_id'   => $parent_id,
			'has_context' => $parent_id > 0,
		);
	}
}
