<?php

namespace App\Http\Middleware;

use App\Models\SelfPaced\Course;
use App\Models\SelfPaced\Enrollment;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

/**
 * EnsureEnrolled Middleware
 *
 * Verifies the authenticated user has an active or completed Enrollment
 * for the Course identified by the {course} route parameter before
 * allowing access to any Learner Portal route.
 *
 * - Unauthenticated users → redirect to login
 * - Authenticated users without an active enrollment → redirect to enrollment/payment page
 *
 * Requirements: 14.4, 14.5 | Property 2: Payment-gated access invariant
 */
class EnsureEnrolled
{
    public function handle(Request $request, Closure $next): Response
    {
        // Unauthenticated — redirect to login
        if (!Auth::check()) {
            return redirect()->route('login')
                ->with('info', 'Please log in to access the learning portal.');
        }

        // Resolve the course from the route parameter
        $course = $request->route('course');

        if (!$course instanceof Course) {
            // Try resolving by ID if route binding gave us an int
            $courseId = $course;
            $course   = Course::find($courseId);
        }

        if (!$course) {
            abort(404, 'Course not found.');
        }

        // Check for an active or completed enrollment (Property 2)
        $enrollment = Enrollment::where('user_id', Auth::id())
            ->where('course_id', $course->id)
            ->whereIn('status', ['active', 'completed'])
            ->first();

        if (!$enrollment) {
            // Check if there's a pending/failed enrollment to redirect to payment
            $pendingEnrollment = Enrollment::where('user_id', Auth::id())
                ->where('course_id', $course->id)
                ->whereIn('status', ['pending_payment', 'payment_failed'])
                ->first();

            if ($pendingEnrollment) {
                return redirect()->route('self-paced.public.payment', [$course, $pendingEnrollment])
                    ->with('info', 'Please complete your payment to access this course.');
            }

            // No enrollment at all — redirect to registration
            return redirect()->route('self-paced.public.register', $course)
                ->with('info', 'You need to enroll in this course before accessing it.');
        }

        return $next($request);
    }
}
