<?php
/**
 * Steps 2–3 — the redirect target (this file's URL is your BB_REDIRECT_URI).
 * Verify the CSRF state, exchange the code for tokens server-side, store the
 * connection, and show a short confirmation of what came back.
 */
require __DIR__ . '/config.php';
require __DIR__ . '/partials.php';

function fail(string $msg): void {
    bb_head('Connection failed');
    echo '<div class="card"><h2 style="color:#dc2626">✗ Connection failed</h2>'
       . '<p class="hint">' . htmlspecialchars($msg) . '</p>'
       . '<a class="btn" href="index.php">Back to start</a></div>';
    bb_foot();
    exit;
}

// The user denied access, or BentBox returned an error.
if (isset($_GET['error'])) {
    fail(($_GET['error']) . ' — ' . ($_GET['error_description'] ?? ''));
}

// CSRF: the returned state must match the one we set in the cookie.
$state    = $_GET['state'] ?? '';
$expected = $_COOKIE[BB_STATE_COOKIE] ?? '';
if (!$state || !$expected || !hash_equals($expected, $state)) {
    fail('Invalid OAuth state (CSRF check failed). Please start again.');
}
setcookie(BB_STATE_COOKIE, '', bb_cookie_opts(time() - 3600)); // consume it

// Exchange the code for tokens (server-side; the secret stays here).
$code = $_GET['code'] ?? '';
if (!$code) fail('No authorization code was returned.');

$resp = bb_exchange_code($code);
$tok  = $resp['json'] ?? null;
if ($resp['http'] < 200 || $resp['http'] >= 300 || empty($tok['access_token'])) {
    error_log('Token exchange failed (HTTP ' . $resp['http'] . '): ' . $resp['raw']);
    fail($tok['error_description'] ?? 'Token exchange failed.');
}

// Store the connection (encrypted cookie). Nothing sensitive is placed in a URL.
bb_store_connection($tok);

// Confirmation page (educational — shows what the exchange returned, minus secrets).
bb_head('Connected', 'The authorization code was exchanged for an access token.');
?>
<div class="card">
    <h2 style="color:#059669">✓ Connection established</h2>
    <p class="hint">Your server now holds an access token for this BentBox account. Here's what came back (tokens hidden):</p>
    <div class="kv">
        <div class="k">User ID</div>       <div class="v"><?= htmlspecialchars($tok['user_id'] ?? '—') ?></div>
        <div class="k">Scopes granted</div><div class="v"><?= htmlspecialchars(implode(', ', $tok['scopes'] ?? [])) ?></div>
        <div class="k">Token type</div>    <div class="v"><?= htmlspecialchars($tok['token_type'] ?? 'bearer') ?></div>
        <div class="k">Expires in</div>    <div class="v"><?= htmlspecialchars((string)($tok['expires_in'] ?? '—')) ?> s</div>
        <div class="k">access_token</div>  <div class="v">•••••••• (stored encrypted, server-side)</div>
    </div>
    <div style="margin-top:22px;">
        <a class="btn" href="upload.php">Continue to upload →</a>
    </div>
</div>
<?php bb_foot();
