<?php
declare(strict_types=1);

namespace App;

use App\Avatar\Lorelei;

final class Community
{
    private ?array $forumStructure = null;
    private array $tableCache = [];
    private array $columnCache = [];

    public function __construct(private \PDO $pdo, private array $config)
    {
    }

    public function getStats(): array
    {
        $threads = (int)$this->pdo->query('SELECT COUNT(*) FROM forum_threads')->fetchColumn();
        $posts = (int)$this->pdo->query('SELECT COUNT(*) FROM forum_posts')->fetchColumn();
        $members = (int)$this->pdo->query('SELECT COUNT(*) FROM users WHERE status = "active"')->fetchColumn();

        return [
            'threads' => $threads,
            'posts' => $posts,
            'members' => $members,
        ];
    }

    public function createThread(int $userId, string $title, string $body): void
    {
        $this->createThreadInBoard($userId, null, $title, $body);
    }

    public function createThreadInBoard(int $userId, ?string $boardSlug, string $title, string $body): void
    {
        $title = trim($title);
        $body = trim($body);
        if ($title === '' || $body === '') {
            throw new \RuntimeException('Titel und Text sind erforderlich.');
        }

        if ($this->hasColumn('forum_threads', 'board_id') && $this->hasTable('forum_boards')) {
            $boardId = null;
            if ($boardSlug !== null && $boardSlug !== '') {
                $board = $this->getBoardBySlug($boardSlug);
                if (!$board) {
                    throw new \RuntimeException('Forum-Bereich nicht gefunden.');
                }
                $boardId = (int)$board['id'];
            }

            $stmt = $this->pdo->prepare('INSERT INTO forum_threads (board_id, user_id, title, body) VALUES (:boardId, :uid, :title, :body)');
            $stmt->bindValue(':boardId', $boardId, $boardId === null ? \PDO::PARAM_NULL : \PDO::PARAM_INT);
            $stmt->bindValue(':uid', $userId, \PDO::PARAM_INT);
            $stmt->bindValue(':title', $title, \PDO::PARAM_STR);
            $stmt->bindValue(':body', $body, \PDO::PARAM_STR);
            $stmt->execute();
            return;
        }

        $stmt = $this->pdo->prepare('INSERT INTO forum_threads (user_id, title, body) VALUES (:uid, :title, :body)');
        $stmt->execute([
            ':uid' => $userId,
            ':title' => $title,
            ':body' => $body,
        ]);
    }

    public function createPost(int $userId, int $threadId, string $body): void
    {
        $stmt = $this->pdo->prepare('INSERT INTO forum_posts (thread_id, user_id, body) VALUES (:tid, :uid, :body)');
        $stmt->execute([
            ':tid' => $threadId,
            ':uid' => $userId,
            ':body' => trim($body),
        ]);
    }

    public function updateThread(int $threadId, string $title, string $body): void
    {
        $stmt = $this->pdo->prepare('UPDATE forum_threads SET title = :title, body = :body, updated_at = NOW() WHERE id = :id');
        $stmt->execute([
            'id' => $threadId,
            'title' => trim($title),
            'body' => trim($body),
        ]);
    }

    public function deleteThread(int $threadId): void
    {
        $stmt = $this->pdo->prepare('DELETE FROM forum_threads WHERE id = :id');
        $stmt->execute(['id' => $threadId]);
    }

    public function updatePost(int $postId, string $body): void
    {
        $stmt = $this->pdo->prepare('UPDATE forum_posts SET body = :body, updated_at = NOW() WHERE id = :id');
        $stmt->execute([
            'id' => $postId,
            'body' => trim($body),
        ]);
    }

    public function deletePost(int $postId): void
    {
        $stmt = $this->pdo->prepare('DELETE FROM forum_posts WHERE id = :id');
        $stmt->execute(['id' => $postId]);
    }

    public function toggleHelpfulHighlight(int $postId, ?int $userId): void
    {
        if (!$this->hasColumn('forum_posts', 'highlighted_at')) {
            return;
        }

        if ($userId === null) {
            $stmt = $this->pdo->prepare('UPDATE forum_posts SET highlighted_by = NULL, highlighted_at = NULL WHERE id = :id');
            $stmt->execute(['id' => $postId]);
            return;
        }

        $stmt = $this->pdo->prepare('UPDATE forum_posts SET highlighted_by = :uid, highlighted_at = NOW() WHERE id = :id');
        $stmt->execute([
            'uid' => $userId,
            'id' => $postId,
        ]);
    }

    public function searchThreads(string $query, int $limit = 50, ?string $boardSlug = null): array
    {
        $conditions = [];
        $params = [];
        $tokens = array_filter(preg_split('/\s+/', trim($query)) ?: [], fn($t) => $t !== '');
        $i = 0;
        foreach ($tokens as $tok) {
            $ph1 = ':t' . $i . 'a';
            $ph2 = ':t' . $i . 'b';
            $conditions[] = "(ft.title LIKE $ph1 OR ft.body LIKE $ph2)";
            $params[$ph1] = '%' . $tok . '%';
            $params[$ph2] = '%' . $tok . '%';
            $i++;
        }
        $defaultBoard = $this->getBoardBySlug('wochenendideen');
        $boardJoin = '';
        $boardSelect = "NULL AS board_slug, NULL AS board_title, NULL AS category_slug, NULL AS category_title";
        if ($this->hasColumn('forum_threads', 'board_id') && $this->hasTable('forum_boards') && $this->hasTable('forum_categories')) {
            $boardJoin = ' LEFT JOIN forum_boards fb ON fb.id = ft.board_id LEFT JOIN forum_categories fc ON fc.id = fb.category_id ';
            $boardSelect = 'fb.slug AS board_slug, fb.title AS board_title, fc.slug AS category_slug, fc.title AS category_title';
        }

        $where = $conditions ? ('AND ' . implode(' AND ', $conditions)) : '';

        $avatarSelect = $this->hasColumn('user_profiles', 'avatar_preset')
            ? ', ' . Lorelei::selectColumns('p')
            : '';
        $sql = "SELECT ft.id, ft.title, ft.body, ft.created_at, ft.updated_at,
                       u.id as uid, u.created_at as user_created,
                       p.display_name$avatarSelect,
                       $boardSelect,
                       (SELECT COUNT(*) FROM forum_posts fp WHERE fp.thread_id = ft.id) AS answers,
                       COALESCE(
                           (SELECT MAX(fp.created_at) FROM forum_posts fp WHERE fp.thread_id = ft.id),
                           ft.created_at
                       ) AS last_activity_at,
                       COALESCE(
                           (
                               SELECT p2.display_name
                               FROM forum_posts fp3
                               JOIN users u2 ON u2.id = fp3.user_id
                               LEFT JOIN user_profiles p2 ON p2.user_id = u2.id
                               WHERE fp3.thread_id = ft.id
                               ORDER BY fp3.created_at DESC
                               LIMIT 1
                           ),
                           p.display_name,
                           'Mitglied'
                       ) AS last_activity_by,
                       (SELECT COUNT(*) FROM forum_posts fp2 WHERE fp2.user_id = u.id) +
                       (SELECT COUNT(*) FROM forum_threads ft2 WHERE ft2.user_id = u.id) AS user_posts
                FROM forum_threads ft
                JOIN users u ON u.id = ft.user_id
                LEFT JOIN user_profiles p ON p.user_id = u.id
                $boardJoin
                WHERE 1=1 $where
                ORDER BY ft.created_at DESC
                LIMIT :lim";
        $stmt = $this->pdo->prepare($sql);
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v, \PDO::PARAM_STR);
        }
        $stmt->bindValue(':lim', $limit, \PDO::PARAM_INT);
        $stmt->execute();
        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
        $rows = array_map(fn(array $row) => $this->applyFallbackBoard($row, $defaultBoard), $rows);
        if ($boardSlug !== null && $boardSlug !== '') {
            $rows = array_values(array_filter($rows, fn(array $row): bool => (string)($row['board_slug'] ?? '') === $boardSlug));
        }
        return $rows;
    }

    public function listThreads(int $limit = 50, ?string $boardSlug = null): array
    {
        return $this->searchThreads('', $limit, $boardSlug);
    }

    public function getThread(int $id): ?array
    {
        $select = 'ft.*, p.display_name';
        if ($this->hasColumn('user_profiles', 'avatar_preset')) {
            $select .= ', ' . Lorelei::selectColumns('p');
        }
        $join = '';
        if ($this->hasColumn('forum_threads', 'board_id') && $this->hasTable('forum_boards') && $this->hasTable('forum_categories')) {
            $select .= ', fb.slug AS board_slug, fb.title AS board_title, fc.slug AS category_slug, fc.title AS category_title';
            $join = ' LEFT JOIN forum_boards fb ON fb.id = ft.board_id LEFT JOIN forum_categories fc ON fc.id = fb.category_id ';
        }
        $stmt = $this->pdo->prepare("SELECT $select FROM forum_threads ft LEFT JOIN user_profiles p ON p.user_id = ft.user_id $join WHERE ft.id = :id");
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        if (!$row) {
            return null;
        }
        return $this->applyFallbackBoard($row, $this->getBoardBySlug('wochenendideen'));
    }

    public function listPosts(int $threadId): array
    {
        $select = 'fp.*, p.display_name';
        if ($this->hasColumn('user_profiles', 'avatar_preset')) {
            $select .= ', ' . Lorelei::selectColumns('p');
        }
        if ($this->hasColumn('forum_posts', 'highlighted_at')) {
            $select .= ', hp.display_name AS highlighted_by_name';
        } else {
            $select .= ', NULL AS highlighted_by_name';
        }
        $join = ' LEFT JOIN user_profiles p ON p.user_id = fp.user_id ';
        if ($this->hasColumn('forum_posts', 'highlighted_at')) {
            $join .= ' LEFT JOIN user_profiles hp ON hp.user_id = fp.highlighted_by ';
        }
        $stmt = $this->pdo->prepare("SELECT $select FROM forum_posts fp $join WHERE fp.thread_id = :id ORDER BY fp.created_at ASC");
        $stmt->execute([':id' => $threadId]);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
    }

    public function getPost(int $postId): ?array
    {
        $stmt = $this->pdo->prepare('SELECT * FROM forum_posts WHERE id = :id LIMIT 1');
        $stmt->execute(['id' => $postId]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        return $row ?: null;
    }

    public function listForumCategories(): array
    {
        $structure = $this->forumStructure();
        $boards = [];
        foreach ($structure as $category) {
            foreach ($category['boards'] as $board) {
                $boards[$board['slug']] = $board;
            }
        }

        $threadsByBoard = [];
        foreach ($this->listThreads(200) as $thread) {
            $slug = (string)($thread['board_slug'] ?? '');
            if ($slug === '' || !isset($boards[$slug])) {
                continue;
            }
            $threadsByBoard[$slug][] = $thread;
        }

        foreach ($structure as &$category) {
            foreach ($category['boards'] as &$board) {
                $items = $threadsByBoard[$board['slug']] ?? [];
                $board['thread_count'] = count($items);
                $replyCount = 0;
                foreach ($items as $item) {
                    $replyCount += (int)($item['answers'] ?? 0);
                }
                $board['post_count'] = $replyCount;
                $board['latest_thread'] = $items[0] ?? null;
            }
            unset($board);
        }
        unset($category);

        return $structure;
    }

    public function getBoardBySlug(string $slug): ?array
    {
        foreach ($this->forumStructure() as $category) {
            foreach ($category['boards'] as $board) {
                if ($board['slug'] === $slug) {
                    if ($this->hasTable('forum_boards')) {
                        $stmt = $this->pdo->prepare('
                            SELECT fb.id, fb.slug, fb.title, fb.description, fb.icon, fc.slug AS category_slug, fc.title AS category_title
                            FROM forum_boards fb
                            JOIN forum_categories fc ON fc.id = fb.category_id
                            WHERE fb.slug = :slug
                            LIMIT 1
                        ');
                        $stmt->execute(['slug' => $slug]);
                        $dbBoard = $stmt->fetch(\PDO::FETCH_ASSOC);
                        if ($dbBoard) {
                            return array_merge($board, $dbBoard);
                        }
                    }

                    return array_merge($board, [
                        'category_slug' => $category['slug'],
                        'category_title' => $category['title'],
                    ]);
                }
            }
        }

        return null;
    }

    public function computePoints(int $userId): float
    {
        // Primär: aggregierte Werte aus user_points_totals, Fallback: Summe aus user_points
        $stmt = $this->pdo->prepare('SELECT total FROM user_points_totals WHERE user_id = :uid');
        $stmt->execute([':uid' => $userId]);
        $total = $stmt->fetchColumn();
        if ($total !== false && $total !== null) {
            return (float)$total;
        }

        $stmt = $this->pdo->prepare('SELECT COALESCE(SUM(amount),0) FROM user_points WHERE user_id = :uid');
        $stmt->execute([':uid' => $userId]);
        return (float)$stmt->fetchColumn();
    }

    /**
     * Vergibt Punkte persistent und berücksichtigt Caps/Bonis gemäß config actions.
     */
    public function addPoints(int $userId, string $group, string $key, array $meta = []): float
    {
        $actions = $this->config['actions'][$group][$key] ?? null;
        if (!$actions || empty($actions['points'])) {
            return 0.0;
        }
        $basePoints = (float)$actions['points'];

        // Boni (einfacher first-Check)
        $bonusPoints = 0.0;
        if (!empty($actions['bonuses'])) {
            if (isset($actions['bonuses']['first'])) {
                $bonusPoints += (float)$actions['bonuses']['first'];
            }
            if (isset($actions['bonuses']['first_helpful_5']) && isset($meta['helpful_count']) && (int)$meta['helpful_count'] >= 5) {
                $bonusPoints += (float)$actions['bonuses']['first_helpful_5'];
            }
        }

        $amount = $basePoints + $bonusPoints;
        if ($amount <= 0) {
            return 0.0;
        }

        $caps = $actions['caps'] ?? [];
        $capDaily = $caps['daily'] ?? null;
        $capTotal = $caps['total'] ?? null;

        $todayStart = (new \DateTimeImmutable('today'))->format('Y-m-d 00:00:00');
        $todayEnd   = (new \DateTimeImmutable('today'))->format('Y-m-d 23:59:59');

        $actionKey = $group . '.' . $key;

        if ($capDaily !== null) {
            $stmt = $this->pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM user_points WHERE user_id = :uid AND action = :action AND created_at BETWEEN :s AND :e");
            $stmt->execute([
                ':uid' => $userId,
                ':action' => $actionKey,
                ':s' => $todayStart,
                ':e' => $todayEnd,
            ]);
            $usedToday = (float)$stmt->fetchColumn();
            $remaining = max(0.0, (float)$capDaily - $usedToday);
            if ($remaining <= 0) {
                return 0.0;
            }
            $amount = min($amount, $remaining);
        }

        if ($capTotal !== null) {
            $stmt = $this->pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM user_points WHERE user_id = :uid AND action = :action");
            $stmt->execute([':uid' => $userId, ':action' => $actionKey]);
            $usedTotal = (float)$stmt->fetchColumn();
            $remaining = max(0.0, (float)$capTotal - $usedTotal);
            if ($remaining <= 0) {
                return 0.0;
            }
            $amount = min($amount, $remaining);
        }

        $stmt = $this->pdo->prepare('INSERT INTO user_points (user_id, action, amount, meta) VALUES (:uid, :action, :amount, :meta)');
        $stmt->execute([
            ':uid' => $userId,
            ':action' => $actionKey,
            ':amount' => $amount,
            ':meta' => $meta ? json_encode($meta) : null,
        ]);

        $stmt = $this->pdo->prepare('INSERT INTO user_points_totals (user_id, total) VALUES (:uid, :amt) ON DUPLICATE KEY UPDATE total = total + VALUES(total)');
        $stmt->execute([':uid' => $userId, ':amt' => $amount]);

        return $amount;
    }

    public function membershipLevel(float $points): array
    {
        $levels = $this->config['levels'] ?? [];
        usort($levels, fn($a,$b) => ($b['min'] ?? 0) <=> ($a['min'] ?? 0));
        foreach ($levels as $lvl) {
            if ($points >= (float)($lvl['min'] ?? 0)) {
                return [
                    'label' => $lvl['label'] ?? 'New Daddy',
                    'icon' => $lvl['icon'] ?? '',
                ];
            }
        }
        $fallback = $levels ? $levels[count($levels)-1] : ['label' => 'New Daddy','icon' => ''];
        return ['label' => $fallback['label'], 'icon' => $fallback['icon'] ?? ''];
    }

    private function forumStructure(): array
    {
        if ($this->forumStructure !== null) {
            return $this->forumStructure;
        }

        $file = dirname(__DIR__, 2) . '/config/community_forums.php';
        $this->forumStructure = file_exists($file) ? (array) require $file : [];
        $this->syncForumStructure();

        return $this->forumStructure;
    }

    private function syncForumStructure(): void
    {
        if (!$this->hasTable('forum_categories') || !$this->hasTable('forum_boards')) {
            return;
        }

        foreach ($this->forumStructure as $categoryIndex => $category) {
            $stmt = $this->pdo->prepare('INSERT INTO forum_categories (slug, title, sort_order) VALUES (:slug, :title, :sortOrder) ON DUPLICATE KEY UPDATE title = VALUES(title), sort_order = VALUES(sort_order)');
            $stmt->execute([
                'slug' => $category['slug'],
                'title' => $category['title'],
                'sortOrder' => $categoryIndex,
            ]);

            $catIdStmt = $this->pdo->prepare('SELECT id FROM forum_categories WHERE slug = :slug LIMIT 1');
            $catIdStmt->execute(['slug' => $category['slug']]);
            $categoryId = (int)$catIdStmt->fetchColumn();

            foreach ($category['boards'] as $boardIndex => $board) {
                $boardStmt = $this->pdo->prepare('
                    INSERT INTO forum_boards (category_id, slug, title, description, icon, sort_order)
                    VALUES (:categoryId, :slug, :title, :description, :icon, :sortOrder)
                    ON DUPLICATE KEY UPDATE
                        category_id = VALUES(category_id),
                        title = VALUES(title),
                        description = VALUES(description),
                        icon = VALUES(icon),
                        sort_order = VALUES(sort_order)
                ');
                $boardStmt->execute([
                    'categoryId' => $categoryId,
                    'slug' => $board['slug'],
                    'title' => $board['title'],
                    'description' => $board['description'],
                    'icon' => $board['icon'] ?? null,
                    'sortOrder' => $boardIndex,
                ]);
            }
        }

        // Migrate legacy uncategorized threads into a default board once board support is available.
        if ($this->hasColumn('forum_threads', 'board_id')) {
            $defaultBoard = $this->getBoardBySlug('wochenendideen');
            if ($defaultBoard && !empty($defaultBoard['id'])) {
                $stmt = $this->pdo->prepare('UPDATE forum_threads SET board_id = :boardId WHERE board_id IS NULL');
                $stmt->execute(['boardId' => (int)$defaultBoard['id']]);
            }
        }
    }

    private function applyFallbackBoard(array $row, ?array $defaultBoard): array
    {
        if (!empty($row['board_slug']) || !$defaultBoard) {
            return $row;
        }

        $row['board_slug'] = $defaultBoard['slug'] ?? null;
        $row['board_title'] = $defaultBoard['title'] ?? null;
        $row['category_slug'] = $defaultBoard['category_slug'] ?? null;
        $row['category_title'] = $defaultBoard['category_title'] ?? null;
        return $row;
    }

    private function hasTable(string $table): bool
    {
        if (array_key_exists($table, $this->tableCache)) {
            return $this->tableCache[$table];
        }

        try {
            $stmt = $this->pdo->prepare('SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :table LIMIT 1');
            $stmt->execute(['table' => $table]);
            return $this->tableCache[$table] = (bool)$stmt->fetchColumn();
        } catch (\Throwable) {
            return $this->tableCache[$table] = false;
        }
    }

    private function hasColumn(string $table, string $column): bool
    {
        $key = $table . '.' . $column;
        if (array_key_exists($key, $this->columnCache)) {
            return $this->columnCache[$key];
        }

        try {
            $stmt = $this->pdo->prepare('SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = :table AND column_name = :column LIMIT 1');
            $stmt->execute([
                'table' => $table,
                'column' => $column,
            ]);
            return $this->columnCache[$key] = (bool)$stmt->fetchColumn();
        } catch (\Throwable) {
            return $this->columnCache[$key] = false;
        }
    }
}
