<?php
/**
 * 编辑帖子
 */
require_once __DIR__ . '/../includes/functions.php';

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

$currentUser = getCurrentUser();
$postId = isset($_GET['id']) ? intval($_GET['id']) : 0;

// 获取帖子信息
$post = db()->queryOne(
    "SELECT p.*, u.username FROM posts p LEFT JOIN users u ON p.user_id = u.id WHERE p.id = ? AND p.status = 1",
    [$postId]
);

if (!$post) {
    setFlashMessage('error', '帖子不存在');
    redirect(SITE_URL . '/admin/posts.php');
}

// 检查权限：管理员或帖子作者可以编辑
if (!($currentUser['role'] >= 1 || $currentUser['id'] == $post['user_id'])) {
    setFlashMessage('error', '您没有权限编辑此帖子');
    redirect(SITE_URL . '/post.php?id=' . $postId);
}

$error = '';

// 处理保存帖子
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit_post') {
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $categoryId = intval($_POST['category_id'] ?? 0);
    
    if (empty($title) || strlen($title) < 5) {
        $error = '标题至少5个字符';
    } elseif (empty($content) || strlen($content) < 10) {
        $error = '内容至少10个字符';
    } else {
        db()->execute(
            "UPDATE posts SET title = ?, content = ?, category_id = ? WHERE id = ?",
            [$title, $content, $categoryId, $postId]
        );
        
        setFlashMessage('success', '帖子已更新');
        redirect(SITE_URL . '/admin/post-edit.php?id=' . $postId);
    }
}

// 处理保存回复
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit_reply') {
    $replyId = intval($_POST['reply_id'] ?? 0);
    $content = trim($_POST['reply_content'] ?? '');
    
    if (!empty($content)) {
        db()->execute(
            "UPDATE replies SET content = ? WHERE id = ? AND post_id = ?",
            [$content, $replyId, $postId]
        );
        setFlashMessage('success', '回复已更新');
    }
    redirect(SITE_URL . '/admin/post-edit.php?id=' . $postId);
}

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

// 获取该帖子的所有主回复（floor_number > 0）
$replies = db()->query(
    "SELECT r.*, u.username, u.avatar 
     FROM replies r 
     LEFT JOIN users u ON r.user_id = u.id 
     WHERE r.post_id = ? AND r.status = 1 AND r.floor_number > 0
     ORDER BY r.floor_number ASC",
    [$postId]
);

// 获取楼中楼回复（floor_number = 0）
$subReplies = []; // 直接挂在主回复下的楼中楼
$nestedSubReplies = []; // 挂在楼中楼下的回复（嵌套）
$parentNames = []; // 存储父回复用户名
$isMainReply = []; // 记录哪些ID是主回复

// 标记所有主回复ID
foreach ($replies as $r) {
    $isMainReply[$r['id']] = true;
}

$subRepliesList = db()->query(
    "SELECT sr.*, su.username, su.avatar 
     FROM replies sr 
     LEFT JOIN users su ON sr.user_id = su.id 
     WHERE sr.post_id = ? AND sr.status = 1 AND sr.floor_number = 0
     ORDER BY sr.created_at ASC",
    [$postId]
);

// 获取所有父回复的用户名
$allParentIds = array_column($subRepliesList, 'parent_id');
if (!empty($allParentIds)) {
    $placeholders = implode(',', array_fill(0, count($allParentIds), '?'));
    $parentUsers = db()->query(
        "SELECT r.id, r.parent_id, r.floor_number, u.username 
         FROM replies r 
         LEFT JOIN users u ON r.user_id = u.id 
         WHERE r.id IN ($placeholders)",
        $allParentIds
    );
    foreach ($parentUsers as $pu) {
        $parentNames[$pu['id']] = $pu['username'];
        if ($pu['floor_number'] > 0) {
            $isMainReply[$pu['id']] = true;
        }
    }
}

// 分组
foreach ($subRepliesList as $sub) {
    $parentId = $sub['parent_id'];
    if (isset($isMainReply[$parentId])) {
        $subReplies[$parentId][] = $sub;
    } else {
        $nestedSubReplies[$parentId][] = $sub;
    }
}

$pageTitle = '编辑帖子';
include __DIR__ . '/header.php';
?>

<div class="admin-content">
    <h1>编辑帖子</h1>
    
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
        <!-- 左侧：编辑帖子 -->
        <div class="admin-section">
            <h2>帖子内容</h2>
            <?php if ($error): ?>
                <div class="alert alert-error"><?php echo e($error); ?></div>
            <?php endif; ?>
            
            <form method="POST" action="" class="admin-form">
                <input type="hidden" name="action" value="edit_post">
                
                <div class="form-group">
                    <label>作者</label>
                    <input type="text" class="form-control" value="<?php echo e($post['username']); ?>" disabled>
                </div>
                
                <div class="form-group">
                    <label>板块</label>
                    <select name="category_id" class="form-control" required>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>" <?php echo $post['category_id'] == $cat['id'] ? 'selected' : ''; ?>>
                                <?php echo e($cat['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>标题</label>
                    <input type="text" name="title" class="form-control" required
                           value="<?php echo e($post['title']); ?>">
                </div>
                
                <div class="form-group">
                    <label>内容</label>
                    <textarea name="content" class="form-control" rows="10" required><?php echo e($post['content']); ?></textarea>
                </div>
                
                <button type="submit" class="btn btn-primary">保存帖子</button>
                <a href="posts.php" class="btn btn-outline" style="margin-left: 10px;">返回</a>
                <a href="../post.php?id=<?php echo $postId; ?>" target="_blank" class="btn btn-outline" style="margin-left: 10px;">查看</a>
            </form>
        </div>
        
        <!-- 右侧：回复列表 -->
        <div class="admin-section">
            <h2>回复列表 (<?php echo count($replies); ?>)</h2>
            
            <div style="max-height: 600px; overflow-y: auto;">
                <?php foreach ($replies as $reply): ?>
                    <div style="border: 1px solid #ddd; border-radius: 4px; padding: 15px; margin-bottom: 15px; background: #f9f9f9;">
                        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
                            <div class="avatar" style="width: 32px; height: 32px;">
                                <?php if ($reply['avatar']): ?>
                                    <img src="<?php echo e($reply['avatar']); ?>" style="width: 100%; height: 100%; border-radius: 50%;">
                                <?php else: ?>
                                    <i class="fas fa-user"></i>
                                <?php endif; ?>
                            </div>
                            <div>
                                <strong><?php echo e($reply['username']); ?></strong>
                                <span style="color: #999; font-size: 12px;"><?php echo $reply['floor_number']; ?>楼 • <?php echo formatTime($reply['created_at']); ?></span>
                            </div>
                        </div>
                        
                        <form method="POST" action="">
                            <input type="hidden" name="action" value="edit_reply">
                            <input type="hidden" name="reply_id" value="<?php echo $reply['id']; ?>">
                            <textarea name="reply_content" class="form-control" rows="3" style="margin-bottom: 10px;"><?php echo e($reply['content']); ?></textarea>
                            <div style="display: flex; gap: 10px;">
                                <button type="submit" class="btn btn-sm btn-primary">保存回复</button>
                                <a href="reply-edit.php?id=<?php echo $reply['id']; ?>" class="btn btn-sm btn-outline">详细编辑</a>
                                <a href="../post.php?id=<?php echo $postId; ?>#reply-<?php echo $reply['id']; ?>" target="_blank" class="btn btn-sm btn-outline">查看</a>
                            </div>
                        </form>
                        
                        <!-- 楼中楼回复（平级显示） -->
                        <?php if (isset($subReplies[$reply['id']]) && !empty($subReplies[$reply['id']])): ?>
                            <div style="margin-top: 10px;">
                                <a href="javascript:void(0)" onclick="toggleSubReplies(<?php echo $reply['id']; ?>)" 
                                   id="toggle-btn-<?php echo $reply['id']; ?>"
                                   style="color: #666; font-size: 13px;">
                                    <i class="fas fa-chevron-down" id="toggle-icon-<?php echo $reply['id']; ?>"></i>
                                    <span id="toggle-text-<?php echo $reply['id']; ?>">收起回复 (<?php echo count($subReplies[$reply['id']]); ?>)</span>
                                </a>
                            </div>
                            <div id="sub-replies-<?php echo $reply['id']; ?>" style="margin-top: 10px; padding-left: 15px; border-left: 3px solid #ddd;">
                                <?php foreach ($subReplies[$reply['id']] as $subReply): ?>
                                    <div style="padding: 12px 0; border-bottom: 1px solid #eee;" id="admin-reply-<?php echo $subReply['id']; ?>">
                                        <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 5px;">
                                            <div class="avatar" style="width: 24px; height: 24px;">
                                                <?php if ($subReply['avatar']): ?>
                                                    <img src="<?php echo e($subReply['avatar']); ?>" style="width: 100%; height: 100%; border-radius: 50%;">
                                                <?php else: ?>
                                                    <i class="fas fa-user" style="font-size: 12px;"></i>
                                                <?php endif; ?>
                                            </div>
                                            <strong style="font-size: 13px;"><?php echo e($subReply['username']); ?></strong>
                                            <span style="color: #666; font-size: 12px;">
                                                回复 @<?php echo e($parentNames[$subReply['parent_id']] ?? '未知'); ?>
                                            </span>
                                            <span style="color: #999; font-size: 12px;">• <?php echo formatTime($subReply['created_at']); ?></span>
                                            <a href="javascript:void(0)" onclick="toggleAdminSingleReply(<?php echo $subReply['id']; ?>)" style="color: #999; margin-left: auto;">
                                                <i class="fas fa-minus-square" id="admin-single-icon-<?php echo $subReply['id']; ?>"></i>
                                            </a>
                                        </div>
                                        <div id="admin-reply-content-<?php echo $subReply['id']; ?>">
                                            <form method="POST" action="">
                                                <input type="hidden" name="action" value="edit_reply">
                                                <input type="hidden" name="reply_id" value="<?php echo $subReply['id']; ?>">
                                                <textarea name="reply_content" class="form-control" rows="2" style="margin-bottom: 5px; font-size: 13px;"><?php echo e($subReply['content']); ?></textarea>
                                                <button type="submit" class="btn btn-sm btn-primary" style="font-size: 12px; padding: 2px 8px;">保存</button>
                                                <a href="reply-edit.php?id=<?php echo $subReply['id']; ?>" class="btn btn-sm btn-outline" style="font-size: 12px; padding: 2px 8px;">详细编辑</a>
                                            </form>
                                            
                                            <!-- 嵌套的楼中楼回复 -->
                                            <?php if (isset($nestedSubReplies[$subReply['id']]) && !empty($nestedSubReplies[$subReply['id']])): ?>
                                                <div style="margin-top: 10px; margin-left: 20px; padding: 8px; background: #e8e8e8; border-radius: 4px; border-left: 3px solid #3498db;">
                                                    <?php foreach ($nestedSubReplies[$subReply['id']] as $nestedReply): ?>
                                                        <div style="padding: 8px; border-bottom: 1px solid #ddd;">
                                                            <div style="display: flex; align-items: center; gap: 6px; margin-bottom: 3px;">
                                                                <strong style="font-size: 12px;"><?php echo e($nestedReply['username']); ?></strong>
                                                                <span style="color: #666; font-size: 11px;">回复 @<?php echo e($parentNames[$nestedReply['parent_id']] ?? '未知'); ?></span>
                                                                <span style="color: #999; font-size: 11px;">• <?php echo formatTime($nestedReply['created_at']); ?></span>
                                                            </div>
                                                            <form method="POST" action="">
                                                                <input type="hidden" name="action" value="edit_reply">
                                                                <input type="hidden" name="reply_id" value="<?php echo $nestedReply['id']; ?>">
                                                                <textarea name="reply_content" class="form-control" rows="1" style="margin-bottom: 3px; font-size: 12px;"><?php echo e($nestedReply['content']); ?></textarea>
                                                                <button type="submit" class="btn btn-sm btn-primary" style="font-size: 11px; padding: 1px 6px;">保存</button>
                                                            </form>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <div id="admin-reply-collapsed-<?php echo $subReply['id']; ?>" style="display: none; font-size: 13px; color: #666;">
                                            <a href="javascript:void(0)" onclick="toggleAdminSingleReply(<?php echo $subReply['id']; ?>)" style="color: #3498db;">
                                                [已折叠] <?php echo e(truncate($subReply['content'], 30)); ?>
                                            </a>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
                
                <?php if (empty($replies)): ?>
                    <p style="color: #999; text-align: center; padding: 40px;">暂无回复</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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