<?php

require_once "lib/upload.php";
require_once "lib/account.php";

function addMeme(string $title, string $memeText, int $imageID): array
{
    global $mysqli;
    $output = ["Status" => "Fail"];
    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";
        }
    }
    return $output;
}

function renderMeme(int $id, int $authorId, string $title, string $textContent, string $createdAt, string $filePath, int $imageWidth, int $imageHeight, string $userNickname, string $meme_template): string
{

    $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);
    $meme_out = str_replace('__TEMPLATE_MEME_IMAGE_WIDTH__', strval($imageWidth), $meme_out);
    $meme_out = str_replace('__TEMPLATE_MEME_IMAGE_HEIGHT__', strval($imageHeight), $meme_out);
    $meme_out = str_replace('__TEMPLATE_MEME_DELETE_BUTTON__', (isModerator() || $_SESSION['ID'] == $authorId) ? "<button onclick=\"deleteMeme($id);\"><i class='ri-delete-bin-line'></i></button>" : '', $meme_out);

    $meme_votes = calculateNetVotes($id);
    $meme_net_votes = $meme_votes['NetVotes'];

    if ($meme_votes['UserVote'] > 0){
        $meme_upvote_active = 'fill';
        $meme_downvote_active = 'line';
        $meme_vote_counter_class = 'positive';
    }
    elseif (($meme_votes['UserVote'] < 0)) {
        $meme_upvote_active = 'line';
        $meme_downvote_active = 'fill';
        $meme_vote_counter_class = 'negative';
    }
    else {
        $meme_downvote_active = 'line';
        $meme_upvote_active = 'line';
        $meme_vote_counter_class = 'neutral';
    }
    $meme_upvote = isLoggedIn() ? "<button onclick=\"voteMeme($id, 1);\"> <i id='meme_votes_upvote_$id' class=\"ri-arrow-up-circle-$meme_upvote_active\"></i></button>" : '';
    $meme_downvote = isLoggedIn() ? "<button onclick=\"voteMeme($id, 0);\"> <i id='meme_votes_downvote_$id' class=\"ri-arrow-down-circle-$meme_downvote_active\"></i></button>" : '';

    $meme_out = str_replace('__TEMPLATE_MEME_VOTES_NUMBER__', strval($meme_net_votes), $meme_out);
    $meme_out = str_replace('__TEMPLATE_MEME_UPVOTE__', $meme_upvote, $meme_out);
    $meme_out = str_replace('__TEMPLATE_MEME_DOWNVOTE__', $meme_downvote, $meme_out);
    $meme_out = str_replace('__TEMPLATE_MEME_ID__', strval($id), $meme_out);
    $meme_out = str_replace('__TEMPLATE_MEME_VOTE_COUNTER_CLASS__', $meme_vote_counter_class, $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, Memes.AuthorID, Files.Path, Files.Width, Files.Height, 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
    $memeID = 0;
    $authorID = 0;
    $title = "";
    $textContent = "";
    $filePath = "";
    $fileType = "";
    $userNickname = "";
    $createdAt = "";
    $imageWidth = 0;
    $imageHeight = 0;
    // Bind the result variables
    $stmtlist->bind_result($memeID, $title, $textContent, $createdAt, $authorID, $filePath, $imageWidth, $imageHeight, $fileType, $userNickname);
    $stmtlist->execute();

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

    // Fetch the results
    $memes_out = '';
    $meme_template = file_get_contents($routerConfig['template_dir'] . "meme.html");
    $stmtlist->store_result();
    while ($stmtlist->fetch()) {
        if (str_starts_with($fileType, 'image')) {
            $memes_out .= renderMeme($memeID, $authorID, $title, $textContent, $createdAt, $filePath, $imageWidth, $imageHeight, $userNickname, $meme_template);
        }
    }
    $meme_add = isLoggedIn() ? file_get_contents($routerConfig['template_dir'] . 'meme_add.html') : '';
    $meme_gallery_out = str_replace('__TEMPLATE_MEMES_HERE__', $memes_out, $meme_gallery_template);
    $meme_gallery_out = str_replace('__TEMPLATE_MEME_ADD__', $meme_add, $meme_gallery_out);

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

function deleteMeme(int $memeID): array
{
    global $mysqli;
    $out = ["Status" => "Fail"];
    if (isLoggedIn()) {
        $query = !isModerator() ? 'DELETE FROM Memes WHERE ID = ? AND AuthorID = ?' : 'DELETE FROM Memes WHERE ID = ?';
        $stmtDelete = $mysqli->prepare($query);
        if (!isModerator()) {
            $stmtDelete->bind_param('ii', $memeID, $_SESSION['ID']);
        } else {
            $stmtDelete->bind_param('i', $memeID);
        }
        $stmtDelete->execute();
        if ($stmtDelete->affected_rows > 0) {
            $out['Status'] = 'Success';
        }
        $stmtDelete->close();
    }
    return $out;
}

function voteMeme(int $memeID, int $isUpvote): array
{
    global $mysqli;
    $out = ["Status" => "Fail"];
    if ($isUpvote != 1) {
        $isUpvote = 0;
    }
    $memeVoteConn = $mysqli->prepare('INSERT INTO MemeVotes (MemeID, UserID, isUpvote) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE isUpvote = VALUES(isUpvote)');
    $memeVoteConn->bind_param('iii', $memeID, $_SESSION['ID'], $isUpvote);
    $memeVoteConn->execute();
    if ($memeVoteConn->affected_rows > 0) {
        $out['Status'] = 'Success';
    }
    $memeVoteConn->close();
    return $out;
}

function deleteVoteMeme(int $memeID): array
{
    global $mysqli;
    $out = ["Status" => "Fail"];
    $memeVoteConn = $mysqli->prepare('DELETE FROM MemeVotes WHERE MemeID = ? AND UserID = ?');
    $memeVoteConn->bind_param('ii', $memeID, $_SESSION['ID']);
    $memeVoteConn->execute();
    if ($memeVoteConn->affected_rows > 0) {
        $out['Status'] = 'Success';
    }
    $memeVoteConn->close();
    return $out;
}

function calculateNetVotes(int $memeID): array
{
    global $mysqli;

    $query = 'SELECT isUpvote, UserID FROM MemeVotes WHERE MemeID = ?';
    $stmt = $mysqli->prepare($query);
    $stmt->bind_param('i', $memeID);
    $stmt->execute();
    $result = $stmt->get_result();

    $netVotes = 0;
    $userVote = 0;
    while ($row = $result->fetch_assoc()) {
        $vote = ($row['isUpvote'] == 1) ? 1 : -1;
        $netVotes += $vote;
        if ($row['UserID'] == $_SESSION['ID']) {
            $userVote = $vote;
        }
    }

    $stmt->close();

    return [
        "NetVotes" => $netVotes,
        "UserVote" => $userVote
    ];
}

function getMemeVotes(int $memeID): array
{
    $voteData = calculateNetVotes($memeID);
    return [
        "Status" => "Success",
        "NetVotes" => $voteData['NetVotes'],
        "UserVote" => $voteData['UserVote']
    ];
}