<?php
/**
 * forum-new.php - 发布新帖子（独立页面，使用 Quill 富媒体编辑器）
 */
$pageTitle = '发布新帖子';
require_once __DIR__ . '/config.php';
requireLogin();

$pdo = getDB();
$error = '';
$success = false;

// Auto-migration: ensure forum_posts table has all required columns
try {
    $pdo->exec("ALTER TABLE `forum_posts` ADD COLUMN `category` VARCHAR(50) NOT NULL DEFAULT 'general' AFTER `content`");
} catch (PDOException $e) { /* column already exists, ignore */ }
try {
    $pdo->exec("ALTER TABLE `forum_posts` ADD COLUMN `views` INT NOT NULL DEFAULT 0 AFTER `category`");
} catch (PDOException $e) { /* ignore */ }
try {
    $pdo->exec("ALTER TABLE `forum_posts` ADD COLUMN `reply_count` INT NOT NULL DEFAULT 0 AFTER `views`");
} catch (PDOException $e) { /* ignore */ }
try {
    $pdo->exec("ALTER TABLE `forum_posts` ADD COLUMN `is_pinned` TINYINT(1) NOT NULL DEFAULT 0 AFTER `reply_count`");
} catch (PDOException $e) { /* ignore */ }
try {
    $pdo->exec("ALTER TABLE `forum_posts` ADD COLUMN `is_locked` TINYINT(1) NOT NULL DEFAULT 0 AFTER `is_pinned`");
} catch (PDOException $e) { /* ignore */ }
try {
    $pdo->exec("ALTER TABLE `forum_posts` ADD COLUMN `updated_at` DATETIME DEFAULT NULL AFTER `created_at`");
} catch (PDOException $e) { /* ignore */ }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title   = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $category= trim($_POST['category'] ?? '');

    if (strlen($title) < 2) {
        $error = '标题至少需要2个字符';
    } elseif (strlen($title) > 200) {
        $error = '标题不能超过200个字符';
    } elseif (empty($content) || $content === '<p><br></p>') {
        $error = '帖子内容不能为空';
    } else {
        $stmt = $pdo->prepare("INSERT INTO forum_posts (user_id, title, content, category, created_at) VALUES (?,?,?,?,NOW())");
        $stmt->execute([$_SESSION['user_id'], $title, $content, $category]);
        $post_id = $pdo->lastInsertId();
        header('Location: /forum-post.php?id=' . $post_id . '&new=1');
        exit;
    }
}

require_once __DIR__ . '/includes/header.php';
?>

<style>
.ql-container { font-size: 15px; }
.ql-editor { min-height: 320px; max-height: 600px; overflow-y: auto; }
.ql-toolbar.ql-snow { border-radius: 8px 8px 0 0; background: #f8f9fa; }
.ql-container.ql-snow { border-radius: 0 0 8px 8px; }
.category-pills .btn { border-radius: 20px; font-size: 0.85rem; }
.category-pills .btn.active { background: var(--bs-primary); color: #fff; border-color: var(--bs-primary); }
</style>

<div class="container py-4">
    <div class="row">
        <!-- 左侧导航条（与 user/cards.php 完全一致） -->
        <div class="col-md-3">
            <?php include __DIR__ . '/user/sidebar.php'; ?>
        </div>

        <!-- 右侧主内容 -->
        <div class="col-md-9">
            <div class="d-flex align-items-center mb-4 gap-3">
                <a href="/forum.php" class="btn btn-outline-secondary btn-sm">
                    <i class="fas fa-arrow-left me-1"></i>返回讨论区
                </a>
                <h4 class="fw-bold mb-0"><i class="fas fa-pen-alt me-2 text-primary"></i>发布新帖子</h4>
            </div>

            <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle me-2"></i><?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php endif; ?>

            <div class="card border-0 shadow-sm">
                <div class="card-body p-4">
                    <form method="POST" id="postForm">
                        <!-- Title -->
                        <div class="mb-4">
                            <label class="form-label fw-bold fs-6">帖子标题 <span class="text-danger">*</span></label>
                            <input type="text" name="title" id="postTitle" class="form-control form-control-lg"
                                   placeholder="请输入一个清晰的标题，让大家一眼看懂你的问题或分享..."
                                   value="<?php echo htmlspecialchars($_POST['title'] ?? ''); ?>"
                                   maxlength="200" required>
                            <div class="text-end text-muted small mt-1"><span id="titleCount">0</span>/200</div>
                        </div>

                        <!-- Category -->
                        <div class="mb-4">
                            <label class="form-label fw-bold fs-6">分类</label>
                            <div class="category-pills d-flex flex-wrap gap-2" id="categoryPills">
                                <?php
                                $cats = ['general'=>'💬 综合讨论','esim'=>'📱 eSIM 使用','phone'=>'📞 电话号码','device'=>'🔧 设备问题','help'=>'🆘 求助','share'=>'🎉 经验分享'];
                                $sel = $_POST['category'] ?? 'general';
                                foreach ($cats as $k => $v):
                                ?>
                                <button type="button" class="btn btn-outline-secondary category-btn <?php echo $sel===$k?'active':''; ?>"
                                        data-cat="<?php echo $k; ?>"><?php echo $v; ?></button>
                                <?php endforeach; ?>
                            </div>
                            <input type="hidden" name="category" id="categoryInput" value="<?php echo htmlspecialchars($sel); ?>">
                        </div>

                        <!-- Content - Quill Editor -->
                        <div class="mb-4">
                            <label class="form-label fw-bold fs-6">帖子内容 <span class="text-danger">*</span></label>
                            <div id="quillEditor"><?php echo $_POST['content'] ?? ''; ?></div>
                            <input type="hidden" name="content" id="contentInput">
                            <div class="text-muted small mt-1">
                                <i class="fas fa-image me-1"></i>支持图片上传（点击工具栏图片按钮）&nbsp;|&nbsp;
                                <i class="fas fa-code me-1"></i>支持代码块 &nbsp;|&nbsp;
                                <i class="fas fa-link me-1"></i>支持插入链接
                            </div>
                        </div>

                        <!-- Submit -->
                        <div class="d-flex gap-3 justify-content-end">
                            <a href="/forum.php" class="btn btn-outline-secondary px-4">
                                <i class="fas fa-times me-1"></i>取消
                            </a>
                            <button type="submit" class="btn btn-primary px-5" id="submitBtn">
                                <i class="fas fa-paper-plane me-2"></i>发布帖子
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Tips -->
            <div class="card border-0 bg-light mt-3">
                <div class="card-body py-3">
                    <h6 class="fw-bold mb-2"><i class="fas fa-lightbulb text-warning me-2"></i>发帖小贴士</h6>
                    <ul class="mb-0 small text-muted ps-3">
                        <li>描述问题时请尽量详细，包括您的设备型号、遇到的具体情况</li>
                        <li>可以插入截图来更清楚地说明问题</li>
                        <li>请遵守社区规范，友善交流</li>
                        <li>相同问题请先搜索是否已有解答</li>
                    </ul>
                </div>
            </div>
        </div><!-- /col-md-9 -->
    </div><!-- /row -->
</div><!-- /container -->

<!-- Quill JS -->
<link href="https://cdn.quilljs.com/1.3.7/quill.snow.css" rel="stylesheet">
<script src="https://cdn.quilljs.com/1.3.7/quill.min.js"></script>
<script>
// Title counter
const titleInput = document.getElementById('postTitle');
const titleCount = document.getElementById('titleCount');
titleInput.addEventListener('input', () => { titleCount.textContent = titleInput.value.length; });
titleCount.textContent = titleInput.value.length;

// Category pills
document.querySelectorAll('.category-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        document.querySelectorAll('.category-btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        document.getElementById('categoryInput').value = btn.dataset.cat;
    });
});

// Quill editor with image upload
const quill = new Quill('#quillEditor', {
    theme: 'snow',
    placeholder: '在这里写下你的帖子内容...\n\n可以分享使用心得、提问、或者讨论任何与 eSIM 相关的话题。',
    modules: {
        toolbar: {
            container: [
                [{ 'header': [1, 2, 3, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'color': [] }, { 'background': [] }],
                [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                [{ 'align': [] }],
                ['blockquote', 'code-block'],
                ['link', 'image'],
                ['clean']
            ],
            handlers: {
                image: imageUploadHandler
            }
        }
    }
});

function imageUploadHandler() {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/jpeg,image/png,image/gif,image/webp');
    input.click();
    input.onchange = async () => {
        const file = input.files[0];
        if (!file) return;
        if (file.size > 5 * 1024 * 1024) {
            alert('图片大小不能超过 5MB');
            return;
        }
        const formData = new FormData();
        formData.append('image', file);
        try {
            const btn = document.getElementById('submitBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>上传中...';
            const res = await fetch('/forum-upload.php', { method: 'POST', body: formData });
            const data = await res.json();
            if (data.success && data.url) {
                const range = quill.getSelection(true);
                quill.insertEmbed(range.index, 'image', data.url);
                quill.setSelection(range.index + 1);
            } else {
                alert('图片上传失败：' + (data.error || '未知错误'));
            }
        } catch(e) {
            alert('图片上传失败，请重试');
        } finally {
            const btn = document.getElementById('submitBtn');
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-paper-plane me-2"></i>发布帖子';
        }
    };
}

// Form submit - copy quill content to hidden input
document.getElementById('postForm').addEventListener('submit', function(e) {
    const content = quill.root.innerHTML;
    if (content === '<p><br></p>' || content.trim() === '') {
        e.preventDefault();
        alert('请填写帖子内容');
        return;
    }
    document.getElementById('contentInput').value = content;
});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
