<?php

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

use App\Http\Controllers\Api\V1\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Course;
use App\Models\Enrollment;
use App\Models\CourseChapter;
use App\Models\ChapterProgress;

class CourseController extends BaseController
{
    /**
     * Get list of enrolled courses.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        try {
            $user = Auth::user();
            
            $query = Enrollment::where('student_id', $user->id)
                ->with(['course', 'courseOffering', 'course.instructor']);
            
            // Search
            if ($request->has('search') && $request->search) {
                $search = $request->search;
                $query->whereHas('course', function($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('code', 'like', "%{$search}%");
                });
            }
            
            // Filter by status
            if ($request->has('status') && $request->status) {
                $query->where('status', $request->status);
            }
            
            $enrollments = $query->orderBy('enrollment_date', 'desc')
                ->paginate($request->get('per_page', 20));
            
            $courses = $enrollments->map(function($enrollment) use ($user) {
                $course = $enrollment->course;
                if (!$course) return null;
                
                // Calculate progress
                $totalChapters = CourseChapter::where('course_id', $course->id)->count();
                $completedChapters = ChapterProgress::where('student_id', $user->id)
                    ->where('course_id', $course->id)
                    ->where('status', 'completed')
                    ->count();
                
                $progress = $totalChapters > 0 ? ($completedChapters / $totalChapters) * 100 : 0;
                
                return [
                    'id' => $course->id,
                    'title' => $course->name,
                    'code' => $course->code,
                    'description' => $course->description,
                    'level' => $course->level,
                    'fees' => $course->fees,
                    'thumbnail' => null, // Add if available
                    'instructor' => $course->instructor ? [
                        'id' => $course->instructor->id,
                        'name' => $course->instructor->name,
                    ] : null,
                    'progress' => round($progress, 2),
                    'total_chapters' => $totalChapters,
                    'completed_chapters' => $completedChapters,
                    'enrolled_at' => $enrollment->enrollment_date ?? $enrollment->created_at,
                ];
            })->filter()->values();
            
            return $this->paginated($courses, $enrollments);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Student Courses API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching courses.', null, 500);
        }
    }
    
    /**
     * Get course details.
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        try {
            $user = Auth::user();
            
            // Verify enrollment
            $enrollment = Enrollment::where('student_id', $user->id)
                ->where('course_id', $id)
                ->with(['course', 'courseOffering', 'course.instructor', 'course.chapters'])
                ->firstOrFail();
            
            $course = $enrollment->course;
            
            // Get chapters with progress
            $chapters = CourseChapter::where('course_id', $course->id)
                ->orderBy('order')
                ->get()
                ->map(function($chapter) use ($user) {
                    $progress = ChapterProgress::where('student_id', $user->id)
                        ->where('chapter_id', $chapter->id)
                        ->first();
                    
                    $isCompleted = $progress && $progress->status === 'completed';
                    
                    return [
                        'id' => $chapter->id,
                        'title' => $chapter->title,
                        'order' => $chapter->order,
                        'is_completed' => $isCompleted,
                        'completed_at' => $isCompleted ? ($progress->completed_at ?? $progress->updated_at) : null,
                    ];
                });
            
            // Calculate overall progress
            $totalChapters = $chapters->count();
            $completedChapters = $chapters->where('is_completed', true)->count();
            $progress = $totalChapters > 0 ? ($completedChapters / $totalChapters) * 100 : 0;
            
            return $this->success([
                'id' => $course->id,
                'title' => $course->name,
                'code' => $course->code,
                'description' => $course->description,
                'level' => $course->level,
                'fees' => $course->fees,
                'thumbnail' => null,
                'instructor' => $course->instructor ? [
                    'id' => $course->instructor->id,
                    'name' => $course->instructor->name,
                    'email' => $course->instructor->email,
                ] : null,
                'chapters' => $chapters,
                'progress' => round($progress, 2),
                'total_chapters' => $totalChapters,
                'completed_chapters' => $completedChapters,
                'enrolled_at' => $enrollment->enrollment_date ?? $enrollment->created_at,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Course not found or you are not enrolled.', null, 404);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Student Course API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching course details.', null, 500);
        }
    }
}

