<?php
/**
 * 登录查看文档系统 - 单文件版 (PHP + SQLite)
 * 
 * 功能：注册、登录、查看受保护的文档（显示“今天有太阳”）
 * 数据库：自动创建 SQLite 文件 database.sqlite，无需手动导入
 */

session_start();
date_default_timezone_set('PRC');
error_reporting(E_ALL);
ini_set('display_errors', 1);

define('DB_FILE', __DIR__ . DIRECTORY_SEPARATOR . 'database.sqlite');
define('APP_NAME', '简单文档系统');

// 初始化数据库
try {
    $pdo = new PDO('sqlite:' . DB_FILE);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    $pdo->exec("CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username VARCHAR(50) NOT NULL UNIQUE,
        password VARCHAR(255) NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");
} catch (PDOException $e) {
    die('数据库初始化失败: ' . $e->getMessage());
}

// 处理动作
$action = $_GET['action'] ?? 'default';
$error = '';
$success = '';

// 注销
if ($action === 'logout') {
    $_SESSION = array();
    session_destroy();
    header('Location: ?action=default');
    exit;
}

// 登录处理
if ($action === 'login' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if (empty($username) || empty($password)) {
        $error = '用户名和密码不能为空';
    } else {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            header('Location: ?action=document');
            exit;
        } else {
            $error = '用户名或密码错误';
        }
    }
    $action = 'default';
}

// 注册处理
if ($action === 'register' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';

    if (empty($username) || empty($password) || empty($confirm)) {
        $error = '所有字段都必须填写';
    } elseif ($password !== $confirm) {
        $error = '两次输入的密码不一致';
    } elseif (strlen($password) < 3) {
        $error = '密码至少需要3个字符';
    } else {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
        $stmt->execute([$username]);
        if ($stmt->fetch()) {
            $error = '用户名已存在';
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
            $stmt->execute([$username, $hash]);
            $success = '注册成功！请登录。';
            $action = 'default';
        }
    }
}

// 文档页面检查登录
if ($action === 'document' && !isset($_SESSION['user_id'])) {
    header('Location: ?action=default&need_login=1');
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo APP_NAME; ?></title>
    <style>
        * { box-sizing: border-box; font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; }
        body { background: #f5f7fa; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; padding: 20px; }
        .container { background: white; border-radius: 16px; box-shadow: 0 10px 25px rgba(0,0,0,0.05); width: 100%; max-width: 480px; padding: 30px; }
        h1 { font-size: 28px; font-weight: 600; color: #1e293b; margin-top: 0; margin-bottom: 8px; }
        .subtitle { color: #64748b; margin-bottom: 24px; font-size: 14px; border-bottom: 1px solid #e2e8f0; padding-bottom: 16px; }
        .form-group { margin-bottom: 20px; }
        label { display: block; font-weight: 500; font-size: 14px; color: #334155; margin-bottom: 6px; }
        input[type="text"], input[type="password"] { width: 100%; padding: 12px 16px; border: 1px solid #cbd5e1; border-radius: 12px; font-size: 16px; transition: 0.2s; }
        input:focus { outline: none; border-color: #6366f1; box-shadow: 0 0 0 3px rgba(99,102,241,0.2); }
        .btn { background: #6366f1; color: white; border: none; padding: 12px 20px; border-radius: 40px; font-size: 16px; font-weight: 500; cursor: pointer; width: 100%; transition: 0.2s; }
        .btn:hover { background: #4f52e0; transform: translateY(-1px); }
        .btn-outline { background: white; color: #334155; border: 1px solid #cbd5e1; }
        .btn-outline:hover { background: #f8fafc; transform: none; }
        .message { background: #fee2e2; color: #b91c1c; padding: 12px 16px; border-radius: 12px; margin-bottom: 24px; font-size: 14px; border-left: 4px solid #ef4444; }
        .success { background: #dcfce7; color: #166534; border-left-color: #22c55e; }
        .info { background: #e0f2fe; color: #075985; border-left-color: #0ea5e9; }
        .nav-links { display: flex; gap: 16px; justify-content: center; margin-top: 24px; }
        .nav-links a { color: #6366f1; text-decoration: none; font-size: 14px; }
        .nav-links a:hover { text-decoration: underline; }
        .doc-box { background: #f8fafc; border-radius: 24px; padding: 40px; text-align: center; border: 1px dashed #94a3b8; }
        .doc-text { font-size: 48px; font-weight: 600; color: #0f172a; margin: 20px 0; }
        .doc-note { color: #475569; margin-top: 20px; }
        hr { border: none; border-top: 1px solid #e2e8f0; margin: 24px 0; }
        .switch-form { text-align: center; margin-top: 20px; }
        .switch-form a { color: #6366f1; font-weight: 500; text-decoration: none; }
    </style>
</head>
<body>
    <div class="container">
        <?php if ($action === 'document' && isset($_SESSION['user_id'])): ?>
            <h1>📄 文档</h1>
            <div class="subtitle">欢迎回来，<?php echo htmlspecialchars($_SESSION['username']); ?></div>
            <div class="doc-box">
                <div style="font-size: 24px;">🌞</div>
                <div class="doc-text">今天有太阳</div>
                <div class="doc-note">—— 这是您登录后才能看到的内容。</div>
            </div>
            <div class="nav-links">
                <a href="?action=logout">🚪 注销登录</a>
                <a href="?action=document">🔄 刷新</a>
            </div>

        <?php elseif ($action === 'register'): ?>
            <h1>📝 注册</h1>
            <div class="subtitle">创建新账户，轻松查阅文档</div>
            <?php if ($error): ?><div class="message"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>
            <?php if ($success): ?><div class="success"><?php echo htmlspecialchars($success); ?></div><?php endif; ?>
            <form method="post" action="?action=register">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>" required>
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" required>
                </div>
                <div class="form-group">
                    <label for="confirm_password">确认密码</label>
                    <input type="password" id="confirm_password" name="confirm_password" required>
                </div>
                <button type="submit" class="btn">注册</button>
            </form>
            <hr>
            <div class="switch-form">已有账户？<a href="?action=default">立即登录</a></div>

        <?php else: ?>
            <h1>🔐 登录</h1>
            <div class="subtitle">登录后即可查看专属文档</div>
            <?php if (isset($_GET['need_login'])): ?><div class="message">请先登录后查看文档</div><?php endif; ?>
            <?php if ($error): ?><div class="message"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>
            <?php if ($success): ?><div class="success"><?php echo htmlspecialchars($success); ?></div><?php endif; ?>
            <form method="post" action="?action=login">
                <div class="form-group">
                    <label for="login_username">用户名</label>
                    <input type="text" id="login_username" name="username" value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>" required>
                </div>
                <div class="form-group">
                    <label for="login_password">密码</label>
                    <input type="password" id="login_password" name="password" required>
                </div>
                <button type="submit" class="btn">登录</button>
            </form>
            <hr>
            <div class="switch-form">还没有账户？<a href="?action=register">立即注册</a></div>
            <div style="margin-top: 20px; text-align: center; color: #94a3b8; font-size: 13px;">⚡ 简易文档系统 · 演示</div>
        <?php endif; ?>
    </div>
</body>
</html>