<?php
namespace Misuzu;

use RuntimeException;

if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_FORUM_LEADERBOARD_VIEW))
    Template::throwError(403);

$forumCtx = $msz->getForumContext();
$usersCtx = $msz->getUsersContext();
$config = $cfg->getValues([
    ['forum_leader.first_year:i', 2018],
    ['forum_leader.first_month:i', 12],
    'forum_leader.unranked.forum:a',
    'forum_leader.unranked.topic:a',
]);

$mode = (string)filter_input(INPUT_GET, 'mode');
$yearMonth = (string)filter_input(INPUT_GET, 'id');
$year = $month = 0;

$currentYear = (int)date('Y');
$currentMonth = (int)date('m');

if(!empty($yearMonth)) {
    $yearMonthLength = strlen($yearMonth);
    if(($yearMonthLength !== 4 && $yearMonthLength !== 6) || !ctype_digit($yearMonth))
        Template::throwError(404);

    $year = (int)substr($yearMonth, 0, 4);
    if($year < $config['forum_leader.first_year'] || $year > $currentYear)
        Template::throwError(404);

    if($yearMonthLength === 6) {
        $month = (int)substr($yearMonth, 4, 2);
        if($month < 1 || $month > 12 || ($year === $config['forum_leader.first_year'] && $month < $config['forum_leader.first_month']))
            Template::throwError(404);
    }
}

if(filter_has_var(INPUT_GET, 'allow_unranked')) {
    $unrankedForums = $unrankedTopics = [];
} else {
    $unrankedForums = $config['forum_leader.unranked.forum'];
    $unrankedTopics = $config['forum_leader.unranked.topic'];
}

$years = $months = [];

for($i = $currentYear; $i >= $config['forum_leader.first_year']; $i--)
    $years[(string)$i] = sprintf('Leaderboard %d', $i);

for($i = $currentYear, $j = $currentMonth;;) {
    $months[sprintf('%d%02d', $i, $j)] = sprintf('Leaderboard %d-%02d', $i, $j);

    if($j <= 1) {
        $i--; $j = 12;
    } else $j--;

    if($i <= $config['forum_leader.first_year'] && $j < $config['forum_leader.first_month'])
        break;
}

$rankings = $forumCtx->getPosts()->generatePostRankings($year, $month, $unrankedForums, $unrankedTopics);
foreach($rankings as $ranking) {
    $ranking->user = $ranking->colour = null;

    if($ranking->userId !== '')
        $ranking->user = $usersCtx->getUserInfo($ranking->userId);
}

$name = 'All Time';

if($year > 0) {
    $name = sprintf("Leaderboard %04d", $year);

    if($month > 0)
        $name .= sprintf("-%02d", $month);
}

if($mode === 'markdown') {
    $markdown = <<<MD
# {$name}

| Rank | Usename | Post count |
| ----:|:------- | ----------:|

MD;

    $totalPostsCount = 0;

    foreach($rankings as $ranking) {
        $totalPostsCount += $ranking->postsCount;
        $markdown .= sprintf("| %s | [%s](%s%s) | %s |\r\n", $ranking->position,
            $ranking->user?->getName() ?? 'Deleted User',
            $msz->getSiteInfo()->getURL(),
            $msz->getURLs()->format('user-profile', ['user' => $ranking->userId]),
            number_format($ranking->postsCount));
    }

    $markdown .= sprintf("\r\nIn total %s posts were made!\r\n", number_format($totalPostsCount));

    Template::set('leaderboard_markdown', $markdown);
}

Template::render('forum.leaderboard', [
    'leaderboard_id' => $yearMonth,
    'leaderboard_name' => $name,
    'leaderboard_years' => $years,
    'leaderboard_months' => $months,
    'leaderboard_data' => $rankings,
    'leaderboard_mode' => $mode,
]);
