<?php
/**
 * Sports Leagues :: Block > Roster
 *
 * @package Sports_Leagues
 */

class Sports_Leagues_Block_Roster {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'init', [ $this, 'register_blocks' ] );
	}

	/**
	 * Register blocks.
	 */
	public function register_blocks() {
		register_block_type(
			Sports_Leagues::dir( 'gutenberg/blocks/roster' ),
			[
				'title'           => 'SL Roster',
				'render_callback' => [ $this, 'server_side_render' ],
			]
		);
	}

	/**
	 * Register blocks.
	 *
	 * @param array $attr the block attributes
	 */
	public function server_side_render( array $attr ) {

		$attr = wp_parse_args(
			$attr,
			[
				'layout'    => '',
				'title'     => '',
				'season_id' => '',
				'team_id'   => '',
				'header'    => false,
			]
		);

		if ( ( ! absint( $attr['team_id'] ) || ! absint( $attr['season_id'] ) ) && Sports_Leagues::is_editing_block_on_backend() ) {
			ob_start();
			sports_leagues()->load_partial(
				[
					'no_data_text' => __( 'Team ID or Season ID is empty', 'sports-leagues' ),
				],
				'general/no-data'
			);

			return ob_get_clean();
		}

		if ( Sports_Leagues::is_editing_block_on_backend() ) {
			$attr['class'] .= ' anwp-sl-disable-link ';
		}

		return sports_leagues()->template->shortcode_loader( 'roster', $attr );
	}
}

return new Sports_Leagues_Block_Roster();
