<?php

use App\Http\Controllers\SelfPaced\Dashboard\DashboardController;
use App\Http\Controllers\SelfPaced\Dashboard\CourseController;
use App\Http\Controllers\SelfPaced\Dashboard\TopicController;
use App\Http\Controllers\SelfPaced\Dashboard\MediaController;
use App\Http\Controllers\SelfPaced\Dashboard\ExamController;
use App\Http\Controllers\SelfPaced\Dashboard\ResultController;
use App\Http\Controllers\SelfPaced\Dashboard\EnrollmentController;
use App\Http\Controllers\SelfPaced\Dashboard\CertificateController;
use App\Http\Controllers\SelfPaced\Dashboard\PaystackConfigController;
use App\Http\Controllers\SelfPaced\Dashboard\PaymentProofController;
use App\Http\Controllers\SelfPaced\Dashboard\BookController as DashboardBookController;
use App\Http\Controllers\SelfPaced\Learner\LearnerController;
use App\Http\Controllers\SelfPaced\Learner\ExamAttemptController;
use App\Http\Controllers\SelfPaced\Learner\CertificatePaymentController;
use App\Http\Controllers\SelfPaced\Learner\ResitPaymentController;
use App\Http\Controllers\SelfPaced\Learner\BookController as LearnerBookController;
use App\Http\Controllers\SelfPaced\Public\PublicController;
use App\Http\Controllers\SelfPaced\Public\VerificationController;
use App\Http\Controllers\SelfPaced\Public\PaystackWebhookController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Self-Paced Learning Portal Routes
|--------------------------------------------------------------------------
|
| Three surfaces:
|   1. Public  — landing page, course detail, registration, payment, verification
|   2. Dashboard — admin/trainer management (permission-gated)
|   3. Learner Portal — trainee study interface (EnsureEnrolled + permission)
|
| Route name prefixes:
|   self-paced.public.*      — public-facing pages
|   self-paced.dashboard.*   — portal management dashboard
|   self-paced.learn.*       — learner portal (authenticated + enrolled)
|   api.self-paced.*         — AJAX API endpoints
|
*/

// ============================================================================
// PUBLIC ROUTES — No authentication required
// Requirements: 13.1–13.7, 11.3–11.5, 5.1–5.5, 1.7, 1.8
// ============================================================================

Route::prefix('self-paced')->name('self-paced.public.')->group(function () {

    // Paystack webhook endpoint (no auth, no CSRF)
    Route::post('/paystack/webhook', [PaystackWebhookController::class, 'handle'])
        ->withoutMiddleware(['web'])
        ->name('paystack.webhook');

    // Landing page — lists all published courses
    Route::get('/', [PublicController::class, 'index'])->name('index');

    // Certificate verification page (public, no auth)
    // Must be declared BEFORE /{course} wildcard
    Route::get('/verify', [VerificationController::class, 'index'])->name('verify');

    // Single course detail page
    Route::get('/courses/{course}', [PublicController::class, 'show'])->name('courses.show');

    // Registration form (Step 1: personal details)
    Route::get('/courses/{course}/register', [PublicController::class, 'register'])->name('register');
    Route::post('/courses/{course}/register', [PublicController::class, 'submitRegistration'])->name('register.submit');

    // Payment page (Step 2 & 3: Paystack)
    Route::middleware(['auth'])
        ->group(function () {
            Route::get('/courses/{course}/payment/{enrollment}', [PublicController::class, 'payment'])->name('payment');
            Route::post('/courses/{course}/payment/{enrollment}/init', [PublicController::class, 'initPayment'])->name('payment.init');
            Route::post('/courses/{course}/payment/{enrollment}/verify', [PublicController::class, 'verifyPayment'])->name('payment.verify');
            Route::post('/courses/{course}/payment/{enrollment}/proof', [PublicController::class, 'submitPaymentProof'])->name('payment.proof');
        });
});

// ============================================================================
// PORTAL DASHBOARD ROUTES — Authenticated + permission-gated
// Requirements: 1.1–1.8, 2.1–2.5, 3.1–3.6, 4.1–4.5, 10.1–10.7, 11.1–11.7, 12.1–12.6
// ============================================================================

Route::middleware(['auth', 'permission:view self-paced courses'])
    ->prefix('self-paced/dashboard')
    ->name('self-paced.dashboard.')
    ->group(function () {

    // ── Dashboard Home ────────────────────────────────────────────────────
    Route::get('/', [DashboardController::class, 'index'])->name('index');

    // ── Courses ───────────────────────────────────────────────────────────
    Route::prefix('courses')->name('courses.')->group(function () {
        Route::get('/', [CourseController::class, 'index'])->name('index');
        Route::get('/create', [CourseController::class, 'create'])->name('create')->middleware('permission:create self-paced courses');
        Route::post('/', [CourseController::class, 'store'])->name('store')->middleware('permission:create self-paced courses');
        Route::get('/{course}', [CourseController::class, 'show'])->name('show');
        Route::get('/{course}/edit', [CourseController::class, 'edit'])->name('edit')->middleware('permission:edit self-paced courses');
        Route::put('/{course}', [CourseController::class, 'update'])->name('update')->middleware('permission:edit self-paced courses');
        Route::delete('/{course}', [CourseController::class, 'destroy'])->name('destroy')->middleware('permission:delete self-paced courses');

        // Downloads management for a course
        Route::get('/{course}/downloads', [MediaController::class, 'downloads'])->name('downloads');
        Route::post('/{course}/downloads', [MediaController::class, 'storeDownload'])->name('downloads.store')->middleware('permission:manage self-paced media');
        Route::delete('/{course}/downloads/{download}', [MediaController::class, 'destroyDownload'])->name('downloads.destroy')->middleware('permission:manage self-paced media');

        // ── Topics (nested under course) ──────────────────────────────────
        Route::prefix('/{course}/topics')->name('topics.')->group(function () {
            Route::get('/', [TopicController::class, 'index'])->name('index');
            Route::get('/create', [TopicController::class, 'create'])->name('create')->middleware('permission:manage self-paced topics');
            Route::post('/', [TopicController::class, 'store'])->name('store')->middleware('permission:manage self-paced topics');
            Route::patch('/reorder', [TopicController::class, 'reorder'])->name('reorder')->middleware('permission:manage self-paced topics');
            Route::get('/{topic}', [TopicController::class, 'show'])->name('show');
            Route::get('/{topic}/edit', [TopicController::class, 'edit'])->name('edit')->middleware('permission:manage self-paced topics');
            Route::put('/{topic}', [TopicController::class, 'update'])->name('update')->middleware('permission:manage self-paced topics');
            Route::delete('/{topic}', [TopicController::class, 'destroy'])->name('destroy')->middleware('permission:manage self-paced topics');

            // ── SubTopics (nested under topic) ────────────────────────────
            Route::prefix('/{topic}/subtopics')->name('subtopics.')->group(function () {
                Route::get('/create', [TopicController::class, 'createSubtopic'])->name('create')->middleware('permission:manage self-paced topics');
                Route::post('/', [TopicController::class, 'storeSubtopic'])->name('store')->middleware('permission:manage self-paced topics');
                Route::patch('/reorder', [TopicController::class, 'reorderSubtopics'])->name('reorder')->middleware('permission:manage self-paced topics');
                Route::get('/{subtopic}', [TopicController::class, 'showSubtopic'])->name('show');
                Route::get('/{subtopic}/edit', [TopicController::class, 'editSubtopic'])->name('edit')->middleware('permission:manage self-paced topics');
                Route::put('/{subtopic}', [TopicController::class, 'updateSubtopic'])->name('update')->middleware('permission:manage self-paced topics');
                Route::delete('/{subtopic}', [TopicController::class, 'destroySubtopic'])->name('destroy')->middleware('permission:manage self-paced topics');

                // ── Media (nested under subtopic) ─────────────────────────
                Route::prefix('/{subtopic}/media')->name('media.')->group(function () {
                    Route::get('/', [MediaController::class, 'index'])->name('index');
                    Route::post('/', [MediaController::class, 'store'])->name('store')->middleware('permission:manage self-paced media');
                    Route::patch('/reorder', [MediaController::class, 'reorder'])->name('reorder')->middleware('permission:manage self-paced media');
                    Route::delete('/{media}', [MediaController::class, 'destroy'])->name('destroy')->middleware('permission:manage self-paced media');
                });
            });
        });
    });

    // ── Exams / Question Bank ─────────────────────────────────────────────
    Route::prefix('exams')->name('exams.')->group(function () {
        // Global question bank (all courses)
        Route::get('/', [ExamController::class, 'index'])->name('index')->middleware('permission:manage self-paced exams');

        // Per-course questions
        Route::get('/courses/{course}/questions', [ExamController::class, 'courseQuestions'])->name('course-questions')->middleware('permission:manage self-paced exams');
        Route::get('/courses/{course}/questions/create', [ExamController::class, 'create'])->name('create')->middleware('permission:manage self-paced exams');
        Route::post('/courses/{course}/questions', [ExamController::class, 'store'])->name('store')->middleware('permission:manage self-paced exams');
        Route::get('/courses/{course}/questions/{question}/edit', [ExamController::class, 'edit'])->name('edit')->middleware('permission:manage self-paced exams');
        Route::put('/courses/{course}/questions/{question}', [ExamController::class, 'update'])->name('update')->middleware('permission:manage self-paced exams');
        Route::delete('/courses/{course}/questions/{question}', [ExamController::class, 'destroy'])->name('destroy')->middleware('permission:manage self-paced exams');

        // Exam settings per course
        Route::get('/courses/{course}/settings', [ExamController::class, 'settings'])->name('settings')->middleware('permission:manage self-paced exams');
        Route::put('/courses/{course}/settings', [ExamController::class, 'updateSettings'])->name('settings.update')->middleware('permission:manage self-paced exams');

        // CSV import
        Route::get('/courses/{course}/import', [ExamController::class, 'importForm'])->name('import')->middleware('permission:manage self-paced exams');
        Route::post('/courses/{course}/import', [ExamController::class, 'import'])->name('import.submit')->middleware('permission:manage self-paced exams');
    });

    // ── Results ───────────────────────────────────────────────────────────
    Route::prefix('results')->name('results.')->middleware('permission:view self-paced results')->group(function () {
        Route::get('/', [ResultController::class, 'index'])->name('index');
        Route::get('/export', [ResultController::class, 'export'])->name('export');
        Route::get('/{result}', [ResultController::class, 'show'])->name('show');
        Route::get('/{result}/result-slip', [ResultController::class, 'downloadResultSlip'])->name('result-slip');
    });

    // ── Enrollments ───────────────────────────────────────────────────────
    Route::prefix('enrollments')->name('enrollments.')->group(function () {
        Route::get('/', [EnrollmentController::class, 'index'])->name('index')->middleware('permission:view self-paced enrollments');
        Route::get('/create', [EnrollmentController::class, 'create'])->name('create')->middleware('permission:manage self-paced enrollments');
        Route::post('/', [EnrollmentController::class, 'store'])->name('store')->middleware('permission:manage self-paced enrollments');
        Route::get('/export', [EnrollmentController::class, 'export'])->name('export')->middleware('permission:manage self-paced enrollments');
        Route::get('/{enrollment}', [EnrollmentController::class, 'show'])->name('show')->middleware('permission:view self-paced enrollments');
        Route::post('/{enrollment}/activate', [EnrollmentController::class, 'activate'])->name('activate')->middleware('permission:manage self-paced enrollments');
        Route::post('/{enrollment}/cancel', [EnrollmentController::class, 'cancel'])->name('cancel')->middleware('permission:manage self-paced enrollments');
        Route::post('/{enrollment}/check-payment', [EnrollmentController::class, 'checkPayment'])->name('check-payment')->middleware('permission:manage self-paced enrollments');
    });

    // ── Certificates ──────────────────────────────────────────────────────
    Route::prefix('certificates')->name('certificates.')->middleware('permission:manage self-paced certificates')->group(function () {
        Route::get('/', [CertificateController::class, 'index'])->name('index');
        Route::get('/export', [CertificateController::class, 'export'])->name('export');
        Route::post('/generate/{result}', [CertificateController::class, 'generate'])->name('generate');
        Route::get('/{certificate}', [CertificateController::class, 'show'])->name('show');
        Route::get('/{certificate}/download', [CertificateController::class, 'download'])->name('download');
        Route::post('/{certificate}/revoke', [CertificateController::class, 'revoke'])->name('revoke');
        Route::post('/{certificate}/regenerate', [CertificateController::class, 'regenerate'])->name('regenerate');
    });

    // ── Paystack Configuration ─────────────────────────────────────────────
    Route::prefix('paystack')->name('paystack.')->middleware('permission:manage self-paced paystack')->group(function () {
        Route::get('/config', [PaystackConfigController::class, 'show'])->name('config.show');
        Route::put('/config', [PaystackConfigController::class, 'update'])->name('config.update');
    });

    // ── Payment Proofs (Cash Payments) ────────────────────────────────────
    Route::prefix('payment-proofs')->name('payment-proofs.')->middleware('permission:verify self-paced payments')->group(function () {
        Route::get('/', [PaymentProofController::class, 'index'])->name('index');
        Route::get('/{proof}', [PaymentProofController::class, 'show'])->name('show');
        Route::post('/{proof}/approve', [PaymentProofController::class, 'approve'])->name('approve');
        Route::post('/{proof}/reject', [PaymentProofController::class, 'reject'])->name('reject');
        Route::get('/{proof}/download', [PaymentProofController::class, 'streamFile'])->name('download');
    });

    // ── Course Books (Management) ──────────────────────────────────────────
    Route::prefix('courses/{course}/book')->name('book.')->middleware('permission:manage self-paced book')->group(function () {
        Route::post('/', [DashboardBookController::class, 'upload'])->name('upload');
        Route::delete('/', [DashboardBookController::class, 'destroy'])->name('destroy');
    });
});

// ============================================================================
// LEARNER PORTAL ROUTES — Authenticated + enrolled
// Requirements: 6.1–6.4, 7.1–7.9, 8.1–8.10, 9.1–9.6, 14.4, 14.5
// ============================================================================

// My enrolled courses — authenticated trainees landing page
Route::middleware(['auth', 'permission:access self-paced learner portal'])
    ->get('/self-paced/my-courses', [LearnerController::class, 'myCourses'])
    ->name('self-paced.learn.my-courses');

Route::middleware(['auth', 'permission:access self-paced learner portal', 'ensure.enrolled'])
    ->prefix('self-paced/learn/{course}')
    ->name('self-paced.learn.')
    ->group(function () {

    // Phase 1 — Course Overview
    Route::get('/overview', [LearnerController::class, 'overview'])->name('overview');

    // Phase 2 — Course Content
    Route::get('/content', [LearnerController::class, 'content'])->name('content');
    Route::get('/content/{subtopicId}', [LearnerController::class, 'content'])->name('content.subtopic');

    // Phase 3 — Exam
    Route::get('/exam/confirm', [ExamAttemptController::class, 'confirm'])->name('exam.confirm');
    Route::post('/exam/start', [ExamAttemptController::class, 'start'])->name('exam.start');
    Route::get('/exam/{attempt}', [ExamAttemptController::class, 'take'])->name('exam.take');
    Route::post('/exam/{attempt}/submit', [ExamAttemptController::class, 'submit'])->name('exam.submit');

    // Phase 4 — Results & Certificate
    Route::get('/results/{result}', [LearnerController::class, 'results'])->name('results');
    Route::get('/results/{result}/result-slip', [LearnerController::class, 'downloadResultSlip'])->name('results.slip');
    Route::get('/results/{result}/certificate', [LearnerController::class, 'downloadCertificate'])->name('results.certificate');

    // ── Payment Proof (unified endpoint for enrollment, certificate, book, resit) ────
    Route::post('/payment-proof/store', [LearnerController::class, 'storePaymentProof'])->name('payment-proof.store');
    Route::get('/payment-proof', [LearnerController::class, 'showPaymentProofForm'])->name('payment-proof.form');

    // ── Certificate Payment (Fee/Download) ────────────────────────────────
    Route::prefix('certificate-payment')->name('certificate-payment.')->group(function () {
        Route::post('/init', [CertificatePaymentController::class, 'init'])->name('init');
        Route::post('/verify', [CertificatePaymentController::class, 'verify'])->name('verify');
        Route::post('/proof', [CertificatePaymentController::class, 'submitProof'])->name('proof');
    });

    // ── Re-sit Payment (Exam Failure Fee) ───────────────────────────────────
    Route::prefix('resit-payment')->name('resit-payment.')->group(function () {
        Route::post('/init', [ResitPaymentController::class, 'init'])->name('init');
        Route::post('/verify', [ResitPaymentController::class, 'verify'])->name('verify');
        Route::post('/proof', [ResitPaymentController::class, 'submitProof'])->name('proof');
    });

    // ── Course Book Purchase ───────────────────────────────────────────────
    Route::prefix('book')->name('book.')->group(function () {
        Route::post('/init-purchase', [LearnerBookController::class, 'initPurchase'])->name('init-purchase');
        Route::post('/verify-purchase', [LearnerBookController::class, 'verifyPurchase'])->name('verify-purchase');
        Route::post('/proof', [LearnerBookController::class, 'submitProof'])->name('proof');
        Route::get('/download/{purchase}', [LearnerBookController::class, 'download'])->name('download');
        Route::get('/download-signed/{bookPurchase}', [LearnerBookController::class, 'downloadSigned'])
            ->name('download-signed')
            ->middleware('signed');
    });
});

// ============================================================================
// API ROUTES — AJAX endpoints (auth required, no ensure.enrolled for timer/answers)
// Requirements: 7.2, 7.3, 8.6, 5.4
// ============================================================================

Route::middleware(['auth'])
    ->prefix('api/self-paced')
    ->name('api.self-paced.')
    ->group(function () {

    // Topic timer ping (POST every 30 seconds from learner portal)
    Route::post('/learn/{course}/timer/{topic}', [LearnerController::class, 'pingTimer'])
        ->name('timer.ping');

    // Mark subtopic as read (AJAX POST)
    Route::post('/learn/{course}/mark-read/{subtopic}', [LearnerController::class, 'markRead'])
        ->name('mark-read');

    // Save exam answer (AJAX POST — idempotent)
    Route::post('/learn/{course}/exam/{attempt}/answer', [ExamAttemptController::class, 'saveAnswer'])
        ->name('exam.answer');

    // Navigate to specific question by index (AJAX GET)
    Route::get('/learn/{course}/exam/{attempt}/question/{index}', [ExamAttemptController::class, 'question'])
        ->name('exam.question');

    // Poll payment status (AJAX GET)
    Route::get('/payment/{course}/{enrollment}/status', [PublicController::class, 'paymentStatus'])
        ->name('payment.status');

    // Certificate verification (AJAX POST — public but also available as API)
    Route::post('/verify', [VerificationController::class, 'verify'])
        ->withoutMiddleware(['auth'])
        ->name('verify');

    // Quill inline image upload (used by subtopic and exam question rich editors)
    Route::post('/media/upload', [MediaController::class, 'uploadInlineImage'])->name('media.upload');
});
