<?php

namespace App\Models;

use App\Core\Model;

class Topic extends Model
{
    protected static string $table = 'topics';

    public static function findBySite(int $siteId): array
    {
        return self::where('site_id = :site_id', ['site_id' => $siteId], 'name ASC');
    }

    public static function findBySiteWithGlobal(int $siteId): array
    {
        $db = self::db();
        $stmt = $db->prepare(
            "SELECT t.*, g.name as global_topic_name, gp.name as global_category_name
             FROM topics t
             LEFT JOIN global_topics g ON t.global_topic_id = g.id
             LEFT JOIN global_topics gp ON g.parent_id = gp.id
             WHERE t.site_id = :site_id
             ORDER BY COALESCE(gp.name, g.name, t.name) ASC, t.name ASC"
        );
        $stmt->execute(['site_id' => $siteId]);
        return $stmt->fetchAll();
    }

    public static function findActiveBySite(int $siteId): array
    {
        return self::where('site_id = :site_id AND is_active = 1', ['site_id' => $siteId], 'article_count ASC, RAND()');
    }

    public static function incrementArticleCount(int $id): void
    {
        $db = self::db();
        $stmt = $db->prepare("UPDATE topics SET article_count = article_count + 1 WHERE id = :id");
        $stmt->execute(['id' => $id]);
    }

    public static function decrementArticleCount(int $id): void
    {
        $db = self::db();
        $stmt = $db->prepare("UPDATE topics SET article_count = GREATEST(article_count - 1, 0) WHERE id = :id");
        $stmt->execute(['id' => $id]);
    }
}
