<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Course;
use App\Models\Enrollment;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class EnrollmentController extends Controller
{
    /**
     * Store a new enrollment (enroll a user in a course)
     */
    public function store(Request $request)
    {
        // Check if user is authenticated
        if (!Auth::check()) {
            return redirect()->route('login')->with('message', 'Please login to enroll in courses.');
        }

        // Validate the request
        $request->validate([
            'course_id' => 'required|exists:courses,id'
        ]);

        $user = Auth::user();
        $course = Course::findOrFail($request->course_id);

        // Check if course is published
        if ($course->status !== 'published') {
            return redirect()->back()->with('error', 'This course is not available for enrollment.');
        }

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

        if ($existingEnrollment) {
            return redirect()->back()->with('info', 'You are already enrolled in this course.');
        }

        // Check if course has reached maximum capacity
        if ($course->max_students && $course->getEnrolledStudentsCount() >= $course->max_students) {
            return redirect()->back()->with('error', 'This course has reached its maximum capacity.');
        }

        // Create enrollment - completely free!
        Enrollment::create([
            'user_id' => $user->id,
            'course_id' => $course->id,
            'status' => 'enrolled',
            'progress' => 0,
            'enrolled_at' => now(),
        ]);

        return redirect()->route('courses.show', $course->slug)->with([
            'success' => 'Successfully enrolled in the course! Start learning now.',
            'enrollment_success' => true,
            'course_title' => $course->title
        ]);
    }

    /**
     * Unenroll a user from a course
     */
    public function unenroll(Request $request, Course $course)
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }

        $user = Auth::user();

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

        if (!$enrollment) {
            return redirect()->back()->with('error', 'You are not enrolled in this course.');
        }

        // Update status to dropped instead of deleting
        $enrollment->update(['status' => 'dropped']);

        return redirect()->back()->with('success', 'Successfully unenrolled from the course.');
    }

    /**
     * Show user's enrolled courses
     */
    public function myCourses()
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }

        $user = Auth::user();
        
        $enrollments = Enrollment::where('user_id', $user->id)
            ->where('status', 'enrolled')
            ->with(['course.teacher', 'course.sessions'])
            ->orderBy('enrolled_at', 'desc')
            ->get();

        return view('student.my-courses', compact('enrollments'));
    }

    /**
     * Show enrollment details
     */
    public function show(Course $course)
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }

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

        if (!$enrollment) {
            return redirect()->route('courses.show', $course->slug)
                ->with('error', 'You are not enrolled in this course.');
        }

        $course->load(['teacher', 'sessions' => function($query) {
            $query->where('is_published', true)->orderBy('session_number');
        }]);

        return view('student.course-progress', compact('course', 'enrollment'));
    }
}
