<?php
// 不需要再次启动会话，因为主index.php已经启动了
// session_start();
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/admin-navigation.php';

if (!isAdmin()) {
    header('Location: /admin');
    exit;
}

if ($_POST) {
    // 调试信息
    error_log("POST data received: " . print_r($_POST, true));
    
    $content = $_POST['content']; // 不对富文本内容进行sanitize，保持HTML格式
    $slug = sanitizeInput($_POST['slug']);
    $title = sanitizeInput($_POST['title'] ?? '');
    $action = $_POST['action'] ?? 'publish';
    
    // 调试信息
    error_log("Content: " . $content);
    error_log("Slug: " . $slug);
    error_log("Action: " . $action);
    
    // 如果标识为空，自动生成一个
    if (empty($slug)) {
        $slug = 'post-' . date('YmdHis') . '-' . substr(uniqid(), -4);
        error_log("Auto-generated slug: " . $slug);
    }
    
    // 内容可以为空，不再验证内容
    $post_data = [
        'id' => uniqid(),
        'title' => $title,
        'content' => $content, // 允许内容为空
        'slug' => $slug,
        'images' => [],
        'status' => $action === 'draft' ? 'draft' : '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')
    ];
    
    // 处理图片上传
    if (!empty($_FILES['images']['name'][0])) {
        $upload_dir = UPLOADS_PATH . '/' . date('Y/m/d');
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
            if (!empty($tmp_name)) {
                $file_name = uniqid() . '_' . $_FILES['images']['name'][$key];
                $file_path = $upload_dir . '/' . $file_name;
                if (move_uploaded_file($tmp_name, $file_path)) {
                    $post_data['images'][] = '/uploads/' . date('Y/m/d') . '/' . $file_name;
                }
            }
        }
    }
    
    $save_result = savePost($post_data);
    error_log("Save result: " . ($save_result ? 'true' : 'false'));
    
    if ($save_result) {
        if ($action === 'draft') {
            $success = '文章已保存为草稿！';
        } else {
            $success = '文章发布成功！';
        }
        error_log("Post saved successfully");
    } else {
        $error = $action === 'draft' ? '草稿保存失败' : '文章发布失败';
        error_log("Post save failed - check directory permissions and disk space");
        
        // 检查目录是否存在
        $year = date('Y', strtotime($post_data['created_at']));
        $month = date('m', strtotime($post_data['created_at']));
        $day = date('d', strtotime($post_data['created_at']));
        $post_dir = POSTS_PATH . "/$year/$month/$day";
        
        if (!is_dir($post_dir)) {
            error_log("Directory does not exist: $post_dir");
        } else {
            error_log("Directory exists: $post_dir");
            error_log("Directory permissions: " . substr(sprintf('%o', fileperms($post_dir)), -4));
        }
    }
}
?>
<!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/admin.css">
    <link rel="stylesheet" href="/assets/css/admin-post.css">
    <!-- Quill富文本编辑器 -->
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
</head>
<body>
    <div class="admin-container">
        <?php renderAdminNavigation('create-post'); ?>
        
        <div class="admin-main">
            <div class="admin-content">
                <h2>发布动态</h2>
                
                <?php if (isset($error)): ?>
                <div class="alert alert-error"><?php echo $error; ?></div>
                <?php endif; ?>
                
                <?php if (isset($success)): ?>
                <div class="alert alert-success"><?php echo $success; ?></div>
                <?php endif; ?>
                
                <form method="POST" enctype="multipart/form-data" class="post-form" id="postForm">
                    <div class="form-group">
                        <label for="title">标题（可选）</label>
                        <input type="text" id="title" name="title" placeholder="输入文章标题">
                    </div>
                    
                    <div class="form-group slug-group">
                        <label for="slug">文章标识 *</label>
                        <div class="slug-preview">
                            <span class="slug-base" id="slugBase">http://localhost:8080/</span>
                            <input type="text" id="slug" name="slug" placeholder="文章标识" required>
                            <span class="slug-suffix">.html</span>
                        </div>
                        <small>用于生成访问链接，只能包含字母、数字、连字符</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="content">内容 *</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>
                    
                    <div class="form-actions">
                        <button type="submit" name="action" value="draft" class="btn btn-secondary">保存草稿</button>
                        <button type="submit" name="action" value="publish" class="btn btn-primary">发布动态</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Quill富文本编辑器 -->
    <script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
    <script>
        // 初始化富文本编辑器
        let quill; // 声明quill变量
        document.addEventListener('DOMContentLoaded', function() {
            // 动态设置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('slug');
            if (slugInput) {
                slugInput.addEventListener('input', function() {
                    // 只允许字母、数字、连字符
                    this.value = this.value.replace(/[^a-zA-Z0-9-]/g, '');
                });
            }
        });

        // 自定义图片上传处理
        quill.getModule('toolbar').addHandler('image', function() {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');
            input.click();

            input.onchange = function() {
                var file = input.files[0];
                if (file) {
                    var formData = new FormData();
                    formData.append('image', file);

                    fetch('/admin/upload-image.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.url) {
                            var range = quill.getSelection();
                            quill.insertEmbed(range.index, 'image', data.url);
                        } else {
                            showNotification('图片上传失败：' + (data.error || '未知错误'), 'error');
                        }
                    })
                    .catch(error => {
                        showNotification('图片上传失败：' + error.message, 'error');
                    });
                }
            };
        });

        // 表单提交处理
        document.getElementById('postForm').addEventListener('submit', function(e) {
            // 同步Quill内容到隐藏的textarea
            const content = quill.root.innerHTML;
            document.getElementById('content').value = content;
            console.log('Content synced:', content);
            
            // 检查内容是否为空 - 移除此验证，允许发布空内容
            // if (quill.getText().trim().length === 0) {
            //     e.preventDefault();
            //     alert('请输入文章内容');
            //     return false;
            // }
            
            // 检查slug是否为空
            const slug = document.querySelector('input[name="slug"]').value.trim();
            if (!slug) {
                e.preventDefault();
                showNotification('请输入文章标识', 'error');
                return false;
            }
            
            // 验证slug格式
            const slugPattern = /^[a-zA-Z0-9-]+$/;
            if (!slugPattern.test(slug)) {
                e.preventDefault();
                showNotification('文章标识只能包含字母、数字和连字符，例如：my-first-post', 'error');
                return false;
            }
            
            console.log('Form validation passed, submitting...');
            
            // 显示提交状态
            if (clickedButton) {
                clickedButton.disabled = true;
                const originalText = clickedButton.textContent;
                clickedButton.textContent = clickedButton.value === 'publish' ? '发布中...' : '保存中...';
                
                // 如果提交失败，恢复按钮状态
                setTimeout(() => {
                    clickedButton.disabled = false;
                    clickedButton.textContent = originalText;
                }, 5000);
            }
            
            // 允许表单正常提交
        });
    </script>
</body>
</html>
