<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

$profilesFile = dirname(__DIR__) . '/privatedata/players-profiles.json';

function clean_owner_key(string $value): string
{
    $value = trim(mb_strtolower($value, 'UTF-8'));
    $value = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value) ?: $value;
    $value = preg_replace('/[^a-z0-9_-]+/i', '-', $value) ?? '';
    $value = preg_replace('/-+/', '-', $value) ?? '';
    return substr(trim(strtolower($value), '-_'), 0, 80);
}


function json_response(array $data): void
{
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}

$ownerKey = clean_owner_key((string)($_GET['owner_key'] ?? ''));

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    json_response([
        'ok' => false,
        'error' => 'Méthode non autorisée'
    ]);
}

if (!is_file($profilesFile)) {
    json_response([
        'ok' => true,
        'players' => []
    ]);
}

$content = file_get_contents($profilesFile);
$profiles = json_decode((string)$content, true);

if (!is_array($profiles)) {
    json_response([
        'ok' => true,
        'players' => []
    ]);
}

$players = [];

foreach ($profiles as $profile) {
    if (!is_array($profile)) {
        continue;
    }

    if ($ownerKey !== '') {
        $owners = $profile['owners'] ?? [];
        if (!is_array($owners) || !in_array($ownerKey, $owners, true)) {
            continue;
        }
    }

    $name = trim((string)($profile['name'] ?? ''));
    $initials = strtoupper(trim((string)($profile['initials'] ?? '')));
    $initials = preg_replace('/[^A-Z0-9]/i', '', $initials) ?? '';
    $initials = substr($initials, 0, 2);

    if ($name === '' || $initials === '') {
        continue;
    }

    $players[] = [
        'name' => $name,
        'initials' => $initials,
        'avatar' => (string)($profile['avatar'] ?? ''),
        'last_seen_at' => (int)($profile['last_seen_at'] ?? 0)
    ];
}

usort($players, static function(array $a, array $b): int {
    return ($b['last_seen_at'] ?? 0) <=> ($a['last_seen_at'] ?? 0);
});

json_response([
    'ok' => true,
    'players' => $players
]);
