<?php

use Illuminate\Support\Facades\Route;

// Only alias the two dashboards (name collision)
use App\Http\Controllers\Admin\DashboardController   as AdminDashboardController;
use App\Http\Controllers\Student\DashboardController as StudentDashboardController;
use App\Http\Controllers\Student\CourseController as StudentCourseController;
use App\Http\Controllers\Admin\LessonController as AdminLessonController;
use App\Http\Controllers\Admin\CalendarController as AdminCalendarController;
use App\Http\Controllers\Student\CalendarController as StudentCalendarController;
use App\Http\Controllers\Admin\BookingController as AdminBookingController;
use App\Http\Controllers\Student\BookingController as StudentBookingController;
use App\Http\Controllers\Student\LessonController as StudentLessonController;
use App\Http\Controllers\IcsFeedController;
use App\Http\Controllers\Student\BookingsListController;
use App\Http\Controllers\Admin\LessonSectionController;
use App\Http\Controllers\Admin\LessonVideoController;
use App\Http\Controllers\Admin\ChapterController;
use App\Http\Controllers\Admin\ModuleController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\Student\LessonController;
use App\Http\Controllers\Admin\StudentController;
use App\Http\Controllers\LevelController;
use App\Http\Controllers\SubjectController;
use App\Http\Controllers\Admin\CourseController;
use App\Http\Controllers\Admin\BillingController;
use App\Http\Controllers\Admin\TeacherController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\Admin\ParentController;
use App\Models\Course;
use App\Models\Lesson;

app('router')->matched(function ($event) {
    \Log::info('Matched route:', [
        'uri' => $event->route->uri(),
        'name' => $event->route->getName(),
    ]);
});

/*Route::get('student/{course}/{lesson}', function ($course, $lesson) {
    \Log::info('Executing route closure now');
    return response("Matched two segments: course={$course}, lesson={$lesson}", 200);
})->where('any1', '.*')->where('any2', '.*');*/


Route::middleware(['auth', 'role:admin|god'])
    ->prefix('admin')
    ->name('admin.')
    ->group(function () {
        Route::get('/users', [App\Http\Controllers\Admin\UserController::class, 'index'])->name('users.index');
        Route::post('users/{user}/role', [App\Http\Controllers\Admin\UserController::class, 'updateRole'])->name('users.updateRole');

    });


// Teacher-only
Route::middleware(['auth', 'role:teacher'])
    ->prefix('teacher')
    ->name('teacher.')
    ->group(function () {
        Route::get('/dashboard', function () {
            return view('teacher.dashboard');
        })->name('dashboard');
		
		Route::post('questions/{question}/answer', [App\Http\Controllers\Student\LessonQuestionController::class, 'answer'])
            ->name('questions.answer');
    });

// Admin-only
Route::middleware(['auth','role:admin'])
    ->prefix('admin')
    ->name('admin.')
    ->group(function () {
        Route::get('/dashboard', [AdminDashboardController::class, 'index'])
            ->name('dashboard');

        //Route::get('/students', [StudentController::class, 'index'])
        //    ->name('students.index');

        Route::get('/teachers', [TeacherController::class, 'index'])
            ->name('teachers.index');

        Route::get('/courses', [CourseController::class, 'index'])
            ->name('courses.index');

        Route::get('/addcourse', [CourseController::class, 'create'])
            ->name('courses.create');
			
		Route::get('/addteacher', [TeacherController::class, 'create'])
			->name('teachers.create');

		Route::post('/addteacher', [TeacherController::class, 'store'])
			->name('teachers.store');		
			
		Route::post('/addcourse', [CourseController::class, 'store'])
			->name('courses.store');
			
        Route::get('/levels', [LevelController::class, 'index'])
			->name('levels.index');
		
        Route::get('/addlevel', [LevelController::class, 'create'])
			->name('levels.create');
		
        Route::post('/addlevel', [LevelController::class, 'store'])
			->name('levels.store');

		Route::get('/subjects', [SubjectController::class, 'index'])
			->name('subjects.index');
		
		Route::get('/addsubject', [SubjectController::class, 'create'])	
			->name('subjects.create');
		
		Route::post('/addsubject', [SubjectController::class, 'store'])
			->name('subjects.store');

		Route::post('/modules', [ModuleController::class, 'store'])
			->name('modules.store');
			
		Route::post('modules/reorder', [ModuleController::class, 'reorder'])
			->name('modules.reorder');	
			
		Route::get('/courses/{course:slug}', [CourseController::class, 'show'])
			->name('courses.show');		
			
		Route::post('/chapters', [ChapterController::class, 'store'])->name('chapters.store');
		
		Route::delete('/chapters/{chapter}', [ChapterController::class, 'destroy'])->name('chapters.destroy');			

		Route::post('/chapters/reorder', [ChapterController::class, 'reorder'])
			->name('chapters.reorder');			

		Route::get('/courses/{course:slug}/chapter/{chapter:slug}', [ChapterController::class, 'show'])
			->withoutScopedBindings()
			->name('chapters.show');
			
		Route::post('/lessons/reorder', [AdminLessonController::class, 'reorder'])
			->name('lessons.reorder');			
			
		Route::get('/courses/{course:slug}/chapter/{chapter:slug}/topic/{lesson:slug}', [AdminLessonController::class, 'show'])
			->name('lessons.show');	

		Route::post('/videos/reorder', [LessonVideoController::class, 'reorder'])
			->name('videos.reorder');

		Route::post('/videos', [LessonVideoController::class, 'store'])
			->name('videos.store');

		Route::delete('/videos/{video}', [LessonVideoController::class, 'destroy'])
			->name('videos.destroy');			
			
		Route::post('/chapters', [ChapterController::class, 'store'])
			->name('chapters.store');			
			
		Route::delete('/chapters/{chapter}', [ChapterController::class, 'destroy'])
			->name('chapters.destroy');		
			
		Route::post('/lessons', [AdminLessonController::class, 'store'])->name('lessons.store');

		Route::delete('courses/{course:slug}/chapter/{chapter:slug}/lesson/{lesson:slug}', 
			[App\Http\Controllers\Admin\LessonController::class, 'destroy']
		)->name('lessons.destroy');
		
		Route::get('/calendar', [AdminCalendarController::class, 'index'])
			->name('calendar');		

		Route::get('/bookings/create', [AdminBookingController::class, 'create'])
			->name('bookings.create');
			
		Route::post('/bookings', [AdminBookingController::class, 'store'])
			->name('bookings.store');

		Route::get('/bookings/block/create', [AdminBookingController::class, 'createBlock'])
			->name('bookings.block.create');

		Route::post('/bookings/block', [AdminBookingController::class, 'storeBlock'])
			->name('bookings.block.store');			

		Route::get('/bookings/series/create', [AdminBookingController::class, 'createSeries'])
			->name('bookings.series.create');
			
		Route::post('/bookings/series', [AdminBookingController::class, 'storeSeries'])
			->name('bookings.series.store');
			
        Route::get('courses/{course:slug}/section/{section:slug}', 
            [LessonSectionController::class, 'show']
        )->name('sections.show');
		
		Route::get('sections', [LessonSectionController::class, 'index'])
			->name('sections.index');

		Route::post('courses/{course:slug}/sections', 
			[LessonSectionController::class, 'store']
		)->name('sections.store');

		Route::put('sections/{lessonSection}', [LessonSectionController::class, 'update'])
			->name('sections.update');

		Route::delete(
			'courses/{course:slug}/section/{section:slug}',
			[LessonSectionController::class, 'destroy']
		)->name('sections.destroy');
		
		Route::post('sections/reorder', [LessonSectionController::class, 'reorder'])
			->name('sections.reorder');			
			
		Route::get('test-section-binding/{section:slug}', function (\App\Models\LessonSection $section) {
			return $section;
		});			
		
		Route::resource('students', StudentController::class);
		
		Route::get('/billing/check-email', [BillingController::class, 'checkEmail'])
			->name('billing.check-email');
		
		Route::resource('parents', ParentController::class)->except(['show']);
    });
	
// Student-only
Route::middleware(['auth', 'role:student'])
    ->prefix('student')
    ->name('student.')
    ->group(function () {
		Route::get('/{course:slug}/{lesson:slug}', [StudentLessonController::class, 'show'])
			->where([
				'course' => '[A-Za-z0-9\-]+',
				'lesson' => '[A-Za-z0-9\-]+',
			])
			->name('course.lesson');	
        Route::get('/dashboard', [StudentDashboardController::class, 'index'])
            ->name('dashboard');
		Route::get('/lessons/{lesson:slug}', [LessonController::class, 'show'])
			->name('lessons.show');
		Route::get('/courses/{course}', [StudentCourseController::class, 'show'])
			->name('courses.show');
			
		Route::get('/calendar', [StudentCalendarController::class, 'index'])
			->name('calendar');
			
		Route::get('/bookings/create', [StudentBookingController::class, 'create'])
			->name('bookings.create');
		
		Route::get('/bookings/series/create', [StudentBookingController::class, 'createSeries'])
			->name('bookings.series.create');

		Route::post('/bookings', [StudentBookingController::class, 'store'])
			->name('bookings.store');	
			
		Route::post('/bookings/series', [StudentBookingController::class, 'storeSeries'])
			->name('bookings.series.store');

		Route::get('/bookings', [BookingsListController::class, 'index'])
			->name('bookings.index');
			
		Route::get('/bookings/{booking}/cancel', [StudentBookingController::class, 'cancelConfirm'])
			->name('bookings.cancel.confirm');
			
		Route::post('/bookings/{booking}/cancel', [StudentBookingController::class, 'cancelStore'])
			->name('bookings.cancel.store');
			
		Route::post('questions/{course:slug}/{lesson:slug}', [App\Http\Controllers\Student\LessonQuestionController::class, 'store'])
			->name('course.lesson.questions.store');


			
});



Route::get('/', [HomeController::class, 'index'])->name('home');

//Route::get('/', function () {
//    return view('welcome');
//});

Route::get('/dashboard', function () {
    $user = auth()->user();

    // Spatie role checks:
    if ($user->hasRole('admin')) {
        return redirect()->route('admin.dashboard');
    }

    // Support either role name you choose for tutors:
    if ($user->hasRole('teacher') || $user->hasRole('tutor')) {
        return redirect()->route('teacher.dashboard');
    }

    // default for everyone else
    return redirect()->route('student.dashboard');

})->middleware('auth')->name('dashboard');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

Route::get('/calendar/teacher/{token}.ics', [IcsFeedController::class, 'teacher'])
    ->name('calendar.teacher.feed')
    ->withoutMiddleware(['web', \App\Http\Middleware\VerifyCsrfToken::class]);

Route::get('/admin/test', function () {
    $user = Auth::user();

    if (!$user || $user->email !== 'jollinski@gmail.com') {
        abort(403, 'Admins only.');
    }

    return 'Hello_admin';
})->middleware('auth');

require __DIR__.'/auth.php';
