<?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;
}

$post_id = $_GET['id'] ?? '';
if (empty($post_id)) {
    header('Location: /admin/posts');
    exit;
}

$post = null;
$years = glob(POSTS_PATH . '/*', GLOB_ONLYDIR);

foreach ($years as $year_dir) {
    $months = glob($year_dir . '/*', GLOB_ONLYDIR);
    foreach ($months as $month_dir) {
        $days = glob($month_dir . '/*', GLOB_ONLYDIR);
        foreach ($days as $day_dir) {
            $post_files = glob($day_dir . '/*.json');
            foreach ($post_files as $post_file) {
                $post_data = json_decode(file_get_contents($post_file), true);
                if ($post_data && isset($post_data['id']) && $post_data['id'] === $post_id) {
                    $post = $post_data;
                    break 4;
                }
            }
        }
    }
}
if (!$post) {
    header('Location: /admin/posts');
    exit;
}

if ($_POST) {
    $content = $_POST['content']; // 不对富文本内容进行sanitize，保持HTML格式
    $slug = sanitizeInput($_POST['slug']);
    $title = sanitizeInput($_POST['title'] ?? '');
    $action = $_POST['action'] ?? 'publish';
    
    if (empty($content) || empty($slug)) {
        $error = '内容和标识不能为空';
    } else {
        $post_data = $post;
        $post_data['title'] = $title;
        $post_data['content'] = $content;
        $post_data['slug'] = $slug;
        $post_data['status'] = $action === 'save_draft' ? 'draft' : 'published';
        $post_data['comments_enabled'] = isset($_POST['comments_enabled']) ? true : false;
        $post_data['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;
                    }
                }
            }
        }
        
        // 保存更新的文章
        $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";
        $post_file = $post_dir . '/' . $post_data['slug'] . '.json';
        
        if (file_put_contents($post_file, json_encode($post_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))) {
            $success = '文章更新成功！';
            $post = $post_data; // 更新显示的数据
            // 重定向到文章管理页面
            header('Location: /admin/posts?updated=1');
            exit;
        } else {
            $error = '文章更新失败';
        }
    }
}
?>
<!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">
    <!-- Quill富文本编辑器 -->
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
</head>
<body>
    <div class="admin-container">
        <?php renderAdminNavigation('posts'); ?>
        
        <div class="admin-main">
            <div class="admin-content post-form">
                <div class="page-header">
                    <h1>编辑文章</h1>
                    <a href="/admin/posts" class="btn btn-secondary">返回文章管理</a>
                </div>
                
                <?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>标题（可选）</label>
                        <input type="text" name="title" value="<?php echo htmlspecialchars($post['title'] ?? ''); ?>" placeholder="输入文章标题">
                    </div>
                    
                    <div class="form-group">
                        <label for="content">内容</label>
                        <div id="editor" style="height: 300px;"><?php echo html_entity_decode($post['content'], ENT_QUOTES, 'UTF-8'); ?></div>
                        <input type="hidden" name="content" id="content" value="<?php echo htmlspecialchars($post['content'], ENT_QUOTES, 'UTF-8'); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label>文章标识 *</label>
                        <input type="text" name="slug" value="<?php echo htmlspecialchars($post['slug']); ?>" placeholder="用于URL的唯一标识" required>
                        <small>用于生成文章链接，只能包含字母、数字、连字符</small>
                    </div>
                    
                    <div class="form-group">
                        <label>上传图片（可选）</label>
                        <input type="file" name="images[]" multiple accept="image/*">
                        <small>可以选择多张图片</small>
                    </div>
                    
                    <div class="form-group">
                        <label>
                            <input type="checkbox" name="comments_enabled" <?php echo (isset($post['comments_enabled']) && $post['comments_enabled']) ? 'checked' : ''; ?>> 允许评论
                        </label>
                        <small>勾选后将启用此文章的评论功能</small>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" name="action" value="publish" class="btn btn-primary">更新文章</button>
                        <button type="submit" name="action" value="save_draft" class="btn btn-secondary">保存草稿</button>
                        <a href="/admin/posts" class="btn btn-secondary">取消</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Quill富文本编辑器 -->
    <script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
    <script>
        // 初始化Quill编辑器
        var quill = new Quill('#editor', {
            theme: 'snow',
            modules: {
                toolbar: [
                    [{ 'header': [1, 2, 3, false] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    ['blockquote', 'code-block'],
                    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                    ['link', 'image'],
                    ['clean']
                ]
            }
        });

        // 自定义图片上传处理
        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', {
                        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 {
                            alert('图片上传失败');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('图片上传失败');
                    });
                }
            };
        });

        // 表单提交时同步编辑器内容
        document.getElementById('postForm').addEventListener('submit', function() {
            document.getElementById('content').value = quill.root.innerHTML;
        });
    </script>
</body>
</html>