<?php

defined( 'ABSPATH' ) || exit;

/**
 * Procedural helpers for the Matches extension (themes and integrations).
 *
 * @package clanbite
 */

use Kernowdev\Clanbite\Extensions\Matches;

/**
 * Resolve the running Matches extension from the loader.
 *
 * @return Matches|null Null when the extension is not installed or not booted.
 */
function clanbite_matches(): ?Matches {
	$loader = clanbite()->extensions;
	if ( null === $loader ) {
		return null;
	}

	$ext = $loader->get( 'cp_matches' );

	return $ext instanceof Matches ? $ext : null;
}

/**
 * Whether the Matches extension should expose the team profile Matches subpage and `/teams/{slug}/matches/` route.
 *
 * @return bool
 */
function clanbite_matches_subpage_team_enabled(): bool {
	if ( ! clanbite_matches() ) {
		return false;
	}

	$defaults = array(
		'subpage_team' => true,
	);
	$stored   = get_option( 'clanbite_matches_settings', array() );
	if ( ! is_array( $stored ) ) {
		$stored = array();
	}
	$merged = wp_parse_args( $stored, $defaults );

	return ! empty( $merged['subpage_team'] );
}

/**
 * Human-readable title for a `cp_team` post ID.
 *
 * @param int $team_id Team post ID (`cp_team`).
 * @return string Empty string when the post is missing or not a team.
 */
function clanbite_matches_team_title( int $team_id ): string {
	if ( $team_id <= 0 ) {
		return '';
	}
	$post = get_post( $team_id );
	if ( ! $post || 'clanbite_team' !== $post->post_type ) {
		return '';
	}

	return get_the_title( $post );
}

/**
 * Away-side label for a match, using a local `cp_team` or external challenge metadata.
 *
 * @param int $match_id Match post ID.
 * @return string
 */
function clanbite_matches_resolve_away_team_title( int $match_id ): string {
	$away = (int) get_post_meta( $match_id, 'cp_match_away_team_id', true );
	if ( $away > 0 ) {
		return clanbite_matches_team_title( $away );
	}

	return sanitize_text_field( (string) get_post_meta( $match_id, 'cp_match_away_external_label', true ) );
}

/**
 * Format a stored GMT datetime string for display using the site timezone.
 *
 * @param string $mysql_gmt Datetime in GMT (MySQL-compatible string).
 * @param string $format    PHP date format passed to `wp_date()`.
 * @return string Empty string when the value cannot be parsed.
 */
function clanbite_matches_format_datetime_local( string $mysql_gmt, string $format ): string {
	if ( '' === trim( $mysql_gmt ) ) {
		return '';
	}
	$ts = strtotime( $mysql_gmt . ' UTC' );
	if ( false === $ts ) {
		return '';
	}

	return wp_date( $format, $ts );
}

/**
 * Map match status keys to localized labels.
 *
 * @return array<string, string> Status slug => translated label.
 */
function clanbite_matches_status_labels(): array {
	return array(
		'scheduled' => __( 'Scheduled', 'clanbite' ),
		'live'      => __( 'Live', 'clanbite' ),
		'finished'  => __( 'Finished', 'clanbite' ),
		'cancelled' => __( 'Cancelled', 'clanbite' ),
	);
}
