<?php

namespace App\Http\Controllers\Courses;

use App\Models\Notification;
use Illuminate\Http\Request;
use App\Models\Courses\Course;
use App\Http\Controllers\Controller;
use App\Models\Courses\CourseAnswer;
use App\Models\Courses\CourseCoupon;
use App\Models\Courses\CourseLesson;
use App\Models\Courses\CourseReview;
use Illuminate\Support\Facades\Auth;
use App\Models\Courses\CourseSection;
use App\Models\Courses\CourseCategory;
use App\Models\Courses\CourseProgress;
use App\Models\Courses\CourseQuestion;
use App\Models\Courses\WishlistCourse;
use App\Models\Courses\CourseEnrollment;
use App\Http\Resources\UserShortResource;
use Illuminate\Support\Facades\Validator;
use App\Http\Resources\Courses\CourseResource;
use App\Http\Resources\Courses\CourseDetailResource;

class CourseController extends Controller
{
    /**
     * Helper method to check if the request is an API request
     */
    protected function isApiRequest(Request $request)
    {
        return $request->expectsJson() || $request->is('api/*');
    }

    /**
     * Display course marketplace homepage
     */
    public function index(Request $request)
    {
        $categories = CourseCategory::where('is_active', true)->get();
        $featuredCourses = Course::where('is_featured', true)
            ->where('is_published', true)
            ->with('instructor', 'category')
            ->orderBy('total_students', 'desc')
            ->limit(8)
            ->get();

        $popularCourses = Course::where('is_published', true)
            ->with('instructor', 'category')
            ->orderBy('total_students', 'desc')
            ->limit(8)
            ->get();

        $newestCourses = Course::where('is_published', true)
            ->with('instructor', 'category')
            ->orderBy('created_at', 'desc')
            ->limit(8)
            ->get();

        $topRatedCourses = Course::where('is_published', true)
            ->where('average_rating', '>=', 4)
            ->with('instructor', 'category')
            ->orderBy('average_rating', 'desc')
            ->limit(8)
            ->get();

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'data' => [
                    'categories' => $categories,
                    'featured_courses' => CourseResource::collection($featuredCourses),
                    'popular_courses' => CourseResource::collection($popularCourses),
                    'newest_courses' => CourseResource::collection($newestCourses),
                    'top_rated_courses' => CourseResource::collection($topRatedCourses)
                ]
            ]);
        }

        return view('front_end.pages.courses.index', compact(
            'categories',
            'featuredCourses',
            'popularCourses',
            'newestCourses',
            'topRatedCourses'
        ));
    }

    /**
     * Display courses by category
     */
    public function category(Request $request, $slug)
    {
        // Check if the slug is actually a numeric ID
        if (is_numeric($slug)) {
            // Fetch the category by ID first
            $categoryById = CourseCategory::find($slug);
            if ($categoryById) {
                // If found, use its slug instead
                $slug = $categoryById->slug;
            }
        }

        $category = CourseCategory::where('slug', $slug)
            ->where('is_active', true)
            ->firstOrFail();

        $courses = Course::where('category_id', $category->id)
            ->where('is_published', true)
            ->with('instructor')
            ->paginate(12);

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'data' => [
                    'category' => $category,
                    'courses' => CourseResource::collection($courses)
                ]
            ]);
        }

        return view('front_end.pages.courses.category', compact('category', 'courses'));
    }

    /**
     * Search courses
     */
    public function search(Request $request)
    {
        $query = $request->input('query');
        $category = $request->input('category');
        $level = $request->input('level');
        $rating = $request->input('rating');
        $price = $request->input('price');
        $sort = $request->input('sort', 'popularity');

        $coursesQuery = Course::where('is_published', true)
            ->with('instructor', 'category');

        // Apply search term
        if ($query) {
            $coursesQuery->where(function ($q) use ($query) {
                $q->where('title', 'like', "%{$query}%")
                    ->orWhere('description', 'like', "%{$query}%");
            });
        }

        // Filter by category
        if ($category) {
            $coursesQuery->where('category_id', $category);
        }

        // Filter by level
        if ($level) {
            $coursesQuery->where('level', $level);
        }

        // Filter by rating
        if ($rating) {
            $coursesQuery->where('average_rating', '>=', $rating);
        }

        // Filter by price
        if ($price === 'free') {
            $coursesQuery->where('price', 0);
        } elseif ($price === 'paid') {
            $coursesQuery->where('price', '>', 0);
        }

        // Sort results
        switch ($sort) {
            case 'popularity':
                $coursesQuery->orderBy('total_students', 'desc');
                break;

            case 'rating':
                $coursesQuery->orderBy('average_rating', 'desc');
                break;

            case 'newest':
                $coursesQuery->orderBy('created_at', 'desc');
                break;

            case 'price_low':
                $coursesQuery->orderBy('price', 'asc');
                break;

            case 'price_high':
                $coursesQuery->orderBy('price', 'desc');
                break;
        }

        $courses = $coursesQuery->paginate(12)->withQueryString();
        $categories = CourseCategory::where('is_active', true)->get();

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'data' => [
                    'courses' => CourseResource::collection($courses),
                    'categories' => $categories,
                ]
            ]);
        }

        return view('front_end.pages.courses.search', compact(
            'courses',
            'categories',
            'query',
            'category',
            'level',
            'rating',
            'price',
            'sort'
        ));
    }

    /**
     * Display course details
     */
    public function show(Request $request, $slug)
    {
        // Check if the slug is actually a numeric ID
        if (is_numeric($slug)) {
            // Fetch the course by ID first
            $courseById = Course::where('id', $slug)->first();

            if ($courseById) {
                // If found, use its slug instead
                $slug = $courseById->slug;
            }
        }

        $course = Course::where('slug', $slug)
            ->where('is_published', true)
            ->with([
                'instructor',
                'category',
                'sections.lessons' => function ($query) {
                    $query->where('is_published', true);
                },
                'reviews' => function ($query) {
                    $query->where('is_approved', true)
                        ->orderBy('created_at', 'desc')
                        ->limit(5);
                }
            ])
            ->firstOrFail();

        $isEnrolled = false;
        $hasReview = false;
        $isInWishlist = false;

        if (Auth::check()) {
            $user = Auth::user();
            $isEnrolled = $course->isEnrolled($user->id);

            $enrollment = CourseEnrollment::where('user_id', $user->id)
                ->where('course_id', $course->id)
                ->first();

            if ($enrollment) {
                $hasReview = $enrollment->hasReview();
            }

            $isInWishlist = WishlistCourse::where('user_id', $user->id)
                ->where('course_id', $course->id)
                ->exists();
        }

        $relatedCourses = Course::where('category_id', $course->category_id)
            ->where('id', '!=', $course->id)
            ->where('is_published', true)
            ->with('instructor')
            ->limit(4)
            ->get();

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'data' => [
                    'course' => new CourseDetailResource($course),
                    'is_enrolled' => $isEnrolled,
                    'has_review' => $hasReview,
                    'is_in_wishlist' => $isInWishlist,
                    'related_courses' => CourseResource::collection($relatedCourses)
                ]
            ]);
        }

        return view('front_end.pages.courses.show', compact(
            'course',
            'isEnrolled',
            'hasReview',
            'isInWishlist',
            'relatedCourses'
        ));
    }


    /**
     * Enroll in a course
     */
    public function enroll(Request $request, $slug)
    {
        // Check if the slug is actually a numeric ID
        if (is_numeric($slug)) {
            // Fetch the course by ID first
            $courseById = Course::find($slug);
            if ($courseById) {
                // If found, use its slug instead
                $slug = $courseById->slug;
            }
        }

        $course = Course::where('slug', $slug)
            ->where('is_published', true)
            ->firstOrFail();

        if (!Auth::check()) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Authentication required to enroll in this course.'
                ], 401);
            }
            return redirect()->route('login')
                ->with('error', 'Please login to enroll in this course.');
        }

        $user = Auth::user();

        // Check if already enrolled
        if ($course->isEnrolled($user->id)) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 'info',
                    'message' => 'You are already enrolled in this course.'
                ]);
            }
            return redirect()->route('courses.learn', $course->slug)
                ->with('info', 'You are already enrolled in this course.');
        }

        // Handle free courses
        if ($course->isFree()) {
            CourseEnrollment::create([
                'user_id' => $user->id,
                'course_id' => $course->id,
                'price_paid' => 0,
            ]);
            Notification::create([
                'from_user_id' => $user->id,
                'to_user_id' => $course->user_id,
                'type' => 'enroll_course',
                'text' => 'enrolled your course.',
                'course_id' => $course->id,
            ]);
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 200,
                    'message' => 'You have successfully enrolled in this course.',
                    'data' => [
                        'course_slug' => $course->slug
                    ]
                ]);
            }

            return redirect()->route('courses.learn', $course->slug)
                ->with('success', 'You have successfully enrolled in this free course.');
        }

        // For paid courses, redirect to checkout
        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'message' => 'Please proceed to checkout.',
                'data' => [
                    'course_slug' => $course->slug,
                    'checkout_url' => route('courses.checkout', $course->slug)
                ]
            ]);
        }

        return redirect()->route('courses.checkout', $course->slug);
    }

    /**
     * Display checkout page
     */
    public function checkout(Request $request, $slug)
    {
        // Check if the slug is actually a numeric ID
        if (is_numeric($slug)) {
            // Fetch the course by ID first
            $courseById = Course::find($slug);
            if ($courseById) {
                // If found, use its slug instead
                $slug = $courseById->slug;
            }
        }

        $course = Course::where('slug', $slug)
            ->where('is_published', true)
            ->with('instructor')
            ->firstOrFail();

        if (!Auth::check()) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Authentication required to checkout.'
                ], 401);
            }
            return redirect()->route('login')
                ->with('error', 'Please login to purchase this course.');
        }

        // Free courses should not be checked out
        if ($course->isFree()) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'This is a free course. Please enroll directly.'
                ], 400);
            }
            return redirect()->route('courses.enroll', $course->slug);
        }

        $user = Auth::user();

        // Already enrolled users should not checkout again
        if ($course->isEnrolled($user->id)) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'You are already enrolled in this course.'
                ], 400);
            }
            return redirect()->route('courses.learn', $course->slug)
                ->with('info', 'You are already enrolled in this course.');
        }

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'data' => [
                    'course' => $course,
                    'price' => $course->price,
                    'discount' => session()->get('coupon_discount', 0),
                    'total' => session()->get('coupon_discount')
                        ? $course->price - session()->get('coupon_discount')
                        : $course->price
                ]
            ]);
        }

        return view('front_end.pages.courses.checkout', compact('course'));
    }

    /**
     * Apply coupon code to a course
     */
    public function applyCoupon(Request $request, $slug)
    {
        $request->validate([
            'coupon_code' => 'required|string|max:20'
        ]);

        // Check if the slug is actually a numeric ID
        if (is_numeric($slug)) {
            // Fetch the course by ID first
            $courseById = Course::find($slug);
            if ($courseById) {
                // If found, use its slug instead
                $slug = $courseById->slug;
            }
        }

        $course = Course::where('slug', $slug)
            ->where('is_published', true)
            ->firstOrFail();

        $couponCode = $request->coupon_code;
        $coupon = CourseCoupon::where('code', $couponCode)
            ->where('course_id', $course->id)
            ->where('is_active', true)
            ->where('expires_at', '>', now())
            ->first();

        if (!$coupon) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Invalid or expired coupon code.'
                ], 400);
            }
            return back()->with('error', 'Invalid or expired coupon code.');
        }

        // Calculate discount
        $discount = 0;
        if ($coupon->discount_type === 'percentage') {
            $discount = ($course->price * $coupon->discount_value) / 100;
        } else {
            $discount = $coupon->discount_value;
        }

        // Ensure discount doesn't exceed course price
        $discount = min($discount, $course->price);

        // Store in session
        session()->put('coupon_id', $coupon->id);
        session()->put('coupon_code', $coupon->code);
        session()->put('coupon_discount', $discount);

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'message' => 'Coupon applied successfully.',
                'data' => [
                    'discount' => $discount,
                    'total' => $course->price - $discount
                ]
            ]);
        }

        return back()->with('success', 'Coupon applied successfully.');
    }

    /**
     * Process course payment
     */
    public function processPayment(Request $request, $slug)
    {
        // Check if the slug is actually a numeric ID
        if (is_numeric($slug)) {
            // Fetch the course by ID first
            $courseById = Course::find($slug);
            if ($courseById) {
                // If found, use its slug instead
                $slug = $courseById->slug;
            }
        }

        $course = Course::where('slug', $slug)
            ->where('is_published', true)
            ->firstOrFail();

        if (!Auth::check()) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Authentication required to complete purchase.'
                ], 401);
            }
            return redirect()->route('login');
        }

        $user = Auth::user();

        // Validate request data
        $validator = Validator::make($request->all(), [
            'payment_method' => 'required|string|in:credit_card,paypal,stripe,bank_transfer',
            'transaction_id' => 'required|string',
            // Add other payment-specific fields based on the payment method
        ]);

        if ($validator->fails()) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Validation error',
                    'errors' => $validator->errors()
                ], 422);
            }
            return back()->withErrors($validator)->withInput();
        }

        // Get final price after discount
        $pricePaid = $course->price;
        $couponId = session()->get('coupon_id');
        $couponDiscount = session()->get('coupon_discount', 0);

        if ($couponDiscount > 0) {
            $pricePaid = $course->price - $couponDiscount;
        }

        // Create enrollment record
        $enrollment = CourseEnrollment::create([
            'user_id' => $user->id,
            'course_id' => $course->id,
            'price_paid' => $pricePaid,
            'payment_method' => $request->payment_method,
            'transaction_id' => $request->transaction_id,
            'coupon_id' => $couponId,
            'discount_amount' => $couponDiscount,
        ]);

        // Update course statistics
        $course->increment('total_students');

        // Clear session data
        session()->forget(['coupon_id', 'coupon_code', 'coupon_discount']);

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'message' => 'Payment processed successfully. You are now enrolled in the course.',
                'data' => [
                    'enrollment_id' => $enrollment->id,
                    'course_slug' => $course->slug
                ]
            ]);
        }

        return redirect()->route('courses.learn', $course->slug)
            ->with('success', 'Payment processed successfully. You are now enrolled in the course.');
    }

    /**
     * Toggle course wishlist
     */
    public function toggleWishlist(Request $request, $slug)
    {
        if (!Auth::check()) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Authentication required to update wishlist.'
                ], 401);
            }
            return redirect()->route('login');
        }

        // Check if the slug is actually a numeric ID
        if (is_numeric($slug)) {
            // Fetch the course by ID first
            $courseById = Course::find($slug);
            if ($courseById) {
                // If found, use its slug instead
                $slug = $courseById->slug;
            }
        }

        $course = Course::where('slug', $slug)
            ->where('is_published', true)
            ->firstOrFail();

        $user = Auth::user();
        $existingWishlistItem = WishlistCourse::where('user_id', $user->id)
            ->where('course_id', $course->id)
            ->first();

        if ($existingWishlistItem) {
            $existingWishlistItem->delete();
            $message = 'Course removed from wishlist.';
            $isInWishlist = false;
        } else {
            WishlistCourse::create([
                'user_id' => $user->id,
                'course_id' => $course->id
            ]);
            $message = 'Course added to wishlist.';
            $isInWishlist = true;
        }

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'message' => $message,
                'data' => [
                    'is_in_wishlist' => $isInWishlist
                ]
            ]);
        }

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => $message,
                'in_wishlist' => $isInWishlist
            ]);
        }

        return back()->with('success', $message);
    }

    /**
     * Learn course content
     */
    public function learn(Request $request, $slug, $lessonId = null)
    {
        // Check if the slug is actually a numeric ID
        if (is_numeric($slug)) {
            // Fetch the course by ID first
            $courseById = Course::find($slug);
            if ($courseById) {
                // If found, use its slug instead
                $slug = $courseById->slug;
            }
        }

        $course = Course::where('slug', $slug)
            ->where('is_published', true)
            ->with([
                'instructor',
                'sections' => function ($query) {
                    $query->orderBy('sort_order');
                },
                'sections.lessons' => function ($query) {
                    $query->where('is_published', true)
                        ->orderBy('sort_order');
                }
            ])
            ->firstOrFail();

        if (!Auth::check()) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Authentication required to access course content.'
                ], 401);
            }
            return redirect()->route('login');
        }

        $user = Auth::user();

        // Check if user is enrolled
        if (!$course->isEnrolled($user->id)) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'You are not enrolled in this course.'
                ], 403);
            }
            return redirect()->route('courses.show', $course->slug)
                ->with('error', 'You need to enroll in this course to access its content.');
        }

        // Find current lesson
        $currentLesson = null;
        $firstLesson = null;

        foreach ($course->sections as $section) {
            if (!$firstLesson && $section->lessons->count() > 0) {
                $firstLesson = $section->lessons->first();
            }

            foreach ($section->lessons as $lesson) {
                if ($lessonId && $lesson->id == $lessonId) {
                    $currentLesson = $lesson;
                    break 2;
                }
            }
        }

        // If no specific lesson was requested, use the first lesson
        if (!$currentLesson && $firstLesson) {
            $currentLesson = $firstLesson;
        }

        // If no lessons are available
        if (!$currentLesson) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'No lessons available in this course yet.'
                ], 404);
            }
            return view('front_end.pages.courses.no_lessons', compact('course'));
        }

        // Get lesson questions
        $questions = CourseQuestion::where('lesson_id', $currentLesson->id)
            ->with(['user', 'answers.user', 'bestAnswer.user'])
            ->orderBy('created_at', 'desc')
            ->get();

        // Get user progress
        $enrollment = CourseEnrollment::where('user_id', $user->id)
            ->where('course_id', $course->id)
            ->firstOrFail();

        $progress = CourseProgress::where('enrollment_id', $enrollment->id)->get();
        $completedLessons = $progress->pluck('lesson_id')->toArray();

        // Calculate progress percentage
        $totalLessons = 0;
        $completedCount = 0;

        foreach ($course->sections as $section) {
            $totalLessons += $section->lessons->count();
            foreach ($section->lessons as $lesson) {
                if (in_array($lesson->id, $completedLessons)) {
                    $completedCount++;
                }
            }
        }

        $progressPercentage = $totalLessons > 0 ? round(($completedCount / $totalLessons) * 100) : 0;

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'data' => [
                    'course' => new CourseDetailResource($course),
                    'current_lesson' => $currentLesson,
                    'questions' => $questions->map(function ($question) {
                        return [
                            'id' => $question->id,
                            'question' => $question->question,
                            'created_at' => $question->created_at,
                            'user' => new UserShortResource($question->user),
                            'answers' => $question->answers->map(function ($answer) {
                                return [
                                    'id' => $answer->id,
                                    'answer' => $answer->answer,
                                    'created_at' => $answer->created_at,
                                    'is_instructor_answer' => $answer->is_instructor_answer,
                                    'user' => new UserShortResource($answer->user),
                                ];
                            }),
                            'best_answer' => $question->bestAnswer ? [
                                'id' => $question->bestAnswer->id,
                                'answer' => $question->bestAnswer->answer,
                                'created_at' => $question->bestAnswer->created_at,
                                'user' => new UserShortResource($question->bestAnswer->user),
                            ] : null,
                        ];
                    }),
                    'completed_lessons' => $completedLessons,
                    'progress_percentage' => $progressPercentage
                ]
            ]);
        }

        return view('front_end.pages.courses.learn', compact(
            'course',
            'currentLesson',
            'questions',
            'completedLessons',
            'progressPercentage'
        ));
    }

    /**
     * Mark lesson as complete
     */
    public function completeLesson(Request $request, $slug, $lessonId)
    {
        // Check if the slug is actually a numeric ID
        if (is_numeric($slug)) {
            // Fetch the course by ID first
            $courseById = Course::find($slug);
            if ($courseById) {
                // If found, use its slug instead
                $slug = $courseById->slug;
            }
        }

        $course = Course::where('slug', $slug)
            ->where('is_published', true)
            ->firstOrFail();

        $lesson = CourseLesson::where('id', $lessonId)
            ->where('course_id', $course->id)
            ->firstOrFail();

        if (!Auth::check()) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Authentication required to mark lessons complete.'
                ], 401);
            }
            return redirect()->route('login');
        }

        $user = Auth::user();
        $enrollment = CourseEnrollment::where('user_id', $user->id)
            ->where('course_id', $course->id)
            ->first();

        if (!$enrollment) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'You are not enrolled in this course.'
                ], 403);
            }
            return redirect()->route('courses.show', $course->slug)
                ->with('error', 'You need to enroll in this course first.');
        }

        // Check if lesson is already completed
        $existingProgress = CourseProgress::where('enrollment_id', $enrollment->id)
            ->where('lesson_id', $lesson->id)
            ->first();

        if (!$existingProgress) {
            // Mark as complete
            CourseProgress::create([
                'enrollment_id' => $enrollment->id,
                'lesson_id' => $lesson->id,
                'completed_at' => now()
            ]);
        }

        // Find next lesson
        $nextLesson = null;
        $foundCurrent = false;
        $sections = CourseSection::where('course_id', $course->id)
            ->orderBy('sort_order')
            ->with(['lessons' => function ($query) {
                $query->where('is_published', true)
                    ->orderBy('sort_order');
            }])
            ->get();

        foreach ($sections as $section) {
            foreach ($section->lessons as $lesson) {
                if ($foundCurrent) {
                    $nextLesson = $lesson;
                    break 2;
                }

                if ($lesson->id == $lessonId) {
                    $foundCurrent = true;
                }
            }
        }

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'message' => 'Lesson marked as complete.',
                'data' => [
                    'next_lesson_id' => $nextLesson ? $nextLesson->id : null,
                    'next_lesson_url' => $nextLesson
                        ? route('courses.learn', ['slug' => $course->slug, 'lessonId' => $nextLesson->id])
                        : null
                ]
            ]);
        }

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Lesson marked as complete.',
                'next_lesson' => $nextLesson ? $nextLesson->id : null
            ]);
        }

        if ($nextLesson) {
            return redirect()->route('courses.learn', [
                'slug' => $course->slug,
                'lessonId' => $nextLesson->id
            ]);
        }

        return redirect()->route('courses.learn', $course->slug)
            ->with('success', 'Lesson marked as complete. You\'ve completed all lessons!');
    }

    /**
     * Ask a question on a lesson
     */
    public function askQuestion(Request $request, $slug, $lessonId)
    {
        $request->validate([
            'question' => 'required|string|min:10'
        ]);

        // Check if the slug is actually a numeric ID
        if (is_numeric($slug)) {
            // Fetch the course by ID first
            $courseById = Course::find($slug);
            if ($courseById) {
                // If found, use its slug instead
                $slug = $courseById->slug;
            }
        }

        $course = Course::where('slug', $slug)->firstOrFail();
        $lesson = CourseLesson::where('id', $lessonId)
            ->where('course_id', $course->id)
            ->firstOrFail();

        if (!Auth::check()) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Authentication required to ask questions.'
                ], 401);
            }
            return redirect()->route('login');
        }

        $user = Auth::user();

        // Check if user is enrolled
        if (!$course->isEnrolled($user->id)) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'You need to be enrolled in this course to ask questions.'
                ], 403);
            }
            return redirect()->route('courses.show', $course->slug)
                ->with('error', 'You need to enroll in this course to ask questions.');
        }

        $question = CourseQuestion::create([
            'user_id' => $user->id,
            'course_id' => $course->id,
            'lesson_id' => $lesson->id,
            'question' => $request->question
        ]);

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'message' => 'Your question has been posted.',
                'data' => [
                    'question' => $question->load('user')
                ]
            ]);
        }

        return back()->with('success', 'Your question has been posted.');
    }

    /**
     * Answer a question
     */
    public function answerQuestion(Request $request, $questionId)
    {
        $request->validate([
            'answer' => 'required|string|min:10'
        ]);

        $question = CourseQuestion::findOrFail($questionId);
        $course = Course::findOrFail($question->course_id);

        if (!Auth::check()) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Authentication required to answer questions.'
                ], 401);
            }
            return redirect()->route('login');
        }

        $user = Auth::user();

        // Only enrolled students or the instructor can answer
        $isEnrolled = $course->isEnrolled($user->id);
        $isInstructor = $user->id === $course->instructor_id;

        if (!$isEnrolled && !$isInstructor) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'You must be enrolled in this course or be the instructor to answer questions.'
                ], 403);
            }
            return back()->with('error', 'You must be enrolled in this course or be the instructor to answer questions.');
        }

        $answer = CourseAnswer::create([
            'question_id' => $question->id,
            'user_id' => $user->id,
            'answer' => $request->answer,
            'is_instructor_answer' => $isInstructor
        ]);

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'message' => 'Your answer has been posted.',
                'data' => [
                    'answer' => $answer->load('user')
                ]
            ]);
        }

        return back()->with('success', 'Your answer has been posted.');
    }

    /**
     * Mark an answer as the best answer
     */
    public function markBestAnswer(Request $request, $answerId)
    {
        $answer = CourseAnswer::findOrFail($answerId);
        $question = CourseQuestion::findOrFail($answer->question_id);

        if (!Auth::check()) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Authentication required to mark best answers.'
                ], 401);
            }
            return redirect()->route('login');
        }

        // Only the question owner or course instructor can mark best answer
        $user = Auth::user();
        $course = Course::findOrFail($question->course_id);
        $isQuestionOwner = $user->id === $question->user_id;
        $isInstructor = $user->id === $course->instructor_id;

        if (!$isQuestionOwner && !$isInstructor) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Only the question owner or course instructor can mark the best answer.'
                ], 403);
            }
            return back()->with('error', 'Only the question owner or course instructor can mark the best answer.');
        }

        // Update question to set this answer as best
        $question->best_answer_id = $answer->id;
        $question->save();

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'message' => 'Answer marked as best answer.',
                'data' => [
                    'question' => $question->load('bestAnswer.user')
                ]
            ]);
        }

        return back()->with('success', 'Answer marked as best answer.');
    }

    /**
     * Submit a course review
     */
    public function submitReview(Request $request, $slug)
    {
        $request->validate([
            'rating' => 'required|integer|min:1|max:5',
            'review' => 'required|string|min:10'
        ]);

        // Check if the slug is actually a numeric ID
        if (is_numeric($slug)) {
            // Fetch the course by ID first
            $courseById = Course::find($slug);
            if ($courseById) {
                // If found, use its slug instead
                $slug = $courseById->slug;
            }
        }

        $course = Course::where('slug', $slug)->firstOrFail();

        if (!Auth::check()) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Authentication required to submit reviews.'
                ], 401);
            }
            return redirect()->route('login');
        }

        $user = Auth::user();

        // Check if user is enrolled
        $enrollment = CourseEnrollment::where('user_id', $user->id)
            ->where('course_id', $course->id)
            ->first();

        if (!$enrollment) {
            if ($this->isApiRequest($request)) {
                return response()->json([
                    'status' => 400,
                    'message' => 'You must be enrolled in this course to submit a review.'
                ], 403);
            }
            return back()->with('error', 'You must be enrolled in this course to submit a review.');
        }

        // Check if user already reviewed this course
        $existingReview = CourseReview::where('user_id', $user->id)
            ->where('course_id', $course->id)
            ->first();

        if ($existingReview) {
            // Update existing review
            $existingReview->rating = $request->rating;
            $existingReview->review = $request->review;
            $existingReview->save();

            $message = 'Your review has been updated.';
        } else {
            // Create new review
            CourseReview::create([
                'user_id' => $user->id,
                'course_id' => $course->id,
                'rating' => $request->rating,
                'review' => $request->review,
                'is_approved' => true // Auto-approve for now
            ]);

            $message = 'Your review has been submitted.';
        }

        // Update course average rating
        $course->updateRating();

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'message' => $message
            ]);
        }

        return back()->with('success', $message);
    }

    /**
     * List all course categories
     */
    public function categories(Request $request)
    {
        $categories = CourseCategory::where('is_active', true)
            ->orderBy('name')
            ->get();

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'data' => [
                    'categories' => $categories
                ]
            ]);
        }

        return view('front_end.pages.courses.categories', compact('categories'));
    }
}
