function display_player_stats_shortcode($atts) { $atts = shortcode_atts([ 'match_id' => '', 'team' => 'teama', ], $atts, 'team_stats_p'); $match_id = sanitize_text_field($atts['match_id']); $team = sanitize_text_field($atts['team']); if (empty($match_id) || !in_array($team, ['teama', 'teamb'])) { return '
Error: Match ID and valid team (teama or teamb) are required.
'; } $csv_file_path = WP_CONTENT_DIR . "/uploads/player_stats_{$team}_match_{$match_id}.csv"; if (!file_exists($csv_file_path)) { $api_url = API_CALL_BASE_URL . "v4/matches/{$match_id}/advance?token=" . GENERATE_DRAFT_TOKEN; error_log("API URL: " . $api_url); $response = wp_remote_get($api_url); if (is_wp_error($response)) { error_log("API Error: " . $response->get_error_message()); return 'Error: Unable to fetch player stats data.
'; } $response_body = wp_remote_retrieve_body($response); error_log("API Response: " . $response_body); $data = json_decode($response_body, true); if (json_last_error() !== JSON_ERROR_NONE) { error_log("JSON Decode Error: " . json_last_error_msg()); return 'Error: Invalid JSON response.
'; } if (!isset($data['response']['items']) || !is_array($data['response']['items'])) { error_log("Invalid Data Structure: " . print_r($data, true)); return 'Error: No valid data in API response.
'; } $items = $data['response']['items']; $batting_stats = $items['player_batting_stats_with_team'][$team] ?? []; $bowling_stats = $items['player_bowling_stats_with_team'][$team] ?? []; if (!is_array($batting_stats) || !is_array($bowling_stats)) { return 'Error: Player stats data is not in the expected format.
'; } $merged_stats = []; foreach ($batting_stats as $batsman) { $player_name = $batsman['batsman_title'] ?? 'Unknown Player'; $merged_stats[$player_name] = [ 'player' => $player_name, 'innings' => $batsman['innings'] ?? '-', 'runs' => $batsman['runs'] ?? '-', 'wickets' => '-', 'bat_sr' => $batsman['strike'] ?? '-', 'bat_avg' => $batsman['average'] ?? '-', 'bowl_eco' => '-', ]; } foreach ($bowling_stats as $bowler) { $player_name = $bowler['bowler_title'] ?? 'Unknown Player'; if (!isset($merged_stats[$player_name])) { $merged_stats[$player_name] = [ 'player' => $player_name, 'innings' => $bowler['innings'] ?? '-', 'runs' => '-', 'wickets' => $bowler['wickets'] ?? '-', 'bat_sr' => '-', 'bat_avg' => '-', 'bowl_eco' => $bowler['econ'] ?? '-', ]; } else { $merged_stats[$player_name]['wickets'] = $bowler['wickets'] ?? '-'; $merged_stats[$player_name]['bowl_eco'] = $bowler['econ'] ?? '-'; } } $csv_handle = fopen($csv_file_path, 'w'); fputcsv($csv_handle, ['Player', 'Innings', 'Runs', 'Wickets', 'BAT SR', 'BAT Avg', 'BOWL ECO']); foreach ($merged_stats as $player_stats) { fputcsv($csv_handle, $player_stats); } fclose($csv_handle); } return 'Player stats fetched successfully.
'; }