<?php

use App\Http\Controllers\ImpersonationController;
use App\Http\Controllers\InquiryController;
use App\Http\Controllers\TrainingFeedbackController;
use App\Http\Controllers\ToolResultController;
use App\Livewire\AssessmentRunner;
use App\Models\AssessmentAttempt;
use App\Models\Course;
use App\Models\Post;
use App\Models\Testimonial;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Public site
|--------------------------------------------------------------------------
*/

Route::view('/coming-soon', 'pages.coming-soon')->name('coming-soon');

Route::get('/', function () {
    return view('pages.home', [
        'testimonials' => Testimonial::where('is_featured', true)->orderBy('sort')->get(),
        'course' => Course::where('is_published', true)->orderBy('sort')->first(),
    ]);
})->name('home');

// The three customer journeys
Route::view('/start/individuals', 'pages.journeys.individuals')->name('journey.individuals');
Route::view('/start/corporates', 'pages.journeys.corporates')->name('journey.corporates');
Route::view('/start/diaspora', 'pages.journeys.diaspora')->name('journey.diaspora');

// Tools & calculators
Route::view('/tools', 'pages.tools.index')->name('tools.index');

Route::get('/tools/{tool}', function (string $tool) {
    abort_unless(in_array($tool, ['budget', 'debt-payoff', 'compound-growth', 'emergency-fund', 'values-clarification', 'wealth-goals', 'loan-cost', 'retirement']), 404);

    return view("pages.tools.{$tool}");
})->name('tools.show');

Route::post('/tools/{tool}/save', [ToolResultController::class, 'store'])->name('tools.save');
Route::post('/tools/{tool}/pdf', [\App\Http\Controllers\PdfReportController::class, 'tool'])->name('tools.pdf');

// Assessments
Route::get('/assessments/{assessment}', AssessmentRunner::class)->name('assessments.show');

Route::get('/assessments/{assessment}/results/{attempt}', function (string $assessment, AssessmentAttempt $attempt) {
    abort_unless($attempt->status === 'completed', 404);
    $attempt->load(['assessment.questions', 'band']);

    return view('pages.assessments.results', ['attempt' => $attempt]);
})->name('assessments.results');

Route::get('/assessments/{assessment}/results/{attempt}/pdf', [\App\Http\Controllers\PdfReportController::class, 'assessment'])
    ->name('assessments.results.pdf');

// Learning
Route::get('/learn', function () {
    return view('pages.learn.index', [
        'courses' => Course::where('is_published', true)->orderBy('sort')->withCount('enrollments')->get(),
    ]);
})->name('learn');

Route::get('/learn/{course}', function (Course $course) {
    abort_unless($course->is_published, 404);
    $course->load('modules.lessons');

    $enrolled = auth()->check()
        && $course->enrollments()->where('user_id', auth()->id())->exists();

    return view('pages.learn.show', ['course' => $course, 'enrolled' => $enrolled]);
})->name('learn.show');

Route::post('/learn/{course}/enroll', function (Course $course) {
    abort_unless($course->is_published, 404);

    \App\Models\Enrollment::firstOrCreate([
        'user_id' => auth()->id(),
        'course_id' => $course->id,
    ]);

    $first = $course->lessons()->first();

    return $first
        ? redirect()->route('learn.lesson', ['course' => $course->slug, 'lesson' => $first->slug])
        : redirect()->route('learn.show', $course);
})->middleware('auth')->name('learn.enroll');

Route::get('/learn/{course}/lessons/{lesson:slug}', \App\Livewire\CoursePlayer::class)->name('learn.lesson');

// Books, About, Contact
Route::view('/books', 'pages.books')->name('books');
Route::view('/about', 'pages.about')->name('about');
Route::view('/coaching', 'pages.coaching')->name('coaching');
Route::view('/coaching/book', 'pages.coaching-book')->name('coaching.book');
Route::view('/debt', 'pages.debt')->name('debt');
Route::view('/speaking', 'pages.speaking')->name('speaking');

// Payment gateway webhooks (CSRF-exempt in bootstrap/app.php).
Route::post('/webhooks/mpesa', [\App\Http\Controllers\WebhookController::class, 'mpesa'])->name('webhooks.mpesa');
Route::post('/webhooks/paystack', [\App\Http\Controllers\WebhookController::class, 'paystack'])->name('webhooks.paystack');
Route::post('/webhooks/flutterwave', [\App\Http\Controllers\WebhookController::class, 'flutterwave'])->name('webhooks.flutterwave');
Route::view('/privacy', 'pages.privacy')->name('privacy');

Route::view('/contact', 'pages.contact')->name('contact');
Route::post('/contact', [InquiryController::class, 'store'])->name('contact.store');

Route::get('/feedback', [TrainingFeedbackController::class, 'index'])->name('feedback.show');
Route::post('/feedback', [TrainingFeedbackController::class, 'store'])->name('feedback.store');

// Consultation booking (multistep)
Route::view('/consultation', 'pages.consultation')->name('consultation');

Route::post('/consultation', function (\Illuminate\Http\Request $request) {
    $data = $request->validate([
        'name' => ['required', 'string', 'max:120'],
        'email' => ['required', 'email', 'max:190'],
        'phone' => ['nullable', 'string', 'max:30'],
        'country' => ['nullable', 'string', 'max:40'],
        'segment' => ['required', 'in:individual,corporate,diaspora'],
        'topic' => ['required', 'in:debt,investing,corporate-training,diaspora-plan,coaching,other'],
        'contact_method' => ['required', 'in:whatsapp,call,email'],
        'preferred_time' => ['required', 'in:morning,afternoon,evening'],
        'message' => ['nullable', 'string', 'max:3000'],
    ]);

    \App\Models\Consultation::create($data);

    \App\Models\Lead::firstOrCreate(
        ['email' => $data['email'], 'source' => 'consultation'],
        ['name' => $data['name'], 'segment' => $data['segment']]
    );

    return response()->json(['booked' => true]);
})->name('consultation.store');

// Resources — downloadable guides with flipbook reader
Route::get('/resources', function (\Illuminate\Http\Request $request) {
    $guides = \App\Models\Guide::published()
        ->when($request->q, fn ($query, $term) => $query->where(fn ($w) => $w
            ->where('title', 'like', "%{$term}%")
            ->orWhere('description', 'like', "%{$term}%")))
        ->when($request->category, fn ($query, $cat) => $query->where('category', $cat))
        ->orderBy('sort')
        ->get();

    return view('pages.resources.index', [
        'guides' => $guides,
        'categories' => \App\Models\Guide::published()->pluck('category')->unique()->filter()->values(),
    ]);
})->name('resources');

Route::get('/resources/{guide}', function (\App\Models\Guide $guide) {
    abort_unless($guide->is_published, 404);

    return view('pages.resources.show', ['guide' => $guide]);
})->name('resources.show');

Route::get('/resources/{guide}/pdf', function (\App\Models\Guide $guide) {
    abort_unless($guide->is_published, 404);
    $guide->increment('download_count');

    return \Barryvdh\DomPDF\Facade\Pdf::loadView('pdf.guide', ['guide' => $guide])
        ->download(\Illuminate\Support\Str::slug($guide->title).'-moneywise.pdf');
})->name('resources.pdf');

// Newsletter signup (footer)
Route::post('/newsletter', function (\Illuminate\Http\Request $request) {
    $data = $request->validate(['email' => ['required', 'email', 'max:190']]);

    \App\Models\Lead::firstOrCreate(
        ['email' => $data['email'], 'source' => 'newsletter'],
    );

    return response()->json(['subscribed' => true]);
})->name('newsletter.store');

// Blog
Route::get('/blog', function (\Illuminate\Http\Request $request) {
    $posts = Post::published()
        ->when($request->q, fn ($query, $term) => $query->where(fn ($w) => $w
            ->where('title', 'like', "%{$term}%")
            ->orWhere('excerpt', 'like', "%{$term}%")
            ->orWhere('body', 'like', "%{$term}%")))
        ->when($request->category, fn ($query, $cat) => $query->where('category', $cat))
        ->latest('published_at')
        ->paginate(9)
        ->withQueryString();

    return view('pages.blog.index', [
        'posts' => $posts,
        'categories' => Post::published()->pluck('category')->unique()->filter()->values(),
    ]);
})->name('blog');

Route::get('/blog/{post}', function (Post $post) {
    abort_if($post->published_at === null || $post->published_at->isFuture(), 404);

    return view('pages.blog.show', ['post' => $post]);
})->name('blog.show');

/*
|--------------------------------------------------------------------------
| Member area
|--------------------------------------------------------------------------
*/

Route::view('dashboard', 'dashboard')
    ->middleware(['auth', 'verified'])
    ->name('dashboard');

Route::view('profile', 'profile')
    ->middleware(['auth'])
    ->name('profile');

// Admin → member impersonation (start is admin-gated inside the controller).
Route::get('impersonate/{user}', [ImpersonationController::class, 'start'])
    ->middleware(['auth'])
    ->name('impersonate.start');
Route::get('impersonate-leave', [ImpersonationController::class, 'leave'])
    ->middleware(['auth'])
    ->name('impersonate.leave');

require __DIR__.'/auth.php';
