<?php

namespace App\Http\Controllers\Courses;

use Illuminate\Routing\Controller as BaseController;
use App\Models\Courses\CourseEnrollment;
use App\Models\Courses\WishlistCourse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Resources\Courses\CourseResource;


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

    /**
     * Constructor to add middleware
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display student dashboard
     */
    public function dashboard(Request $request)
    {
        $userId = Auth::id();

        $enrollments = CourseEnrollment::where('user_id', $userId)
            ->with(['course.instructor'])
            ->orderBy('created_at', 'desc')
            ->get();

        $inProgressCourses = $enrollments->filter(function ($enrollment) {
            return $enrollment->getProgressPercentage() > 0 && $enrollment->getProgressPercentage() < 100;
        })->take(4);

        $completedCourses = $enrollments->filter(function ($enrollment) {
            return $enrollment->getProgressPercentage() == 100;
        })->take(4);

        $recentlyEnrolledCourses = $enrollments->take(4);

        $wishlist = WishlistCourse::where('user_id', $userId)
            ->with('course.instructor')
            ->orderBy('created_at', 'desc')
            ->limit(4)
            ->get();

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'data' => [
                    'enrollments_count' => $enrollments->count(),
                    'in_progress_courses' => $inProgressCourses->map(function($enrollment) {
                        return [
                            'id' => $enrollment->id,
                            'progress_percentage' => $enrollment->getProgressPercentage(),
                            'created_at' => $enrollment->created_at,
                            'course' => new CourseResource($enrollment->course)
                        ];
                    }),
                    'completed_courses' => $completedCourses->map(function($enrollment) {
                        return [
                            'id' => $enrollment->id,
                            'progress_percentage' => $enrollment->getProgressPercentage(),
                            'created_at' => $enrollment->created_at,
                            'course' => new CourseResource($enrollment->course)
                        ];
                    }),
                    'recently_enrolled_courses' => $recentlyEnrolledCourses->map(function($enrollment) {
                        return [
                            'id' => $enrollment->id,
                            'progress_percentage' => $enrollment->getProgressPercentage(),
                            'created_at' => $enrollment->created_at,
                            'course' => new CourseResource($enrollment->course)
                        ];
                    }),
                    'wishlist' => $wishlist->map(function($wishlistItem) {
                        return [
                            'id' => $wishlistItem->id,
                            'created_at' => $wishlistItem->created_at,
                            'course' => new CourseResource($wishlistItem->course)
                        ];
                    })
                ]
            ]);
        }

        return view('front_end.pages.courses.student.dashboard', compact(
            'enrollments',
            'inProgressCourses',
            'completedCourses',
            'recentlyEnrolledCourses',
            'wishlist'
        ));
    }

    /**
     * My courses list
     */
    public function myCourses(Request $request)
    {
        $enrollments = CourseEnrollment::where('user_id', Auth::id())
            ->with(['course.instructor'])
            ->orderBy('created_at', 'desc')
            ->paginate(9);

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'data' => [
                    'enrollments' => $enrollments->map(function($enrollment) {
                        return [
                            'id' => $enrollment->id,
                            'progress_percentage' => $enrollment->getProgressPercentage(),
                            'created_at' => $enrollment->created_at,
                            'course' => new CourseResource($enrollment->course)
                        ];
                    })
                ]
            ]);
        }

        return view('front_end.pages.courses.student.my_courses', compact('enrollments'));
    }

    /**
     * My wishlist
     */
    public function wishlist(Request $request)
    {
        $wishlist = WishlistCourse::where('user_id', Auth::id())
            ->with('course.instructor')
            ->orderBy('created_at', 'desc')
            ->paginate(9);

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'data' => [
                    'wishlist' => $wishlist->map(function($wishlistItem) {
                        return [
                            'id' => $wishlistItem->id,
                            'created_at' => $wishlistItem->created_at,
                            'course' => new CourseResource($wishlistItem->course)
                        ];
                    })
                ]
            ]);
        }

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

    /**
     * Purchase history
     */
    public function purchaseHistory(Request $request)
    {
        $enrollments = CourseEnrollment::where('user_id', Auth::id())
            ->whereNotNull('transaction_id')
            ->with(['course'])
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        if ($this->isApiRequest($request)) {
            return response()->json([
                'status' => 200,
                'data' => [
                    'purchases' => $enrollments->map(function($enrollment) {
                        return [
                            'id' => $enrollment->id,
                            'price_paid' => $enrollment->price_paid,
                            'payment_method' => $enrollment->payment_method,
                            'transaction_id' => $enrollment->transaction_id,
                            'created_at' => $enrollment->created_at,
                            'course' => new CourseResource($enrollment->course)
                        ];
                    })
                ]
            ]);
        }

        return view('front_end.pages.courses.student.purchase_history', compact('enrollments'));
    }

    /**
     * Remove course from wishlist
     */
    public function removeFromWishlist(Request $request, $id)
    {
        $wishlistItem = WishlistCourse::where('id', $id)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $wishlistItem->delete();

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

        return back()->with('success', 'Course removed from wishlist.');
    }
}
