<?php
declare(strict_types=1);

session_start();

if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ./');
    exit;
}

$configFile = dirname(__DIR__) . '/privatedata/admin-parties-config.php';
if (!is_file($configFile)) {
    exit('Configuration admin manquante.');
}
require $configFile;

if (isset($_POST['password'])) {
    if (password_verify((string)$_POST['password'], $ADMIN_PARTIES_PASSWORD_HASH ?? '')) {
        $_SESSION['admin_parties_ok'] = true;
        header('Location: ./');
        exit;
    }
}

if (empty($_SESSION['admin_parties_ok'])) {
    ?>
    <!doctype html><html lang="fr"><head><meta charset="utf-8"><title>Admin profils Chrono Party</title><meta name="viewport" content="width=device-width, initial-scale=1"></head>
    <body style="background:#0f1024;font-family:Arial,sans-serif;color:white;padding:20px">
        <form method="post" style="max-width:420px;margin:80px auto;background:rgba(255,255,255,.08);padding:25px;border-radius:18px;border:1px solid rgba(255,255,255,.15)">
            <h2>👤 Admin profils</h2>
            <input type="password" name="password" placeholder="Mot de passe" style="width:100%;padding:13px;box-sizing:border-box;border-radius:10px;border:0">
            <button style="margin-top:12px;padding:13px;width:100%;background:#7c5cff;color:white;border:0;border-radius:10px;font-weight:bold">Connexion</button>
        </form>
    </body></html>
    <?php
    exit;
}

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

function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }

function cleanOwnerKey(string $value): string {
    $value = trim(strtolower($value));
    $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 normalizePlayerKey(string $name, string $initials): string {
    $name = trim(strtolower($name));
    $initials = trim(strtolower($initials));
    $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(trim($name . '-' . $initials, '-'));
}

function makeScopedProfileKey(string $ownerKey, string $name, string $initials): string {
    $ownerKey = cleanOwnerKey($ownerKey) ?: 'default';
    $playerKey = normalizePlayerKey($name, $initials);
    return $ownerKey . '__' . ($playerKey ?: bin2hex(random_bytes(4)));
}

function readProfiles(string $file): array {
    if (!is_file($file)) return [];
    $json = json_decode((string)file_get_contents($file), true);
    return is_array($json) ? $json : [];
}

function writeProfiles(string $file, array $profiles): void {
    file_put_contents($file, json_encode($profiles, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);
}

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

function profileOwnerMatchesAdmin(array $profile, string $ownerKey): bool {
    $ownerKey = cleanOwnerKey($ownerKey) ?: 'default';
    $profileOwner = cleanOwnerKey((string)($profile['owner_key'] ?? ''));

    if ($profileOwner !== '' && $profileOwner !== 'default' && $profileOwner === $ownerKey) {
        return true;
    }

    $owners = $profile['owners'] ?? [];
    if (is_array($owners)) {
        foreach ($owners as $owner) {
            if (cleanOwnerKey((string)$owner) === $ownerKey) {
                return true;
            }
        }
    }

    return false;
}

function findProfileConflicts(array $profiles, string $playerKey, string $ownerKey, string $ignoreStorageKey = ''): array {
    $conflicts = [];
    foreach ($profiles as $storageKey => $profile) {
        if ($ignoreStorageKey !== '' && (string)$storageKey === $ignoreStorageKey) continue;
        if (!is_array($profile)) continue;

        $existingPlayerKey = (string)($profile['player_key'] ?? '');
        if ($existingPlayerKey === '') {
            $existingPlayerKey = normalizePlayerKey((string)($profile['name'] ?? ''), (string)($profile['initials'] ?? ''));
        }
        if ($existingPlayerKey === '' || $existingPlayerKey !== $playerKey) continue;

        $existingOwner = cleanOwnerKey((string)($profile['owner_key'] ?? 'default')) ?: 'default';
        $conflicts[] = [
            'storage_key' => (string)$storageKey,
            'owner_key' => $existingOwner,
            'same_owner' => profileOwnerMatchesAdmin($profile, $ownerKey),
        ];
    }
    return $conflicts;
}

$profiles = readProfiles($profilesFile);
$message = '';
$error = '';

if (empty($_SESSION['csrf_admin_profils'])) {
    $_SESSION['csrf_admin_profils'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_admin_profils'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = (string)($_POST['csrf'] ?? '');
    if (!hash_equals($_SESSION['csrf_admin_profils'] ?? '', $csrf)) {
        exit('Action refusée : jeton CSRF invalide.');
    }

    $action = (string)($_POST['action'] ?? '');
    $id = trim((string)($_POST['id'] ?? ''));

    if ($action === 'create') {
        $ownerKey = cleanOwnerKey((string)($_POST['new_owner_key'] ?? '')) ?: 'default';
        $name = trim((string)($_POST['new_name'] ?? ''));
        $initials = strtoupper(trim((string)($_POST['new_initials'] ?? '')));
        $initials = preg_replace('/[^A-Z0-9]/i', '', $initials) ?? '';
        $initials = substr($initials, 0, 2);
        $avatar = trim((string)($_POST['new_avatar'] ?? ''));

        if ($name === '' || $initials === '') {
            $error = 'Prénom et initiale obligatoires pour créer un profil.';
        } else {
            $playerKey = normalizePlayerKey($name, $initials);
            $newKey = makeScopedProfileKey($ownerKey, $name, $initials);
            $conflicts = findProfileConflicts($profiles, $playerKey, $ownerKey);

            if (!empty($conflicts)) {
                $otherAccount = null;
                foreach ($conflicts as $conflict) {
                    if (!$conflict['same_owner']) { $otherAccount = $conflict['owner_key']; break; }
                }
                $error = $otherAccount
                    ? 'Ce prénom et cette initiale sont déjà utilisés sur un autre compte (' . $otherAccount . ').'
                    : 'Ce prénom existe déjà pour ce compte.';
            } else {
                $profiles[$newKey] = [
                    'id' => createPlayerId(),
                    'owner_key' => $ownerKey,
                    'owners' => [$ownerKey],
                    'player_key' => $playerKey,
                    'name' => $name,
                    'initials' => $initials,
                    'avatar' => $avatar,
                    'created_at' => time(),
                    'last_seen_at' => time(),
                    'games' => 0
                ];
                writeProfiles($profilesFile, $profiles);
                $message = 'Profil créé pour le compte ' . $ownerKey . '.';
            }
        }
    }

    if ($id !== '' && isset($profiles[$id]) && is_array($profiles[$id])) {
        if ($action === 'save') {
            $name = trim((string)($_POST['name'] ?? ''));
            $initials = strtoupper(substr(preg_replace('/[^A-Z0-9]/i', '', trim((string)($_POST['initials'] ?? ''))) ?? '', 0, 2));
            $avatar = trim((string)($_POST['avatar'] ?? ''));
            $ownerKey = cleanOwnerKey((string)($_POST['owner_key'] ?? ($profiles[$id]['owner_key'] ?? 'default'))) ?: 'default';
            $playerKey = normalizePlayerKey($name, $initials);
            $newStorageKey = makeScopedProfileKey($ownerKey, $name, $initials);
            $conflicts = findProfileConflicts($profiles, $playerKey, $ownerKey, $id);

            if ($name === '' || $initials === '') {
                $error = 'Prénom et initiale obligatoires.';
            } elseif (!empty($conflicts)) {
                $otherAccount = null;
                foreach ($conflicts as $conflict) {
                    if (!$conflict['same_owner']) { $otherAccount = $conflict['owner_key']; break; }
                }
                $error = $otherAccount
                    ? 'Modification refusée : ce prénom et cette initiale sont déjà utilisés sur un autre compte (' . $otherAccount . ').'
                    : 'Modification refusée : ce prénom existe déjà pour ce compte.';
            } elseif ($newStorageKey !== $id && isset($profiles[$newStorageKey])) {
                $error = 'Modification refusée : une fiche existe déjà avec cette clé.';
            } else {
                $updated = $profiles[$id];
                $updated['name'] = $name;
                $updated['initials'] = $initials;
                $updated['avatar'] = $avatar;
                $updated['owner_key'] = $ownerKey;
                $owners = $updated['owners'] ?? [];
                if (!is_array($owners)) { $owners = []; }
                if (!in_array($ownerKey, $owners, true)) { $owners[] = $ownerKey; }
                $updated['owners'] = $owners;
                $updated['player_key'] = $playerKey;
                $updated['updated_at'] = time();

                if ($newStorageKey !== $id) {
                    unset($profiles[$id]);
                }
                $profiles[$newStorageKey] = $updated;
                writeProfiles($profilesFile, $profiles);
                $message = 'Profil modifié.';
            }
        }

        if ($action === 'delete') {
            unset($profiles[$id]);
            writeProfiles($profilesFile, $profiles);
            $message = 'Profil supprimé de ce compte.';
        }
    }

    if ($error === '') {
        $redirectOwner = cleanOwnerKey((string)($_POST['filter_owner_after'] ?? ''));
        header('Location: ./' . ($redirectOwner !== '' ? '?owner=' . urlencode($redirectOwner) : ''));
        exit;
    }
}

$profiles = readProfiles($profilesFile);
$ownerFilter = cleanOwnerKey((string)($_GET['owner'] ?? ''));

$ownerKeys = [];
foreach ($profiles as $profile) {
    if (!is_array($profile)) continue;
    $owner = cleanOwnerKey((string)($profile['owner_key'] ?? ''));
    if ($owner !== '') $ownerKeys[$owner] = true;
    $owners = $profile['owners'] ?? [];
    if (is_array($owners)) {
        foreach ($owners as $legacyOwner) {
            $legacyOwner = cleanOwnerKey((string)$legacyOwner);
            if ($legacyOwner !== '') $ownerKeys[$legacyOwner] = true;
        }
    }
}
ksort($ownerKeys);

$visibleProfiles = [];
foreach ($profiles as $id => $profile) {
    if (!is_array($profile)) continue;
    if ($ownerFilter !== '') {
        $profileOwner = cleanOwnerKey((string)($profile['owner_key'] ?? ''));
        $legacyOwners = $profile['owners'] ?? [];
        $legacyMatch = is_array($legacyOwners) && in_array($ownerFilter, $legacyOwners, true);
        if ($profileOwner !== $ownerFilter && !$legacyMatch) continue;
    }
    $visibleProfiles[$id] = $profile;
}

uasort($visibleProfiles, static function(array $a, array $b): int {
    $oa = (string)($a['owner_key'] ?? '');
    $ob = (string)($b['owner_key'] ?? '');
    $cmp = strcasecmp($oa, $ob);
    if ($cmp !== 0) return $cmp;
    return strcasecmp(trim(($a['name'] ?? '') . ' ' . ($a['initials'] ?? '')), trim(($b['name'] ?? '') . ' ' . ($b['initials'] ?? '')));
});
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Admin profils joueurs</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{margin:0;font-family:Arial,sans-serif;background:#0f1024;color:white;padding:20px}.container{max-width:1250px;margin:auto}h1{margin-top:0}.card{background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.15);border-radius:18px;padding:16px;margin-bottom:14px}.grid{display:grid;grid-template-columns:1.15fr 1fr .45fr .65fr 1fr auto auto;gap:10px;align-items:center}.createGrid{display:grid;grid-template-columns:1fr 1fr .4fr .7fr auto;gap:10px;align-items:end}.filterGrid{display:grid;grid-template-columns:1fr auto auto;gap:10px;align-items:end}label{display:block;font-size:13px;color:rgba(255,255,255,.7);margin-bottom:6px}input,select{width:100%;padding:11px;border-radius:10px;border:1px solid rgba(255,255,255,.2);background:rgba(255,255,255,.08);color:white;font-weight:bold;box-sizing:border-box}select option{color:#111}button,a.btn{border:0;border-radius:10px;padding:11px 13px;font-weight:bold;cursor:pointer;text-decoration:none;color:white;display:inline-block}.save{background:#7c3aed}.create{background:#16a34a}.delete{background:#dc2626}.view{background:#0891b2}.logout{background:#374151}.filter{background:#f97316}.id{font-size:12px;color:rgba(255,255,255,.65);word-break:break-all;margin-top:4px}.message{background:#14532d;padding:12px;border-radius:12px;margin-bottom:15px}.error{background:#7f1d1d;padding:12px;border-radius:12px;margin-bottom:15px}.header{color:rgba(255,255,255,.7);font-size:13px;font-weight:bold}.actions{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:18px}.help{font-size:13px;color:rgba(255,255,255,.68);line-height:1.45;margin-top:8px}.pill{display:inline-block;padding:4px 8px;border-radius:999px;background:rgba(124,92,255,.25);font-size:12px;margin-top:5px}@media(max-width:950px){.grid,.createGrid,.filterGrid{grid-template-columns:1fr}.header{display:none}}
</style>
</head>
<body>
<div class="container">
<h1>👤 Admin profils joueurs</h1>
<div class="actions">
  <a class="btn view" href="/classement-joueurs/">🏆 Classement joueurs</a>
  <a class="btn view" href="/statistiques/">📊 Statistiques</a>
  <a class="btn logout" href="?logout=1">Déconnexion</a>
</div>

<?php if ($message): ?><div class="message"><?= h($message) ?></div><?php endif; ?>
<?php if ($error): ?><div class="error"><?= h($error) ?></div><?php endif; ?>

<form method="get" class="card">
  <h2>🔎 Voir les prénoms d’un compte</h2>
  <div class="filterGrid">
    <div>
      <label>Compte / licence</label>
      <select name="owner">
        <option value="">Tous les comptes</option>
        <?php foreach (array_keys($ownerKeys) as $owner): ?>
          <option value="<?= h($owner) ?>" <?= $ownerFilter === $owner ? 'selected' : '' ?>><?= h($owner) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <button class="filter" type="submit">Filtrer</button>
    <a class="btn logout" href="./">Tous</a>
  </div>
  <div class="help">Le compte affiché correspond à la clé envoyée par le jeu : client_id, code cadeau ou accès utilisé.</div>
</form>

<form method="post" class="card">
  <h2>➕ Créer un prénom pour un compte</h2>
  <input type="hidden" name="action" value="create">
  <input type="hidden" name="csrf" value="<?= h($csrfToken) ?>">
  <input type="hidden" name="filter_owner_after" value="<?= h($ownerFilter) ?>">
  <div class="createGrid">
    <div><label>Compte / licence</label><input name="new_owner_key" value="<?= h($ownerFilter) ?>" placeholder="gift-cp-mercier-jerome"></div>
    <div><label>Prénom</label><input name="new_name" placeholder="Giovanni"></div>
    <div><label>Initiale</label><input name="new_initials" maxlength="2" placeholder="C"></div>
    <div><label>Avatar</label><input name="new_avatar" placeholder="😀 🦊 🦖"></div>
    <div><button class="create" type="submit">Créer</button></div>
  </div>
  <div class="help">Le prénom créé apparaîtra uniquement dans les suggestions de ce compte.</div>
</form>

<div class="card header grid"><div>Profil</div><div>Compte</div><div>Initiale</div><div>Avatar</div><div>Prénom</div><div>Voir</div><div>Action</div></div>

<?php if (empty($visibleProfiles)): ?>
  <div class="card">Aucun profil joueur enregistré pour ce filtre.</div>
<?php else: ?>
  <?php foreach ($visibleProfiles as $id => $profile): ?>
    <?php
      $playerId=(string)($profile['id']??$id);
      $name=(string)($profile['name']??'');
      $initials=(string)($profile['initials']??'');
      $avatar=(string)($profile['avatar']??'');
      $owner=(string)($profile['owner_key']??'');
      $legacyOwners=$profile['owners']??[];
      if ($owner === '' && is_array($legacyOwners) && !empty($legacyOwners)) $owner=(string)$legacyOwners[0];
    ?>
    <form method="post" class="card grid">
      <input type="hidden" name="id" value="<?= h($id) ?>">
      <input type="hidden" name="action" value="save">
      <input type="hidden" name="csrf" value="<?= h($csrfToken) ?>">
      <input type="hidden" name="filter_owner_after" value="<?= h($ownerFilter) ?>">
      <div><strong><?= h(trim($avatar . ' ' . $name . ' ' . $initials)) ?></strong><div class="id"><?= h($playerId) ?></div><span class="pill"><?= h($id) ?></span></div>
      <div><input name="owner_key" value="<?= h($owner) ?>" placeholder="compte"></div>
      <div><input name="initials" maxlength="2" value="<?= h($initials) ?>" placeholder="C"></div>
      <div><input name="avatar" value="<?= h($avatar) ?>" placeholder="😀"></div>
      <div><input name="name" value="<?= h($name) ?>" placeholder="Prénom"></div>
      <div><a class="btn view" href="/joueur/?id=<?= urlencode($playerId) ?>" target="_blank">Voir</a></div>
      <div><button class="save" type="submit">Enregistrer</button></div>
    </form>
    <form method="post" onsubmit="return confirm('Supprimer ce profil de ce compte ?');" style="margin:-8px 0 14px;">
      <input type="hidden" name="id" value="<?= h($id) ?>">
      <input type="hidden" name="action" value="delete">
      <input type="hidden" name="csrf" value="<?= h($csrfToken) ?>">
      <input type="hidden" name="filter_owner_after" value="<?= h($ownerFilter) ?>">
      <button class="delete" type="submit">Supprimer ce prénom</button>
    </form>
  <?php endforeach; ?>
<?php endif; ?>
</div>
</body>
</html>
