<?php

namespace App\Http\Controllers;

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

class CourseLibraryController extends Controller
{
    /**
     * Display the course library.
     */
    public function index(): Response
    {
        $levels = Level::with(['courses' => function($query) {
            $query->withCount('modules');
        }])->get();

        $enrolledCourseIds = Enrollment::where('user_id', auth()->id())
            ->pluck('course_id')
            ->toArray();

        return Inertia::render('Courses/Library', [
            'levels' => $levels->map(function($level) use ($enrolledCourseIds) {
                return [
                    'id' => $level->id,
                    'name' => $level->name,
                    'code' => $level->code,
                    'courses' => $level->courses->map(function($course) use ($enrolledCourseIds) {
                        return [
                            'id' => $course->id,
                            'title' => $course->title,
                            'description' => $course->description,
                            'thumbnail' => $course->thumbnail_url,
                            'slug' => $course->slug,
                            'modulesCount' => $course->modules_count,
                            'isEnrolled' => in_array($course->id, $enrolledCourseIds),
                        ];
                    })
                ];
            })
        ]);
    }

    /**
     * Enroll in a course.
     */
    public function enroll(Request $request, Course $course)
    {
        $user = auth()->user();

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

        if (!$exists) {
            Enrollment::create([
                'user_id' => $user->id,
                'course_id' => $course->id,
                'status' => 'active',
                'enrolled_at' => now(),
            ]);
        }

        return redirect()->route('courses.learn', ['course' => $course->slug])
            ->with('status', "Berhasil mendaftar di kursus: {$course->title}");
    }
}
