<?php
include_once '_category.php';

function track_check_category(int $user, int $category): int {
    global $pdo;
    static $cache = [];

    if($user < 1 || $category < 1)
        return false;

    $trackId = "{$user}-{$category}";
    if(isset($cache[$trackId]))
        return $cache[$trackId];

    $cache[$trackId] = 0;
    $children = category_child_ids($category);

    foreach($children as $child)
        $cache[$trackId] += track_check_category($user, $child);

    $countUnread = $pdo->prepare('
        SELECT COUNT(ti.`topic_id`)
        FROM `fmf_topics` AS ti
        LEFT JOIN `fmf_track` AS tt
        ON tt.`topic_id` = ti.`topic_id` AND tt.`user_id` = :user
        WHERE ti.`cat_id` = :category
        AND ti.`topic_bumped` >= NOW() - INTERVAL 1 MONTH
        AND (
            tt.`track_timestamp` IS NULL
            OR tt.`track_timestamp` < ti.`topic_bumped`
        )
    ');
    $countUnread->bindValue('category', $category);
    $countUnread->bindValue('user', $user);
    $cache[$trackId] += $countUnread->execute() ? (int)$countUnread->fetchColumn() : 0;

    return $cache[$trackId];
}

function track_check_topic(int $user, int $topic): bool {
    global $pdo;
    static $cache = [];

    if($user < 1 || $topic < 1)
        return false;

    $trackId = "{$user}-{$topic}";
    if(isset($cache[$trackId]))
        return $cache[$trackId];

    $getUnread = $pdo->prepare('
        SELECT
            :user AS `target_user_id`,
            (
                SELECT
                    `target_user_id` > 0
                AND
                    t.`topic_bumped` > NOW() - INTERVAL 1 MONTH
                AND (
                    SELECT COUNT(ti.`topic_id`) < 1
                    FROM `fmf_track` AS tt
                    RIGHT JOIN `fmf_topics` AS ti
                    ON ti.`topic_id` = tt.`topic_id`
                    WHERE ti.`topic_id` = t.`topic_id`
                    AND tt.`user_id` = `target_user_id`
                    AND `track_timestamp` >= `topic_bumped`
                )
            )
        FROM `fmf_topics` AS t
        WHERE t.`topic_id` = :topic
    ');
    $getUnread->bindValue('user', $user);
    $getUnread->bindValue('topic', $topic);

    return $cache[$trackId] = ($getUnread->execute() ? $getUnread->fetchColumn(1) : false);
}

function update_track(int $user, int $topic, int $category): void {
    global $pdo;

    if($user < 1 || $topic < 1 || $category < 1)
        return;

    $updateTrack = $pdo->prepare('
        REPLACE INTO `fmf_track`
            (`cat_id`, `topic_id`, `user_id`)
        VALUES
            (:category, :topic, :user)
    ');
    $updateTrack->bindValue('category', $category);
    $updateTrack->bindValue('topic', $topic);
    $updateTrack->bindValue('user', $user);
    $updateTrack->execute();
}