<?php

use App\Http\Controllers\AdminController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\CartController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\CourseController;
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\ProgressController;
use App\Http\Controllers\ReceiptController;
use App\Http\Controllers\SubscriptionController;
use App\Http\Controllers\NoteController;
use App\Http\Controllers\AIController;
use App\Http\Controllers\TeacherController;
use App\Http\Controllers\ViewController;
use App\Http\Controllers\RevisorController;
use Illuminate\Support\Facades\Route;
// Middleware para verificar el rol del usuario
use App\Http\Middleware\RoleMiddleware;
use Laravel\Socialite\Facades\Socialite;
use App\Http\Controllers\ExerciseController;
use App\Http\Controllers\MessageController;

use App\Http\Controllers\ChapterController;

/**
 * AUTH
 */
Route::view('/login', 'pages.auth.login')->name('login');
Route::post('signin', [AuthController::class, 'signin'])->name('auth.signin.submit');
Route::view('/register', 'pages.auth.register')->name('registerPage');
Route::post('signup', [AuthController::class, 'signup'])->name('auth.signup.submit');
Route::get('logout', [AuthController::class, 'logout'])->name('auth.logout.submit');
Route::get('/login-google', function () {
    return Socialite::driver('google')->redirect();
})->name('login-google');
Route::get('/google-callback', [AuthController::class, 'google_signup'])->name('google-callback');

// Enviar correo para cambiar contraseña
Route::view('/resetPasswordForm', 'pages.auth.restartPassword')->name('resetPasswordForm');
Route::post('send_reset_password_mail', [AuthController::class, 'send_reset_password_mail'])->name('auth.restartPassword.submit');

// Cambiar contraseña
Route::get('/reset-password/{token}', [AuthController::class, 'showResetForm'])->name('password.reset.form');
Route::post('/reset-password', [AuthController::class, 'submitNewPassword'])->name('password.reset.submit');

// Si ponen el enlace mal
Route::get('/reset-password', function () {
    return redirect()->route('login'); // o 'mainPage' si prefieres
});



/**
 * PÁGINAS COMUNES
 */
Route::view('/', 'pages.common.main_page')->name('mainPage');
Route::get('/best-courses', [CourseController::class, 'tops5'])->name('bestCourses');
Route::view('/faq', 'pages.common.faqPage')->name('faqPage');

/**
 * ESTUDIANTE (Rutas protegidas por auth)
 */
Route::middleware(['auth'])->group(function () {
    // PARA PRUEBAS POSTMAN
        Route::get('/csrf-token', function () {
        return response()->json(['csrf_token' => csrf_token()]);
    });

    // --- Páginas generales autenticadas ---
    Route::get('/home', [UserController::class, 'getUserGeneralInfo'])->name('homePage');
    Route::get('/discover', [ViewController::class, 'discover'])->name('discoverPage');
    Route::get('/revisor', [RevisorController::class, 'index'])->name('revisorPage');
    Route::get('/revisor/course/{id}', [RevisorController::class, 'course'])->name('revisorCourse');
    Route::get('/revisor/course/{id}/approve', [RevisorController::class, 'approve'])->name('revisor.approve');
    Route::get('/revisor/course/{id}/undo', [RevisorController::class, 'undo'])->name('revisor.undo');
    Route::post('/revisor/course/{id}/reject', [RevisorController::class, 'reject'])->name('revisor.reject');

    // --- Perfil y configuración ---
    Route::get('/myProfile', [UserController::class, 'getMyInfo'])->name('myProfilePage');
    Route::get('/settings', [UserController::class, 'getMyInfo2'])->name('settingsPage');
    Route::put('/settings', [UserController::class, 'editMyInfo'])->name('updateProfile');
    Route::delete('/delete-account', [UserController::class, 'deleteAccount'])->name('deleteAccount');

    // --- Cursos del usuario ---
    Route::get('/myCourses', [UserController::class, 'myCourses'])->name('myCoursesPage');
    Route::post('/filter-courses', [UserController::class, 'filterCourses'])->name('filterCourses');

    // --- Notas ---
    Route::get('/myNotes', [NoteController::class, 'getMyNotes'])->name('myNotesPage');
    Route::get('/note/{id}', [NoteController::class, 'show'])->name('note.show');
    Route::put('/note/{id}', [NoteController::class, 'update'])->name('note.update');
    Route::delete('/note/{id}', [NoteController::class, 'destroy'])->name('note.destroy');
    Route::post('/notes/create', [NoteController::class, 'createAndRedirect'])->name('note.create');
    Route::get('/notes/show', [NoteController::class, 'show2'])->name('myNotes2');
    Route::get('/notes/{id}/content', [NoteController::class, 'getNoteContent'])->name('note.content');

    // --- Certificados ---
    Route::get('/myCertificates', [UserController::class, 'getMyCertificates'])->name('myCertificatesPage');

    // --- Compras y recibos ---
    Route::get('/myPurchases', [ReceiptController::class, 'getPurchaseHistory'])->name('myPurchasesPage');
    Route::get('/receipts/{id}/download', [ReceiptController::class, 'download'])->name('downloadReceipt');
    Route::get('/receipts/{id}/details', [ReceiptController::class, 'show'])->name('detailsReceipt');

    // --- Carrito ---
    Route::get('/cart', [CartController::class, 'index'])->name('myCartPage');
    Route::delete('/cart/{course}', [CartController::class, 'destroy'])->name('cart.destroy');
    Route::post('/cart/{course}/{price}', [CartController::class, 'store'])->name('cart.store');

    // --- Pasarela de pago ---
    Route::post('/checkout', [PaymentController::class, 'checkout'])->name('checkout');
    Route::get('/payment/success', [PaymentController::class, 'paymentSuccess'])->name('payment.success');
    Route::get('/payment/cancel', [PaymentController::class, 'paymentCancel'])->name('payment.cancel');
    // Suscripciones
    Route::post('/checkoutSubscription/{id}', [PaymentController::class, 'checkoutSubscription'])->name('checkoutSubscription');
    Route::get('/payment/subscriptionSuccess', [PaymentController::class, 'subscriptionSuccess'])->name('subscription.success');
    Route::get('/payment/subscriptionCancel', [PaymentController::class, 'subscriptionCancel'])->name('subscription.cancel');
    Route::post('/cancelSubscription/{id}', [SubscriptionController::class, 'cancelSubscription'])->name('cancelSubscription');

    /**
     * CURSOS
     */
    Route::prefix('course')->group(function () {
        // Info y acceso
        Route::get('/info/{id}', [CourseController::class, 'showCourseInfo'])->name('showCourseInfo');
        Route::post('/access/{id}', [CourseController::class, 'accessCourse'])->name('course.access');
        // Capítulos
        Route::get('/chapter/{id}', [CourseController::class, 'showChapter'])->name('course.chapter.show');
        Route::post('chapter/{chapterId}/next',[ProgressController::class, 'nextChapter'])->name('course.chapter.next');
        Route::get('chapter/{chapterId}/exam',[CourseController::class, 'showExam'])->name('course.chapter.exam');
        Route::post('chapter/{chapterId}/submit-exam',[CourseController::class, 'submitExam'])->name('course.chapter.submitExam');
        Route::get('chapter/{chapterId}/score',[CourseController::class, 'showScore'])->name('course.chapter.score');
        // Favoritos
        Route::post('/toggle-favorite', [CourseController::class, 'toggleFavorite'])->name('toggle.favorite');


        // RUTA PARA ELIMINAR UN CURSO (SOLO PARA EL PROPIETARIO)
        Route::delete('/{id}/delete', [CourseController::class, 'destroy'])->name('course.destroy');
        // RUTA PARA ELIMINAR UN CURSO (SOLO PARA EL PROPIETARIO)
    });

    // --- Ejercicios ---
    Route::post('/exercise/answer', [ProgressController::class, 'answerExercise'])->name('exercise.answer');

    /**
     * API (para usuario autenticado)
     */
    Route::prefix('api')->group(function () {
        Route::get('current-chapter/{id}', [ProgressController::class, 'current_chapter'])->name('api.current.chapter');
        Route::get('chapter-exercises/{id}', [ProgressController::class, 'chapter_exercises'])->name('api.chapter.exercises');
        Route::get('user-course-status/{id}', [CourseController::class, 'userCourse_status'])->name('api.user.course.status');
        Route::get('user-chapterFull/{id}', [ProgressController::class, 'chapter_full'])->name('api.user.chapter.full');
        Route::get('user-courseProgress/{id}', [ProgressController::class, 'course_progress'])->name('api.user.course.progress');
        // IA
        Route::get('/ai/ping', [AIController::class, 'ping']);
        Route::post('/ai/ask/{course}/{chapter}', [AIController::class, 'askAI']);
        // TTS
        Route::post('/text-to-speech', [AIController::class, 'messageRead']);
        // Discover API (Manav)
        // Route::get('categories', [CategoryController::class, 'getCategories'])->name('api.categories');
        // Route::get('categories/{category}/subcategories', [CategoryController::class, 'getSubcategoriesByCategoryId'])->name('api.categories.subcategories');
        Route::get('courses', [CourseController::class, 'getCourses'])->name('api.courses');
        Route::post('courses/save', [CourseController::class, 'save'])->name('courses.save');


        // RUTAS DE CAPÍTULO (SOLO PARA EL PROPIETARIO)
        Route::post('/chapter/store', [ChapterController::class, 'store'])->name('chapter.store');
        Route::delete('/chapter/destroy', [ChapterController::class, 'destroy'])->name('chapter.destroy');

        // Ruta para actualizar un curso (SOLO PARA EL PROPIETARIO)
        Route::put('/course/update', [CourseController::class, 'update'])->name('course.update');

        // Ruta para actualizar un capítulo (SOLO PARA EL PROPIETARIO)	
        Route::put('/chapter/update', [ChapterController::class, 'update'])->name('chapter.update');

        // RUTA PARA CREAR UN NUEVO EJERICIO (SOLO PARA EL PROPIETARIO)
        Route::post('/exercise/create', [ExerciseController::class, 'store'])->name('exercise.store');
        
        // RUTAS CAPÍTULO (SOLO PARA EL PROPIETARIO)


        // RUTAS PARA SISTEMA DE FORO
        Route::get('/getMessages', [MessageController::class, 'index'])->name('getForumMessages');
        Route::post('/sendMessage', [MessageController::class, 'store'])->name('sendForumMessage');

        // RUTAS PARA SISTEMA DE FORO
    });

    /**
     * SUBSCRIPCIONES (Página de productos)
     * By Manav Kumar Sharma
     */
    Route::prefix('subscriptions')->group(function () {
        Route::get('/', [SubscriptionController::class, 'index'])->name('subscriptionProductPage');
    });

    // --- Premios ---
    Route::view('/myAwards', 'pages.student.myAwards')->name('myAwardsPage');

    /**
     * RUTAS PARA TEACHER (y Admin)
     */
    Route::middleware([RoleMiddleware::class.':Teacher,Admin'])->group(function () {
        
        Route::prefix('teacher')->group(function () {
            Route::get('/dashboard', [TeacherController::class, 'dashboard'])->name('teacher.dashboard');
            Route::get('/course/{id}/edit', [TeacherController::class, 'editCourseView'])->name('course.edit.view');
            Route::get('/course/stats/{id}', [TeacherController::class, 'showCourseStats'])->name('course.stats');
            Route::get('/test', [TeacherController::class, 'asd'])->name('#');

            // POST
            Route::post('/course/create', [CourseController::class, 'create'])->name('create.course');

            // Ruta de capítulos
            Route::get('/course/{course}/edit/chapter/{chapter}', [ChapterController::class, 'edit'])->name('chapter.edit');
        });

        Route::prefix('admin')->group(function () {
            // --- Crud Usuario ---
            Route::get('/crudUsuarios', [AdminController::class, 'usuarios'])->name('crudUsuarios');
            Route::post('/deleteUser', [AdminController::class, 'deleteUser'])->name('deleteUser');
            Route::get('/subscriptionsJSON', [AdminController::class, 'subscriptionsJSON']);
            Route::get('/rolesJSON', [AdminController::class, 'rolesJSON']);
            Route::put('/users/{id}', [AdminController::class, 'updateUser'])->name('users.update');
            Route::post('/createUser', [AdminController::class, 'createUser'])->name('users.create');
            Route::post('/createRole', [AdminController::class, 'createRole']);
            Route::get('/teacher-requests', [AdminController::class, 'showReviewRequests'])->name('admin.teacher.requests');
            Route::post('/teacher-requests/approve/{id}', [AdminController::class, 'approveTeacher'])->name('admin.teacher.approve');
            Route::post('/teacher-requests/reject/{id}', [AdminController::class, 'rejectTeacher'])->name('admin.teacher.reject');
        });
    });

    // --- Soporte ---
    Route::view('/support', 'pages.common.support')->name('support');
    Route::post('/support/send', [UserController::class, 'send'])->name('support.send');

    // Request Teacher
    Route::view('/request-teacher', 'pages.common.requestTeacher')->name('teacher.request');
    Route::post('/request-teacher', [UserController::class, 'submitTeacherRequest'])->name('teacher.request.submit');
});