<?php
declare(strict_types=1);

namespace App;

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

    public function createThread(int $userId, string $title, string $body): void
    {
        $stmt = $this->pdo->prepare('INSERT INTO forum_threads (user_id, title, body) VALUES (:uid, :title, :body)');
        $stmt->execute([
            ':uid' => $userId,
            ':title' => trim($title),
            ':body' => trim($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 searchThreads(string $query, int $limit = 50): 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++;
        }
        $where = $conditions ? ('AND ' . implode(' AND ', $conditions)) : '';

        $sql = "SELECT ft.id, ft.title, ft.body, ft.created_at,
                       u.id as uid, u.created_at as user_created,
                       p.display_name,
                       (SELECT COUNT(*) FROM forum_posts fp WHERE fp.thread_id = ft.id) AS answers,
                       (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
                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();
        return $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
    }

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

    public function getThread(int $id): ?array
    {
        $stmt = $this->pdo->prepare('SELECT ft.*, p.display_name FROM forum_threads ft LEFT JOIN user_profiles p ON p.user_id = ft.user_id WHERE ft.id = :id');
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        return $row ?: null;
    }

    public function listPosts(int $threadId): array
    {
        $stmt = $this->pdo->prepare('SELECT fp.*, p.display_name FROM forum_posts fp LEFT JOIN user_profiles p ON p.user_id = fp.user_id WHERE fp.thread_id = :id ORDER BY fp.created_at ASC');
        $stmt->execute([':id' => $threadId]);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
    }

    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'] ?? ''];
    }
}
