<?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/validator/article-validator.php';
require_once __DIR__ . '/../../includes/resultsHelper.php';

if (isset($_GET["category"]) && !empty($_GET["category"]) && articleCategoryValidator($_GET["category"])) {

    $category = $_GET["category"];

    try {
        $articleManager = ArticleManager::getInstance();
        $userManager = UserManager::getInstance();

        $allArticles = $articleManager->getArticlesByCategory($category);

        $safeArrayResults = [];
        foreach ($allArticles as $article) {
            $authorName = $userManager->findUser($article->getAuthor())["vorname"] . " " . $userManager->findUser($article->getAuthor())["nachname"];
            $safeArrayResults[] = [
                "id" => $article->getID(),
                "title" => $article->getTitle(),
                "content" => $article->getContent(),
                "author" => $authorName,
                "category" => $article->getCategory(),
                "tags" => $article->getTags(),
                "creationDate" => $article->getCreationDate(),
                "likes" => $article->getLikes(),
            ];
        }

        // Session dient hier (wie bei search-results) als Zwischenspeicher, damit
        // js/showCategory.js den kompletten Datensatz per showCategory-data.php
        // nachladen kann, ohne die Kategorie-Abfrage ein zweites Mal auszuführen.
        $_SESSION['category_results'] = $safeArrayResults;
        $_SESSION['category_name'] = $category;

    } catch (Exception $e) {
        $_SESSION["message"] = "internal_error";
        include_once "content/404.php";
        exit();
    }

} else {
    $_SESSION["message"] = "invalid_category";
    include_once "content/404.php";
    exit();
}