<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header("Content-Type: application/json");

require_once "../model/CommentManager.php";

if (!isset($_SESSION["user_email"])) {
    echo json_encode([
        "success" => false,
        "message" => "Du musst angemeldet sein, um zu kommentieren."
    ]);
    exit();
}

$articleId = $_POST["article_id"] ?? null;
$content = trim($_POST["content"] ?? "");
$parentCommentId = $_POST["parent_comment_id"] ?? null;

if ($parentCommentId === "" || $parentCommentId === "0") {
    $parentCommentId = null;
}

if (empty($articleId) || empty($content)) {
    echo json_encode([
        "success" => false,
        "message" => "Kommentar darf nicht leer sein."
    ]);
    exit();
}

try {
    $commentManager = CommentManager::getInstance();

    $commentId = $commentManager->addComment(
        $articleId,
        $_SESSION["user_email"],
        $content,
        $parentCommentId
    );

    echo json_encode([
        "success" => true,
        "commentId" => $commentId,
        "author" => $_SESSION["user_email"],
        "content" => $content,
        "created" => date("Y-m-d H:i:s"),
        "parentCommentId" => $parentCommentId
    ]);

} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Kommentar konnte nicht gespeichert werden."
    ]);
}