<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once '../model/LocalArticleManager.php';
require_once '../model/ArticleManager.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();
            
            $results = $articleManager->search($search);

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

            if ($sortStyle === 'alphabet') {
                // Titel aufsteigend alphabetiisch sortiert
                usort($results, function ($a, $b) {
                    return strcasecmp($a->getTitle(), $b->getTitle());
                });
            } elseif ($sortStyle === 'likes') {
                usort($results, function($a, $b) {
                    return $b->getLikeCount() <=> $a->getLikeCount();
                });
            } elseif ($sortStyle === 'newest') {
                // Datum neu zu alt sortiert
                usort($results, function($a, $b) {
                    return strcmp($b->getCreationDate(), $a->getCreationDate());
                });
            } elseif ($sortStyle === 'oldest') {
                // Datum alt zu neu sortiert
                usort($results, function($a, $b) {
                    return strcmp($a->getCreationDate(), $b->getCreationDate());
                });
            }

            // Ergebnisse werden in ein flaches array umgewandelt, da sont incomplete-PHP error im Ergebnis
            $safeArrayResults = [];
            foreach ($results as $obj) {
                $safeArrayResults[] = [
                    "id" => $obj->getId(),
                    "title" => $obj->getTitle(),
                    "content" => $obj->getContent(),
                    "author" => $obj->getAuthor(),
                    "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';
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    if (!searchLimitValidator($limit)) {
        $limit = 10;
    }
    $page  = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    header("Location: ../../index.php?pfad=search-results&q=" . urlencode($search) . "&sort=" . urlencode($sort) . "&limit=" . $limit . "&page=" . $page);
    exit();
    
}

?>