<?php
$file = __DIR__ . "/messages.txt";
$upload_dir = __DIR__ . '/uploads/';

if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0755, true); // 确保 uploads 文件夹存在
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['clear'])) {
        file_put_contents($file, "");
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    } else {
        $msg = trim($_POST['message'] ?? '');
        $upload_info = '';

        if (isset($_FILES['upload_file']) && $_FILES['upload_file']['error'] === UPLOAD_ERR_OK) {
            $filename = basename($_FILES['upload_file']['name']);
            $target_file = $upload_dir . $filename;

            // 防止重名
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            $name = pathinfo($filename, PATHINFO_FILENAME);
            $i = 1;
            while (file_exists($target_file)) {
                $filename = $name . "_" . $i . "." . $ext;
                $target_file = $upload_dir . $filename;
                $i++;
            }

            if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $target_file)) {
                $file_url = 'uploads/' . $filename;
                if (preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $filename)) {
                    $upload_info = '<br><img src="' . htmlspecialchars($file_url) . '" alt="上传图片" style="max-width:100%;border:1px solid #ccc;margin-top:6px;">';
                } else {
                    $upload_info = '<br><a href="' . htmlspecialchars($file_url) . '" download>📎 下载文件：' . htmlspecialchars($filename) . '</a>';
                }
            }
        }

        if ($msg !== '' || $upload_info !== '') {
            $msg = htmlspecialchars($msg) . $upload_info;
            $line = "[" . date("Y-m-d H:i:s") . "]\n" . $msg . "\n---\n";
            file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
        }

        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
}

$messages = file_exists($file) ? file_get_contents($file) : "";
$blocks = array_filter(explode("---", $messages));
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简易聊天室</title>
<style>
body { font-family: Arial, sans-serif; margin:15px; background:#f4f4f4; }
h2 { text-align:center; }
#chat-box {
    border:1px solid #ccc;
    padding:10px;
    height:60vh;
    overflow-y:scroll;
    background:#fff;
    word-wrap:break-word;
    border-radius:8px;
}
.message {
    margin-bottom:12px;
    padding-bottom:8px;
    border-bottom:1px dashed #ddd;
}
.time {
    font-size:14px;
    color:#555;
}
.copy-btn {
    margin-left:8px;
    font-size:12px;
    padding:2px 6px;
    border:1px solid #999;
    border-radius:4px;
    cursor:pointer;
    background:#f1f1f1;
}
.copy-btn:hover { background:#ddd; }
.text {
    margin-top:4px;
    font-size:16px;
}
textarea {
    width:100%;
    height:80px;
    margin-top:10px;
    padding:8px;
    border:1px solid #ccc;
    border-radius:6px;
    font-size:16px;
    box-sizing:border-box;
    resize:vertical;
}
input[type="file"] {
    margin-top:10px;
    font-size:14px;
}
button {
    padding:10px 15px;
    margin-top:10px;
    font-size:16px;
    border:none;
    border-radius:6px;
    cursor:pointer;
}
button[type="submit"]:first-of-type {
    background:#4CAF50;
    color:white;
    width:48%;
}
button[name="clear"] {
    background:#f44336;
    color:white;
    width:48%;
}
.form-buttons {
    display:flex;
    justify-content:space-between;
    gap:4%;
}
img {
    max-width:100%;
    border:1px solid #ccc;
    margin-top:6px;
    border-radius:4px;
}
</style>
</head>
<body>
<h2>📱 简易聊天室</h2>

<div id="chat-box">
<?php foreach ($blocks as $block): 
    $lines = array_filter(explode("\n", trim($block)));
    if (count($lines) >= 2): 
        $time = $lines[0];
        $msg  = implode("\n", array_slice($lines, 1));
?>
    <div class="message">
        <div class="time">
            <?= htmlspecialchars($time) ?>
            <button class="copy-btn" data-text="<?= htmlspecialchars(strip_tags($msg)) ?>">复制</button>
        </div>
        <div class="text"><?= $msg ?></div>
    </div>
<?php endif; endforeach; ?>
</div>

<form method="post" action="" enctype="multipart/form-data">
  <textarea name="message" placeholder="输入消息，支持多行代码或文件说明"></textarea>
  <input type="file" name="upload_file" accept="image/*,.pdf,.txt,.zip,.rar,.doc,.docx,.xls,.xlsx">
  <div class="form-buttons">
    <button type="submit">发送</button>
    <button type="submit" name="clear" value="1" onclick="return confirm('确定要清空所有记录吗？')">清空记录</button>
  </div>
</form>

<script>
function copyText(text, btn) {
    const ta = document.createElement('textarea');
    ta.value = text;
    ta.style.position = 'fixed';
    ta.style.opacity = '0';
    document.body.appendChild(ta);
    ta.focus();
    ta.select();
    let ok = false;
    try {
        ok = document.execCommand('copy');
    } catch (e) {
        console.warn(e);
    }
    document.body.removeChild(ta);
    if (ok) {
        alert('已复制');
    } else {
        alert('复制失败，请手动选择复制');
    }
}
document.querySelectorAll('.copy-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        const text = btn.getAttribute('data-text');
        copyText(text, btn);
    });
});
</script>
</body>
</html>
