<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

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

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

function normalize_key(string $name, string $initials): string
{
    $name = trim(mb_strtolower($name, 'UTF-8'));
    $initials = trim(mb_strtolower($initials, 'UTF-8'));

    $name = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $name) ?: $name;
    $initials = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $initials) ?: $initials;

    $name = preg_replace('/[^a-z0-9 -]/i', '', $name) ?? '';
    $initials = preg_replace('/[^a-z0-9]/i', '', $initials) ?? '';
    $name = preg_replace('/\s+/', '-', trim($name)) ?? '';

    return strtolower($name . '-' . $initials);
}

function create_player_id(): string
{
    return 'player_' . bin2hex(random_bytes(8));
}

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

$raw = file_get_contents('php://input');
$input = json_decode($raw ?: '', true);

if (!is_array($input)) {
    json_response([
        'ok' => false,
        'error' => 'Données invalides'
    ]);
}

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

if ($name === '' || $initials === '') {
    json_response([
        'ok' => false,
        'error' => 'Prénom ou initiale manquant'
    ]);
}

if (!is_dir(dirname($profilesFile))) {
    json_response([
        'ok' => false,
        'error' => 'Dossier privatedata introuvable'
    ]);
}

if (!is_file($profilesFile)) {
    file_put_contents($profilesFile, "{}", LOCK_EX);
}

$key = normalize_key($name, $initials);

if ($key === '-' || $key === '') {
    json_response([
        'ok' => false,
        'error' => 'Identité joueur invalide'
    ]);
}

$handle = fopen($profilesFile, 'c+');

if (!$handle) {
    json_response([
        'ok' => false,
        'error' => 'Impossible d’ouvrir le fichier joueurs'
    ]);
}

flock($handle, LOCK_EX);
rewind($handle);
$content = stream_get_contents($handle);
$profiles = json_decode((string)$content, true);

if (!is_array($profiles)) {
    $profiles = [];
}

if (!isset($profiles[$key]) || !is_array($profiles[$key])) {
    $profiles[$key] = [
        'id' => create_player_id(),
        'name' => $name,
        'initials' => $initials,
        'created_at' => time(),
        'last_seen_at' => time(),
        'games' => 0
    ];
} else {
    $profiles[$key]['name'] = (string)($profiles[$key]['name'] ?? $name);
    $profiles[$key]['initials'] = (string)($profiles[$key]['initials'] ?? $initials);
    $profiles[$key]['last_seen_at'] = time();
}

rewind($handle);
ftruncate($handle, 0);
fwrite($handle, json_encode($profiles, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
fflush($handle);
flock($handle, LOCK_UN);
fclose($handle);

json_response([
    'ok' => true,
    'player' => [
        'id' => $profiles[$key]['id'],
        'name' => $profiles[$key]['name'],
        'initials' => $profiles[$key]['initials'],
        'key' => $key
    ]
]);
