<?php

// routes/web.php

use App\Facades\AdminCache;
use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\PaymentGateways\RazorpayController;
use App\Http\Controllers\PaymentGateways\StripeController;
use App\Http\Controllers\PrivacyPolicyController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\TermsConditionsController;
use App\Http\Controllers\Whatsapp\WhatsAppWebhookController;
use App\Http\Middleware\SanitizeInputs;
use Corbital\Installer\Http\Controllers\InstallController;
use Illuminate\Support\Facades\Route;

// Home route
Route::get('/', function () {
    return view('welcome');
})->name('home');

Route::get('/validate', [InstallController::class, 'validate'])->name('validate');
Route::post('/validate', [InstallController::class, 'validateLicense'])->name('validate.license');

// Authentication related routes
require __DIR__.'/auth.php';

// Authenticated user routes
Route::middleware(['auth', SanitizeInputs::class])->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');

    // Email testing route using our Laravel Emails package
    Route::post('/test-email-package', [\App\Http\Controllers\TestEmailController::class, 'testSmtpWithPackage'])->name('test-email-package');
});

// WhatsApp Webhook Route (Supports GET & POST)
Route::match(['get', 'post'], '/whatsapp/webhook', [WhatsAppWebhookController::class, '__invoke'])
    ->name('whatsapp.webhook');

Route::match(['get', 'post'], 'webhooks/stripe', [StripeController::class, 'webhook'])
    ->name('webhook.stripe');

Route::match(['get', 'post'], 'webhooks/razorpay', [RazorpayController::class, 'webhook'])
    ->name('webhook.razorpay');

Route::get('back-to-admin', [AuthenticatedSessionController::class, 'back_to_admin'])->name('back.to.admin');
Route::get('/privacy-policy', [PrivacyPolicyController::class, 'show'])->name('privacy.policy');
Route::get('/terms-conditions', [TermsConditionsController::class, 'show'])->name('terms.conditions');

// AdminCache Browser Test Route
Route::get('/test-admin-cache', function () {
    $stats = [];

    // Test 1: Basic cache operations
    $startTime = microtime(true);

    AdminCache::put('browser_test_basic', 'This value was cached!', ['admin.test'], 300);
    $retrievedValue = AdminCache::get('browser_test_basic');

    $stats['basic_test'] = [
        'status' => $retrievedValue === 'This value was cached!' ? 'PASSED' : 'FAILED',
        'value' => $retrievedValue,
        'time' => round((microtime(true) - $startTime) * 1000, 2).'ms',
    ];

    // Test 2: Remember pattern (should be fast on second call)
    $startTime = microtime(true);

    $expensiveOperation = AdminCache::remember('browser_test_expensive', function () {
        // Simulate expensive operation
        usleep(100000); // 100ms delay

        return 'Expensive operation result: '.now()->format('H:i:s');
    }, ['admin.test'], 300);

    $stats['remember_test'] = [
        'result' => $expensiveOperation,
        'time' => round((microtime(true) - $startTime) * 1000, 2).'ms',
        'note' => 'First time will be slow (~100ms), subsequent calls should be <1ms',
    ];

    // Test 3: Dashboard-like data
    $startTime = microtime(true);

    $dashboardData = AdminCache::remember('browser_test_dashboard', function () {
        // Simulate dashboard data gathering
        return [
            'total_users' => rand(100, 500),
            'active_tenants' => rand(20, 100),
            'revenue' => '$'.number_format(rand(1000, 50000), 2),
            'generated_at' => now()->format('Y-m-d H:i:s'),
        ];
    }, ['admin.dashboard', 'admin.test'], 600);

    $stats['dashboard_test'] = [
        'data' => $dashboardData,
        'time' => round((microtime(true) - $startTime) * 1000, 2).'ms',
    ];

    // Test 4: Cache invalidation
    AdminCache::put('browser_test_invalidation', 'Before invalidation', ['admin.test.invalidate'], 300);
    $beforeInvalidation = AdminCache::get('browser_test_invalidation');

    AdminCache::invalidateTag('admin.test.invalidate');
    $afterInvalidation = AdminCache::get('browser_test_invalidation');

    $stats['invalidation_test'] = [
        'before' => $beforeInvalidation,
        'after' => $afterInvalidation,
        'status' => ($beforeInvalidation && ! $afterInvalidation) ? 'PASSED' : 'FAILED',
    ];

    // Get cache statistics
    $cacheStats = AdminCache::getCacheStatistics();

    return view('admin-cache-test', [
        'stats' => $stats,
        'cache_stats' => $cacheStats,
        'test_time' => now()->format('Y-m-d H:i:s'),
    ]);
})->name('test.admin.cache');

// Include debug routes for development
if (config('app.debug')) {
    require __DIR__.'/debug.php';
}

Route::fallback(function () {
    return response()->view('errors.404', [], 404);
});
