<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\StoreController;
use App\Http\Controllers\OrderController;
use App\Http\Controllers\WebhookController;
use App\Http\Controllers\GenericWebhookController;
use App\Http\Controllers\WebhookSourceController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\UserController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

// Custom Domain Handler (must be first)
Route::get('/', function (Illuminate\Http\Request $request) {
    // Check if this is a custom domain (detected by middleware)
    $isCustomDomain = $request->attributes->get('isCustomDomain', false);
    $sellerDomain = $request->attributes->get('sellerDomain');

    if ($isCustomDomain && $sellerDomain) {
        // Custom domain detected - show default sales page or 404
        return app(\App\Http\Controllers\SalesPagePublicController::class)->showBySellerDomain($sellerDomain);
    }

    // Default homepage for main domain
    if (auth()->check()) {
        return redirect()->route('dashboard');
    }
    return view('welcome');
})->name('home');

// Webhook endpoints (public - no CSRF protection needed)
Route::post('/webhook/{store}', [WebhookController::class, 'handle'])->name('webhook.handle');
Route::post('/webhook/generic/{token}', [GenericWebhookController::class, 'handle'])->name('webhook.generic');
Route::get('/webhook/generic/{token}/test', [GenericWebhookController::class, 'test'])->name('webhook.generic.test');

// Pos Laju Webhook endpoint (public - no auth required)
// Pos Laju Webhook - Handle both GET (validation) and POST (actual webhook)
Route::match(['get', 'post'], '/api/poslaju/webhook', [\App\Http\Controllers\PoslajuWebhookController::class, 'handle'])->name('poslaju.webhook');

// PWA Routes (public - required for service worker and manifest)
Route::get('/manifest.json', [\App\Http\Controllers\ManifestController::class, 'show'])->name('pwa.manifest');
Route::get('/api/vapid-public-key', [\App\Http\Controllers\PushSubscriptionController::class, 'vapidPublicKey'])->name('pwa.vapid');

// Auth routes (Laravel UI)
Auth::routes(['verify' => true]);

// Authenticated routes
Route::middleware(['auth', 'verified'])->group(function () {

    // Dashboard
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    Route::get('/dashboard/export-analytics', [DashboardController::class, 'exportAnalytics'])->name('dashboard.export-analytics');

    // Sales Reports
    Route::prefix('reports')->name('reports.')->group(function () {
        Route::get('/sales', [App\Http\Controllers\SalesReportController::class, 'index'])->name('sales');
        Route::get('/sales/pdf', [App\Http\Controllers\SalesReportController::class, 'exportPdf'])->name('sales.pdf');
        Route::get('/sales/excel', [App\Http\Controllers\SalesReportController::class, 'exportExcel'])->name('sales.excel');
    });

    // PWA Push Subscription Routes (authenticated)
    Route::post('/push-subscription', [\App\Http\Controllers\PushSubscriptionController::class, 'store'])->name('push.subscribe');
    Route::delete('/push-subscription', [\App\Http\Controllers\PushSubscriptionController::class, 'destroy'])->name('push.unsubscribe');

    // User management - index accessible by managers too
    Route::get('users', [UserController::class, 'index'])->name('users.index');

    // Stop Impersonating - Must be OUTSIDE admin middleware (accessed while impersonating)
    Route::post('users/stop-impersonating', [UserController::class, 'stopImpersonating'])->name('users.stop-impersonating');

    // Admin-only routes (must be before resource routes to avoid conflicts)
    Route::middleware('admin')->group(function () {
        // Generic Webhooks Management (admin-only) - MUST be before stores resource
        Route::prefix('stores/webhooks')->name('stores.webhooks.')->group(function () {
            Route::get('/', [WebhookSourceController::class, 'index'])->name('index');
            Route::get('/create', [WebhookSourceController::class, 'create'])->name('create');
            Route::post('/', [WebhookSourceController::class, 'store'])->name('store');
            Route::get('/{webhook}', [WebhookSourceController::class, 'show'])->name('show');
            Route::get('/{webhook}/edit', [WebhookSourceController::class, 'edit'])->name('edit');
            Route::put('/{webhook}', [WebhookSourceController::class, 'update'])->name('update');
            Route::delete('/{webhook}', [WebhookSourceController::class, 'destroy'])->name('destroy');
            Route::post('/{webhook}/toggle', [WebhookSourceController::class, 'toggle'])->name('toggle');
            Route::post('/{webhook}/regenerate', [WebhookSourceController::class, 'regenerateToken'])->name('regenerate');
        });

        // Admin-only store deletion
        Route::delete('stores/{store}', [StoreController::class, 'destroy'])->name('stores.destroy');

        // User management (except index which is above for managers)
        Route::resource('users', UserController::class)->except(['index']);

        // User Impersonation - Start (Admin only)
        Route::post('users/{user}/impersonate', [UserController::class, 'impersonate'])->name('users.impersonate');

        // TikTok Shop Access Toggle (Admin only)
        Route::post('users/{user}/toggle-tiktok', [UserController::class, 'toggleTikTokAccess'])->name('users.toggle-tiktok');

        // TikTok Shops Management (Admin only)
        Route::resource('tiktok-shops-management', \App\Http\Controllers\TikTokShopsManagementController::class)->except(['show']);

        // Manager Management
        Route::prefix('admin/managers')->name('admin.managers.')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\ManagerController::class, 'index'])->name('index');
            Route::get('/{manager}/assign-sellers', [\App\Http\Controllers\Admin\ManagerController::class, 'assignSellers'])->name('assign-sellers');
            Route::post('/{manager}/assign-sellers', [\App\Http\Controllers\Admin\ManagerController::class, 'storeSellers'])->name('store-sellers');
            Route::delete('/{manager}/sellers/{seller}', [\App\Http\Controllers\Admin\ManagerController::class, 'removeSeller'])->name('remove-seller');
        });

        // System Settings
        Route::get('/settings', [\App\Http\Controllers\SettingsController::class, 'index'])->name('settings.index');
        Route::put('/settings', [\App\Http\Controllers\SettingsController::class, 'update'])->name('settings.update');
        Route::post('/settings/maintenance/enable', [\App\Http\Controllers\SettingsController::class, 'enableMaintenanceMode'])->name('settings.maintenance.enable');
        Route::post('/settings/maintenance/disable', [\App\Http\Controllers\SettingsController::class, 'disableMaintenanceMode'])->name('settings.maintenance.disable');

        // Cloudflare Settings
        Route::get('/cloudflare-settings', [\App\Http\Controllers\CloudflareSettingsController::class, 'index'])->name('cloudflare-settings.index');
        Route::put('/cloudflare-settings', [\App\Http\Controllers\CloudflareSettingsController::class, 'update'])->name('cloudflare-settings.update');
        Route::post('/cloudflare-settings/test', [\App\Http\Controllers\CloudflareSettingsController::class, 'testConnection'])->name('cloudflare-settings.test');
        Route::get('/cloudflare-settings/zone', [\App\Http\Controllers\CloudflareSettingsController::class, 'getZoneDetails'])->name('cloudflare-settings.zone');
        Route::get('/cloudflare-settings/dns-records', [\App\Http\Controllers\CloudflareSettingsController::class, 'listDnsRecords'])->name('cloudflare-settings.dns-records');

        // Custom Domains Management (Admin only - moved from general auth)
        Route::resource('seller-domains', App\Http\Controllers\SellerDomainController::class);
        Route::post('seller-domains/{sellerDomain}/verify', [App\Http\Controllers\SellerDomainController::class, 'verify'])->name('seller-domains.verify');

        // Forecasting & Business Intelligence (Admin only)
        Route::prefix('forecasting')->name('forecasting.')->group(function () {
            Route::get('/', [App\Http\Controllers\ForecastingController::class, 'index'])->name('index');
            Route::get('/import', [App\Http\Controllers\ForecastingController::class, 'showImport'])->name('import');
            Route::post('/import', [App\Http\Controllers\ForecastingController::class, 'import'])->name('import.store');
            Route::get('/template', [App\Http\Controllers\ForecastingController::class, 'downloadTemplate'])->name('template');
            Route::get('/expenses', [App\Http\Controllers\ForecastingController::class, 'showExpenseUpdate'])->name('expenses');
            Route::post('/expenses', [App\Http\Controllers\ForecastingController::class, 'updateExpense'])->name('expenses.update');
            Route::post('/channel-sales', [App\Http\Controllers\ForecastingController::class, 'updateChannelSales'])->name('channel-sales.update');
            Route::post('/orders', [App\Http\Controllers\ForecastingController::class, 'updateOrders'])->name('orders.update');
            Route::get('/prophet-forecast', [App\Http\Controllers\ForecastingController::class, 'getProphetForecast'])->name('prophet');
            Route::get('/ai-insights', [App\Http\Controllers\ForecastingController::class, 'getAIInsights'])->name('ai-insights');
            Route::get('/multi-year-data', [App\Http\Controllers\ForecastingController::class, 'getMultiYearQuarterlyData'])->name('multi-year-data');
            Route::post('/project-future', [App\Http\Controllers\ForecastingController::class, 'projectFutureYear'])->name('project-future');

            // Seller KPI Performance Routes
            Route::get('/seller-kpi', [App\Http\Controllers\SellerKpiController::class, 'index'])->name('seller-kpi.index');
            Route::get('/seller-kpi/set-targets', [App\Http\Controllers\SellerKpiController::class, 'showSetTargets'])->name('seller-kpi.set-targets');
            Route::post('/seller-kpi/set-targets', [App\Http\Controllers\SellerKpiController::class, 'saveTargets'])->name('seller-kpi.save-targets');
            Route::get('/seller-kpi/{userId}', [App\Http\Controllers\SellerKpiController::class, 'show'])->name('seller-kpi.show');
            Route::post('/seller-kpi/forecast', [App\Http\Controllers\SellerKpiController::class, 'generateForecast'])->name('seller-kpi.forecast');
            Route::get('/team-performance', [App\Http\Controllers\SellerKpiController::class, 'teamPerformance'])->name('team-performance');
            Route::post('/seller-kpi/sync', [App\Http\Controllers\SellerKpiController::class, 'syncActualSales'])->name('seller-kpi.sync');
            Route::post('/seller-kpi/targets', [App\Http\Controllers\SellerKpiController::class, 'setTargets'])->name('seller-kpi.targets');
            Route::post('/seller-kpi/update-manual', [App\Http\Controllers\SellerKpiController::class, 'updateManualData'])->name('seller-kpi.update-manual');

            // Marketing Strategy Routes
            Route::get('/marketing-strategy', [App\Http\Controllers\MarketingStrategyController::class, 'index'])->name('marketing-strategy.index');
            Route::get('/marketing-strategy/input', [App\Http\Controllers\MarketingStrategyController::class, 'showInput'])->name('marketing-strategy.input');
            Route::post('/marketing-strategy/input', [App\Http\Controllers\MarketingStrategyController::class, 'saveInput'])->name('marketing-strategy.save');
            Route::post('/marketing-strategy/ai-suggestions', [App\Http\Controllers\MarketingStrategyController::class, 'getAiSuggestions'])->name('marketing-strategy.ai');
        });
    });

    // TikTok Shop Management (Admin + Authorized Managers)
    Route::middleware('tiktok.access')->prefix('tiktok-shop')->name('tiktok-shop.')->group(function () {
        Route::get('/', [App\Http\Controllers\TikTokShopController::class, 'index'])->name('index');
        Route::get('/upload', [App\Http\Controllers\TikTokShopController::class, 'uploadForm'])->name('upload');
        Route::post('/upload', [App\Http\Controllers\TikTokShopController::class, 'upload'])->name('upload.process');
        Route::get('/preview', [App\Http\Controllers\TikTokShopController::class, 'preview'])->name('preview');
        Route::post('/import', [App\Http\Controllers\TikTokShopController::class, 'import'])->name('import');
        Route::delete('/{id}', [App\Http\Controllers\TikTokShopController::class, 'destroy'])->name('destroy');
        Route::get('/daily-stats', [App\Http\Controllers\TikTokShopController::class, 'dailyStats'])->name('daily-stats');

        // Ads Spending Routes
        Route::post('/ads/upload', [App\Http\Controllers\TikTokShopController::class, 'uploadAds'])->name('ads.upload');
        Route::get('/ads/preview', [App\Http\Controllers\TikTokShopController::class, 'previewAds'])->name('ads.preview');
        Route::post('/ads/import', [App\Http\Controllers\TikTokShopController::class, 'importAds'])->name('ads.import');
        Route::delete('/ads/{id}', [App\Http\Controllers\TikTokShopController::class, 'destroyAds'])->name('ads.destroy');
    });

    // Stores Management (for all authenticated users - sellers can create their own stores)
    Route::get('stores/create', [StoreController::class, 'create'])->name('stores.create');
    Route::post('stores', [StoreController::class, 'store'])->name('stores.store');
    Route::resource('stores', StoreController::class)->except(['create', 'store', 'destroy']);
    Route::post('stores/{store}/sync', [StoreController::class, 'sync'])->name('stores.sync');
    Route::post('stores/{store}/webhooks/enable', [StoreController::class, 'enableWebhooks'])->name('stores.webhooks.enable');
    Route::post('stores/{store}/webhooks/disable', [StoreController::class, 'disableWebhooks'])->name('stores.webhooks.disable');

    // Checkout / Manual Order Entry (POS)
    Route::get('checkout', [OrderController::class, 'create'])->name('checkout');
    Route::post('checkout', [OrderController::class, 'store'])->name('checkout.store');

    // Product Catalog (for sellers)
    Route::post('products/{product}/toggle', [App\Http\Controllers\ProductController::class, 'toggle'])->name('products.toggle');
    Route::resource('products', App\Http\Controllers\ProductController::class);
    Route::get('products/search/api', [App\Http\Controllers\ProductController::class, 'search'])->name('products.search.api');

    // Postcode Lookup API
    Route::get('api/postcode/lookup', [App\Http\Controllers\PostcodeController::class, 'lookup'])->name('postcode.lookup');

    // Customer Lookup API (for auto-fill feature)
    Route::post('api/customer/lookup', [App\Http\Controllers\CustomerController::class, 'lookup'])->name('customer.lookup');

    // Orders Management
    Route::resource('orders', OrderController::class)->except(['create', 'store']);
    Route::post('orders/sync', [OrderController::class, 'sync'])->name('orders.sync');
    Route::post('orders/sync-historical', [OrderController::class, 'syncHistorical'])->name('orders.sync.historical');
    Route::post('orders/sync-store/{store}', [OrderController::class, 'syncSingleStore'])->name('orders.sync.store');
    Route::post('orders/sync-store/{store}/historical', [OrderController::class, 'syncSingleStoreHistorical'])->name('orders.sync.store.historical');
    Route::post('orders/sync-store/{store}/major', [OrderController::class, 'syncSingleStoreMajor'])->name('orders.sync.store.major');

    // Invoice routes
    Route::get('orders/{order}/invoice', [OrderController::class, 'invoice'])->name('orders.invoice');
    Route::get('orders/{order}/invoice/download', [OrderController::class, 'downloadInvoice'])->name('orders.invoice.download');
    Route::get('orders/{order}/invoice/pdf', [OrderController::class, 'viewInvoicePdf'])->name('orders.invoice.pdf');

    // Pos Laju AWB routes
    Route::post('orders/{order}/generate-awb', [OrderController::class, 'generateAWB'])->name('orders.generate-awb');
    Route::get('orders/{order}/track-shipment', [OrderController::class, 'trackShipment'])->name('orders.track-shipment');
    Route::get('orders/{order}/awb/print', [OrderController::class, 'printAWB'])->name('orders.awb.print');
    Route::get('orders/{order}/awb/download', [OrderController::class, 'downloadAWB'])->name('orders.awb.download');

    // WhatsApp Notification
    Route::post('orders/{order}/send-whatsapp', [OrderController::class, 'sendWhatsApp'])->name('orders.send-whatsapp');

    // Mark Order as Completed
    Route::post('orders/{order}/mark-completed', [OrderController::class, 'markAsCompleted'])->name('orders.mark-completed');

    // Bulk Actions
    Route::post('orders/bulk-action/bulk_push_awb', [OrderController::class, 'bulkPushAwb'])->name('orders.bulk.push-awb');
    Route::post('orders/bulk-action/bulk_download_awb', [OrderController::class, 'bulkDownloadAwb'])->name('orders.bulk.download-awb');
    Route::post('orders/bulk-action/bulk_download_invoice', [OrderController::class, 'bulkDownloadInvoice'])->name('orders.bulk.download-invoice');
    Route::post('orders/bulk-action/bulk_completed', [OrderController::class, 'bulkMarkCompleted'])->name('orders.bulk.mark-completed');

    // Profile/Settings
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::put('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::put('/profile/password', [ProfileController::class, 'updatePassword'])->name('profile.password');

    // Poslaju Settings
    Route::get('/poslaju-settings', [App\Http\Controllers\PoslajuSettingsController::class, 'index'])->name('poslaju-settings.index');
    Route::put('/poslaju-settings', [App\Http\Controllers\PoslajuSettingsController::class, 'update'])->name('poslaju-settings.update');

    // WhatsApp Notification Settings
    Route::get('/whatsapp-settings', [App\Http\Controllers\WhatsAppSettingsController::class, 'index'])->name('whatsapp-settings.index');
    Route::put('/whatsapp-settings', [App\Http\Controllers\WhatsAppSettingsController::class, 'update'])->name('whatsapp-settings.update');

    // Google Sheets Sync (Sellers only)
    Route::prefix('settings/google-sheets')->name('settings.google-sheets')->group(function () {
        Route::get('/', function () {
            return view('settings.google-sheets');
        });
    });
    Route::get('/auth/google', [App\Http\Controllers\GoogleAuthController::class, 'redirectToGoogle'])->name('google-sheets.auth');
    Route::get('/auth/google/callback', [App\Http\Controllers\GoogleAuthController::class, 'handleGoogleCallback'])->name('google-sheets.callback');
    Route::delete('/google-sheets/disconnect', [App\Http\Controllers\GoogleAuthController::class, 'disconnect'])->name('google-sheets.disconnect');
    Route::post('/google-sheets/sync-recent', [App\Http\Controllers\GoogleAuthController::class, 'syncRecent'])->name('google-sheets.sync-recent');
    Route::post('/google-sheets/manual-sync', [App\Http\Controllers\GoogleAuthController::class, 'manualSync'])->name('google-sheets.manual-sync');

    // Google Sheets Import (Disaster Recovery - Admin Only)
    Route::middleware('admin')->group(function () {
        Route::get('/google-sheets/import-preview', [App\Http\Controllers\GoogleAuthController::class, 'showImportPreview'])->name('google-sheets.import-preview');
        Route::post('/google-sheets/import', [App\Http\Controllers\GoogleAuthController::class, 'importOrders'])->name('google-sheets.import');
    });

    // Sales Pages Management
    Route::resource('sales-pages', App\Http\Controllers\SalesPageController::class);
    Route::post('sales-pages/{salesPage}/duplicate', [App\Http\Controllers\SalesPageController::class, 'duplicate'])->name('sales-pages.duplicate');

});

// Public Sales Page Routes (No Authentication Required)
Route::get('/p/{seller}', [App\Http\Controllers\SalesPagePublicController::class, 'showSellerLanding'])->name('seller.landing');
Route::get('/p/{seller}/{slug}', [App\Http\Controllers\SalesPagePublicController::class, 'show'])->name('sales-page.show');
Route::post('/api/sales-page/{slug}/track-view', [App\Http\Controllers\SalesPagePublicController::class, 'trackView'])->name('sales-page.track-view');
Route::post('/api/sales-page/{slug}/order', [App\Http\Controllers\SalesPagePublicController::class, 'submitOrder'])->name('sales-page.submit-order');
Route::get('/thank-you', [App\Http\Controllers\SalesPagePublicController::class, 'thankYou'])->name('sales-page.thank-you');

// Sales Page Payment Routes (Public)
Route::get('/payment/{salesPageOrder}/select', [App\Http\Controllers\SalesPagePaymentController::class, 'showPaymentSelection'])->name('sales-page.payment.select');
Route::post('/payment/{salesPageOrder}/process', [App\Http\Controllers\SalesPagePaymentController::class, 'processPayment'])->name('sales-page.payment.process');
Route::match(['get', 'post'], '/payment/return', [App\Http\Controllers\SalesPagePaymentController::class, 'handleReturn'])->name('sales-page.payment.return');
Route::post('/payment/callback', [App\Http\Controllers\SalesPagePaymentController::class, 'handleCallback'])->name('sales-page.payment.callback')->withoutMiddleware(['web']);

// Postcode Lookup API (Public)
Route::get('/api/postcode/{postcode}', function($postcode) {
    $data = DB::table('malaysia_postcodes')
        ->where('postcode', $postcode)
        ->first();

    if ($data) {
        return response()->json([
            'success' => true,
            'city' => $data->city,
            'state' => $data->state,
        ]);
    }

    return response()->json([
        'success' => false,
        'message' => 'Postcode not found'
    ], 404);
})->name('api.postcode.lookup');

// Custom Domain Slug Handler (must be last - catch-all for custom domains)
Route::get('/{slug}', function(Illuminate\Http\Request $request, $slug) {
    // Check if this is a custom domain (detected by middleware)
    $isCustomDomain = $request->attributes->get('isCustomDomain', false);
    $sellerDomain = $request->attributes->get('sellerDomain');

    if ($isCustomDomain && $sellerDomain) {
        // Custom domain detected - show sales page by slug
        return app(\App\Http\Controllers\SalesPagePublicController::class)->showBySellerDomainSlug($sellerDomain, $slug);
    }

    // Not a custom domain - return 404
    abort(404);
})->where('slug', '[a-zA-Z0-9\-_]+');
