<?php
/**
 * Frontend AJAX endpoints (public, cache-friendly).
 *
 * @package Chess_Podium
 */
if (!defined('ABSPATH')) {
    exit;
}

final class ChessPodium_FrontendAjax
{
    public static function init(): void
    {
        add_action('wp_ajax_chess_podium_standings', [self::class, 'ajax_standings']);
        add_action('wp_ajax_nopriv_chess_podium_standings', [self::class, 'ajax_standings']);
        add_action('wp_ajax_chess_podium_player_photo', [self::class, 'ajax_player_photo']);
        add_action('wp_ajax_nopriv_chess_podium_player_photo', [self::class, 'ajax_player_photo']);
    }

    public static function ajax_standings(): void
    {
        nocache_headers();

        $tid = isset($_REQUEST['tournament_id']) ? max(0, (int) $_REQUEST['tournament_id']) : 0;
        $page = isset($_REQUEST['page']) ? max(1, (int) $_REQUEST['page']) : 1;
        $perPage = isset($_REQUEST['per_page']) ? (int) $_REQUEST['per_page'] : 50;
        $perPage = min(200, max(10, $perPage));
        $nonce = isset($_REQUEST['_ajax_nonce']) ? (string) $_REQUEST['_ajax_nonce'] : '';

        if ($tid <= 0 || !wp_verify_nonce($nonce, 'chess_podium_standings_' . $tid)) {
            wp_send_json_error(['message' => 'Invalid request'], 400);
        }

        if (!class_exists('ChessPodiumPlugin')) {
            wp_send_json_error(['message' => 'Plugin not loaded'], 500);
        }

        $payload = ChessPodiumPlugin::get_async_standings_payload($tid, $page, $perPage);
        wp_send_json_success($payload);
    }

    /**
     * Lazy-load player profile photo (FIDE / Wikipedia) after the public profile HTML is sent.
     */
    public static function ajax_player_photo(): void
    {
        nocache_headers();

        $tid = isset($_REQUEST['tournament_id']) ? max(0, (int) $_REQUEST['tournament_id']) : 0;
        $pid = isset($_REQUEST['player_id']) ? max(0, (int) $_REQUEST['player_id']) : 0;
        $nonce = isset($_REQUEST['_ajax_nonce']) ? (string) wp_unslash($_REQUEST['_ajax_nonce']) : '';

        if ($tid <= 0 || $pid <= 0 || !wp_verify_nonce($nonce, 'chess_podium_player_photo_' . $tid)) {
            wp_send_json_error(['message' => 'Invalid request'], 400);
        }

        if (!class_exists('ChessPodiumPlugin')) {
            wp_send_json_error(['message' => 'Plugin not loaded'], 500);
        }

        $url = ChessPodiumPlugin::fetch_tournament_player_profile_photo_with_network($tid, $pid);
        wp_send_json_success(['url' => $url]);
    }
}

