<?php
/**
 * 创建帖子页面
 */
require_once __DIR__ . '/includes/functions.php';

// 检查是否登录
if (!isLoggedIn()) {
    setFlashMessage('error', '请先登录后再发帖');
    redirect(SITE_URL . '/login.php');
}

$error = '';
$success = '';

// 获取板块列表
$categories = db()->query("SELECT id, name FROM categories WHERE status = 1 ORDER BY sort_order ASC");

// 默认选中的板块
$defaultCategory = isset($_GET['category']) ? intval($_GET['category']) : 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $categoryId = intval($_POST['category_id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $csrfToken = $_POST['csrf_token'] ?? '';

    // 验证 CSRF Token
    if (!validateCsrfToken($csrfToken)) {
        $error = '安全验证失败，请刷新页面重试';
    }
    // 验证板块
    elseif ($categoryId <= 0) {
        $error = '请选择板块';
    }
    // 验证标题
    elseif (empty($title) || strlen($title) < 5 || strlen($title) > 200) {
        $error = '标题长度必须在 5-200 个字符之间';
    }
    // 验证内容
    elseif (empty($content) || strlen(strip_tags($content)) < 10) {
        $error = '内容长度至少为 10 个字符';
    } else {
        // 检查板块是否存在
        $category = db()->queryOne("SELECT id FROM categories WHERE id = ? AND status = 1", [$categoryId]);
        if (!$category) {
            $error = '所选板块不存在';
        } else {
            $user = getCurrentUser();

            // 创建帖子
            $postId = db()->insert(
                "INSERT INTO posts (user_id, category_id, title, content) VALUES (?, ?, ?, ?)",
                [$user['id'], $categoryId, $title, $content]
            );

            if ($postId) {
                // 更新用户发帖数
                db()->execute(
                    "UPDATE users SET post_count = post_count + 1 WHERE id = ?",
                    [$user['id']]
                );

                // 更新板块帖子数
                db()->execute(
                    "UPDATE categories SET post_count = post_count + 1 WHERE id = ?",
                    [$categoryId]
                );

                setFlashMessage('success', '帖子发布成功！');
                redirect(SITE_URL . '/post.php?id=' . $postId);
            } else {
                $error = '发布失败，请稍后重试';
            }
        }
    }
}

$pageTitle = '发布帖子';
include __DIR__ . '/templates/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2><i class="fas fa-edit"></i> 发布新帖子</h2>
    </div>
    <div class="card-body">
        <?php if ($error): ?>
            <div class="alert alert-error"><?php echo e($error); ?></div>
        <?php endif; ?>

        <form method="POST" action="" id="post-form">
            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">

            <div class="form-group">
                <label for="category_id">选择板块</label>
                <select id="category_id" name="category_id" class="form-control" required>
                    <option value="">请选择板块</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo $cat['id']; ?>" <?php echo $defaultCategory == $cat['id'] ? 'selected' : ''; ?>>
                            <?php echo e($cat['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label for="title">标题</label>
                <input type="text" id="title" name="title" class="form-control" required
                       placeholder="请输入标题（5-200个字符）"
                       value="<?php echo e($_POST['title'] ?? ''); ?>">
            </div>

            <div class="form-group">
                <label>内容</label>
                <div id="editor-container" style="height: 300px; border: 1px solid #ddd; border-radius: 8px;"></div>
                <input type="hidden" name="content" id="content-input">
                <div id="content-error" class="form-error" style="color: #e74c3c; font-size: 14px; margin-top: 5px; display: none;">请输入帖子内容（至少10个字符）</div>
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-primary btn-lg" id="submit-btn">
                    <i class="fas fa-paper-plane"></i> 发布帖子
                </button>
                <a href="index.php" class="btn btn-outline" style="margin-left: 10px;">取消</a>
            </div>
        </form>

        <!-- 富文本编辑器样式 -->
        <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
        <script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
        <script>
            // 初始化 Quill 编辑器
            var quill = new Quill('#editor-container', {
                theme: 'snow',
                placeholder: '请输入帖子内容（至少10个字符）...',
                modules: {
                    toolbar: [
                        [{ 'header': [1, 2, 3, false] }],
                        ['bold', 'italic', 'underline', 'strike'],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        ['link', 'image'],
                        ['clean']
                    ]
                }
            });

            // 表单提交处理
            document.getElementById('post-form').addEventListener('submit', function(e) {
                e.preventDefault();
                
                var htmlContent = quill.root.innerHTML;
                var contentInput = document.getElementById('content-input');
                var errorDiv = document.getElementById('content-error');
                
                // 获取纯文本长度
                var tempDiv = document.createElement('div');
                tempDiv.innerHTML = htmlContent;
                var plainText = tempDiv.textContent || tempDiv.innerText || '';
                plainText = plainText.replace(/\s+/g, '');
                
                if (plainText.length < 10) {
                    errorDiv.style.display = 'block';
                    return false;
                }
                
                errorDiv.style.display = 'none';
                contentInput.value = htmlContent;
                
                // 使用 AJAX 提交表单
                var formData = new FormData(this);
                
                fetch('', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.text())
                .then(html => {
                    // 如果返回的是 HTML，说明有错误，刷新页面显示错误信息
                    document.open();
                    document.write(html);
                    document.close();
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('提交失败，请重试');
                });
            });
        </script>
    </div>
</div>

<?php include __DIR__ . '/templates/footer.php'; ?>
