<?php
require_once __DIR__ . '/../includes/functions.php';

$currentUser = getCurrentUser();

// 如果没有登录，跳转到登录页
if (!$currentUser) {
    header('Location: ' . SITE_URL . '/mobile/login.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postId = (int)($_POST['post_id'] ?? 0);
    $content = trim($_POST['content'] ?? '');
    
    if ($postId <= 0) {
        header('Location: ' . SITE_URL . '/mobile/index.php');
        exit;
    }
    
    if (empty($content)) {
        header('Location: ' . SITE_URL . '/mobile/post.php?id=' . $postId . '&error=empty');
        exit;
    }
    
    $db = Database::getInstance();
    
    // 检查帖子是否存在
    $post = $db->queryOne("SELECT * FROM posts WHERE id = ? AND status = 1", [$postId]);
    if (!$post) {
        header('Location: ' . SITE_URL . '/mobile/index.php');
        exit;
    }
    
    // 创建回复
    $replyId = $db->insert(
        "INSERT INTO replies (post_id, user_id, content, status, created_at) VALUES (?, ?, ?, 1, NOW())",
        [$postId, $currentUser['id'], $content]
    );
    
    // 更新帖子回复数
    $db->query("UPDATE posts SET reply_count = reply_count + 1 WHERE id = ?", [$postId]);
    
    // 更新用户回复数
    $db->query("UPDATE users SET reply_count = reply_count + 1 WHERE id = ?", [$currentUser['id']]);
    
    // 如果回复的不是自己的帖子，发送通知
    if ($post['user_id'] != $currentUser['id']) {
        $db->query(
            "INSERT INTO notifications (user_id, sender_id, post_id, type, content, is_read, created_at) VALUES (?, ?, ?, 'reply', ?, 0, NOW())",
            [$post['user_id'], $currentUser['id'], $postId, $currentUser['username'] . ' 回复了你的帖子']
        );
    }
    
    // 跳转到帖子页面，并定位到新回复
    header('Location: ' . SITE_URL . '/mobile/post.php?id=' . $postId . '#reply-' . $replyId);
    exit;
}

header('Location: ' . SITE_URL . '/mobile/index.php');
exit;
