<?php

namespace App\Http\Controllers;

use App\Models\Course;
use App\Models\Lesson;
use App\Models\Enrollment;
use App\Models\UserProgress;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class CoursePlayerController extends Controller
{
    /**
     * Display the course player.
     */
    public function show(Request $request, string $courseSlug, string $lessonSlug = null): Response
    {
        $user = $request->user();
        
        $course = Course::where('slug', $courseSlug)
            ->with(['modules.lessons'])
            ->firstOrFail();

        // Check enrollment
        $isEnrolled = Enrollment::where('user_id', $user->id)
            ->where('course_id', $course->id)
            ->exists();

        if (!$isEnrolled) {
            return Inertia::render('Errors/Unauthorized', [
                'message' => 'Anda belum terdaftar di kursus ini.'
            ]);
        }

        // Get all lessons for navigation and progress check
        $allLessons = $course->modules->flatMap->lessons;
        
        // Find current lesson with vocabularies
        $currentLesson = $lessonSlug 
            ? Lesson::where('slug', $lessonSlug)->with('vocabularies')->firstOrFail()
            : $allLessons->first()->load('vocabularies');

        // Get user progress for this course
        $completedLessonsIds = UserProgress::where('user_id', $user->id)
            ->whereIn('lesson_id', $allLessons->pluck('id'))
            ->pluck('lesson_id')
            ->toArray();

        return Inertia::render('Courses/Player', [
            'course' => [
                'id' => $course->id,
                'title' => $course->title,
                'slug' => $course->slug,
                'modules' => $course->modules->map(function ($module) use ($completedLessonsIds) {
                    return [
                        'id' => $module->id,
                        'title' => $module->title,
                        'lessons' => $module->lessons->map(function ($lesson) use ($completedLessonsIds) {
                            return [
                                'id' => $lesson->id,
                                'title' => $lesson->title,
                                'slug' => $lesson->slug,
                                'type' => $lesson->type,
                                'is_completed' => in_array($lesson->id, $completedLessonsIds),
                            ];
                        })
                    ];
                })
            ],
            'currentLesson' => [
                'id' => $currentLesson->id,
                'title' => $currentLesson->title,
                'slug' => $currentLesson->slug,
                'type' => $currentLesson->type,
                'content' => $currentLesson->content,
                'video_url' => $currentLesson->video_url,
                'content_pdf' => $currentLesson->content_pdf,
                'vocabularies' => $currentLesson->vocabularies,
            ],
            'progress' => [
                'completed_count' => count($completedLessonsIds),
                'total_count' => count($allLessons),
                'percentage' => count($allLessons) > 0 ? round((count($completedLessonsIds) / count($allLessons)) * 100) : 0,
            ]
        ]);
    }

    /**
     * Mark a lesson as completed.
     */
    public function complete(Request $request, Lesson $lesson)
    {
        $user = $request->user();

        $alreadyCompleted = UserProgress::where('user_id', $user->id)
            ->where('lesson_id', $lesson->id)
            ->exists();

        UserProgress::updateOrCreate(
            ['user_id' => $user->id, 'lesson_id' => $lesson->id],
            ['completed_at' => now()]
        );

        if (!$alreadyCompleted) {
            $user->increment('xp_points', 50);
        }

        return back()->with('success', 'Materi selesai! +50 XP');
    }
}
