<?php
session_start();
require "db.php";

/* ================= CONFIG ================= */
$client_id = "1500663655707185182";
$client_secret = "fH0GJsHCSnDQZ6yHUEPbnRBqJUxTtvmr";
$redirect_uri = "https://rewire.kryptondev.com/Auth/discord_callback.php";

/* ADMIN ROLE CHECK CONFIG */
$guild_id = "1500600843450323076"; 
$admin_role_id = "1500619070800662798";
$bot_token = "MTUwMDY2MzY1NTcwNzE4NTE4Mg.GlAPQV.e1iQe6n8HWFIpb1P8bzSJYjR1oIKoaTIr2Z8A0"; 

/* ================= STATE CHECK ================= */
if (
    !isset($_GET["state"], $_SESSION["discord_state"]) ||
    $_GET["state"] !== $_SESSION["discord_state"]
) {
    die("Invalid state.");
}

/* ================= GET TOKEN ================= */
$code = $_GET["code"] ?? "";
if (!$code) die("Missing code.");

$ch = curl_init("https://discord.com/api/oauth2/token");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS => http_build_query([
        "client_id" => $client_id,
        "client_secret" => $client_secret,
        "grant_type" => "authorization_code",
        "code" => $code,
        "redirect_uri" => $redirect_uri
    ]),
    CURLOPT_HTTPHEADER => [
        "Content-Type: application/x-www-form-urlencoded"
    ]
]);

$tokenResponse = json_decode(curl_exec($ch), true);
curl_close($ch);

$accessToken = $tokenResponse["access_token"] ?? null;
if (!$accessToken) die("Discord token failed.");

/* ================= GET USER ================= */
$ch = curl_init("https://discord.com/api/users/@me");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $accessToken"
    ]
]);

$discordUser = json_decode(curl_exec($ch), true);
curl_close($ch);

$discordId = $discordUser["id"];
$username = $discordUser["username"];
$email = $discordUser["email"] ?? null;
$avatar = $discordUser["avatar"] ?? null;

/* ================= ADMIN ROLE CHECK ================= */
$isAdmin = false;

$ch = curl_init("https://discord.com/api/guilds/$guild_id/members/$discordId");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bot $bot_token"
    ]
]);

$memberResponse = json_decode(curl_exec($ch), true);
curl_close($ch);

if (isset($memberResponse["roles"]) && in_array($admin_role_id, $memberResponse["roles"])) {
    $isAdmin = true;
}

/* ================= DATABASE ================= */
$stmt = $pdo->prepare("SELECT * FROM users WHERE discord_id = ?");
$stmt->execute([$discordId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    $stmt = $pdo->prepare("
        INSERT INTO users (username, email, discord_id, avatar, provider)
        VALUES (?, ?, ?, ?, 'discord')
    ");
    $stmt->execute([$username, $email, $discordId, $avatar]);

    $userId = $pdo->lastInsertId();
} else {
    $userId = $user["id"];
    $username = $user["username"];
    $email = $user["email"];
    $avatar = $user["avatar"];
}

/* ================= SESSION ================= */
$_SESSION["user"] = [
    "id" => $userId,
    "username" => $username,
    "email" => $email,
    "discord_id" => $discordId,
    "avatar" => $avatar,
    "is_admin" => $isAdmin
];

/* ================= REDIRECT ================= */
header("Location: ../Index.php");
exit;