<?php
require_once "lib/account.php";
/**
 * Retrieves news articles based on the current user's privilege level.
 * The function queries the NewsArticles and Users tables to fetch articles
 * that the user has the privilege to view. Articles are joined with user
 * information to include the author's nickname.
 *
 * @global mysqli $mysqli The mysqli database connection object.
 * @return array Returns an associative array with a status key indicating the success or failure,
 *               and an 'Articles' key containing an array of articles if successful.
 */
function getNewsArticles() :array
    {
        global $mysqli;

        $output = ["Status" => "Fail"]; // Default Status is "Fail"

        $articles = [];
            $stmt = $mysqli->prepare("SELECT NewsArticles.ID, NewsArticles.WrittenAt, NewsArticles.WrittenBy, NewsArticles.Title, NewsArticles.Body, NewsArticles.FileList, Users.Nickname FROM NewsArticles INNER JOIN Users ON NewsArticles.WrittenBy = Users.ID WHERE NewsArticles.PrivilegeLevel <= ?;");
            $id = 0;
            $writtenAt = "";
            $writtenBy = 0;
            $title = "";
            $body = "";
            $filelist = 0;
            $writtenByName = "";

            $stmt->bind_param("i", $_SESSION["privilege_level"]);
            $stmt->bind_result($id, $writtenAt, $writtenBy, $title, $body, $filelist, $writtenByName);

            $stmt->execute();

            while ($stmt->fetch()) {
                $articles[] = [
                    'ID' => $id,
                    'WrittenAt' => $writtenAt,
                    'Title' => $title,
                    'Body' => $body,
                    'WrittenByName' =>$writtenByName
                ];
            }

            // Check if any results were fetched
            if (!empty($articles)) {
                $output["Status"] = "Success";
                $output["Articles"] = $articles;
            }

        return $output;
}

/**
 * Adds a new news article to the database if the user is logged in and has the appropriate
 * privilege level. The function sanitizes the title and body of the article to prevent XSS attacks.
 *
 * @global mysqli $mysqli The mysqli database connection object.
 * @global array $routerConfig Configuration array that includes default permission settings.
 * @param string $title The title of the news article. Default value is "Nazov".
 * @param string $body The body of the news article. Default value is "Obsah".
 * @param int $privilegeLevel The privilege level required to view the article. If set to 0, uses default from configuration.
 * @return array Returns an associative array with a status key that indicates the success or failure of the operation.
 */
function addNewsArticle(string $title="Nazov", string $body="Obsah", int $privilegeLevel=0) :array
{
    global $mysqli;
    global $routerConfig;


    if ($privilegeLevel == 0){
        $privilegeLevel = $routerConfig['newsarticle']['default_permissions'];
    }

    $output = ["Status" => "Fail"]; // Default Status is "Fail"
    if (isLoggedIn() && $privilegeLevel <= $_SESSION["privilege_level"]) {
        $query = $mysqli->prepare("INSERT INTO NewsArticles (WrittenBy, Title, Body, FileList, PrivilegeLevel) VALUES (?, ?, ?, 0, ?);");
        $minpriv = intval($privilegeLevel);
        $query->bind_param("issi", $_SESSION["ID"], htmlspecialchars($title), htmlspecialchars($body), $minpriv);
        $query->execute();
        if ($query->affected_rows > 0) {
            $output["Status"] = "Success";
        }
        $query->close();
    }
    return $output;
}

/**
 * Adds a comment to a news article.
 *
 * @param int $userId User who is commenting.
 * @param int $newsArticleId ID of the news article.
 * @param string $commentText The content of the comment.
 * @param int|null $parentId ID of the parent comment if it's a reply.
 * @return array Status array indicating success or failure.
 * @global mysqli $mysqli The mysqli database connection object.
 */
function addNewsComment(int $userId, int $newsArticleId, string $commentText, ?int $parentId = null): array {
    global $mysqli;

    $output = ["Status" => "Fail"]; // Default Status is "Fail"

    if (!isLoggedIn()) {
        $output['Error'] = "User must be logged in.";
        return $output;
    }

    // Prepare the SQL statement to prevent SQL injection
    $stmt = $mysqli->prepare("INSERT INTO NewsComments (ParentID, UserID, NewsArticleID, CommentText) VALUES (?, ?, ?, ?);");

    // Bind parameters. 'i' denotes an integer and 's' denotes a string.
    $stmt->bind_param("iiis", $parentId, $userId, $newsArticleId, $commentText);

    // Execute the query
    if ($stmt->execute()) {
        // Check if any rows were affected
        if ($stmt->affected_rows > 0) {
            $output["Status"] = "Success";
        } else {
            $output["Error"] = "No rows affected.";
        }
    } else {
        $output["Error"] = $stmt->error;
    }

    // Close statement
    $stmt->close();

    return $output;
}
