<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\DocumentModel;
use App\Models\ActivityLogModel;
use App\Models\UserProfileModel;

class DashboardController extends BaseController
{
    public function index()
    {
        $docModel  = model(DocumentModel::class);
        $userModel = model(UserProfileModel::class);

        $docStats  = $docModel->getStats();
        $topCited  = $docModel->getTopCited(5);
        $topDl     = $docModel->where('status', 'published')
                              ->orderBy('download_count', 'DESC')
                              ->limit(5)->findAll();
        $recentLogs = model(ActivityLogModel::class)->getRecentLogs(10);

        $userCounts = [
            'total'   => $userModel->countAll(),
            'student' => $userModel->where('role', 'student')->countAllResults(),
            'lecturer'=> $userModel->where('role', 'lecturer')->countAllResults(),
            'admin'   => $userModel->whereIn('role', ['admin','super_admin'])->countAllResults(),
        ];

        // Store name + role in session for display
        $user    = auth()->user();
        $profile = model(UserProfileModel::class)->findByUserId($user->id);
        session()->set('user_name', $profile['name'] ?? $user->username);
        session()->set('user_role', $profile['role'] ?? 'admin');

        return view('admin/dashboard', [
            'title'       => 'Dashboard',
            'docStats'    => $docStats,
            'topCited'    => $topCited,
            'topDl'       => $topDl,
            'recentLogs'  => $recentLogs,
            'userCounts'  => $userCounts,
        ]);
    }
}
