<?php
session_start();
$config = require 'config.php';

if (!isset($_GET['code'])) {
    die('Keine Autorisierungscode empfangen');
}

// Token holen
$ch = curl_init('https://discord.com/api/oauth2/token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'client_id' => $config['client_id'],
    'client_secret' => $config['client_secret'],
    'grant_type' => 'authorization_code',
    'code' => $_GET['code'],
    'redirect_uri' => $config['redirect_uri'],
    'scope' => 'identify guilds.members.read'
]));
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);

if (!isset($data['access_token'])) {
    die('Fehler beim Token-Austausch');
}

$access_token = $data['access_token'];

// API Request Funktion
function apiRequest($url, $token) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $token"
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

// User-Daten holen
$user = apiRequest('https://discord.com/api/users/@me', $access_token);

// Mitgliedschaft prüfen
$guild_member = apiRequest("https://discord.com/api/users/@me/guilds/{$config['guild_id']}/member", $access_token);

if (isset($guild_member['message'])) {
    die('Du bist nicht auf dem Discord-Server.');
}

// 🆕 Rollen-ID → Rollenname Mapping
$role_names = [
    "1350944151381999666" => "Geschäftsführung",
    "1350944244843544709" => "Stv. Geschäftsführung",
    "1350943536891297914" => "Leitungsebene",
    "1350945302395224206" => "Werkstattleiter",
    "1350945473338544138" => "Ausbilder",
    "1350945530519224320" => "Meister",
    "1350945581194809376" => "Tuner",
    "1350945688560861285" => "Stift"

];

// 🆕 Rollen-Rang (höchste zuerst)
$role_order = [
    "1350944151381999666",
    "1350944244843544709",
    "1350943536891297914",
    "1350945302395224206",
    "1350945473338544138",
    "1350945530519224320",
    "1350945581194809376",
    "1350945688560861285"
];

// 🆕 Höchste Rolle finden
$main_role_name = "Mitglied"; // Fallback
foreach ($role_order as $role_id) {
    if (in_array($role_id, $guild_member['roles'])) {
        $main_role_name = $role_names[$role_id];
        break; // erste gefundene Rolle nehmen
    }
}

// Rollen prüfen (ob die Person die „Adminrolle“ hat)
$hasRole = in_array($config['role_id'], $guild_member['roles']);

// Session setzen
$_SESSION['user'] = [
    'id' => $user['id'],
    'username' => $user['username'],
    'discriminator' => $user['discriminator'],
    'avatar' => $user['avatar'],
    'hasRole' => $hasRole,
    'nickname' => $guild_member['nick'] ?? $user['username'], // Nick wenn vorhanden
    'main_role' => $main_role_name // 🆕 höchster Rollenname
];

header('Location: index.php');
exit;
?>
