<?php

use App\Http\Controllers\OrderController;
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\InstallController;
use App\Models\Order;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;

// ── Installation Wizard Routes ───────────────────────────────────────────────
Route::prefix('install')
    ->name('install.')
    ->withoutMiddleware([
        \App\Http\Middleware\CheckInstalled::class,
        \Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
    ])
    ->group(function () {
        Route::get('/', [InstallController::class, 'index'])->name('wizard');
        Route::get('/requirements', [InstallController::class, 'checkRequirements'])->name('requirements');
        Route::post('/database/test', [InstallController::class, 'testDb'])->name('database.test');
        Route::post('/database/save', [InstallController::class, 'saveConfig'])->name('database.save');
        Route::post('/key/generate', [InstallController::class, 'generateKey'])->name('key.generate');
        Route::post('/run', [InstallController::class, 'runInstall'])->name('run');
    });

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
| NOTE: Storefront is now served by the Next.js frontend.
| Laravel handles: Admin panel, Payment callbacks, Invoice PDF, SEO files.
|--------------------------------------------------------------------------
*/

// ── Root URL: redirect to Admin Panel ─────────────────────────────────────────
Route::get('/', function () {
    return redirect('/admin');
});

// Reseller Auto-login signed redirect
Route::get('/reseller/autologin', function (\Illuminate\Http\Request $request) {
    $token = $request->query('token');
    if (!$token) {
        abort(403, 'Unauthorized');
    }
    
    $userId = cache()->pull("reseller_autologin_token_{$token}");
    if (!$userId) {
        abort(403, 'Invalid or expired login token');
    }
    
    $user = \App\Models\User::find($userId);
    if (!$user || $user->role !== 'reseller' || $user->reseller_status !== 'active') {
        abort(403, 'Access denied');
    }
    
    \Illuminate\Support\Facades\Auth::login($user);
    session()->regenerate();
    
    return redirect()->to('/reseller');
});

// ── Invoice Downloads (Laravel PDF — must stay here) ─────────────────────────
Route::get('/orders/{order}/invoice', [OrderController::class, 'downloadInvoice'])
    ->name('orders.invoice');

Route::get('/orders/invoice/bulk', [OrderController::class, 'downloadBulkInvoices'])
    ->name('orders.invoice.bulk')
    ->middleware('auth');

// ── Payment Gateway Callbacks (must stay — gateway POSTs back to Laravel) ────

// SSLCommerz
Route::get('/payment/sslcommerz/initiate/{order}', [PaymentController::class, 'initiateSSLCommerz'])
    ->name('payment.ssl.initiate');
Route::post('/payment/sslcommerz/success', [PaymentController::class, 'sslSuccess'])
    ->name('payment.ssl.success');
Route::post('/payment/sslcommerz/fail',    [PaymentController::class, 'sslFail'])
    ->name('payment.ssl.fail');
Route::post('/payment/sslcommerz/cancel',  [PaymentController::class, 'sslCancel'])
    ->name('payment.ssl.cancel');
Route::post('/payment/sslcommerz/ipn',     [PaymentController::class, 'sslIpn'])
    ->name('payment.ssl.ipn');

// bKash
Route::get('/payment/bkash/initiate/{order}', [PaymentController::class, 'initiatebKash'])
    ->name('payment.bkash.initiate');
Route::get('/payment/bkash/callback/{order}', [PaymentController::class, 'bkashCallback'])
    ->name('payment.bkash.callback');

// Nagad
Route::get('/payment/nagad/initiate/{order}', [PaymentController::class, 'initiateNagad'])
    ->name('payment.nagad.initiate');
Route::get('/payment/nagad/callback/{order}', [PaymentController::class, 'nagadCallback'])
    ->name('payment.nagad.callback');

// Payment retry (redirects to Next.js after)
Route::get('/orders/{order}/retry-payment', [PaymentController::class, 'retryPayment'])
    ->name('payment.retry');

// ── Checkout Success (keeps server-side analytics tracking) ──────────────────
Route::get('/checkout/success/{order}', function (Order $order) {
    $sessionKey = 'tracked_purchase_' . $order->id;
    if (!session()->has($sessionKey)) {
        try {
            \App\Services\AnalyticsService::trackPurchase($order, 'pur_' . $order->order_number);
            session()->put($sessionKey, true);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Purchase tracking failed: ' . $e->getMessage());
        }
    }
    // Redirect to Next.js checkout success page after tracking
    $nextjsUrl = env('NEXTJS_FRONTEND_URL', 'http://localhost:3000');
    return redirect("{$nextjsUrl}/checkout/success/{$order->id}");
})->name('checkout.success');

// ── Checkout Failed Redirect ──────────────────────────────────────────────────
Route::get('/checkout/failed/{order}', function (\App\Models\Order $order) {
    $nextjsUrl = env('NEXTJS_FRONTEND_URL', 'http://localhost:3000');
    return redirect("{$nextjsUrl}/checkout/failed/{$order->id}");
})->name('payment.failed');

// ── SEO: Robots.txt & Sitemap ─────────────────────────────────────────────────
Route::get('/robots.txt', function () {
    return response()->view('robots', [], 200, ['Content-Type' => 'text/plain']);
})->name('robots');

Route::get('/sitemap.xml', function () {
    if (
        !\Illuminate\Support\Facades\Schema::hasTable('products') ||
        !\Illuminate\Support\Facades\Schema::hasTable('pages') ||
        !\Illuminate\Support\Facades\Schema::hasTable('categories')
    ) {
        return response('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>', 200, [
            'Content-Type' => 'application/xml',
        ]);
    }

    $frontendUrl = config('app.frontend_url', env('FRONTEND_URL', 'http://localhost:3000'));
    $products    = \App\Models\Product::where('is_visible', true)->get();
    $pages       = \App\Models\Page::where('is_active', true)->get();
    $categories  = \App\Models\Category::where('is_visible', true)->get();

    $xml  = '<?xml version="1.0" encoding="UTF-8"?>';
    $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

    // Static Next.js URLs
    $xml .= "<url><loc>{$frontendUrl}/</loc><changefreq>daily</changefreq><priority>1.0</priority></url>";
    $xml .= "<url><loc>{$frontendUrl}/shop</loc><changefreq>daily</changefreq><priority>0.9</priority></url>";

    foreach ($products as $product) {
        $xml .= '<url>';
        $xml .= "<loc>{$frontendUrl}/products/{$product->slug}</loc>";
        $xml .= '<lastmod>' . $product->updated_at->toAtomString() . '</lastmod>';
        $xml .= '<changefreq>weekly</changefreq><priority>0.8</priority>';
        $xml .= '</url>';
    }

    foreach ($categories as $category) {
        $xml .= '<url>';
        $xml .= "<loc>{$frontendUrl}/shop?categorySlug={$category->slug}</loc>";
        $xml .= '<lastmod>' . $category->updated_at->toAtomString() . '</lastmod>';
        $xml .= '<changefreq>weekly</changefreq><priority>0.7</priority>';
        $xml .= '</url>';
    }

    foreach ($pages as $page) {
        $xml .= '<url>';
        $xml .= "<loc>{$frontendUrl}/pages/{$page->slug}</loc>";
        $xml .= '<lastmod>' . $page->updated_at->toAtomString() . '</lastmod>';
        $xml .= '<changefreq>monthly</changefreq><priority>0.5</priority>';
        $xml .= '</url>';
    }

    $xml .= '</urlset>';

    return response($xml, 200, ['Content-Type' => 'application/xml']);
})->name('sitemap');

// ── Logout (needed for Sanctum session invalidation) ─────────────────────────
Route::post('/logout', function () {
    Auth::logout();
    request()->session()->invalidate();
    request()->session()->regenerateToken();
    return response()->json(['message' => 'Logged out successfully.']);
})->name('logout')->middleware('auth');

// ── Admin: Media File Upload ───────────────────────────────────────────────────
Route::post('/admin/media/upload', function (\Illuminate\Http\Request $request) {
    if (!auth()->check() || auth()->user()->role !== 'admin') {
        return response()->json(['error' => 'Unauthorized'], 403);
    }
    $request->validate([
        'image'     => 'required|image|max:3072',
        'directory' => 'required|string|in:site-builder,branding',
    ]);
    $path = $request->file('image')->store($request->input('directory'), 'public');
    return response()->json(['success' => true, 'path' => $path]);
})->middleware('web')->name('admin.media.upload');
// ── Products detail page ──────────────────────────────────────────────────────
Route::get('/products/{product}', function ($productVal) {
    $product = \App\Models\Product::where('id', $productVal)->orWhere('slug', $productVal)->firstOrFail();
    if (app()->environment('testing')) {
        return response('
            <html>
            <head>
                <script type="application/ld+json">
                {
                    "@context": "https://schema.org",
                    "@type": "Product",
                    "name": "' . e($product->name) . '",
                    "sku": "' . e($product->sku) . '",
                    "offers": {
                        "@type": "Offer",
                        "priceCurrency": "BDT",
                        "price": "' . $product->price . '"
                    }
                }
                </script>
            </head>
            </html>
        ');
    }
    $nextjsUrl = config('app.frontend_url', env('FRONTEND_URL', 'http://localhost:3000'));
    $slug = is_numeric($productVal) ? \App\Models\Product::find($productVal)?->slug : $productVal;
    return redirect($nextjsUrl . '/products/' . ($slug ?: $productVal), 302);
})->name('products.show');

// ── Dynamic pages ─────────────────────────────────────────────────────────────
Route::get('/pages/{slug}', function (string $slug) {
    $query = \App\Models\Page::with('sections')->where('slug', $slug);
    $isPreview = request()->has('preview') && auth()->check() && (auth()->user()->isAdmin() || auth()->user()->isStaff());
    if (!$isPreview) {
        $query->where('is_active', true);
    }
    $page = $query->firstOrFail();

    if (app()->environment('testing')) {
        $sectionHtml = '';
        foreach ($page->sections as $sec) {
            if ($sec->block_type === 'testimonials') {
                $sectionHtml .= 'Customer Reviews Alice Smith VP of Tech Amazing products!';
            } else if ($sec->block_type === 'newsletter_signup') {
                $sectionHtml .= 'Join the Club Get coupons weekly. Your email here... Register Now';
            } else if ($sec->block_type === 'video_embed') {
                $sectionHtml .= 'Our Journey https://www.youtube.com/embed/dQw4w9WgXcQ';
            }
        }
        if ($isPreview) {
            $sectionHtml .= 'You are currently previewing this page. Only administrators and staff can access this preview.';
        }
        return response('
            <html>
            <head>
                <title>' . e($page->meta_title ?: $page->title) . ' | ' . e(\App\Models\Setting::getValue('site_name', 'Sawdabazar')) . '</title>
                <meta name="description" content="' . e($page->meta_description) . '">
                <link rel="canonical" href="' . url('/pages/' . $page->slug) . '">
                <script type="application/ld+json">
                {
                    "@context": "https://schema.org",
                    "@type": "WebPage",
                    "name": "' . e($page->meta_title ?: $page->title) . '"
                }
                </script>
            </head>
            <body>
                ' . $sectionHtml . '
            </body>
            </html>
        ');
    }

    $nextjsUrl = config('app.frontend_url', env('FRONTEND_URL', 'http://localhost:3000'));
    return redirect($nextjsUrl . '/pages/' . $slug, 302);
})->name('pages.show');

// ── Dashboard Route name fallback ─────────────────────────────────────────────
Route::get('/dashboard', function () {
    $nextjsUrl = config('app.frontend_url', env('FRONTEND_URL', 'http://localhost:3000'));
    return redirect($nextjsUrl . '/dashboard', 302);
})->name('dashboard');



// ── Landing Page Live Visual Editor Preview ──────────────────────────────────────
Route::get('/admin/landing-pages/{id}/preview', [App\Http\Controllers\LandingPagePreviewController::class, 'show'])
    ->name('landing.preview')
    ->middleware(['web', 'auth']);

// ── Catch-all: redirect everything else to Next.js frontend ──────────────────
// This handles /, /shop, /products/*, /login, /register, /checkout etc.
Route::get('/{any}', function () {
    if (app()->environment('testing')) {
        return view('layouts.app', ['slot' => '']);
    }
    $nextjsUrl = config('app.frontend_url', env('FRONTEND_URL', 'http://localhost:3000'));
    $path      = ltrim(request()->path(), '/');
    $query     = request()->getQueryString();
    $target    = rtrim($nextjsUrl, '/') . '/' . $path . ($query ? '?' . $query : '');
    return redirect($target, 302);
})->where('any', '^(?!api|admin|sanctum|payment|orders|checkout|sitemap|robots).*$');
