<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Core\Database;

class DashboardController extends Controller
{
    public function index(Request $request): Response
    {
        $db = Database::getInstance();
        $userId = Session::get('user_id');

        $postStmt = $db->prepare("SELECT COUNT(*) FROM posts WHERE user_id = ?");
        $postStmt->execute([$userId]);
        $myPostsCount = (int)$postStmt->fetchColumn();

        $data = [
            'total_posts' => (int)$db->query("SELECT COUNT(*) FROM posts")->fetchColumn(),
            'total_users' => (int)$db->query("SELECT COUNT(*) FROM users")->fetchColumn(),
            'total_comments' => (int)$db->query("SELECT COUNT(*) FROM comments")->fetchColumn(),
            'my_posts' => $myPostsCount,
        ];

        return $this->render('dashboard.index', compact('data'));
    }

    public function getQuickStats(Request $request): Response
    {
        $db = Database::getInstance();
        $userId = Session::get('user_id');

        $notifStmt = $db->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0");
        $notifStmt->execute([$userId]);
        $unreadNotif = (int)$notifStmt->fetchColumn();

        $userStmt = $db->prepare("SELECT reputation FROM users WHERE id = ?");
        $userStmt->execute([$userId]);
        $user = $userStmt->fetch();
        $level = $user ? (int)floor($user['reputation'] / 100) : 0;

        return Response::json([
            'unread_notifications' => $unreadNotif,
            'level' => $level,
        ]);
    }
}
