<?php

namespace App\Http\Controllers\Api\V1\Instructor;

use App\Http\Controllers\Api\V1\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use App\Models\Course;
use App\Models\Enrollment;
use App\Models\ClassSessionVideo;
use App\Models\Assignment;
use App\Models\AssignmentSubmission;

class DashboardController extends BaseController
{
    /**
     * Get instructor dashboard statistics.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        try {
            $instructor = Auth::user();
            
            // Get instructor's course IDs
            $courseIds = Course::where('instructor_id', $instructor->id)
                ->where('is_active', true)
                ->pluck('id');
            
            // Statistics
            $totalCourses = Course::where('instructor_id', $instructor->id)
                ->where('is_active', true)
                ->count();
            
            $totalStudents = Enrollment::whereIn('course_id', $courseIds)
                ->distinct()
                ->count('student_id');
            
            $totalEnrollments = Enrollment::whereIn('course_id', $courseIds)->count();
            
            $totalVideos = ClassSessionVideo::whereIn('course_id', $courseIds)
                ->where('is_published', true)
                ->count();
            
            $totalAssignments = Assignment::whereIn('course_id', $courseIds)->count();
            
            $pendingGradings = AssignmentSubmission::whereHas('assignment', function($q) use ($courseIds) {
                $q->whereIn('course_id', $courseIds);
            })
            ->where('status', 'submitted')
            ->count();
            
            // Recent activities
            $recentCourses = Course::where('instructor_id', $instructor->id)
                ->where('is_active', true)
                ->orderBy('updated_at', 'desc')
                ->limit(5)
                ->get()
                ->map(function($course) {
                    return [
                        'id' => $course->id,
                        'name' => $course->name,
                        'code' => $course->code,
                        'updated_at' => $course->updated_at,
                    ];
                });
            
            $recentEnrollments = Enrollment::whereIn('course_id', $courseIds)
                ->with(['student', 'course'])
                ->orderBy('created_at', 'desc')
                ->limit(5)
                ->get()
                ->map(function($enrollment) {
                    return [
                        'id' => $enrollment->id,
                        'student' => [
                            'id' => $enrollment->student->id ?? null,
                            'name' => $enrollment->student->name ?? 'N/A',
                        ],
                        'course' => [
                            'id' => $enrollment->course->id ?? null,
                            'name' => $enrollment->course->name ?? 'N/A',
                        ],
                        'enrolled_at' => $enrollment->created_at,
                    ];
                });
            
            $recentVideos = ClassSessionVideo::whereIn('course_id', $courseIds)
                ->with('course')
                ->where('is_published', true)
                ->orderBy('session_date', 'desc')
                ->limit(5)
                ->get()
                ->map(function($video) {
                    return [
                        'id' => $video->id,
                        'title' => $video->title,
                        'course' => [
                            'id' => $video->course->id ?? null,
                            'name' => $video->course->name ?? 'N/A',
                        ],
                        'session_date' => $video->session_date,
                    ];
                });
            
            return $this->success([
                'statistics' => [
                    'total_courses' => $totalCourses,
                    'total_students' => $totalStudents,
                    'total_enrollments' => $totalEnrollments,
                    'total_videos' => $totalVideos,
                    'total_assignments' => $totalAssignments,
                    'pending_gradings' => $pendingGradings,
                ],
                'recent_activities' => [
                    'courses' => $recentCourses,
                    'enrollments' => $recentEnrollments,
                    'videos' => $recentVideos,
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Instructor Dashboard API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching dashboard data.', null, 500);
        }
    }
}

