<?php
session_start();
$config = require 'config.php';
require 'db.php'; // Stelle sicher, dass hier die $dbhandle-Verbindung aufgebaut wird

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 = array_keys($role_names);

// 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']);

// Server-Nickname oder globalen Username nehmen
$nickname = $guild_member['nick'] ?? $user['username'];

// ✅ Prüfen ob User schon in der Datenbank existiert
$stmt = $dbhandle->prepare("SELECT id FROM users WHERE discord_id = ?");
$stmt->bind_param("s", $user['id']);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    // User existiert → hole interne User-ID
    $stmt->bind_result($user_id);
    $stmt->fetch();
} else {
    // User existiert nicht → neuen Eintrag erstellen
    $insert = $dbhandle->prepare("INSERT INTO users (discord_id, discord_name) VALUES (?, ?)");
    $insert->bind_param("ss", $user['id'], $nickname);
    $insert->execute();
    $user_id = $insert->insert_id;
    $insert->close();
}

$stmt->close();

// Session setzen
$_SESSION['user'] = [
    'id' => $user_id, // interne DB-ID
    'discord_id' => $user['id'],
    'username' => $user['username'],
    'discriminator' => $user['discriminator'],
    'avatar' => $user['avatar'],
    'hasRole' => $hasRole,
    'nickname' => $nickname, // Server-Nickname
    'main_role' => $main_role_name
];

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