<?php
/**
 * bentbox_callback.php
 * Steps 2 + 3: BentBox sends the creator back here after they approve (or cancel).
 *
 * Its full URL must be registered with BentBox and set as BENTBOX_REDIRECT_URI,
 * character for character (same scheme, host and path, no trailing slash).
 *
 *   ?code=…&state=…               approved: check state, exchange the code
 *   ?error=access_denied&state=…   the creator cancelled
 */
require_once __DIR__ . '/bentbox_config.php';

header('Cache-Control: no-store');

$state = (string)($_GET['state'] ?? '');
$code  = (string)($_GET['code'] ?? '');
$error = (string)($_GET['error'] ?? '');

$ok = false;
$message = '';

if (!bb_check_state($state)) {
    // Stale tab, a reused link, or a forged request. Never exchange the code.
    $message = 'This sign-in link has expired or was already used. Please try connecting again.';
} elseif ($error === 'access_denied') {
    $message = 'You cancelled the connection, so nothing was changed. You can connect any time.';
} elseif ($error !== '' || $code === '') {
    $message = 'BentBox didn\'t complete the connection. Please try again.';
} else {
    $r = bb_exchange_code($code);   // server-to-server; uses your client_secret
    if ($r['ok']) {
        header('Location: bentbox_upload.php?connected=1');
        exit;
    }
    error_log('BentBox token exchange failed: ' . $r['error']);
    $message = 'We couldn\'t finish connecting your BentBox account. Please try again in a moment.';
}
?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Connect BentBox</title>
    <style>
        body{font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;background:#f1f5f9;color:#0f172a;
             margin:0;padding:60px 20px;line-height:1.6;}
        .card{max-width:520px;margin:0 auto;background:#fff;border-radius:16px;padding:40px 32px;text-align:center;
              box-shadow:0 8px 30px rgba(0,0,0,.06);}
        h1{font-size:1.35rem;margin:0 0 10px;}
        p{color:#64748b;margin:0 0 24px;}
        a.btn{display:inline-block;background:#2563eb;color:#fff;text-decoration:none;padding:12px 24px;
              border-radius:10px;font-weight:700;}
        a.alt{display:block;margin-top:14px;color:#64748b;font-size:.9rem;}
    </style>
</head>
<body>
    <div class="card">
        <h1>BentBox isn't connected</h1>
        <p><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></p>
        <a class="btn" href="bentbox_connect.php">Connect BentBox</a>
        <a class="alt" href="/">Back to the site</a>
    </div>
</body>
</html>
