<?php

declare(strict_types=1);

use App\Http\Controllers\Marketing\ContactController;
use App\Http\Controllers\Marketing\KnowledgeBaseController;
use App\Http\Controllers\Marketing\QuoteAcceptController;
use App\Models\Plan;
use App\Models\Service;
use App\Models\User;
use App\Models\WinbackRecipient;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;

Route::get('/', function () {
    $data = Cache::remember('marketing:home-stats', 300, fn () => [
        'customerCount' => User::role('customer')->count(),
        'serviceCount' => Service::where('status', 'active')->count(),
        'startingPrices' => [
            'vps' => Plan::where('service_type', 'vps')->where('status', 'active')->min('price'),
            'dedicated' => Plan::where('service_type', 'dedicated')->where('status', 'active')->min('price'),
            'hosting' => Plan::where('service_type', 'hosting')->where('status', 'active')->min('price'),
        ],
    ]);

    return Inertia::render('Marketing/Home', $data);
})->name('home');
Route::redirect('/products', '/', 301);
Route::get('/vps-hosting', function () {
    $plans = Plan::query()
        ->where('service_type', 'vps')
        ->where('status', 'active')
        ->with('prices')
        ->orderBy('sort_order')
        ->orderBy('price')
        ->get();

    $addOns = \App\Models\PlanConfigGroup::query()
        ->where('service_type', 'vps')
        ->where('is_active', true)
        ->where('mode', 'preset')
        ->with(['options' => fn ($q) => $q->where('is_active', true)->orderBy('sort_order'), 'options.values' => fn ($q) => $q->orderBy('sort_order')])
        ->orderBy('sort_order')
        ->get();

    // Workload key → default plan slug + alternates. Drives the WorkloadPicker chips.
    $workloadMap = [
        'personal_site' => ['default' => 'vps-2',    'alternates' => ['vps-1', 'vps-4'],         'label' => 'Personal site / blog',   'icon' => 'tabler-world'],
        'saas' => ['default' => 'vps-4',    'alternates' => ['vps-2', 'vps-8'],         'label' => 'Web app / SaaS backend', 'icon' => 'tabler-cloud'],
        'dev_staging' => ['default' => 'vps-2',    'alternates' => ['vps-1', 'vps-4'],         'label' => 'Development / staging',  'icon' => 'tabler-code'],
        'discord_bot' => ['default' => 'vps-1',    'alternates' => ['vps-2'],                  'label' => 'Discord bot / daemon',   'icon' => 'tabler-brand-discord'],
        'vpn' => ['default' => 'vps-1',    'alternates' => ['vps-2'],                  'label' => 'VPN / proxy / Tailscale', 'icon' => 'tabler-shield-lock'],
        'storage_target' => ['default' => 'stor-1tb', 'alternates' => ['stor-500', 'vps-4'],      'label' => 'Storage / backup target', 'icon' => 'tabler-database'],
        'database' => ['default' => 'vps-16',   'alternates' => ['vps-8', 'vps-32'],        'label' => 'Database (Postgres / MySQL)', 'icon' => 'tabler-database-cog'],
        'cicd' => ['default' => 'vps-8',    'alternates' => ['vps-4', 'vps-16'],        'label' => 'CI/CD runner',           'icon' => 'tabler-git-branch'],
        'not_sure' => ['default' => null,       'alternates' => [],                         'label' => 'Not sure — help me pick', 'icon' => 'tabler-help'],
    ];

    // 12-app catalog for the mini-quiz Step 1.
    $appExamples = [
        ['key' => 'wordpress', 'label' => 'WordPress / static blog', 'plan' => 'vps-1',    'icon' => 'tabler-brand-wordpress'],
        ['key' => 'ghost',     'label' => 'Ghost / Mastodon (small)', 'plan' => 'vps-2',   'icon' => 'tabler-message-circle'],
        ['key' => 'bitwarden', 'label' => 'Bitwarden / Vaultwarden', 'plan' => 'vps-1',    'icon' => 'tabler-key'],
        ['key' => 'plex',      'label' => 'Plex / Jellyfin',         'plan' => 'stor-500', 'icon' => 'tabler-movie'],
        ['key' => 'nextcloud', 'label' => 'Nextcloud / file sync',   'plan' => 'stor-1tb', 'icon' => 'tabler-cloud-upload'],
        ['key' => 'gitea',     'label' => 'Gitea / self-hosted git', 'plan' => 'vps-2',    'icon' => 'tabler-git-merge'],
        ['key' => 'mattermost', 'label' => 'Mattermost / chat',       'plan' => 'vps-4',    'icon' => 'tabler-messages'],
        ['key' => 'postgres',  'label' => 'Postgres / MySQL DB',     'plan' => 'vps-16',   'icon' => 'tabler-database'],
        ['key' => 'mautic',    'label' => 'Mautic / marketing app',  'plan' => 'vps-4',    'icon' => 'tabler-mail-forward'],
        ['key' => 'elk',       'label' => 'ELK stack / logging',     'plan' => 'vps-8',    'icon' => 'tabler-stack-3'],
        ['key' => 'docker',    'label' => 'Docker swarm / k3s',      'plan' => 'vps-8',    'icon' => 'tabler-brand-docker'],
        ['key' => 'other',     'label' => 'Other / not listed',      'plan' => null,       'icon' => 'tabler-question-mark'],
    ];

    return Inertia::render('Marketing/VpsHosting', [
        'plans' => $plans,
        'addOns' => $addOns,
        'workloadMap' => $workloadMap,
        'appExamples' => $appExamples,
    ]);
})->name('vps-hosting');
Route::get('/dedicated-servers', function () {
    $plans = Plan::query()
        ->where('service_type', 'dedicated')
        ->where('status', 'active')
        ->with('prices')
        ->orderBy('sort_order')
        ->orderBy('price')
        ->get();

    return Inertia::render('Marketing/DedicatedServers', [
        'plans' => $plans,
    ]);
})->name('dedicated-servers');

Route::get('/dedicated-servers/{slug}', function (string $slug) {
    $plan = Plan::query()
        ->where('service_type', 'dedicated')
        ->where('slug', $slug)
        ->where('status', 'active')
        ->with('prices')
        ->firstOrFail();

    // Configurable add-on groups attached to this specific chassis,
    // scoped to the 14th-gen Dedicated configurator namespace so we
    // don't leak unrelated groups (e.g., Server Management, Veeam) into
    // the per-chassis customizer.
    $configGroups = $plan->configGroups()
        ->where('is_active', true)
        ->where('mode', 'preset')
        ->where('name', 'like', 'Dedicated 14th Gen%')
        ->with(['options' => fn ($q) => $q->where('is_active', true)->orderBy('sort_order'), 'options.values' => fn ($q) => $q->orderBy('sort_order')])
        ->orderBy('sort_order')
        ->get();

    return Inertia::render('Marketing/DedicatedServerDetail', [
        'plan' => $plan,
        'configGroups' => $configGroups,
    ]);
})->name('dedicated-servers.show');
Route::get('/web-hosting', function () {
    $plans = Plan::query()
        ->where('service_type', 'hosting')
        ->where('status', 'active')
        ->orderBy('sort_order')
        ->orderBy('price')
        ->get();

    return Inertia::render('Marketing/WebHosting', [
        'plans' => $plans,
    ]);
})->name('web-hosting');
Route::get('/game-servers', function () {
    $plans = Plan::query()
        ->where('service_type', 'game')
        ->where('status', 'active')
        ->orderBy('sort_order')
        ->orderBy('price')
        ->get();

    return Inertia::render('Marketing/GameServers', [
        'plans' => $plans,
    ]);
})->name('game-servers');
Route::redirect('/battlefield-acp', '/game-servers', 301);
Route::get('/pricing', function () {
    $plans = Plan::query()
        ->public()
        ->with('prices')
        ->withCount('configGroups')
        ->orderBy('service_type')
        ->orderBy('sort_order')
        ->orderBy('price')
        ->get();

    $byoConfigGroups = \App\Models\PlanConfigGroup::buildYourOwn()
        ->active()
        ->with(['options' => fn ($q) => $q->active()->orderBy('sort_order'), 'options.values'])
        ->orderBy('sort_order')
        ->get()
        ->keyBy('service_type');

    return Inertia::render('Marketing/Pricing', [
        'plans' => $plans,
        'groupedPlans' => $plans->groupBy('service_type'),
        'byoConfigGroups' => $byoConfigGroups,
    ]);
})->name('pricing');
Route::get('/about', function () {
    $data = Cache::remember('marketing:about-stats', 300, fn () => [
        'customerCount' => User::role('customer')->count(),
        'serviceCount' => Service::where('status', 'active')->count(),
    ]);

    return Inertia::render('Marketing/About', $data);
})->name('about');
Route::get('/contact', fn () => Inertia::render('Marketing/Contact'))->name('contact');
Route::post('/contact', [ContactController::class, 'store'])->name('contact.store');

Route::get('/api-docs', fn () => Inertia::render('Marketing/ApiDocs'))->name('api-docs');

// Legal pages
Route::get('/terms-of-service', fn () => Inertia::render('Marketing/TermsOfService'))->name('terms');
Route::get('/privacy-policy', fn () => Inertia::render('Marketing/PrivacyPolicy'))->name('privacy');
Route::get('/acceptable-use', fn () => Inertia::render('Marketing/AcceptableUse'))->name('aup');
Route::redirect('/terms', '/terms-of-service', 301);
Route::redirect('/privacy', '/privacy-policy', 301);
Route::get('/sla', fn () => Inertia::render('Marketing/Sla'))->name('sla');

// Knowledge Base
Route::get('/knowledge-base', [KnowledgeBaseController::class, 'index'])->name('knowledge-base');
Route::get('/knowledge-base/search', [KnowledgeBaseController::class, 'search'])->name('knowledge-base.search');
Route::get('/knowledge-base/{category:slug}', [KnowledgeBaseController::class, 'category'])->name('knowledge-base.category');
Route::get('/knowledge-base/{category:slug}/{article:slug}', [KnowledgeBaseController::class, 'article'])->name('knowledge-base.article');
Route::post('/knowledge-base/articles/{article}/vote', [KnowledgeBaseController::class, 'vote'])->name('knowledge-base.vote');

// Quotes (public, signed URLs)
Route::get('/quotes/{quote}', [QuoteAcceptController::class, 'show'])->name('quotes.show')->middleware('signed');
Route::post('/quotes/{quote}/accept', [QuoteAcceptController::class, 'accept'])->name('quotes.accept')->middleware('signed');
Route::post('/quotes/{quote}/reject', [QuoteAcceptController::class, 'reject'])->name('quotes.reject')->middleware('signed');

// Win-back unsubscribe (signed URL, no auth required)
Route::get('/unsubscribe/winback/{recipient}', function (WinbackRecipient $recipient) {
    $recipient->update(['unsubscribed_at' => now()]);

    return Inertia::render('Marketing/Unsubscribed');
})->name('winback.unsubscribe')->middleware('signed');
