<?php
/**
 * The Template for displaying Player >> Game Stats Section.
 *
 * This template can be overridden by copying it to yourtheme/sports-leagues/player/player-stats.php.
 *
 * @var object $data - Object with args.
 *
 * @author        Andrei Strekozov <anwp.pro>
 * @package       Sports-Leagues/Templates
 * @since         0.6.0
 *
 * @version       0.14.0
 */

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

$data = (object) wp_parse_args(
	$data,
	[
		'season_dropdown' => '',
		'season_id'       => '',
		'player_id'       => '',
		'header'          => true,
	]
);

/*
|--------------------------------------------------------------------
| Prepare Stats Data (using centralized preparation method)
|--------------------------------------------------------------------
*/
$template_data = sports_leagues()->player_stats->prepare_player_stats_template_data( $data );

if ( false === $template_data ) {
	return;
}

// Load previous version (before stat groups)
if ( empty( $template_data->stat_groups ) ) {
	return sports_leagues()->load_partial( $data, 'player/player-stats', 'v1' );
}

// Extract prepared data
$stats_columns        = $template_data->stats_columns;
$stat_groups          = $template_data->stat_groups;
$player_stats_grouped = $template_data->player_stats_grouped;
$game_permalinks      = $template_data->game_permalinks;
$teams_data           = $template_data->teams_data;
$custom_date_format   = $template_data->custom_date_format;
$stats_class          = $template_data->stats_class;

/**
 * Hook: sports-leagues/tmpl-player/player_stats_before
 *
 * @param object $data PLayer data
 *
 * @since 0.6.0
 */
do_action( 'sports-leagues/tmpl-player/player_stats_before', $data );

wp_enqueue_style( 'anwp-data-tables' );
wp_enqueue_script( 'anwp-data-tables' );
wp_enqueue_script( 'sl-data-tables' );
?>
<div class="anwp-section player_stats player_stats--v0">

	<?php
	if ( Sports_Leagues::string_to_bool( $data->header ) ) {
		sports_leagues()->load_partial(
			[
				'text' => Sports_Leagues_Text::get_value( 'player__player_stats__player_stats', __( 'Player Stats', 'sports-leagues' ) ),
			],
			'general/header'
		);
	}

	if ( ! empty( $player_stats_grouped ) && is_array( $player_stats_grouped ) ) :

		foreach ( $player_stats_grouped as $team_id => $team_data ) :

			// Team data (use pre-fetched team data for performance)
			$team = $teams_data[ $team_id ] ?? sports_leagues()->team->get_team_by_id( $team_id );

			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo sports_leagues()->helper->render_team_header( $team->logo, $team->title, $team_id );

			foreach ( $team_data as $stat_group_id => $stat_group_data ) :
				if ( ! empty( sports_leagues()->player_stats->get_stats_group_by_id( $stat_group_id )->name ) ) :
					sports_leagues()->load_partial(
						[
							'text'  => sports_leagues()->player_stats->get_stats_group_by_id( $stat_group_id )->name,
							'class' => 'mt-3 mb-2',
						],
						'general/subheader'
					);
				endif;
				?>
				<table class="anwp-stats-table anwp-sl-player-stats w-100 my-0 nowrap cell-border compact stripe">
					<thead>
					<tr class="small">
						<th class="no-sort text-left"><?php echo esc_html( Sports_Leagues_Text::get_value( 'player__player_stats__date', __( 'Date', 'sports-leagues' ) ) ); ?></th>
						<th class="no-sort text-left"><?php echo esc_html( Sports_Leagues_Text::get_value( 'player__player_stats__vs', __( 'VS', 'sports-leagues' ) ) ); ?></th>
						<?php
						foreach ( $stats_columns as $column ) :
							if ( 'hidden' === $column->visibility || ! in_array( $stat_group_id, $column->groups, true ) ) {
								continue;
							}
							?>
							<th class="text-right <?php echo esc_attr( 'composed' === $column->type ? 'no-sort' : '' ); ?>" data-toggle="<?php echo $column->name ? 'anwp-sl-tooltip' : ''; ?>" data-tippy-content="<?php echo esc_attr( $column->name ); ?>">
								<?php echo esc_html( $column->abbr ); ?>
							</th>
						<?php endforeach; ?>
					</tr>
					</thead>
					<tbody>
					<?php
					foreach ( $stat_group_data as $game_id => $game_data ) :
						$game_date = date_i18n( $custom_date_format ?: 'j M Y', strtotime( $game_data['data']->kickoff ) );

						// Get opposite team
						$team_id_opp = absint( $game_data['data']->home_team ) === $team_id ? absint( $game_data['data']->away_team ) : absint( $game_data['data']->home_team );
						$team_opp    = $teams_data[ $team_id_opp ] ?? sports_leagues()->team->get_team_by_id( $team_id_opp );
						?>
						<tr data-sl-game-datetime="<?php echo esc_attr( date_i18n( 'c', strtotime( $game_data['data']->kickoff ) ) ); ?>">
							<td class="text-left text-nowrap align-middle text-right game__date-formatted anwp-text-xs px-1 anwp-w-30"><?php echo esc_html( $game_date ); ?></td>
							<td class="anwp-text-center text-nowrap small">
								<?php
								// Use partial template for opponent cell
								sports_leagues()->load_partial(
									[
										'team_opp'       => $team_opp,
										'game_permalink' => $game_permalinks[ $game_id ] ?? '',
									],
									'player/player-stats-opponent-cell'
								);
								?>
							</td>
							<?php
							foreach ( $stats_columns as $column ) :
								if ( 'hidden' === $column->visibility || ! in_array( $stat_group_id, $column->groups, true ) ) {
									continue;
								}

								$cell_value = sports_leagues()->player_stats->render_player_game_stats( $game_data['stats'], $column );
								$data_order = sports_leagues()->player_stats->calculate_data_order( $cell_value, $column );
								?>
								<td class="text-right anwp-w-15  <?php echo esc_attr( $stats_class ); ?>" <?php echo $data_order ? sprintf( 'data-order="%s"', esc_attr( $data_order ) ) : ''; ?>>
									<?php echo esc_html( $cell_value ); ?>
								</td>
							<?php endforeach; ?>
						</tr>
					<?php endforeach; ?>
					</tbody>
					<tfoot>
					<tr class="small">
						<th class="no-sort text-left"><?php echo esc_html( Sports_Leagues_Text::get_value( 'player__player_stats__date', __( 'Date', 'sports-leagues' ) ) ); ?></th>
						<th class="no-sort text-left"><?php echo esc_html( Sports_Leagues_Text::get_value( 'player__player_stats__vs', __( 'VS', 'sports-leagues' ) ) ); ?></th>
						<?php
						foreach ( $stats_columns as $column ) :
							if ( 'hidden' === $column->visibility || ! in_array( $stat_group_id, $column->groups, true ) ) {
								continue;
							}
							?>
							<th class="text-right" data-toggle="<?php echo $column->name ? 'anwp-sl-tooltip' : ''; ?>" data-tippy-content="<?php echo esc_attr( $column->name ); ?>">
								<?php echo esc_html( $column->abbr ); ?>
							</th>
						<?php endforeach; ?>
					</tr>
					</tfoot>
				</table>
				<?php
			endforeach;
		endforeach;
	else :
		sports_leagues()->load_partial(
			[
				'no_data_text' => Sports_Leagues_Text::get_value( 'player__player_stats__no_data', __( 'No Data', 'sports-leagues' ) ),
			],
			'general/no-data'
		);
	endif;
	?>
</div>
