<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();

require_once 'config.php';  // must define CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, USER_AGENT

function debug_log($msg) {
    error_log("[DEBUG] " . $msg);
}

$code = $_GET['code'] ?? '';
$state = $_GET['state'] ?? '';

$tokenResult = null;
$errorMessage = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $code = trim($_POST['code'] ?? '');
    $state = trim($_POST['state'] ?? '');

    if ($code === '' || $state === '') {
        $errorMessage = "Bitte sowohl Code als auch State eingeben.";
    } else {
        if (!isset($_SESSION['oauth_state']) || $state !== $_SESSION['oauth_state']) {
            $errorMessage = "State-Parameter stimmt nicht mit Session überein.";
        } else {
            $postData = http_build_query([
                'grant_type'   => 'authorization_code',
                'code'         => $code,
                'redirect_uri' => REDIRECT_URI,
            ]);

            $headers = [
                "Authorization: Basic " . base64_encode(CLIENT_ID . ":" . CLIENT_SECRET),
                "Content-Type: application/x-www-form-urlencoded",
                "User-Agent: " . USER_AGENT,
            ];

            $context = stream_context_create([
                'http' => [
                    'method'  => 'POST',
                    'header'  => implode("\r\n", $headers),
                    'content' => $postData,
                    'ignore_errors' => true,
                ]
            ]);

            $response = file_get_contents('https://www.reddit.com/api/v1/access_token', false, $context);

            if ($response === false) {
                $errorMessage = "Fehler beim Zugriff auf den Token-Endpunkt.";
            } else {
                $tokenData = json_decode($response, true);
                if (!isset($tokenData['access_token'])) {
                    $errorMessage = "Kein Access Token erhalten: " . htmlspecialchars($response);
                } else {
                    $tokenResult = $tokenData;
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>OAuth Access Token Generator</title>
</head>
<body>
<h2>OAuth Access Token manuell abrufen</h2>
<form method="POST" action="">
    <label>Code:</label><br>
    <input type="text" name="code" size="80" value="<?php echo htmlspecialchars($code); ?>" required><br><br>

    <label>State:</label><br>
    <input type="text" name="state" size="80" value="<?php echo htmlspecialchars($state); ?>" required><br><br>

    <input type="submit" value="Access Token anfordern">
</form>

<?php if ($errorMessage): ?>
    <h3 style="color:red;">Fehler:</h3>
    <pre><?php echo $errorMessage; ?></pre>
<?php endif; ?>

<?php if ($tokenResult): ?>
    <h3>Erfolgreich erhaltenes Access Token:</h3>
    <pre><?php echo htmlspecialchars(json_encode($tokenResult, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); ?></pre>
<?php endif; ?>

</body>
</html>
