<?php

namespace App\Services\Administrator;

use App\Models\LoginActivity;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class AdministratorMetricsService
{
    public function __construct(
        protected AdministratorSharedService $shared,
        protected User $userModel,
        protected LoginActivity $loginActivityModel,
    ) {
    }

    public function metrics(): array
    {
        $schoolYear = $this->shared->getSchoolYear();
        $semester = $this->shared->getSemester();

        $recentActivities = method_exists($this->loginActivityModel, 'getLastActivities')
            ? ($this->loginActivityModel->getLastActivities(4) ?? [])
            : [];

        $totalAdmins = method_exists($this->userModel, 'countAdminsBySchoolYear')
            ? (int) ($this->userModel->countAdminsBySchoolYear($schoolYear) ?? 0)
            : 0;

        $teachers = method_exists($this->userModel, 'getUsersByRoleAndSchoolYear')
            ? ($this->userModel->getUsersByRoleAndSchoolYear('teacher', $schoolYear) ?? [])
            : [];

        $teacherAssistants = method_exists($this->userModel, 'getUsersByRoleAndSchoolYear')
            ? ($this->userModel->getUsersByRoleAndSchoolYear('teacher_assistant', $schoolYear) ?? [])
            : [];

        $parents = method_exists($this->userModel, 'getUsersByRoleAndSchoolYear')
            ? ($this->userModel->getUsersByRoleAndSchoolYear('parent', $schoolYear) ?? [])
            : [];

        $totalStudents = (int) (
            DB::table('student_class')
                ->join('students', 'students.id', '=', 'student_class.student_id')
                ->where('student_class.school_year', $schoolYear)
                ->whereNotNull('student_class.class_section_id')
                ->where('students.is_active', 1)
                ->distinct('student_class.student_id')
                ->count('student_class.student_id')
        );

        return [
            'counts' => [
                'students' => $totalStudents,
                'teachers' => $this->shared->countUniqueEntities($teachers),
                'teacherAssistants' => $this->shared->countUniqueEntities($teacherAssistants),
                'admins' => $totalAdmins,
                'parents' => $this->shared->countUniqueEntities($parents),
            ],
            'recentActivities' => collect($recentActivities)->map(function ($activity) {
                return [
                    'login_time' => is_array($activity) ? ($activity['login_time'] ?? null) : ($activity->login_time ?? null),
                    'email' => is_array($activity) ? ($activity['email'] ?? null) : ($activity->email ?? null),
                ];
            })->values()->all(),
            'meta' => [
                'schoolYear' => $schoolYear,
                'semester' => $semester,
            ],
        ];
    }
}