<?php

namespace App\Http\Controllers;

use App\Models\Course;
use App\Models\Enrollment;
use Illuminate\Http\Request;
use App\Services\SrsService;
use Inertia\Inertia;
use Inertia\Response;

class DashboardController extends Controller
{
    protected $srsService;

    public function __construct(SrsService $srsService)
    {
        $this->srsService = $srsService;
    }

    /**
     * Display the student dashboard.
     */
    public function index(Request $request): Response
    {
        $user = $request->user();
        
        // Fetch enrolled courses with their progress
        $enrolledCourses = Enrollment::where('user_id', $user->id)
            ->with(['course' => function($query) {
                $query->withCount('modules');
                $query->with(['level']);
            }])
            ->get()
            ->map(function ($enrollment) use ($user) {
                $course = $enrollment->course;
                
                // Calculate progress (this logic will be refined in the future)
                // For now, we'll try to find any completed lessons in this course
                $totalLessons = \App\Models\Lesson::whereIn('module_id', $course->modules->pluck('id'))->count();
                $completedLessonsCount = \App\Models\UserProgress::where('user_id', $user->id)
                    ->whereIn('lesson_id', function($query) use ($course) {
                        $query->select('id')
                            ->from('lessons')
                            ->whereIn('module_id', $course->modules->pluck('id'));
                    })
                    ->count();

                $progress = $totalLessons > 0 ? round(($completedLessonsCount / $totalLessons) * 100) : 0;

                return [
                    'id' => $course->id,
                    'title' => $course->title,
                    'thumbnail' => $course->thumbnail_url,
                    'level' => $course->level->code ?? 'Basic',
                    'progress' => $progress,
                    'lessonsCount' => $totalLessons,
                    'completedLessons' => $completedLessonsCount,
                    'slug' => $course->slug,
                ];
            });

        // Fetch Real SRS Stats
        $dueCount = $this->srsService->getDueReviews($user, 1000)->count();
        $newCount = $this->srsService->getNewCards($user, 1000)->count();

        return Inertia::render('Dashboard', [
            'stats' => [
                'xp_points' => $user->xp_points ?? 0,
                'current_streak' => $user->current_streak ?? 0,
                'active_courses' => $enrolledCourses->count(),
                'certificates' => 0, 
                'srs_due' => $dueCount,
                'srs_new' => $newCount,
            ],
            'activeCourses' => $enrolledCourses,
            'user' => [
                'name' => $user->name,
                'avatar' => $user->avatar_url,
                'rank' => 'Genin',
                'xp_points' => $user->xp_points ?? 0,
            ]
        ]);
    }
}
