<?php
/**
 * 编辑回复
 */
require_once __DIR__ . '/../includes/functions.php';

// 检查是否登录且是管理员
if (!isLoggedIn() || !isAdmin()) {
    setFlashMessage('error', '您没有权限访问此页面');
    redirect(SITE_URL . '/index.php');
}

$replyId = isset($_GET['id']) ? intval($_GET['id']) : 0;

// 获取回复信息
$reply = db()->queryOne(
    "SELECT r.*, u.username, p.title as post_title, p.id as post_id 
     FROM replies r 
     LEFT JOIN users u ON r.user_id = u.id 
     LEFT JOIN posts p ON r.post_id = p.id 
     WHERE r.id = ? AND r.status = 1",
    [$replyId]
);

if (!$reply) {
    setFlashMessage('error', '回复不存在');
    redirect(SITE_URL . '/admin/replies.php');
}

$error = '';

// 处理保存
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $content = trim($_POST['content'] ?? '');
    
    if (empty($content)) {
        $error = '内容不能为空';
    } else {
        db()->execute(
            "UPDATE replies SET content = ? WHERE id = ?",
            [$content, $replyId]
        );
        
        setFlashMessage('success', '回复已更新');
        redirect(SITE_URL . '/admin/replies.php');
    }
}

$pageTitle = '编辑回复';
include __DIR__ . '/header.php';
?>

<div class="admin-content">
    <h1>编辑回复</h1>
    
    <div class="admin-section">
        <?php if ($error): ?>
            <div class="alert alert-error"><?php echo e($error); ?></div>
        <?php endif; ?>
        
        <div style="margin-bottom: 20px; padding: 15px; background: #f8f9fa; border-radius: 4px;">
            <p><strong>所属帖子：</strong><a href="../post.php?id=<?php echo $reply['post_id']; ?>" target="_blank"><?php echo e($reply['post_title']); ?></a></p>
            <p><strong>回复用户：</strong><?php echo e($reply['username']); ?></p>
            <p><strong>楼层：</strong><?php echo $reply['floor_number']; ?>楼</p>
        </div>
        
        <form method="POST" action="" class="admin-form">
            <div class="form-group">
                <label>回复内容</label>
                <textarea name="content" class="form-control" rows="10" required><?php echo e($reply['content']); ?></textarea>
            </div>
            
            <button type="submit" class="btn btn-primary">保存修改</button>
            <a href="replies.php" class="btn btn-outline" style="margin-left: 10px;">返回</a>
            <a href="../post.php?id=<?php echo $reply['post_id']; ?>#reply-<?php echo $replyId; ?>" target="_blank" class="btn btn-outline" style="margin-left: 10px;">查看回复</a>
        </form>
    </div>
</div>

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