<?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 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 normalizePlayerText(string $value): string {
    $value = trim($value);
    $value = preg_replace('/\s+/u', ' ', $value) ?? $value;
    return mb_strtolower($value, 'UTF-8');
}

function makePlayerId(string $name, string $initials): string {
    $base = normalizePlayerText($name . '-' . $initials);
    $base = preg_replace('/[^a-z0-9\-_]+/i', '-', $base) ?? $base;
    $base = trim($base, '-');
    return 'player_' . ($base !== '' ? $base : bin2hex(random_bytes(4))) . '_' . substr(bin2hex(random_bytes(4)), 0, 6);
}

function mergeValues($target, $source, string $key = '') {
    if ($key === 'id' || $key === 'name' || $key === 'initials' || $key === 'avatar') {
        return ($target !== null && $target !== '') ? $target : $source;
    }

    if (is_numeric($target) && is_numeric($source)) {
        return $target + $source;
    }

    if (is_array($target) && is_array($source)) {
        $isListTarget = array_keys($target) === range(0, count($target) - 1);
        $isListSource = array_keys($source) === range(0, count($source) - 1);

        if ($isListTarget && $isListSource) {
            $merged = $target;
            foreach ($source as $item) {
                if (!in_array($item, $merged, true)) {
                    $merged[] = $item;
                }
            }
            return $merged;
        }

        foreach ($source as $k => $v) {
            $target[$k] = array_key_exists($k, $target)
                ? mergeValues($target[$k], $v, (string)$k)
                : $v;
        }
        return $target;
    }

    return ($target !== null && $target !== '') ? $target : $source;
}

function mergeProfiles(array $targetProfile, array $sourceProfile, string $sourceId): array {
    $merged = mergeValues($targetProfile, $sourceProfile);
    $merged['merged_ids'] = $merged['merged_ids'] ?? [];
    if (!in_array($sourceId, $merged['merged_ids'], true)) {
        $merged['merged_ids'][] = $sourceId;
    }
    return $merged;
}

$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') {
        $name = trim((string)($_POST['new_name'] ?? ''));
        $initials = strtoupper(trim((string)($_POST['new_initials'] ?? '')));
        $avatar = trim((string)($_POST['new_avatar'] ?? ''));

        if ($name === '' || $initials === '') {
            $error = 'Prénom et initiale obligatoires pour créer un profil.';
        } else {
            $alreadyExists = false;
            foreach ($profiles as $profile) {
                if (
                    normalizePlayerText((string)($profile['name'] ?? '')) === normalizePlayerText($name)
                    && normalizePlayerText((string)($profile['initials'] ?? '')) === normalizePlayerText($initials)
                ) {
                    $alreadyExists = true;
                    break;
                }
            }

            if ($alreadyExists) {
                $error = 'Ce profil existe déjà.';
            } else {
                $newId = makePlayerId($name, $initials);
                $profiles[$newId] = [
                    'id' => $newId,
                    'name' => $name,
                    'initials' => $initials,
                    'avatar' => $avatar,
                    'created_at' => date('c'),
                    'updated_at' => date('c'),
                ];
                writeProfiles($profilesFile, $profiles);
                $message = 'Profil créé.';
            }
        }
    }

    if ($action === 'merge') {
        $sourceId = trim((string)($_POST['merge_source_id'] ?? ''));
        $targetId = trim((string)($_POST['merge_target_id'] ?? ''));

        if ($sourceId === '' || $targetId === '' || $sourceId === $targetId) {
            $error = 'Sélection de fusion invalide.';
        } elseif (!isset($profiles[$sourceId]) || !isset($profiles[$targetId])) {
            $error = 'Profil source ou profil destination introuvable.';
        } else {
            $profiles[$targetId] = mergeProfiles($profiles[$targetId], $profiles[$sourceId], $sourceId);
            $profiles[$targetId]['updated_at'] = date('c');
            unset($profiles[$sourceId]);
            writeProfiles($profilesFile, $profiles);
            $message = 'Profils fusionnés. Le profil doublon a été supprimé des suggestions.';
        }
    }

    if ($id !== '' && isset($profiles[$id])) {

        if ($action === 'save') {
            $profiles[$id]['id'] = $profiles[$id]['id'] ?? $id;
            $profiles[$id]['name'] = trim((string)($_POST['name'] ?? ''));
            $profiles[$id]['initials'] = strtoupper(trim((string)($_POST['initials'] ?? '')));
            $profiles[$id]['avatar'] = trim((string)($_POST['avatar'] ?? ''));
            $profiles[$id]['updated_at'] = date('c');

            writeProfiles($profilesFile, $profiles);
            $message = 'Profil modifié.';
        }

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

$profiles = readProfiles($profilesFile);

uasort($profiles, static function(array $a, array $b): int {
    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:1150px;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.4fr .8fr .5fr .7fr auto auto;gap:10px;align-items:center}.createGrid{display:grid;grid-template-columns:1fr .4fr .7fr auto;gap:10px;align-items:end}.mergeGrid{display:grid;grid-template-columns:1fr 1fr 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}.merge{background:#f97316}.delete{background:#dc2626}.view{background:#0891b2}.logout{background:#374151}.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}@media(max-width:850px){.grid,.createGrid,.mergeGrid{grid-template-columns:1fr}}
</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="post" class="card">
  <h2>➕ Créer un profil</h2>
  <input type="hidden" name="action" value="create">
  <input type="hidden" name="csrf" value="<?= h($csrfToken) ?>">
  <div class="createGrid">
    <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 profil créé apparaîtra dans les suggestions du jeu en Classique et en Coop.</div>
</form>

<?php if (count($profiles) >= 2): ?>
<form method="post" class="card" onsubmit="return confirm('Fusionner ces deux profils ? Le profil source sera supprimé et ses données seront ajoutées au profil destination.');">
  <h2>🔀 Fusionner deux profils</h2>
  <input type="hidden" name="action" value="merge">
  <input type="hidden" name="csrf" value="<?= h($csrfToken) ?>">
  <div class="mergeGrid">
    <div>
      <label>Profil doublon à supprimer</label>
      <select name="merge_source_id" required>
        <option value="">Choisir le doublon</option>
        <?php foreach ($profiles as $pid => $p): ?>
          <option value="<?= h($pid) ?>"><?= h(trim(($p['avatar'] ?? '') . ' ' . ($p['name'] ?? '') . ' ' . ($p['initials'] ?? ''))) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label>Profil principal à garder</label>
      <select name="merge_target_id" required>
        <option value="">Choisir le profil principal</option>
        <?php foreach ($profiles as $pid => $p): ?>
          <option value="<?= h($pid) ?>"><?= h(trim(($p['avatar'] ?? '') . ' ' . ($p['name'] ?? '') . ' ' . ($p['initials'] ?? ''))) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div><button class="merge" type="submit">Fusionner</button></div>
  </div>
  <div class="help">Exemple : tu fusionnes “Snadrine C” vers “Sandrine C”. “Snadrine C” disparaît des suggestions.</div>
</form>
<?php endif; ?>

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

<?php if (empty($profiles)): ?>
  <div class="card">Aucun profil joueur enregistré.</div>
<?php else: ?>
  <?php foreach ($profiles as $id => $profile): ?>
    <?php $playerId=(string)($profile['id']??$id); $name=(string)($profile['name']??''); $initials=(string)($profile['initials']??''); $avatar=(string)($profile['avatar']??''); ?>
    <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) ?>">
      <div><strong><?= h(trim($avatar . ' ' . $name . ' ' . $initials)) ?></strong><div class="id"><?= h($playerId) ?></div></div>
      <div><input name="name" value="<?= h($name) ?>" placeholder="Prénom"></div>
      <div><input name="initials" maxlength="2" value="<?= h($initials) ?>" placeholder="C"></div>
      <div><input name="avatar" value="<?= h($avatar) ?>" placeholder="😀 🦊 🦖"></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 ? Attention : uniquement pour les tests.');" 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) ?>">
      <button class="delete" type="submit">Supprimer ce profil test</button>
    </form>
  <?php endforeach; ?>
<?php endif; ?>

</div>
</body>
</html>
