<?php
// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $filename = isset($_POST['filename']) ? trim($_POST['filename']) : '';
    $content = isset($_POST['content']) ? $_POST['content'] : '';
    
    if (!empty($filename)) {
        if (!preg_match('/\.txt$/i', $filename)) {
            $filename .= '.txt';
        }
        file_put_contents($filename, $content);
    }
}

// 处理文件查看请求
$currentContent = '';
$currentFilename = '';
if (isset($_GET['file'])) {
    $fileToView = $_GET['file'];
    if (file_exists($fileToView) && is_file($fileToView)) {
        $currentContent = file_get_contents($fileToView);
        $currentFilename = basename($fileToView);
    }
}

// 处理文件下载请求
if (isset($_GET['download'])) {
    $fileToDownload = $_GET['download'];
    if (file_exists($fileToDownload) && is_file($fileToDownload)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($fileToDownload).'"');
        header('Content-Length: ' . filesize($fileToDownload));
        readfile($fileToDownload);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP记事本</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
        textarea { width: 100%; height: 300px; margin-bottom: 10px; }
        input[type="text"] { width: 100%; padding: 8px; margin-bottom: 10px; }
        button { padding: 8px 15px; background-color: #4CAF50; color: white; border: none; cursor: pointer; }
        .file-list { margin-top: 20px; border-top: 1px solid #ddd; padding-top: 20px; }
        .file-item { margin: 5px 0; padding: 5px; }
        .file-item a { color: #0066cc; text-decoration: none; margin-right: 10px; }
        .file-item a:hover { text-decoration: underline; }
    </style>
</head>
<body>
    <h1>PHP记事本</h1>
    <form method="POST">
        <textarea name="content" placeholder="在这里输入内容..."><?php echo htmlspecialchars($currentContent); ?></textarea>
        <input type="text" name="filename" placeholder="输入文件名（不带扩展名会自动添加.txt）" value="<?php echo htmlspecialchars($currentFilename); ?>">
        <button type="submit">保存</button>
    </form>
    
    <div class="file-list">
        <h2>文件列表</h2>
        <?php
        $files = scandir(__DIR__);
        foreach ($files as $file) {
            if ($file !== '.' && $file !== '..' && is_file($file) && $file !== basename(__FILE__)) {
                echo '<div class="file-item">';
                echo htmlspecialchars($file);
                echo ' <a href="?file='.urlencode($file).'">编辑</a>';
                echo ' <a href="?download='.urlencode($file).'">下载</a>';
                echo '</div>';
            }
        }
        ?>
    </div>
</body>
</html>