<?php
// 处理POST请求（发布文章）
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isAdmin()) {
    error_log("POST request received. POST data: " . print_r($_POST, true));
    
    $content = $_POST['content']; // 不对富文本内容进行sanitize，保持HTML格式
    $slug = sanitizeInput($_POST['slug']);
    $title = sanitizeInput($_POST['title'] ?? '');
    
    error_log("Content: " . substr($content, 0, 100) . "...");
    error_log("Slug: " . $slug);
    error_log("Title: " . $title);
    
    if (!empty($content) && !empty($slug)) {
        $post_data = [
            'id' => uniqid(),
            'title' => $title,
            'content' => $content,
            'slug' => $slug,
            'images' => [],
            'status' => 'published',
            'comments_enabled' => isset($_POST['comments_enabled']) ? true : false,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        error_log("Attempting to save post: " . print_r($post_data, true));
        $save_result = savePost($post_data);
        
        if ($save_result) {
            $success_message = '文章发布成功！';
            error_log("Post saved successfully");
            // 重定向到首页避免重复提交
            header('Location: /');
            exit;
        } else {
            $error_message = '文章发布失败，请检查权限设置';
            error_log("Post save failed");
        }
    } else {
        $error_message = '内容和标识不能为空';
        error_log("Content or slug is empty");
    }
}

// 调试：检查会话数据
error_log("Home.php - Session ID: " . session_id());
error_log("Home.php - Session data: " . print_r($_SESSION, true));
error_log("Home.php - isAdmin result: " . (isAdmin() ? 'true' : 'false'));
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo getSiteName(); ?></title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <!-- Quill富文本编辑器 -->
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <!-- 朋友圈头部 -->
        <div class="moments-header">
            <div class="cover-image">
                <img src="<?php echo getBackgroundImage(); ?>" alt="封面图片">
            </div>
            <!-- 顶部工具栏 - 悬浮在图片上 -->
            <div class="top-toolbar">
                <?php if (isAdmin()): ?>
                    <div class="toolbar-icons">
                        <button class="icon-btn post-icon" id="postBtn" title="发布动态">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M12 5v14M5 12h14"/>
                            </svg>
                        </button>
                        <a href="/admin" class="icon-btn admin-icon" title="后台管理">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <circle cx="12" cy="12" r="3"/>
                                <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1 1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
                            </svg>
                        </a>
                        <a href="/api/logout.php" class="icon-btn logout-icon" title="退出登录">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
                                <polyline points="16,17 21,12 16,7"/>
                                <line x1="21" y1="12" x2="9" y2="12"/>
                            </svg>
                        </a>
                    </div>
                <?php else: ?>
                    <div class="toolbar-icons">
                        <a href="/admin/login" class="icon-btn login-icon" title="登录">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                                <circle cx="12" cy="7" r="4"/>
                            </svg>
                        </a>
                    </div>
                <?php endif; ?>
            </div>
            <div class="user-info">
                <img src="<?php echo getAvatarImage(); ?>" alt="头像" class="avatar">
                <h2><?php echo DEFAULT_ADMIN_NICK; ?></h2>
            </div>
        </div>

        <!-- 消息提示 -->
        <?php if (isset($success_message)): ?>
            <div class="alert alert-success"><?php echo $success_message; ?></div>
        <?php endif; ?>
        
        <?php if (isset($error_message)): ?>
            <div class="alert alert-error"><?php echo $error_message; ?></div>
        <?php endif; ?>

        <!-- 动态列表 -->
        <div class="moments-list">
            <?php
            $posts = getAllPosts();
            foreach ($posts as $post):
            ?>
            <div class="moment-item">
                <div class="moment-header">
                    <img src="<?php echo getAvatarImage(); ?>" alt="头像" class="moment-avatar">
                    <div class="moment-info">
                        <h3><?php echo DEFAULT_ADMIN_NICK; ?></h3>
                        <span class="moment-time"><?php echo formatDate($post['created_at']); ?></span>
                    </div>
                </div>
                <div class="moment-content">
                    <?php if (!empty($post['title'])): ?>
                    <h4 class="moment-title"><?php echo htmlspecialchars($post['title']); ?></h4>
                    <?php endif; ?>
                    <div><?php echo $post['content']; ?></div>
                    <?php if (!empty($post['images'])): ?>
                    <div class="moment-images">
                        <?php foreach ($post['images'] as $image): ?>
                        <img src="<?php echo $image; ?>" alt="图片" class="moment-image">
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="moment-actions">
                    <a href="/<?php echo date('Y/m/d', strtotime($post['created_at'])); ?>/<?php echo $post['slug']; ?>.html" class="view-detail">查看详情</a>
                    <span class="comment-count"><?php echo count(getComments($post['id'])); ?> 条评论</span>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- 发布动态弹窗 -->
    <div id="postModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="hidePostModal()">&times;</span>
            <h2>发布动态</h2>
            <form method="POST" action="/" class="post-form">
                <div class="form-group">
                    <label>标题（可选）</label>
                    <input type="text" name="title" placeholder="输入文章标题">
                </div>
                
                <div class="form-group slug-group">
                    <div class="slug-preview">
                        <span class="slug-base" id="slugBase">http://localhost:8080/archives/</span>
                        <input type="text" name="slug" id="slugInput" placeholder="文章标识" required>
                        <span class="slug-suffix">.html</span>
                    </div>
                    <small>用于生成访问链接，只能包含字母、数字、连字符</small>
                </div>
                
                <div class="form-group">
                    <label>内容 *</label>
                    <div id="editor" style="height: 180px;"></div>
                    <textarea name="content" id="content" style="display: none;"></textarea>
                </div>
                
                <div class="form-group checkbox-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="comments_enabled"> 允许评论
                    </label>
                </div>
                
                <button type="submit" class="btn btn-primary">发布</button>
            </form>
        </div>
    </div>

    <script src="/assets/js/main.js"></script>
    <!-- Quill富文本编辑器 -->
    <script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
    <script>
        let quill;
        
        // 初始化富文本编辑器
        document.addEventListener('DOMContentLoaded', function() {
            // 绑定发布按钮事件
            const postBtn = document.getElementById('postBtn');
            if (postBtn) {
                postBtn.addEventListener('click', showPostModal);
            }
            
            // 动态设置URL基础部分
            const slugBase = document.getElementById('slugBase');
            if (slugBase) {
                const currentHost = window.location.protocol + '//' + window.location.host;
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const day = String(now.getDate()).padStart(2, '0');
                slugBase.textContent = currentHost + '/' + year + '/' + month + '/' + day + '/';
            }
            
            // 初始化Quill编辑器
            quill = new Quill('#editor', {
                theme: 'snow',
                placeholder: '分享新鲜事...',
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline', 'strike'],
                        ['blockquote', 'code-block'],
                        [{ 'header': 1 }, { 'header': 2 }],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        [{ 'script': 'sub'}, { 'script': 'super' }],
                        [{ 'indent': '-1'}, { 'indent': '+1' }],
                        [{ 'direction': 'rtl' }],
                        [{ 'size': ['small', false, 'large', 'huge'] }],
                        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'font': [] }],
                        [{ 'align': [] }],
                        ['clean'],
                        ['link', 'image']
                    ]
                }
            });
            
            // 文章标识输入验证
            const slugInput = document.getElementById('slugInput');
            if (slugInput) {
                slugInput.addEventListener('input', function() {
                    // 只允许字母、数字、连字符
                    this.value = this.value.replace(/[^a-zA-Z0-9-]/g, '');
                });
            }
            
            // 表单提交处理
            const postForm = document.querySelector('.post-form');
            if (postForm) {
                postForm.addEventListener('submit', function(e) {
                    console.log('Form submit event triggered');
                    
                    // 同步Quill内容到隐藏的textarea
                    const content = quill.root.innerHTML;
                    document.getElementById('content').value = content;
                    
                    console.log('Content:', content);
                    console.log('Quill text:', quill.getText().trim());
                    
                    // 验证内容不为空 - 移除此验证，允许发布空内容
                    // if (quill.getText().trim().length === 0) {
                    //     e.preventDefault();
                    //     alert('请输入文章内容');
                    //     return false;
                    // }
                    
                    // 验证文章标识不为空
                    const slug = document.getElementById('slugInput').value.trim();
                    console.log('Slug:', slug);
                    
                    if (!slug) {
                        e.preventDefault();
                        showNotification('请输入文章标识', 'error');
                        return false;
                    }
                    
                    // 验证文章标识格式
                    if (!/^[a-zA-Z0-9-]+$/.test(slug)) {
                        e.preventDefault();
                        showNotification('文章标识只能包含字母、数字和连字符', 'error');
                        return false;
                    }
                    
                    console.log('All validations passed, submitting form');
                    // 如果所有验证都通过，允许表单提交
                    return true;
                });
            }
        });
    </script>
</body>
</html>
