<?php

namespace Modules\Users\Services;

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

class UserService
{
    /**
     * Get role statistics for dashboard
     */
    public function getRoleStatistics(): array
    {
        return [
            'total' => User::count(),
            'admin' => User::where('role', 'admin')->count(),
            'teacher' => User::where('role', 'teacher')->count(),
            'student' => User::where('role', 'student')->count(),
            'guardian' => User::where('role', 'guardian')->count(),
            'active' => User::where('is_active', true)->count(),
            'inactive' => User::where('is_active', false)->count(),
        ];
    }

    /**
     * Get user activity summary
     */
    public function getUserActivitySummary(int $userId): array
    {
        $user = User::find($userId);
        
        if (!$user) {
            return [];
        }

        $summary = [
            'last_login' => $user->last_login_at ?? null,
            'created_at' => $user->created_at,
            'is_active' => $user->is_active,
        ];

        // Add role-specific activity data
        switch ($user->role) {
            case 'student':
                if ($user->student) {
                    $summary['enrollment_count'] = $user->student->enrollments()->count();
                    $summary['result_count'] = DB::table('results')
                        ->where('student_id', $user->student->id)
                        ->count();
                }
                break;

            case 'teacher':
                if ($user->teacher) {
                    $summary['subject_count'] = $user->teacher->subjects()->count();
                    $summary['classroom_count'] = $user->teacher->classrooms()->count();
                }
                break;

            case 'guardian':
                if ($user->guardian) {
                    $summary['children_count'] = $user->guardian->students()->count();
                }
                break;
        }

        return $summary;
    }

    /**
     * Get role-specific data for user
     */
    public function getRoleSpecificData(User $user): array
    {
        $data = [];

        switch ($user->role) {
            case 'student':
                if ($user->student) {
                    $data = [
                        'student_id' => $user->student->student_id,
                        'admission_date' => $user->student->admission_date,
                        'current_enrollments' => $user->student->enrollments()
                            ->with(['classroom.academicYear', 'academicYear'])
                            ->where('is_active', true)
                            ->get(),
                        'recent_results' => DB::table('results')
                            ->join('subjects', 'results.subject_id', '=', 'subjects.id')
                            ->join('exam_types', 'results.exam_type_id', '=', 'exam_types.id')
                            ->where('results.student_id', $user->student->id)
                            ->select('subjects.name as subject_name', 'exam_types.name as exam_name', 'results.marks', 'results.entered_at')
                            ->orderBy('results.entered_at', 'desc')
                            ->limit(5)
                            ->get(),
                    ];
                }
                break;

            case 'teacher':
                if ($user->teacher) {
                    $data = [
                        'teacher_id' => $user->teacher->teacher_id,
                        'hire_date' => $user->teacher->hire_date,
                        'qualification' => $user->teacher->qualification,
                        'subjects' => $user->teacher->subjects()->with('classroom')->get(),
                        'classrooms' => $user->teacher->classrooms()->with('academicYear')->get(),
                    ];
                }
                break;

            case 'guardian':
                if ($user->guardian) {
                    $data = [
                        'occupation' => $user->guardian->occupation,
                        'relationship' => $user->guardian->relationship,
                        'children' => $user->guardian->students()
                            ->with(['user', 'enrollments.classroom'])
                            ->get(),
                    ];
                }
                break;

            case 'admin':
                $data = [
                    'system_stats' => $this->getRoleStatistics(),
                    'recent_activities' => $this->getRecentSystemActivities(),
                ];
                break;
        }

        return $data;
    }

    /**
     * Create a new user with role-specific profile
     */
    public function createUser(array $data): User
    {
        DB::beginTransaction();

        try {
            // Create user account
            $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => Hash::make($data['password'] ?? 'password123'),
                'role' => $data['role'],
                'is_active' => $data['is_active'] ?? true,
            ]);

            // Create role-specific profile if needed
            $this->createRoleSpecificProfile($user, $data);

            DB::commit();

            return $user->load(['student', 'teacher', 'guardian']);

        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    /**
     * Update user information
     */
    public function updateUser(User $user, array $data): User
    {
        DB::beginTransaction();

        try {
            // Update user account
            $userUpdateData = [
                'name' => $data['name'],
                'email' => $data['email'],
            ];

            if (isset($data['password']) && !empty($data['password'])) {
                $userUpdateData['password'] = Hash::make($data['password']);
            }

            if (isset($data['is_active'])) {
                $userUpdateData['is_active'] = $data['is_active'];
            }

            $user->update($userUpdateData);

            // Update role-specific profile if needed
            $this->updateRoleSpecificProfile($user, $data);

            DB::commit();

            return $user->load(['student', 'teacher', 'guardian']);

        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    /**
     * Get recent system activities for admin dashboard
     */
    private function getRecentSystemActivities(): array
    {
        // This would typically come from an activity log table
        // For now, return recent user registrations
        return User::latest()
            ->limit(10)
            ->get(['id', 'name', 'email', 'role', 'created_at'])
            ->toArray();
    }

    /**
     * Create role-specific profile
     */
    private function createRoleSpecificProfile(User $user, array $data): void
    {
        switch ($user->role) {
            case 'student':
                if (isset($data['student_data'])) {
                    $user->student()->create(array_merge($data['student_data'], [
                        'user_id' => $user->id,
                    ]));
                }
                break;

            case 'teacher':
                if (isset($data['teacher_data'])) {
                    $user->teacher()->create(array_merge($data['teacher_data'], [
                        'user_id' => $user->id,
                    ]));
                }
                break;

            case 'guardian':
                if (isset($data['guardian_data'])) {
                    $user->guardian()->create(array_merge($data['guardian_data'], [
                        'user_id' => $user->id,
                    ]));
                }
                break;
        }
    }

    /**
     * Update role-specific profile
     */
    private function updateRoleSpecificProfile(User $user, array $data): void
    {
        switch ($user->role) {
            case 'student':
                if (isset($data['student_data']) && $user->student) {
                    $user->student->update($data['student_data']);
                }
                break;

            case 'teacher':
                if (isset($data['teacher_data']) && $user->teacher) {
                    $user->teacher->update($data['teacher_data']);
                }
                break;

            case 'guardian':
                if (isset($data['guardian_data']) && $user->guardian) {
                    $user->guardian->update($data['guardian_data']);
                }
                break;
        }
    }
}
