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

require_once '../model/ArticleManager.php';
require_once '../model/UserManager.php';
require_once '../model/Article.php';
require_once '../validator/search-validator.php';

if ($_SERVER["REQUEST_METHOD"] === "GET" && isset($_GET["q"])) {

    $search = trim($_GET["q"]);
    if (!searchQueryValidator($search)) {
        $_SESSION["search_results"] = [];
        $_SESSION["search_query"] = "";
        $_SESSION["message"] = "invalid_search_query";
    } else {
        try {

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

            $results = $articleManager->search($search);

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

            $_SESSION["search_results"] = $safeArrayResults;
            $_SESSION["search_query"] = $search;
            $_SESSION["message"] = "new_search_results";

        } catch (Exception $e) {
            $_SESSION["message"] = "internal_error";
        }
    }

    $sort = $_GET['sort'] ?? 'alphabet';
    $_SESSION['search_sort'] = $sort;

    $category = $_GET['category'] ?? 'all';
    $_SESSION['search_category'] = $category;

    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    if (!searchLimitValidator($limit)) {
        $limit = 10;
    }
    $_SESSION['search_limit'] = $limit;

    // Neue Suche -> immer wieder bei Seite 1 beginnen
    header("Location: ../../index.php?pfad=search-results&q=" . urlencode($search) . "&sort=" . urlencode($sort) . "&category=" . urlencode($category) . "&limit=" . $limit . "&page=1");
    exit();

}