<?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\CourseChapter;

class CourseController extends BaseController
{
    /**
     * Get list of instructor's courses.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        try {
            $instructor = Auth::user();
            
            $query = Course::where('instructor_id', $instructor->id)
                ->where('is_active', true)
                ->withCount('enrollments');
            
            // Search
            if ($request->has('search') && $request->search) {
                $search = $request->search;
                $query->where(function($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('code', 'like', "%{$search}%");
                });
            }
            
            $courses = $query->orderBy('created_at', 'desc')
                ->paginate($request->get('per_page', 20));
            
            $data = $courses->map(function($course) {
                return [
                    'id' => $course->id,
                    'name' => $course->name,
                    'code' => $course->code,
                    'description' => $course->description,
                    'level' => $course->level,
                    'fees' => $course->fees,
                    'enrollments_count' => $course->enrollments_count,
                    'created_at' => $course->created_at,
                    'updated_at' => $course->updated_at,
                ];
            });
            
            return $this->paginated($data, $courses);
        } catch (\Exception $e) {
            Log::error('Instructor 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 {
            $instructor = Auth::user();
            
            $course = Course::where('id', $id)
                ->where('instructor_id', $instructor->id)
                ->with(['chapters', 'enrollments.student'])
                ->firstOrFail();
            
            // Get enrolled students count
            $enrolledStudents = $course->enrollments->count();
            
            // Get chapters info
            $totalChapters = $course->chapters->count();
            $publishedChapters = $course->chapters->where('is_published', true)->count();
            
            // Get enrolled students list
            $students = $course->enrollments->map(function($enrollment) {
                $student = $enrollment->student;
                return [
                    'id' => $student->id ?? null,
                    'name' => $student->name ?? 'N/A',
                    'email' => $student->email ?? 'N/A',
                    'enrolled_at' => $enrollment->created_at,
                ];
            });
            
            // Get chapters list
            $chapters = $course->chapters->map(function($chapter) {
                return [
                    'id' => $chapter->id,
                    'title' => $chapter->title,
                    'order' => $chapter->order,
                    'is_published' => $chapter->is_published,
                ];
            })->sortBy('order')->values();
            
            return $this->success([
                'id' => $course->id,
                'name' => $course->name,
                'code' => $course->code,
                'description' => $course->description,
                'level' => $course->level,
                'fees' => $course->fees,
                'statistics' => [
                    'total_students' => $enrolledStudents,
                    'total_chapters' => $totalChapters,
                    'published_chapters' => $publishedChapters,
                ],
                'chapters' => $chapters,
                'students' => $students,
                'created_at' => $course->created_at,
                'updated_at' => $course->updated_at,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Course not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Instructor Course API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching course details.', null, 500);
        }
    }
}

