<?php

require_once "lib/upload.php";

function addMeme(string $title, string $memeText, int $imageID): array
{
    global $mysqli;
    $output = ["Status" => "Fail"];
    echo isLoggedIn()  ? "a" : "b";
    echo fileExists($imageID);
    echo !empty($title)  ? "x" : "y";
    echo !empty($memeText)  ? "a" : "b";
    echo !empty($imageID)  ? "a" : "b";
    echo $imageID;
    if (isLoggedIn() && fileExists($imageID, false) && !empty($title) && !empty($memeText) && !empty($imageID) && $imageID > 0) {
        $stmtMemeAdd = $mysqli->prepare('INSERT INTO Memes (AuthorID, Title, TextContent, FileID) VALUES (?, ?, ?, ?)');
        $stmtMemeAdd->bind_param('issi', $_SESSION['ID'], htmlspecialchars($title), htmlspecialchars($memeText), $imageID);
        if($stmtMemeAdd->execute() && $stmtMemeAdd->affected_rows > 0) {
            $output["Status"] = "Success";
            $output["Meme"] = "Funny";
            $output["Error"] = $stmtMemeAdd->error;
        }
    }
    return $output;
}

function renderMeme(string $title, string $textContent, string $createdAt, string $filePath, string $userNickname): string
{
    global $routerConfig;
    $meme_template = file_get_contents($routerConfig['template_dir'] . "meme.html");

    $meme_out = str_replace('__TEMPLATE_MEME_TITLE__', htmlspecialchars($title), $meme_template);
    $meme_out = str_replace('__TEMPLATE_MEME_AUTHOR__', htmlspecialchars($userNickname), $meme_out);
    $meme_out = str_replace('__TEMPLATE_MEME_DATE__', htmlspecialchars($createdAt), $meme_out);
    $meme_out = str_replace('__TEMPLATE_MEME_IMAGE__', htmlspecialchars($filePath), $meme_out);

    return str_replace('__TEMPLATE_MEME_TEXT__', htmlspecialchars($textContent), $meme_out);
}

function renderMemeGallery(): string
{
    global $mysqli;
    global $routerConfig;
    $stmtlist = $mysqli->prepare('SELECT Memes.ID, Memes.Title, Memes.TextContent, Memes.CreatedAt, Files.Path, Files.Type, Users.Nickname FROM Memes INNER JOIN Users ON Memes.AuthorID = Users.ID INNER JOIN Files ON Memes.FileID = Files.ID');

    // Execute the prepared statement
    $stmtlist->execute();
    $memeID = 0;
    $title = "";
    $textContent = "";
    $filePath = "";
    $fileType = "";
    $userNickname = "";
    $createdAt = "";
    // Bind the result variables
    $stmtlist->bind_result($memeID, $title, $textContent, $createdAt, $filePath, $fileType, $userNickname);

    $meme_gallery_template = file_get_contents($routerConfig['template_dir'] . 'meme_gallery.html');

    // Fetch the results
    $memes_out = '';
    while ($stmtlist->fetch()) {
        if ($fileType == 'image') {
            $memes_out .= renderMeme($title, $textContent, $createdAt, $filePath, $userNickname);
        }
    }
    $meme_gallery_out = str_replace('__TEMPLATE_MEMES_HERE__', $memes_out, $meme_gallery_template);

// Close the statement
    $stmtlist->close();
    return $meme_gallery_out;
}