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

require_once 'php/model/Article.php';
require_once 'php/model/ArticleManager.php';
require_once 'php/model/UserManager.php';
require_once 'php/model/CommentManager.php';

if (isset($_GET["id"]) && !empty($_GET["id"])){
    try {
        $id = $_GET["id"];
        $articleManager = ArticleManager::getInstance();
        $article = $articleManager->getArticle($id);
        if($article != null){
            $title = $article->getTitle();
            $content = $article->getContent();
            $category = $article->getCategory();
            $author = $article->getAuthor();
            $tags = $article->getTags();
            $articleObj = $article; // Objekt für die Like-Abfagen sichern

            $userManager = UserManager::getInstance();
            $name = $userManager->findUser($author)["vorname"]." ".$userManager->findUser($author)["nachname"];
        }else{
            //header("location: index.php?pfad=404");
            include_once "content/404.php";
            exit();
        }

        if($_GET["pfad"] == "updateArticle"){
            if($article->getAuthor() != $_SESSION["user_email"]){
                $_SESSION["message"] = "unauthorized_access";
                header("location: index.php");
                exit();
            }
        }

        $commentManager = CommentManager::getInstance();
        $comments = $commentManager->getCommentsByArticle($_GET["id"]);

        foreach ($comments as $comment) {
            if ($comment->isReply()) {
                $parentId = $comment->getParentCommentId();
                $repliesByParent[$parentId][] = $comment;
            } else {
                $mainComments[] = $comment;
            }
        }

    } catch (Throwable $e) {
        $_SESSION["message"] = "internal_error";
        header("Location: index.php");
        exit();
    }
}else{
    $_SESSION["message"] = "missing_id";
}
?>