<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\Session;
use App\Models\TextLesson;
use App\Models\Webinar;
use Illuminate\Support\Facades\DB;

class CheckLectureAccess
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = auth()->user();
        
        if (!$user) {
            return redirect('/login');
        }

        // Get the lecture ID from the route
        $lectureId = $request->route('id');
        $lecture = null;
        $lectureType = null;

        // Determine if this is a session or text lesson based on route
        if ($request->is('*/sessions/*') || $request->is('*/session/*')) {
            $lecture = Session::find($lectureId);
            $lectureType = 'session';
        } elseif ($request->is('*/text-lessons/*') || $request->is('*/text-lesson/*')) {
            $lecture = TextLesson::find($lectureId);
            $lectureType = 'text_lesson';
        }

        if (!$lecture) {
            abort(404);
        }

        // Check if user is admin, creator, or teacher
        $webinar = Webinar::find($lecture->webinar_id);
        if ($user->isAdmin() || 
            ($webinar && ($webinar->creator_id == $user->id || $webinar->teacher_id == $user->id))) {
            return $next($request);
        }

        // Check if user has purchased the webinar
        if ($webinar && !$webinar->checkUserHasBought($user)) {
            abort(403, trans('public.user_not_access_content'));
        }

        // Check if there are specific user restrictions for this lecture
        $hasRestrictions = DB::table('lecture_user')
            ->where('lecture_id', $lectureId)
            ->where('lecture_type', $lectureType)
            ->exists();

        if ($hasRestrictions) {
            // Check if the current user is in the allowed list
            $isAllowed = DB::table('lecture_user')
                ->where('lecture_id', $lectureId)
                ->where('lecture_type', $lectureType)
                ->where('user_id', $user->id)
                ->exists();

            if (!$isAllowed) {
                return response()->view('errors.lecture_access_restricted', [
                    'lecture' => $lecture,
                    'lectureType' => $lectureType
                ], 403);
            }
        }

        return $next($request);
    }
}

