<?php
session_start();
require_once __DIR__ . '/db/config.php';
$pdo = db();

if (isset($_SESSION['user_id'])) {
    $userId = $_SESSION['user_id'];
    $pdo->query("UPDATE users SET role = 'admin' WHERE id = " . $userId);
    $_SESSION['role'] = 'admin';
    
    $username = $_SESSION['username'] ?? 'User';
    
    echo "<!DOCTYPE html>
    <html lang='zh-CN'>
    <head>
        <meta charset='UTF-8'>
        <title>Account Rescued</title>
        <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
    </head>
    <body class='bg-light d-flex align-items-center justify-content-center' style='height: 100vh;'>
        <div class='card shadow p-5 text-center' style='max-width: 500px;'>
            <h1 class='text-success mb-4'>✅ 成功修复!</h1>
            <p class='lead mb-4'>您的账号 (<strong>" . htmlspecialchars($username) . "</strong>) 已成功提升为<strong>管理员</strong>权限。</p>
            <a href='admin.php' class='btn btn-primary btn-lg px-5'>进入后台</a>
        </div>
    </body>
    </html>";
} else {
    // If not logged in, just make the first found user admin and log them in
    $stmt = $pdo->query("SELECT * FROM users ORDER BY id ASC LIMIT 1");
    $user = $stmt->fetch();
    
    if ($user) {
        $pdo->query("UPDATE users SET role = 'admin' WHERE id = " . $user['id']);
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['role'] = 'admin';
        
        header('Location: rescue.php');
        exit;
    } else {
        echo "<h1>Rescue failed</h1><p>No users found in database. Please register first.</p><p><a href='index.php'>Go to Home</a></p>";
    }
}