<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\Admin\UserController;
use App\Http\Controllers\Admin\CategoryController;
use App\Http\Controllers\Admin\ProductController;
use App\Http\Controllers\Admin\OrderController;
use App\Http\Controllers\Admin\CommissionController;
use App\Http\Controllers\Admin\SettingController;
use App\Http\Controllers\Admin\ContactController as AdminContactController;
use App\Http\Controllers\Admin\EmailTemplateController;
use App\Http\Controllers\Admin\EmailLogController;
use App\Http\Controllers\Member\DashboardController as MemberDashboardController;
use App\Http\Controllers\Member\NetworkController;
use App\Http\Controllers\Member\CommissionController as MemberCommissionController;
use App\Http\Controllers\Member\ProductController as MemberProductController;
use App\Http\Controllers\Member\ProfileController;
use App\Http\Controllers\PublicProductController;
use App\Http\Controllers\CartController;
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\ContactController;
use App\Http\Controllers\NewsletterController;
use App\Http\Controllers\PlanController;
use App\Http\Controllers\Admin\PlanController as AdminPlanController;
use App\Http\Controllers\WithdrawalController;
use App\Http\Controllers\AuditLogController;
use App\Http\Controllers\SellerDocumentController;
use App\Http\Controllers\DisputeController;
use App\Http\Controllers\DeliveryController;

use App\Http\Controllers\Member\SavingsController;
use App\Http\Controllers\Admin\SavingsAdminController;

// ==================== PAGES PUBLIQUES ====================
Route::get('/', function () {
    return view('home');
})->name('home');

// Route publique de test pour génération AI (sans auth)
Route::post('/api/test-generate-description', function (\Illuminate\Http\Request $request) {
    $name = $request->input('name', 'Produit Test');
    $category = $request->input('category_name');
    $price = $request->input('price');
    $imageBase64 = $request->input('image_base64');
    
    // Analyse de l'image si fournie
    $colorAnalysis = null;
    $visionAnalysis = null;
    $visualDesc = '';
    $productInfo = null;
    
    if ($imageBase64) {
        // Analyse des couleurs (locale, rapide)
        $colorAnalysis = \App\Helpers\ImageAnalyzer::analyze($imageBase64);
        
        // Analyse IA du produit (OpenAI Vision)
        try {
            $visionService = new \App\Services\VisionAIService();
            $visionAnalysis = $visionService->analyzeProduct($imageBase64);
            
            if ($visionAnalysis['success']) {
                $productInfo = $visionAnalysis['data'];
                
                // Générer une description enrichie avec l'IA
                $description = $visionService->generateProductDescription(
                    $name, 
                    $category, 
                    $price, 
                    $visionAnalysis, 
                    $colorAnalysis
                );
                
                // Ajout catégorie si différente
                if ($category && $category !== '-- Sélectionner --') {
                    $categoryPhrases = [
                        " Parfait pour la catégorie {$category}.",
                        " Un incontournable de la catégorie {$category}.",
                    ];
                    $description .= $categoryPhrases[array_rand($categoryPhrases)];
                }
                
                return response()->json([
                    'success' => true,
                    'description' => $description,
                    'mode' => 'vision_ai',
                    'product_identified' => true,
                    'product_info' => [
                        'type' => $productInfo['product_type'] ?? null,
                        'category' => $productInfo['product_category'] ?? null,
                        'style' => $productInfo['style'] ?? null,
                        'material' => $productInfo['material'] ?? null,
                        'brand' => $productInfo['brand_visible'] ?? null,
                        'quality' => $productInfo['estimated_quality'] ?? null,
                        'features' => $productInfo['key_features'] ?? [],
                    ],
                    'color_analysis' => $colorAnalysis
                ]);
            }
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Vision AI error: ' . $e->getMessage());
        }
        
        // Fallback sur l'analyse de couleur simple
        $visualDesc = \App\Helpers\ImageAnalyzer::getVisualDescription($colorAnalysis);
    }
    
    // Générateur de secours (template) si pas d'analyse IA
    $tone = 'standard';
    if ($price) {
        if ($price >= 100000) $tone = 'premium';
        elseif ($price >= 50000) $tone = 'quality';
        elseif ($price <= 10000) $tone = 'accessible';
    }
    
    // Phrases d'accroche variées
    $intros = [
        'premium' => [
            "Découvrez {$name}, un produit d'exception qui incarne le luxe et l'élégance.",
            "Laissez-vous séduire par {$name}, une pièce d'exception pour les connaisseurs.",
            "{$name} représente l'excellence absolue, un choix raffiné pour les plus exigeants.",
            "Offrez-vous le meilleur avec {$name}, symbole de prestige et de raffinement.",
            "Entrez dans l'univers du luxe avec {$name}, une création d'exception.",
        ],
        'quality' => [
            "{$name} allie qualité supérieure et design soigné pour une satisfaction garantie.",
            "Optez pour l'excellence avec {$name}, un produit qui dépasse les attentes.",
            "{$name} incarne le parfait équilibre entre qualité premium et prix juste.",
            "Faites confiance à {$name}, un choix intelligent pour les amateurs de qualité.",
            "Avec {$name}, bénéficiez d'une qualité professionnelle à portée de main.",
        ],
        'standard' => [
            "{$name} est le choix parfait pour allier qualité et praticité.",
            "Découvrez {$name}, votre nouveau compagnon du quotidien.",
            "{$name} répond à toutes vos attentes avec style et efficacité.",
            "Simplifiez-vous la vie avec {$name}, pensé pour votre confort.",
            "Adoptez {$name}, un produit fiable qui ne vous décevra jamais.",
        ],
        'accessible' => [
            "{$name} offre un excellent rapport qualité-prix pour tous les budgets.",
            "Profitez de la qualité à petit prix avec {$name}.",
            "{$name} prouve que qualité rime avec accessibilité.",
            "Avec {$name}, faites-vous plaisir sans vous ruiner.",
            "Découvrez {$name}, la solution maligne pour votre quotidien.",
        ],
    ];
    
    // Corps de description variés
    $bodies = [
        'premium' => [
            "Conçu avec les meilleurs matériaux et un savoir-faire artisanal incomparable, chaque détail a été pensé pour satisfaire les plus exigeants.",
            "Fruit d'un travail minutieux et de matériaux nobles, ce produit incarne la perfection dans ses moindres détails.",
            "L'alliance de techniques traditionnelles et d'innovations modernes garantit une qualité exceptionnelle qui perdure dans le temps.",
            "Chaque élément est sélectionné avec soin pour offrir une expérience sensorielle unique et mémorable.",
        ],
        'quality' => [
            "Ce produit offre un excellent rapport qualité-prix et répond aux standards les plus exigeants.",
            "Sa conception robuste et ses finitions soignées en font un investissement durable et intelligent.",
            "Testé et approuvé, il garantit des performances optimales pour un usage quotidien ou professionnel.",
            "Son design ergonomique et ses matériaux de qualité assurent confort et longévité.",
        ],
        'standard' => [
            "Ce produit répond à tous vos besoins avec un design moderne et des performances fiables.",
            "Polyvalent et pratique, il s'adapte parfaitement à votre mode de vie.",
            "Sa simplicité d'utilisation et son efficacité en font un indispensable au quotidien.",
            "Conçu pour durer, il vous accompagnera fidèlement jour après jour.",
        ],
        'accessible' => [
            "Pratique et fonctionnel, ce produit répond efficacement à vos besoins du quotidien.",
            "Simple mais efficace, il remplit sa mission sans fioritures inutiles.",
            "Idéal pour débuter ou compléter votre équipement sans vous ruiner.",
            "Compact et pratique, il trouve sa place partout et convient à tous.",
        ],
    ];
    
    // Conclusions variées
    $conclusions = [
        'premium' => [
            "Un investissement dans la qualité qui vous accompagnera pendant de nombreuses années.",
            "Offrez-vous l'excellence, vous le méritez.",
            "Un choix qui témoigne de votre goût pour les belles choses.",
            "La perfection n'attend que vous.",
        ],
        'quality' => [
            "Idéal pour ceux qui recherchent le meilleur sans compromis.",
            "Un achat réfléchi qui vous satisfera pleinement.",
            "La qualité au juste prix, c'est possible.",
            "Faites le choix de la durabilité.",
        ],
        'standard' => [
            "Un indispensable qui saura vous satisfaire au quotidien.",
            "Commandez maintenant et profitez-en rapidement.",
            "Rejoignez les milliers de clients satisfaits.",
            "N'attendez plus pour vous équiper.",
        ],
        'accessible' => [
            "La qualité accessible à tous, sans compromis sur l'essentiel.",
            "Petit prix, grande satisfaction garantie.",
            "L'essentiel à portée de main.",
            "Parfait pour démarrer sans se ruiner.",
        ],
    ];
    
    // Sélection aléatoire
    $intro = $intros[$tone][array_rand($intros[$tone])];
    $body = $bodies[$tone][array_rand($bodies[$tone])];
    $conclusion = $conclusions[$tone][array_rand($conclusions[$tone])];
    
    // Assemblage avec description visuelle
    $description = "{$intro}";
    
    // Ajouter la description visuelle après l'intro si disponible
    if (!empty($visualDesc)) {
        $description .= " Ce produit{$visualDesc}";
    }
    
    $description .= " {$body} {$conclusion}";
    
    // Ajout catégorie (varié)
    if ($category && $category !== '-- Sélectionner --') {
        $categoryPhrases = [
            " Parfait pour la catégorie {$category}.",
            " Un incontournable de la catégorie {$category}.",
            " Idéal dans la catégorie {$category}.",
            " Le meilleur choix en {$category}.",
        ];
        $description .= $categoryPhrases[array_rand($categoryPhrases)];
    }
    
    return response()->json([
        'success' => true,
        'description' => $description,
        'mode' => $colorAnalysis ? 'color_only' : 'template',
        'product_identified' => false,
        'color_analysis' => $colorAnalysis
    ]);
})->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class]);

Route::get('/about', function () {
    return view('about');
})->name('about');

Route::get('/faq', function () {
    return view('faq');
})->name('faq');

Route::get('/contact', function () {
    return view('contact');
})->name('contact');

// Pages légales
Route::view('/privacy', 'legal.privacy')->name('privacy');
Route::view('/terms', 'legal.terms')->name('terms');
Route::view('/legal-notices', 'legal.notices')->name('legal.notices');

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

Route::post('/newsletter/subscribe', [NewsletterController::class, 'subscribe'])->name('newsletter.subscribe');

Route::view('/blog', 'blog')->name('public.blog');
Route::view('/newsletter', 'newsletter')->name('public.newsletter');

Route::get('/investments', [\App\Http\Controllers\InvestmentController::class, 'index'])->name('investments.index');

Route::get('/shop', [PublicProductController::class, 'index'])->name('shop.index');
Route::get('/shop/{product}', [PublicProductController::class, 'show'])->name('shop.show');
Route::get('/u/{username}', [\App\Http\Controllers\Shop\UserShopController::class, 'show'])->name('user.shop');

// Routes blog (avec contrôleur)
Route::get('/blog', [\App\Http\Controllers\PublicBlogController::class, 'index'])->name('public.blog');
Route::get('/blog/{slug}', [\App\Http\Controllers\PublicBlogController::class, 'show'])->name('public.blog.show');

Route::get('/plan', [PlanController::class, 'index'])->name('plan');

// ==================== ROUTES PRODUITS (PUBLIC) ====================
Route::get('/products', [PublicProductController::class, 'index'])->name('products');
Route::get('/products/{product}', [PublicProductController::class, 'show'])->name('products.show');

// ==================== BOUTIQUE PERSONNALISÉE ISOLÉE (DROPSHIPPING) ====================
// Toutes les routes de l'écosystème isolé pour le dropshipping
Route::get('/u/{username}/collection', [\App\Http\Controllers\Shop\UserShopController::class, 'collection'])->name('user.shop.collection');
Route::get('/u/{username}/about', [\App\Http\Controllers\Shop\UserShopController::class, 'about'])->name('user.shop.about');
Route::get('/u/{username}/contact', [\App\Http\Controllers\Shop\UserShopController::class, 'contact'])->name('user.shop.contact');

// Détail produit dans l'écosystème
Route::get('/u/{username}/product/{product}', [\App\Http\Controllers\Shop\UserShopController::class, 'productDetail'])->name('user.shop.product');

// Panier dans l'écosystème
Route::get('/u/{username}/cart', [\App\Http\Controllers\Shop\UserShopController::class, 'cart'])->name('user.shop.cart');
Route::get('/u/{username}/cart-count', [\App\Http\Controllers\Shop\UserShopController::class, 'cartCount'])->name('user.shop.cart.count');
Route::get('/u/{username}/cart-items', [\App\Http\Controllers\Shop\UserShopController::class, 'cartItems'])->name('user.shop.cart.items');
Route::post('/u/{username}/add-to-cart', [\App\Http\Controllers\Shop\UserShopController::class, 'addToCart'])->name('user.shop.cart.add');
Route::post('/u/{username}/update-cart', [\App\Http\Controllers\Shop\UserShopController::class, 'updateCart'])->name('user.shop.cart.update');
Route::post('/u/{username}/remove-from-cart', [\App\Http\Controllers\Shop\UserShopController::class, 'removeFromCart'])->name('user.shop.cart.remove');

// Checkout dans l'écosystème
Route::get('/u/{username}/checkout', [\App\Http\Controllers\Shop\UserShopController::class, 'checkout'])->name('user.shop.checkout');
Route::post('/u/{username}/get-shipping-fees', [\App\Http\Controllers\Shop\UserShopController::class, 'getShippingFees'])->name('user.shop.shipping-fees');
Route::post('/u/{username}/place-order', [\App\Http\Controllers\Shop\UserShopController::class, 'placeOrder'])->name('user.shop.place-order');

// ==================== ROUTES PANIER & CHECKOUT SITE OFFICIEL ====================

Route::get('/cart', [CartController::class, 'index'])->name('cart.index');
// Routes spécifiques du panier - DOIVENT être AVANT les routes avec paramètres wildcard
Route::get('/cart/can-add/{productId}', [CartController::class, 'canAddProduct'])->name('cart.can-add');
Route::post('/cart/apply-discount', [CartController::class, 'applyDiscount'])->name('cart.apply-discount');
Route::delete('/cart/remove-discount', [CartController::class, 'removeDiscount'])->name('cart.remove-discount');
Route::post('/cart/apply-coupon', [CartController::class, 'applyCoupon'])->name('cart.apply-coupon');
Route::delete('/cart/remove-coupon', [CartController::class, 'removeCoupon'])->name('cart.remove-coupon');
Route::post('/cart/apply-promo', [CartController::class, 'applyPromo'])->name('cart.apply-promo');
// Routes avec paramètres wildcard - DOIVENT être APRÈS les routes spécifiques
Route::post('/cart/{productId}', [CartController::class, 'add'])->name('cart.add');
Route::put('/cart/{id}', [CartController::class, 'update'])->name('cart.update');
Route::delete('/cart/{id}', [CartController::class, 'remove'])->name('cart.remove');
Route::delete('/cart', [CartController::class, 'clear'])->name('cart.clear');

// ==================== CHECKOUT ====================
Route::get('/checkout', [CartController::class, 'checkout'])->name('checkout');
Route::post('/checkout/process', [CartController::class, 'process'])->name('checkout.process');
Route::get('/cart/check-multi-seller', [CartController::class, 'checkMultiSellerApi'])->name('cart.check-multi-seller');

Route::get('/order/{order}/success', [\App\Http\Controllers\Shop\OrderController::class, 'success'])->name('shop.order.success');
Route::get('/order/{order}', [\App\Http\Controllers\Shop\OrderController::class, 'show'])->name('shop.order.show');

// ROUTES MANQUANTES AJOUTÉES
Route::post('/checkout/save', [CartController::class, 'saveCheckout'])->name('checkout.save');
Route::get('/api/shipping/countries', [CartController::class, 'getCountries'])->name('api.shipping.countries');
Route::get('/api/shipping/cities', [CartController::class, 'getCities'])->name('api.shipping.cities');
Route::get('/api/shipping/districts', [CartController::class, 'getDistricts'])->name('api.shipping.districts');
Route::post('/api/shipping/calculate', [CartController::class, 'calculateShipping'])->name('api.shipping.calculate');

Route::post('/payment/init', [PaymentController::class, 'initOrderPayment'])->name('payment.init');
Route::get('/payment/callback', [PaymentController::class, 'callback'])->name('payment.callback');
Route::get('/payment/success', [PaymentController::class, 'success'])->name('payment.success');
Route::get('/payment/error', [PaymentController::class, 'error'])->name('payment.error');

// Routes Mobile Money
Route::post('/payment/mobile-money/initiate', [\App\Http\Controllers\MobileMoneyPaymentController::class, 'initiate'])->name('payment.mobile-money.initiate');
Route::get('/payment/mobile-money/callback', [\App\Http\Controllers\MobileMoneyPaymentController::class, 'callback'])->name('payment.mobile-money.callback');
Route::get('/api/mobile-money/networks', [\App\Http\Controllers\MobileMoneyPaymentController::class, 'getNetworks'])->name('api.mobile-money.networks');

// Routes produit d'investissement
Route::middleware(['auth', 'role:member'])->group(function () {
    Route::get('/investment-product', [\App\Http\Controllers\InvestmentProductController::class, 'show'])->name('investment-product');
    Route::post('/investment-product/initiate', [\App\Http\Controllers\InvestmentProductController::class, 'initiatePayment'])->name('investment-product.initiate');
    Route::get('/investment-product/callback', [\App\Http\Controllers\InvestmentProductController::class, 'paymentCallback'])->name('investment-product.callback');
    Route::get('/api/investment-product/status', [\App\Http\Controllers\InvestmentProductController::class, 'checkStatus'])->name('api.investment-product.status');
});


// ==================== WEBHOOKS & PAIEMENTS ====================

// Webhook Flutterwave (pas d'authentification requise - vérifie signature)
Route::post('/webhook/flutterwave', [PaymentController::class, 'webhook'])->withoutMiddleware('web')->name('webhook.flutterwave');

// Admin: Reconciliation paiements
Route::middleware(['auth', 'admin'])->group(function () {
    Route::post('/admin/payment/reconciliate', [PaymentController::class, 'reconciliate'])->name('admin.payment.reconciliate');
});

// ==================== RETRAITS (PROBLEMS #6) ====================
Route::middleware('auth')->prefix('withdrawals')->name('withdrawals.')->group(function () {
    Route::get('/', [WithdrawalController::class, 'index'])->name('index');
    Route::get('/create', [WithdrawalController::class, 'create'])->name('create');
    Route::post('/', [WithdrawalController::class, 'store'])->name('store');
    Route::get('/{withdrawal}/verify-2fa', [WithdrawalController::class, 'verify2FA'])->name('verify-2fa');
    Route::post('/{withdrawal}/confirm-2fa', [WithdrawalController::class, 'confirm2FA'])->name('confirm-2fa');
    Route::post('/{withdrawal}/approve', [WithdrawalController::class, 'approve'])->middleware('admin')->name('approve');
    Route::post('/{withdrawal}/reject', [WithdrawalController::class, 'reject'])->middleware('admin')->name('reject');
});

// ==================== AUDIT LOGS (PROBLEM #7) ====================
Route::middleware(['auth', 'role:admin,comptabilite'])->prefix('audit-logs')->name('audit-logs.')->group(function () {
    Route::get('/', [AuditLogController::class, 'index'])->name('index');
    Route::get('/{log}', [AuditLogController::class, 'show'])->name('show');
    Route::get('/sensitive/changes', [AuditLogController::class, 'sensitiveChanges'])->name('sensitive-changes');
    Route::get('/user/activity', [AuditLogController::class, 'userActivity'])->name('user-activity');
    Route::get('/model/{model}/{modelId}', [AuditLogController::class, 'modelHistory'])->name('model-history');
});

// ==================== SELLER DOCUMENTS (CORRECTED - UNIFIED ROUTES) ====================
// Routes avec préfixe seller/documents (utilisé par les vues)
Route::middleware('auth')->prefix('seller/documents')->name('seller.documents.')->group(function () {
    Route::get('/', [SellerDocumentController::class, 'index'])->name('index');
    Route::get('/create', [SellerDocumentController::class, 'create'])->name('create');
    Route::post('/', [SellerDocumentController::class, 'store'])->name('store');
    Route::get('/{document}', [SellerDocumentController::class, 'show'])->name('show');
    Route::get('/{document}/edit', [SellerDocumentController::class, 'edit'])->name('edit');
    Route::put('/{document}', [SellerDocumentController::class, 'update'])->name('update');
    Route::delete('/{document}', [SellerDocumentController::class, 'destroy'])->name('destroy');
    Route::get('/{document}/download', [SellerDocumentController::class, 'download'])->name('download');
    Route::post('/{document}/verify', [SellerDocumentController::class, 'verify'])->middleware('role:admin,verifier')->name('verify');
    Route::get('/{document}/access-logs', [SellerDocumentController::class, 'accessLogs'])->name('access-logs');
});

// Routes avec préfixe seller-documents (utilisé par le controller et les tests) - Alias
Route::middleware('auth')->prefix('seller-documents')->name('seller-documents.')->group(function () {
    Route::get('/', [SellerDocumentController::class, 'index'])->name('index');
    Route::get('/create', [SellerDocumentController::class, 'create'])->name('create');
    Route::post('/', [SellerDocumentController::class, 'store'])->name('store');
    Route::get('/{document}', [SellerDocumentController::class, 'show'])->name('show');
    Route::get('/{document}/download', [SellerDocumentController::class, 'download'])->name('download');
    Route::post('/{document}/verify', [SellerDocumentController::class, 'verify'])->middleware('role:admin,verifier')->name('verify');
    Route::get('/{document}/access-logs', [SellerDocumentController::class, 'accessLogs'])->name('access-logs');
});


// ==================== DISPUTES (PROBLEM #9) ====================
Route::middleware('auth')->prefix('disputes')->name('disputes.')->group(function () {
    Route::get('/', [DisputeController::class, 'index'])->name('index');
    Route::get('/order/{order}/create', [DisputeController::class, 'create'])->name('create');
    Route::post('/order/{order}', [DisputeController::class, 'store'])->name('store');
    Route::get('/{dispute}', [DisputeController::class, 'show'])->name('show');
    Route::put('/{dispute}', [DisputeController::class, 'update'])->name('update');
    Route::post('/{dispute}/resolve', [DisputeController::class, 'resolve'])->middleware('role:verifier')->name('resolve');
    Route::post('/{dispute}/escalate', [DisputeController::class, 'escalate'])->middleware('role:verifier')->name('escalate');
});

// ==================== DELIVERIES (PROBLEM #10) ====================
Route::middleware('auth')->prefix('deliveries')->name('deliveries.')->group(function () {
    Route::get('/', [DeliveryController::class, 'index'])->name('index');
    Route::get('/order/{order}/create', [DeliveryController::class, 'create'])->name('create');
    Route::post('/order/{order}', [DeliveryController::class, 'store'])->name('store');
    Route::get('/{delivery}', [DeliveryController::class, 'show'])->name('show');
    Route::post('/{delivery}/assign', [DeliveryController::class, 'assign'])->name('assign');
    Route::put('/{delivery}/status', [DeliveryController::class, 'updateStatus'])->name('update-status');
    Route::post('/{delivery}/upload-proof', [DeliveryController::class, 'uploadProof'])->name('upload-proof');
    Route::post('/{delivery}/verify', [DeliveryController::class, 'verify'])->middleware('role:verifier')->name('verify');
});

// ==================== AUTHENTIFICATION ====================
// Rate Limiting: login=5/min, register=3/hour, password-reset=3/hour

// Routes publiques - Formulaires d'affichage (pas de rate limit)
Route::get('/register', [AuthController::class, 'showRegister'])->name('register');
Route::get('/login', [AuthController::class, 'showMemberLogin'])->name('login');
Route::get('/admin/login', [AuthController::class, 'showAdminLogin'])->name('admin.login');
Route::get('/member/login', [AuthController::class, 'showMemberLogin'])->name('member.login');
Route::get('/member/register', [AuthController::class, 'showRegister'])->name('member.register');
Route::get('/member/verify-email', [AuthController::class, 'showVerifyEmail'])->name('member.verify-email');
Route::get('/member/verify-success', function() { return view('member.auth.verify-success'); })->name('member.verify-success');
Route::get('/seller/login', [AuthController::class, 'showSellerLogin'])->name('seller.login');
Route::get('/seller/register', [AuthController::class, 'showSellerRegister'])->name('seller.register');
Route::get('/forgot-password', [\App\Http\Controllers\Auth\PasswordResetController::class, 'showForgotForm'])->name('password.request');
Route::get('/reset-password/{token}', [\App\Http\Controllers\Auth\PasswordResetController::class, 'showResetForm'])->name('password.reset');

// Routes LOGIN avec Rate Limiting (5 tentatives/minute)
Route::middleware('throttle:login')->group(function () {
    Route::post('/login', [AuthController::class, 'memberLogin'])->name('login.post');
    Route::post('/admin/login', [AuthController::class, 'adminLogin'])->name('admin.login.post');
    Route::post('/member/login', [AuthController::class, 'memberLogin'])->name('member.login.post');
    Route::post('/seller/login', [AuthController::class, 'sellerLogin'])->name('seller.login.post');
});

// Routes INSCRIPTION avec Rate Limiting (3 inscriptions/heure)
Route::middleware('throttle:register')->group(function () {
    Route::post('/register', [AuthController::class, 'register'])->name('register.post');
    Route::post('/member/register', [AuthController::class, 'register'])->name('member.register.post');
    Route::post('/seller/register', [AuthController::class, 'sellerRegister'])->name('seller.register.post');
});

// Routes EMAIL VERIFICATION avec Rate Limiting
Route::middleware('throttle:password-reset')->group(function () {
    Route::post('/member/verify-email', [AuthController::class, 'verifyEmail'])->name('member.verify-email.post');
    Route::post('/member/resend-code', [AuthController::class, 'resendVerificationCode'])->name('member.resend-code');
});

// Routes MOT DE PASSE OUBLIÉ avec Rate Limiting (3 demandes/heure)
Route::middleware('throttle:password-reset')->group(function () {
    Route::post('/forgot-password', [\App\Http\Controllers\Auth\PasswordResetController::class, 'sendResetLink'])->name('password.email');
    Route::post('/reset-password', [\App\Http\Controllers\Auth\PasswordResetController::class, 'resetPassword'])->name('password.update');
});

// Routes LOGOUT (pas de rate limit nécessaire)
Route::post('/seller/logout', [AuthController::class, 'logout'])->name('seller.logout');

Route::post('/logout', [AuthController::class, 'logout'])->name('logout');

// ==================== AUTHENTIFICATION 2FA ====================
Route::middleware('auth')->prefix('2fa')->name('2fa.')->group(function () {
    Route::get('/', [\App\Http\Controllers\Auth\TwoFactorController::class, 'show'])->name('show');
    Route::post('/verify', [\App\Http\Controllers\Auth\TwoFactorController::class, 'verify'])->name('verify');
    Route::post('/resend', [\App\Http\Controllers\Auth\TwoFactorController::class, 'resend'])->name('resend');
    Route::post('/enable', [\App\Http\Controllers\Auth\TwoFactorController::class, 'enable'])->name('enable');
    Route::post('/disable', [\App\Http\Controllers\Auth\TwoFactorController::class, 'disable'])->name('disable');
});

// Simple redirect routes for main panel access
Route::redirect('/admin', '/admin/dashboard');
Route::redirect('/member', '/member/dashboard');
Route::redirect('/seller', '/seller/kyc');

// ==================== ESPACE ADMIN ====================

// Route pour arrêter l'impersonation (accessible sans middleware admin car besoin pour revenir depuis compte membre)
Route::post('/stop-impersonate', [UserController::class, 'stopImpersonate'])->middleware('auth')->name('stop-impersonate');

Route::middleware('admin')->prefix('admin')->name('admin.')->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\Admin\DashboardController::class, 'index'])->name('dashboard');
    
    Route::get('users', [UserController::class, 'index'])->middleware('permission:users,view')->name('users.index');
    Route::get('users/create', [UserController::class, 'create'])->middleware('permission:users,create')->name('users.create');
    Route::post('users', [UserController::class, 'store'])->middleware('permission:users,create')->name('users.store');
    Route::get('users/{user}', [UserController::class, 'show'])->middleware('permission:users,view')->name('users.show');
    Route::get('users/{user}/edit', [UserController::class, 'edit'])->middleware('permission:users,edit')->name('users.edit');
    Route::put('users/{user}', [UserController::class, 'update'])->middleware('permission:users,edit')->name('users.update');
    Route::delete('users/{user}', [UserController::class, 'destroy'])->middleware('permission:users,delete')->name('users.destroy');
    Route::post('users/{user}/ban', [UserController::class, 'ban'])->middleware('permission:users,edit')->name('users.ban');
    Route::post('users/{user}/unban', [UserController::class, 'unban'])->middleware('permission:users,edit')->name('users.unban');
    Route::post('users/{user}/impersonate', [UserController::class, 'impersonate'])->middleware('permission:users,view')->name('users.impersonate');
    Route::post('stop-impersonate', [UserController::class, 'stopImpersonate'])->name('stop-impersonate');
    
    Route::get('categories', [CategoryController::class, 'index'])->middleware('permission:categories,view')->name('categories.index');
    Route::get('categories/create', [CategoryController::class, 'create'])->middleware('permission:categories,create')->name('categories.create');
    Route::post('categories', [CategoryController::class, 'store'])->middleware('permission:categories,create')->name('categories.store');
    Route::get('categories/{category}', [CategoryController::class, 'show'])->middleware('permission:categories,view')->name('categories.show');
    Route::get('categories/{category}/edit', [CategoryController::class, 'edit'])->middleware('permission:categories,edit')->name('categories.edit');
    Route::put('categories/{category}', [CategoryController::class, 'update'])->middleware('permission:categories,edit')->name('categories.update');
    Route::delete('categories/{category}', [CategoryController::class, 'destroy'])->middleware('permission:categories,delete')->name('categories.destroy');
    
    Route::get('products', [ProductController::class, 'index'])->middleware('permission:products,view')->name('products.index');
    Route::get('products/create', [ProductController::class, 'create'])->middleware('permission:products,create')->name('products.create');
    Route::post('products', [ProductController::class, 'store'])->middleware('permission:products,create')->name('products.store');
    Route::post('ai/generate-description-ajax', [ProductController::class, 'generateDescriptionAjax'])->name('ai.generate-description-ajax');
    Route::get('products/{product}', [ProductController::class, 'show'])->middleware('permission:products,view')->name('products.show');
    Route::get('products/{product}/edit', [ProductController::class, 'edit'])->middleware('permission:products,edit')->name('products.edit');
    Route::put('products/{product}', [ProductController::class, 'update'])->middleware('permission:products,edit')->name('products.update');
    Route::delete('products/{product}', [ProductController::class, 'destroy'])->middleware('permission:products,delete')->name('products.destroy');
    
    Route::get('orders', [OrderController::class, 'index'])->middleware('permission:orders,view')->name('orders.index');
    Route::post('orders/bulk-status', [OrderController::class, 'bulkUpdateStatus'])->middleware('permission:orders,edit')->name('orders.bulk-status');
    Route::match(['get', 'post'], 'orders/delivery-proofs', [OrderController::class, 'deliveryProofs'])->middleware('permission:orders,view')->name('orders.delivery-proofs');
    Route::get('orders/{order}', [OrderController::class, 'show'])->middleware('permission:orders,view')->name('orders.show');
    Route::put('orders/{order}/status', [OrderController::class, 'updateStatus'])->middleware('permission:orders,edit')->name('orders.update-status');
    Route::post('orders/{order}/upload-proof', [OrderController::class, 'uploadProof'])->middleware('permission:orders,edit')->name('orders.upload-proof');
    Route::get('orders/{order}/delivery-proof', [OrderController::class, 'showDeliveryProof'])->middleware('permission:orders,view')->name('orders.delivery-proof.show');
    Route::post('orders/{order}/delivery-proof/approve', [OrderController::class, 'approveDeliveryProof'])->middleware('permission:orders,edit')->name('orders.delivery-proof.approve');
    Route::post('orders/{order}/delivery-proof/reject', [OrderController::class, 'rejectDeliveryProof'])->middleware('permission:orders,edit')->name('orders.delivery-proof.reject');
    Route::post('orders/{order}/delivery-proof/transmit', [OrderController::class, 'transmitDeliveryProof'])->middleware('permission:orders,edit')->name('orders.delivery-proof.transmit');
    
    Route::get('commissions', [CommissionController::class, 'index'])->middleware('permission:commissions,view')->name('commissions.index');
    Route::get('commissions/by-user', [CommissionController::class, 'byUser'])->middleware('permission:commissions,view')->name('commissions.by-user');
    Route::put('commissions/{commission}/status', [CommissionController::class, 'updateStatus'])->middleware('permission:commissions,edit')->name('commissions.update-status');
    
    Route::get('settings', [SettingController::class, 'index'])->middleware('permission:settings,view')->name('settings.index');
    Route::put('settings', [SettingController::class, 'update'])->middleware('permission:settings,edit')->name('settings.update');
    Route::post('settings/wallet', [SettingController::class, 'updateWallet'])->middleware('permission:settings,edit')->name('settings.wallet');
    Route::post('settings/notifications', [SettingController::class, 'updateNotifications'])->middleware('permission:settings,edit')->name('settings.notifications');
    Route::post('settings/payment', [SettingController::class, 'updatePayment'])->middleware('permission:settings,edit')->name('settings.payment');
    Route::post('settings/general', [SettingController::class, 'updateGeneral'])->middleware('permission:settings,edit')->name('settings.general');
    Route::post('settings/clear-cache', [SettingController::class, 'clearCache'])->middleware('permission:settings,edit')->name('settings.clear-cache');
    Route::post('settings/test-email', [SettingController::class, 'testEmail'])->middleware('permission:settings,edit')->name('settings.test-email');
    
    // Paramètres du site (logo, identité, etc.)
    Route::get('settings/site', [\App\Http\Controllers\Admin\SiteSettingsController::class, 'index'])->middleware('permission:settings,view')->name('settings.site');
    Route::put('settings/site', [\App\Http\Controllers\Admin\SiteSettingsController::class, 'update'])->middleware('permission:settings,edit')->name('settings.site.update');
    
    Route::get('plans', [AdminPlanController::class, 'index'])->middleware('permission:settings,view')->name('plans');
    
    Route::get('contacts', [AdminContactController::class, 'index'])->middleware('permission:contacts,view')->name('contacts.index');
    Route::put('contacts/{contact}/status', [AdminContactController::class, 'updateStatus'])->middleware('permission:contacts,view')->name('contacts.update-status');
    Route::delete('contacts/{contact}', [AdminContactController::class, 'destroy'])->middleware('permission:contacts,delete')->name('contacts.destroy');
    
    Route::resource('email-templates', EmailTemplateController::class);
    Route::post('email-templates/{emailTemplate}/send-test', [EmailTemplateController::class, 'sendTest'])->name('email-templates.send-test');
    Route::get('email-logs', [EmailLogController::class, 'index'])->name('email-logs.index');
    Route::get('email-logs/{emailLog}', [EmailLogController::class, 'show'])->name('email-logs.show');
    
    Route::get('profile', [\App\Http\Controllers\Admin\ProfileController::class, 'edit'])->name('profile.edit');
    Route::put('profile', [\App\Http\Controllers\Admin\ProfileController::class, 'update'])->name('profile.update');
    Route::post('profile/preferences', [\App\Http\Controllers\Admin\ProfileController::class, 'updatePreferences'])->name('profile.preferences');
    Route::post('profile/upload-photo', [\App\Http\Controllers\Admin\ProfileController::class, 'uploadPhoto'])->name('profile.upload-photo');
    
    Route::get('shipping-fees', [\App\Http\Controllers\Admin\ShippingFeeController::class, 'index'])->middleware('permission:shipping,view')->name('shipping-fees.index');
    Route::get('shipping-fees/create', [\App\Http\Controllers\Admin\ShippingFeeController::class, 'create'])->middleware('permission:shipping,create')->name('shipping-fees.create');
    Route::post('shipping-fees', [\App\Http\Controllers\Admin\ShippingFeeController::class, 'store'])->middleware('permission:shipping,create')->name('shipping-fees.store');
    Route::get('shipping-fees/{shippingFee}/edit', [\App\Http\Controllers\Admin\ShippingFeeController::class, 'edit'])->middleware('permission:shipping,edit')->name('shipping-fees.edit');
    Route::put('shipping-fees/{shippingFee}', [\App\Http\Controllers\Admin\ShippingFeeController::class, 'update'])->middleware('permission:shipping,edit')->name('shipping-fees.update');
    Route::delete('shipping-fees/{shippingFee}', [\App\Http\Controllers\Admin\ShippingFeeController::class, 'destroy'])->middleware('permission:shipping,delete')->name('shipping-fees.destroy');
    
    // Nouvelles routes AJAX pour shipping-fees
    Route::get('shipping-fees/country/{country}', [\App\Http\Controllers\Admin\ShippingFeeController::class, 'getCountryZones'])->middleware('permission:shipping,view')->name('shipping-fees.country-zones');
    Route::post('shipping-fees/{id}/update-fee', [\App\Http\Controllers\Admin\ShippingFeeController::class, 'updateFee'])->middleware('permission:shipping,edit')->name('shipping-fees.update-fee');
    Route::post('shipping-fees/{id}/toggle-status', [\App\Http\Controllers\Admin\ShippingFeeController::class, 'toggleStatus'])->middleware('permission:shipping,edit')->name('shipping-fees.toggle-status');
    Route::post('shipping-fees/mass-action', [\App\Http\Controllers\Admin\ShippingFeeController::class, 'massAction'])->middleware('permission:shipping,edit')->name('shipping-fees.mass-action');
    Route::post('shipping-fees/mass-update', [\App\Http\Controllers\Admin\ShippingFeeController::class, 'massUpdate'])->middleware('permission:shipping,edit')->name('shipping-fees.mass-update');
    Route::post('shipping-fees/sync', [\App\Http\Controllers\Admin\ShippingFeeController::class, 'sync'])->middleware('permission:shipping,create')->name('shipping-fees.sync');
    
    Route::get('newsletter', [\App\Http\Controllers\Admin\NewsletterController::class, 'index'])->middleware('permission:settings,view')->name('newsletter.index');
    Route::post('newsletter/send', [\App\Http\Controllers\Admin\NewsletterController::class, 'send'])->middleware('permission:settings,edit')->name('newsletter.send');
    Route::delete('newsletter/{newsletter}', [\App\Http\Controllers\Admin\NewsletterController::class, 'destroy'])->middleware('permission:settings,delete')->name('newsletter.destroy');
    
    // Activity Logs
    Route::get('activity-logs', [\App\Http\Controllers\Admin\ActivityLogController::class, 'index'])->name('activity-logs.index');
    Route::get('activity-logs/export', [\App\Http\Controllers\Admin\ActivityLogController::class, 'export'])->name('activity-logs.export');
    Route::get('activity-logs/user/{user}', [\App\Http\Controllers\Admin\ActivityLogController::class, 'userActivity'])->name('activity-logs.user');
    Route::delete('activity-logs/{activityLog}', [\App\Http\Controllers\Admin\ActivityLogController::class, 'destroy'])->name('activity-logs.destroy');
    Route::post('activity-logs/clear', [\App\Http\Controllers\Admin\ActivityLogController::class, 'clear'])->name('activity-logs.clear');

    // Exports
    Route::get('exports', [\App\Http\Controllers\Admin\ExportController::class, 'index'])->name('exports.index');
    Route::get('exports/commissions', [\App\Http\Controllers\Admin\ExportController::class, 'commissions'])->name('exports.commissions');
    Route::get('exports/orders', [\App\Http\Controllers\Admin\ExportController::class, 'orders'])->name('exports.orders');
    Route::get('exports/users', [\App\Http\Controllers\Admin\ExportController::class, 'users'])->name('exports.users');
    Route::get('exports/wallets', [\App\Http\Controllers\Admin\ExportController::class, 'wallets'])->name('exports.wallets');
    Route::get('exports/transactions', [\App\Http\Controllers\Admin\ExportController::class, 'transactions'])->name('exports.transactions');
    Route::get('exports/withdrawals', [\App\Http\Controllers\Admin\ExportController::class, 'withdrawals'])->name('exports.withdrawals');
    Route::get('exports/amm-status', [\App\Http\Controllers\Admin\ExportController::class, 'ammStatus'])->name('exports.amm-status');
    Route::get('exports/sellers', [\App\Http\Controllers\Admin\ExportController::class, 'sellers'])->name('exports.sellers');
    Route::get('exports/products', [\App\Http\Controllers\Admin\ExportController::class, 'products'])->name('exports.products');
    
    // Analytics avec onglets
    Route::get('analytics', [\App\Http\Controllers\Admin\AnalyticsController::class, 'index'])->name('analytics.index');
    Route::post('analytics/send-amm-reminder', [\App\Http\Controllers\Admin\AnalyticsController::class, 'sendAmmReminder'])->name('analytics.send-amm-reminder');
    Route::post('analytics/bulk-amm-reminders', [\App\Http\Controllers\Admin\AnalyticsController::class, 'sendBulkAmmReminders'])->name('analytics.bulk-amm-reminders');
    
    Route::get('investment-categories', [\App\Http\Controllers\Admin\InvestmentCategoryController::class, 'index'])->middleware('permission:settings,view')->name('investment-categories.index');
    Route::get('investment-categories/create', [\App\Http\Controllers\Admin\InvestmentCategoryController::class, 'create'])->middleware('permission:settings,create')->name('investment-categories.create');
    Route::post('investment-categories', [\App\Http\Controllers\Admin\InvestmentCategoryController::class, 'store'])->middleware('permission:settings,create')->name('investment-categories.store');
    Route::get('investment-categories/{investmentCategory}/edit', [\App\Http\Controllers\Admin\InvestmentCategoryController::class, 'edit'])->middleware('permission:settings,edit')->name('investment-categories.edit');
    Route::put('investment-categories/{investmentCategory}', [\App\Http\Controllers\Admin\InvestmentCategoryController::class, 'update'])->middleware('permission:settings,edit')->name('investment-categories.update');
    Route::delete('investment-categories/{investmentCategory}', [\App\Http\Controllers\Admin\InvestmentCategoryController::class, 'destroy'])->middleware('permission:settings,delete')->name('investment-categories.destroy');
    
    Route::get('investment-products', [\App\Http\Controllers\Admin\InvestmentProductController::class, 'index'])->middleware('permission:settings,view')->name('investment-products.index');
    Route::get('investment-products/create', [\App\Http\Controllers\Admin\InvestmentProductController::class, 'create'])->middleware('permission:settings,create')->name('investment-products.create');
    Route::post('investment-products', [\App\Http\Controllers\Admin\InvestmentProductController::class, 'store'])->middleware('permission:settings,create')->name('investment-products.store');
    Route::get('investment-products/{investmentProduct}/edit', [\App\Http\Controllers\Admin\InvestmentProductController::class, 'edit'])->middleware('permission:settings,edit')->name('investment-products.edit');
    Route::put('investment-products/{investmentProduct}', [\App\Http\Controllers\Admin\InvestmentProductController::class, 'update'])->middleware('permission:settings,edit')->name('investment-products.update');
    Route::delete('investment-products/{investmentProduct}', [\App\Http\Controllers\Admin\InvestmentProductController::class, 'destroy'])->middleware('permission:settings,delete')->name('investment-products.destroy');
    
    // Routes images produits d'investissement
    Route::delete('investment-products/{investmentProduct}/images/{image}', [\App\Http\Controllers\Admin\InvestmentProductController::class, 'deleteImage'])->middleware('permission:settings,edit')->name('investment-products.images.delete');
    Route::post('investment-products/{investmentProduct}/images/{image}/primary', [\App\Http\Controllers\Admin\InvestmentProductController::class, 'setPrimaryImage'])->middleware('permission:settings,edit')->name('investment-products.images.primary');
    Route::post('investment-products/{investmentProduct}/images/reorder', [\App\Http\Controllers\Admin\InvestmentProductController::class, 'reorderImages'])->middleware('permission:settings,edit')->name('investment-products.images.reorder');
    Route::post('investment-products/{investmentProduct}/generate-description', [\App\Http\Controllers\Admin\InvestmentProductController::class, 'generateDescription'])->middleware('permission:settings,edit')->name('investment-products.generate-description');

    // ==================== NOUVELLES ROUTES ADMIN ====================

    // Feature Toggles
    Route::get('features', [\App\Http\Controllers\Admin\FeatureToggleController::class, 'index'])
        ->middleware('permission:settings,view')
        ->name('features.index');
    Route::post('features/{key}/toggle', [\App\Http\Controllers\Admin\FeatureToggleController::class, 'toggle'])
        ->middleware('permission:settings,edit')
        ->name('features.toggle');
    Route::put('features/{key}/config', [\App\Http\Controllers\Admin\FeatureToggleController::class, 'updateConfig'])
        ->middleware('permission:settings,edit')
        ->name('features.config');
    Route::get('features/{key}/config', [\App\Http\Controllers\Admin\FeatureToggleController::class, 'showConfig'])
        ->middleware('permission:settings,view')
        ->name('features.show-config');
    Route::get('features/ai/config', [\App\Http\Controllers\Admin\FeatureToggleController::class, 'aiConfig'])
        ->middleware('permission:settings,view')
        ->name('features.ai-config');
    Route::get('features/config', [\App\Http\Controllers\Admin\FeatureToggleController::class, 'configAll'])
        ->middleware('permission:settings,view')
        ->name('features.config-all');
    Route::get('features/test-ai', [\App\Http\Controllers\Admin\FeatureToggleController::class, 'testAiConfig'])
        ->middleware('permission:settings,view')
        ->name('features.test-ai');
    Route::get('features/initialize', [\App\Http\Controllers\Admin\FeatureToggleController::class, 'initialize'])
        ->name('admin.features.initialize');

    // MLM Management
    Route::get('mlm', [\App\Http\Controllers\Admin\MlmController::class, 'index'])
        ->middleware('permission:settings,view')
        ->name('mlm.index');
    Route::put('mlm/levels/{level}', [\App\Http\Controllers\Admin\MlmController::class, 'updateLevel'])
        ->middleware('permission:settings,edit')
        ->name('mlm.update-level');
    Route::put('mlm/ranks/{rank}', [\App\Http\Controllers\Admin\MlmController::class, 'updateRank'])
        ->middleware('permission:settings,edit')
        ->name('mlm.update-rank');
    Route::post('mlm/ranks', [\App\Http\Controllers\Admin\MlmController::class, 'storeRank'])
        ->middleware('permission:settings,edit')
        ->name('mlm.store-rank');
    Route::delete('mlm/ranks/{rank}', [\App\Http\Controllers\Admin\MlmController::class, 'destroyRank'])
        ->middleware('permission:settings,delete')
        ->name('mlm.destroy-rank');

    // Sellers Management (CRUD complet)
    Route::get('sellers', [\App\Http\Controllers\Admin\SellerController::class, 'index'])->name('sellers.index');
    Route::get('sellers/create', [\App\Http\Controllers\Admin\SellerController::class, 'create'])->name('sellers.create');
    Route::post('sellers', [\App\Http\Controllers\Admin\SellerController::class, 'store'])->name('sellers.store');
    Route::get('sellers/{seller}', [\App\Http\Controllers\Admin\SellerController::class, 'show'])->name('sellers.show');
    Route::get('sellers/{seller}/edit', [\App\Http\Controllers\Admin\SellerController::class, 'edit'])->name('sellers.edit');
    Route::put('sellers/{seller}', [\App\Http\Controllers\Admin\SellerController::class, 'update'])->name('sellers.update');
    Route::delete('sellers/{seller}', [\App\Http\Controllers\Admin\SellerController::class, 'destroy'])->name('sellers.destroy');
    Route::post('sellers/{seller}/approve-kyc', [\App\Http\Controllers\Admin\SellerController::class, 'approveKyc'])->name('sellers.approve-kyc');
    Route::post('sellers/{seller}/reject-kyc', [\App\Http\Controllers\Admin\SellerController::class, 'rejectKyc'])->name('sellers.reject-kyc');
    Route::post('sellers/{seller}/toggle-active', [\App\Http\Controllers\Admin\SellerController::class, 'toggleActive'])->name('sellers.toggle-active');
    Route::post('sellers/{seller}/toggle-featured', [\App\Http\Controllers\Admin\SellerController::class, 'toggleFeatured'])->name('sellers.toggle-featured');
    Route::put('sellers/{seller}/commission', [\App\Http\Controllers\Admin\SellerController::class, 'updateCommission'])->name('sellers.update-commission');

    // Wallets Management
    Route::get('wallets', [\App\Http\Controllers\Admin\WalletController::class, 'index'])->name('wallets.index');
    Route::get('wallets/withdrawals', [\App\Http\Controllers\Admin\WalletController::class, 'withdrawals'])->name('wallets.withdrawals');
    Route::get('withdrawals', [\App\Http\Controllers\Admin\WalletController::class, 'withdrawals'])->name('withdrawals.index');
    Route::get('withdrawals/{withdrawal}', [\App\Http\Controllers\Admin\WalletController::class, 'showWithdrawal'])->name('withdrawals.show');
    Route::get('wallets/{wallet}', [\App\Http\Controllers\Admin\WalletController::class, 'show'])->name('wallets.show');
    Route::post('wallets/{wallet}/credit', [\App\Http\Controllers\Admin\WalletController::class, 'credit'])->name('wallets.credit');
    Route::post('wallets/{wallet}/debit', [\App\Http\Controllers\Admin\WalletController::class, 'debit'])->name('wallets.debit');
    Route::post('wallets/withdrawals/{withdrawal}/approve', [\App\Http\Controllers\Admin\WalletController::class, 'approveWithdrawal'])->name('wallets.withdrawals.approve');
    Route::post('wallets/withdrawals/{withdrawal}/reject', [\App\Http\Controllers\Admin\WalletController::class, 'rejectWithdrawal'])->name('wallets.withdrawals.reject');
    Route::post('withdrawals/{withdrawal}/approve', [\App\Http\Controllers\Admin\WalletController::class, 'approveWithdrawal'])->name('withdrawals.approve');
    Route::post('withdrawals/{withdrawal}/reject', [\App\Http\Controllers\Admin\WalletController::class, 'rejectWithdrawal'])->name('withdrawals.reject');

    // Disputes Management
    Route::get('disputes', [\App\Http\Controllers\Admin\DisputeController::class, 'index'])->name('disputes.index');
    Route::get('disputes/{dispute}', [\App\Http\Controllers\Admin\DisputeController::class, 'show'])->name('disputes.show');
    Route::put('disputes/{dispute}/status', [\App\Http\Controllers\Admin\DisputeController::class, 'updateStatus'])->name('disputes.update-status');
    Route::post('disputes/{dispute}/assign', [\App\Http\Controllers\Admin\DisputeController::class, 'assign'])->name('disputes.assign');
    Route::post('disputes/{dispute}/message', [\App\Http\Controllers\Admin\DisputeController::class, 'addMessage'])->name('disputes.add-message');
    Route::post('disputes/{dispute}/refund', [\App\Http\Controllers\Admin\DisputeController::class, 'refund'])->name('disputes.refund');

    // Coupons Management
    Route::get('coupons', [\App\Http\Controllers\Admin\CouponController::class, 'index'])->name('coupons.index');
    Route::get('coupons/create', [\App\Http\Controllers\Admin\CouponController::class, 'create'])->name('coupons.create');
    Route::post('coupons', [\App\Http\Controllers\Admin\CouponController::class, 'store'])->name('coupons.store');
    Route::get('coupons/{coupon}/edit', [\App\Http\Controllers\Admin\CouponController::class, 'edit'])->name('coupons.edit');
    Route::put('coupons/{coupon}', [\App\Http\Controllers\Admin\CouponController::class, 'update'])->name('coupons.update');
    Route::delete('coupons/{coupon}', [\App\Http\Controllers\Admin\CouponController::class, 'destroy'])->name('coupons.destroy');
    Route::post('coupons/{coupon}/toggle', [\App\Http\Controllers\Admin\CouponController::class, 'toggle'])->name('coupons.toggle');

    // Loyalty Management
    Route::get('loyalty', [\App\Http\Controllers\Admin\LoyaltyController::class, 'index'])->name('loyalty.index');
    Route::get('loyalty/levels', [\App\Http\Controllers\Admin\LoyaltyController::class, 'levels'])->name('loyalty.levels');
    Route::get('loyalty/levels/create', [\App\Http\Controllers\Admin\LoyaltyController::class, 'createLevel'])->name('loyalty.levels.create');
    Route::post('loyalty/levels', [\App\Http\Controllers\Admin\LoyaltyController::class, 'storeLevel'])->name('loyalty.levels.store');
    Route::get('loyalty/levels/{level}/edit', [\App\Http\Controllers\Admin\LoyaltyController::class, 'editLevel'])->name('loyalty.levels.edit');
    Route::put('loyalty/levels/{level}', [\App\Http\Controllers\Admin\LoyaltyController::class, 'updateLevel'])->name('loyalty.levels.update');
    Route::delete('loyalty/levels/{level}', [\App\Http\Controllers\Admin\LoyaltyController::class, 'destroyLevel'])->name('loyalty.levels.destroy');
    Route::post('loyalty/levels/initialize', [\App\Http\Controllers\Admin\LoyaltyController::class, 'initializeDefaultLevels'])->name('loyalty.levels.initialize');
    Route::get('loyalty/{user}', [\App\Http\Controllers\Admin\LoyaltyController::class, 'show'])->name('loyalty.show');
    Route::post('loyalty/{user}/add', [\App\Http\Controllers\Admin\LoyaltyController::class, 'addPoints'])->name('loyalty.add');
    Route::post('loyalty/{user}/deduct', [\App\Http\Controllers\Admin\LoyaltyController::class, 'deductPoints'])->name('loyalty.deduct');

    // Badges Management
    Route::get('badges', [\App\Http\Controllers\Admin\BadgeController::class, 'index'])->name('badges.index');
    Route::get('badges/create', [\App\Http\Controllers\Admin\BadgeController::class, 'create'])->name('badges.create');
    Route::post('badges', [\App\Http\Controllers\Admin\BadgeController::class, 'store'])->name('badges.store');
    Route::get('badges/{badge}/edit', [\App\Http\Controllers\Admin\BadgeController::class, 'edit'])->name('badges.edit');
    Route::put('badges/{badge}', [\App\Http\Controllers\Admin\BadgeController::class, 'update'])->name('badges.update');
    Route::delete('badges/{badge}', [\App\Http\Controllers\Admin\BadgeController::class, 'destroy'])->name('badges.destroy');
    Route::post('badges/{badge}/toggle', [\App\Http\Controllers\Admin\BadgeController::class, 'toggle'])->name('badges.toggle');
    Route::post('badges/{badge}/assign', [\App\Http\Controllers\Admin\BadgeController::class, 'assignToUser'])->name('badges.assign');
    Route::post('badges/recalculate', [\App\Http\Controllers\Admin\BadgeController::class, 'recalculate'])->name('badges.recalculate');

    // Leaderboards Management
    Route::get('leaderboards', [\App\Http\Controllers\Admin\LeaderboardController::class, 'index'])->name('leaderboards.index');
    Route::post('leaderboards/calculate', [\App\Http\Controllers\Admin\LeaderboardController::class, 'calculate'])->name('leaderboards.calculate');
    Route::post('leaderboards/reset', [\App\Http\Controllers\Admin\LeaderboardController::class, 'reset'])->name('leaderboards.reset');

    // Promotions Management
    Route::get('promotions', [\App\Http\Controllers\Admin\PromotionController::class, 'index'])->name('promotions.index');
    Route::get('promotions/create', [\App\Http\Controllers\Admin\PromotionController::class, 'create'])->name('promotions.create');
    Route::post('promotions', [\App\Http\Controllers\Admin\PromotionController::class, 'store'])->name('promotions.store');
    Route::get('promotions/generate-code', [\App\Http\Controllers\Admin\PromotionController::class, 'generateCode'])->name('promotions.generate-code');
    Route::get('promotions/{promotion}', [\App\Http\Controllers\Admin\PromotionController::class, 'show'])->name('promotions.show');
    Route::get('promotions/{promotion}/edit', [\App\Http\Controllers\Admin\PromotionController::class, 'edit'])->name('promotions.edit');
    Route::put('promotions/{promotion}', [\App\Http\Controllers\Admin\PromotionController::class, 'update'])->name('promotions.update');
    Route::delete('promotions/{promotion}', [\App\Http\Controllers\Admin\PromotionController::class, 'destroy'])->name('promotions.destroy');
    Route::post('promotions/{promotion}/toggle', [\App\Http\Controllers\Admin\PromotionController::class, 'toggle'])->name('promotions.toggle');
    Route::post('promotions/quick-flash-sale', [\App\Http\Controllers\Admin\PromotionController::class, 'quickFlashSale'])->name('promotions.quick-flash-sale');

    // Top Sponsors (Parrain du mois)
    Route::get('top-sponsors', [\App\Http\Controllers\Admin\TopSponsorController::class, 'index'])->name('top-sponsors.index');
    Route::post('top-sponsors/award', [\App\Http\Controllers\Admin\TopSponsorController::class, 'awardTopSponsor'])->name('top-sponsors.award');
    Route::get('top-sponsors/history', [\App\Http\Controllers\Admin\TopSponsorController::class, 'history'])->name('top-sponsors.history');

    // Blog Management
    Route::get('blog', [\App\Http\Controllers\Admin\BlogController::class, 'index'])->name('blog.index');
    Route::get('blog/categories', [\App\Http\Controllers\Admin\BlogController::class, 'categories'])->name('blog.categories');
    Route::post('blog/categories', [\App\Http\Controllers\Admin\BlogController::class, 'createCategory'])->name('blog.categories.store');
    Route::post('blog/categories/rename', [\App\Http\Controllers\Admin\BlogController::class, 'renameCategory'])->name('blog.categories.rename');
    Route::post('blog/categories/delete', [\App\Http\Controllers\Admin\BlogController::class, 'deleteCategory'])->name('blog.categories.delete');

    Route::get('blog/tags', [\App\Http\Controllers\Admin\BlogController::class, 'tags'])->name('blog.tags');
    Route::post('blog/tags/rename', [\App\Http\Controllers\Admin\BlogController::class, 'renameTag'])->name('blog.tags.rename');
    Route::post('blog/tags/delete', [\App\Http\Controllers\Admin\BlogController::class, 'deleteTag'])->name('blog.tags.delete');

    Route::get('blog/create', [\App\Http\Controllers\Admin\BlogController::class, 'create'])->name('blog.create');
    Route::post('blog', [\App\Http\Controllers\Admin\BlogController::class, 'store'])->name('blog.store');
    Route::get('blog/{post}/edit', [\App\Http\Controllers\Admin\BlogController::class, 'edit'])->name('blog.edit');
    Route::put('blog/{post}', [\App\Http\Controllers\Admin\BlogController::class, 'update'])->name('blog.update');
    Route::delete('blog/{post}', [\App\Http\Controllers\Admin\BlogController::class, 'destroy'])->name('blog.destroy');
    Route::post('blog/{post}/toggle-featured', [\App\Http\Controllers\Admin\BlogController::class, 'toggleFeatured'])->name('blog.toggle-featured');

    // Languages Management
    Route::get('languages', [\App\Http\Controllers\Admin\LanguageController::class, 'index'])->name('languages.index');
    Route::post('languages', [\App\Http\Controllers\Admin\LanguageController::class, 'store'])->name('languages.store');
    Route::put('languages/{language}', [\App\Http\Controllers\Admin\LanguageController::class, 'update'])->name('languages.update');
    Route::delete('languages/{language}', [\App\Http\Controllers\Admin\LanguageController::class, 'destroy'])->name('languages.destroy');
    Route::post('languages/{language}/toggle', [\App\Http\Controllers\Admin\LanguageController::class, 'toggle'])->name('languages.toggle');
    Route::post('languages/{language}/set-default', [\App\Http\Controllers\Admin\LanguageController::class, 'setDefault'])->name('languages.set-default');

    // Currencies Management
    Route::get('currencies', [\App\Http\Controllers\Admin\CurrencyController::class, 'index'])->name('currencies.index');
    Route::post('currencies', [\App\Http\Controllers\Admin\CurrencyController::class, 'store'])->name('currencies.store');
    Route::put('currencies/{rate}', [\App\Http\Controllers\Admin\CurrencyController::class, 'update'])->name('currencies.update');
    Route::delete('currencies/{rate}', [\App\Http\Controllers\Admin\CurrencyController::class, 'destroy'])->name('currencies.destroy');
    Route::post('currencies/set-default', [\App\Http\Controllers\Admin\CurrencyController::class, 'setDefault'])->name('currencies.set-default');

    // Reviews Management
    Route::get('reviews', [\App\Http\Controllers\Admin\ReviewController::class, 'index'])->name('reviews.index');
    Route::get('reviews/{review}', [\App\Http\Controllers\Admin\ReviewController::class, 'show'])->name('reviews.show');
    Route::post('reviews/{review}/approve', [\App\Http\Controllers\Admin\ReviewController::class, 'approve'])->name('reviews.approve');
    Route::post('reviews/{review}/reject', [\App\Http\Controllers\Admin\ReviewController::class, 'reject'])->name('reviews.reject');
    Route::delete('reviews/{review}', [\App\Http\Controllers\Admin\ReviewController::class, 'destroy'])->name('reviews.destroy');

    // Notifications Management
    Route::get('notifications', [\App\Http\Controllers\Admin\NotificationController::class, 'index'])->name('notifications.index');
    Route::get('notifications/create', [\App\Http\Controllers\Admin\NotificationController::class, 'create'])->name('notifications.create');
    Route::post('notifications', [\App\Http\Controllers\Admin\NotificationController::class, 'store'])->name('notifications.store');
    Route::delete('notifications/{notification}', [\App\Http\Controllers\Admin\NotificationController::class, 'destroy'])->name('notifications.destroy');
    Route::delete('notifications', [\App\Http\Controllers\Admin\NotificationController::class, 'deleteAll'])->name('notifications.delete-all');

    // AI Module
    Route::get('ai', [\App\Http\Controllers\Admin\AiController::class, 'index'])->name('ai.index');
    Route::post('ai/generate-description', [\App\Http\Controllers\Admin\AiController::class, 'generateDescription'])->name('ai.generate-description');
    Route::post('ai/generate-description-ajax', [\App\Http\Controllers\Admin\AiController::class, 'generateDescriptionAjax'])->name('ai.generate-description-ajax');
    Route::get('ai/stagnant-leaders', [\App\Http\Controllers\Admin\AiController::class, 'detectStagnantLeaders'])->name('ai.stagnant-leaders');
    Route::post('ai/generate-report', [\App\Http\Controllers\Admin\AiController::class, 'generateReport'])->name('ai.generate-report');

    // Pool de Partage
    Route::get('pool', [\App\Http\Controllers\Admin\PoolController::class, 'index'])->name('pool.index');
    Route::post('pool/update-settings', [\App\Http\Controllers\Admin\PoolController::class, 'updateSettings'])->name('pool.update-settings');
    Route::post('pool/distribute', [\App\Http\Controllers\Admin\PoolController::class, 'distribute'])->name('pool.distribute');
    Route::get('pool/history', [\App\Http\Controllers\Admin\PoolController::class, 'history'])->name('pool.history');
    Route::get('pool/details/{month}/{year}', [\App\Http\Controllers\Admin\PoolController::class, 'showDetails'])->name('pool.details');
    
    // Système d'épargne
    Route::get('savings', [\App\Http\Controllers\Admin\SavingsAdminController::class, 'index'])->name('savings.index');
    Route::get('savings/plans', [\App\Http\Controllers\Admin\SavingsAdminController::class, 'plans'])->name('savings.plans');
    Route::post('savings/plans', [\App\Http\Controllers\Admin\SavingsAdminController::class, 'storePlan'])->name('savings.store-plan');
    Route::post('savings/plans/{plan}/toggle', [\App\Http\Controllers\Admin\SavingsAdminController::class, 'togglePlan'])->name('savings.toggle-plan');
    Route::put('savings/plans/{plan}', [\App\Http\Controllers\Admin\SavingsAdminController::class, 'updatePlan'])->name('savings.update-plan');
    Route::delete('savings/plans/{plan}', [\App\Http\Controllers\Admin\SavingsAdminController::class, 'deletePlan'])->name('savings.delete-plan');
    Route::get('savings/unlock-requests', [\App\Http\Controllers\Admin\SavingsAdminController::class, 'unlockRequests'])->name('savings.unlock-requests');
    Route::post('savings/unlock-requests/{unlockRequest}/approve', [\App\Http\Controllers\Admin\SavingsAdminController::class, 'approveUnlock'])->name('savings.approve-unlock');
    Route::post('savings/unlock-requests/{unlockRequest}/reject', [\App\Http\Controllers\Admin\SavingsAdminController::class, 'rejectUnlock'])->name('savings.reject-unlock');
    Route::delete('savings/unlock-requests/{unlockRequest}', [\App\Http\Controllers\Admin\SavingsAdminController::class, 'deleteUnlockRequest'])->name('savings.delete-unlock-request');
    Route::get('savings/settings', [\App\Http\Controllers\Admin\SavingsAdminController::class, 'settings'])->name('savings.settings');
    Route::post('savings/settings', [\App\Http\Controllers\Admin\SavingsAdminController::class, 'updateSettings'])->name('savings.update-settings');

    // ==================== ROUTES CRUD COMPLÈTES ====================

    // Email Logs (DELETE manquait)
    Route::delete('email-logs/{emailLog}', [EmailLogController::class, 'destroy'])->name('email-logs.destroy');
    Route::delete('email-logs', [EmailLogController::class, 'deleteAll'])->name('email-logs.delete-all');

    // Orders (PUT & DELETE manquaient)
    Route::put('orders/{order}', [OrderController::class, 'update'])->name('orders.update');
    Route::delete('orders/{order}', [OrderController::class, 'destroy'])->name('orders.destroy');
    Route::post('orders/{order}/cancel', [OrderController::class, 'cancel'])->name('orders.cancel');

    // Commissions (DELETE manquait)
    Route::delete('commissions/{commission}', [CommissionController::class, 'destroy'])->name('commissions.destroy');
    Route::post('commissions/{commission}/approve', [CommissionController::class, 'approve'])->name('commissions.approve');
    Route::post('commissions/{commission}/reject', [CommissionController::class, 'reject'])->name('commissions.reject');
    Route::post('commissions/approve-multiple', [CommissionController::class, 'approveMultiple'])->name('commissions.approve-multiple');

    // Products (Complete CRUD)
    Route::post('products/bulk-action', [ProductController::class, 'bulkAction'])->name('products.bulk-action');
    Route::post('products/{product}/toggle-active', [ProductController::class, 'toggleActive'])->name('products.toggle-active');
    Route::post('products/{product}/toggle-featured', [ProductController::class, 'toggleFeatured'])->name('products.toggle-featured');
    Route::get('products/{product}/images', [ProductController::class, 'getImages'])->name('products.images');
    Route::post('products/{product}/images', [ProductController::class, 'addImages'])->name('products.add-images');
    Route::delete('products/{product}/images/{image}', [ProductController::class, 'removeImage'])->name('products.remove-image');

    // Categories (Complete CRUD - DELETE was missing)
    Route::post('categories/{category}/toggle', [CategoryController::class, 'toggle'])->name('categories.toggle');
    Route::post('categories/bulk-action', [CategoryController::class, 'bulkAction'])->name('categories.bulk-action');

    // Users (Complete CRUD)
    Route::post('users/bulk-action', [UserController::class, 'bulkAction'])->name('users.bulk-action');
    Route::get('users/{user}/wallet', [UserController::class, 'walletInfo'])->name('users.wallet');
    Route::get('users/{user}/transactions', [UserController::class, 'transactions'])->name('users.transactions');
    Route::get('users/{user}/orders', [UserController::class, 'orders'])->name('users.orders');
    Route::get('users/{user}/commissions', [UserController::class, 'commissions'])->name('users.commissions');

    // Transactions Management
    Route::get('transactions', [\App\Http\Controllers\Admin\TransactionController::class, 'index'])->name('transactions.index');
    Route::get('transactions/{transaction}', [\App\Http\Controllers\Admin\TransactionController::class, 'show'])->name('transactions.show');
    Route::put('transactions/{transaction}/status', [\App\Http\Controllers\Admin\TransactionController::class, 'updateStatus'])->name('transactions.update-status');
    Route::delete('transactions/{transaction}', [\App\Http\Controllers\Admin\TransactionController::class, 'destroy'])->name('transactions.destroy');
    Route::post('transactions/export', [\App\Http\Controllers\Admin\TransactionController::class, 'export'])->name('transactions.export');

    // Payments Management
    Route::get('payments', [\App\Http\Controllers\Admin\PaymentController::class, 'index'])->name('payments.index');
    Route::get('payments/{payment}', [\App\Http\Controllers\Admin\PaymentController::class, 'show'])->name('payments.show');
    Route::put('payments/{payment}', [\App\Http\Controllers\Admin\PaymentController::class, 'update'])->name('payments.update');
    Route::post('payments/{payment}/refund', [\App\Http\Controllers\Admin\PaymentController::class, 'refund'])->name('payments.refund');
    Route::post('payments/{payment}/retry', [\App\Http\Controllers\Admin\PaymentController::class, 'retry'])->name('payments.retry');
    Route::delete('payments/{payment}', [\App\Http\Controllers\Admin\PaymentController::class, 'destroy'])->name('payments.destroy');

    // Blog Categories Management
    Route::get('blog-categories', [\App\Http\Controllers\Admin\BlogCategoryController::class, 'index'])->name('blog-categories.index');
    Route::post('blog-categories', [\App\Http\Controllers\Admin\BlogCategoryController::class, 'store'])->name('blog-categories.store');
    Route::put('blog-categories/{category}', [\App\Http\Controllers\Admin\BlogCategoryController::class, 'update'])->name('blog-categories.update');
    Route::delete('blog-categories/{category}', [\App\Http\Controllers\Admin\BlogCategoryController::class, 'destroy'])->name('blog-categories.destroy');

    // Tags Management
    Route::get('tags', [\App\Http\Controllers\Admin\TagController::class, 'index'])->name('tags.index');
    Route::post('tags', [\App\Http\Controllers\Admin\TagController::class, 'store'])->name('tags.store');
    Route::put('tags/{tag}', [\App\Http\Controllers\Admin\TagController::class, 'update'])->name('tags.update');
    Route::delete('tags/{tag}', [\App\Http\Controllers\Admin\TagController::class, 'destroy'])->name('tags.destroy');

    // Pages Management
    Route::get('pages', [\App\Http\Controllers\Admin\PageController::class, 'index'])->name('pages.index');
    Route::get('pages/create', [\App\Http\Controllers\Admin\PageController::class, 'create'])->name('pages.create');
    Route::post('pages', [\App\Http\Controllers\Admin\PageController::class, 'store'])->name('pages.store');
    Route::get('pages/{page}/edit', [\App\Http\Controllers\Admin\PageController::class, 'edit'])->name('pages.edit');
    Route::put('pages/{page}', [\App\Http\Controllers\Admin\PageController::class, 'update'])->name('pages.update');
    Route::delete('pages/{page}', [\App\Http\Controllers\Admin\PageController::class, 'destroy'])->name('pages.destroy');

    // Menu Management
    Route::get('menu', [\App\Http\Controllers\Admin\MenuController::class, 'index'])->name('menu.index');
    Route::post('menu', [\App\Http\Controllers\Admin\MenuController::class, 'store'])->name('menu.store');
    Route::put('menu/{menu}', [\App\Http\Controllers\Admin\MenuController::class, 'update'])->name('menu.update');
    Route::delete('menu/{menu}', [\App\Http\Controllers\Admin\MenuController::class, 'destroy'])->name('menu.destroy');

    // SEO Settings
    Route::get('seo', [\App\Http\Controllers\Admin\SeoController::class, 'index'])->name('seo.index');
    Route::put('seo/{page}', [\App\Http\Controllers\Admin\SeoController::class, 'update'])->name('seo.update');
    Route::post('seo/sitemap', [\App\Http\Controllers\Admin\SeoController::class, 'generateSitemap'])->name('seo.sitemap');

    // Backup Management
    Route::get('backups', [\App\Http\Controllers\Admin\BackupController::class, 'index'])->name('backups.index');
    Route::post('backups/create', [\App\Http\Controllers\Admin\BackupController::class, 'create'])->name('backups.create');
    Route::post('backups/{backup}/restore', [\App\Http\Controllers\Admin\BackupController::class, 'restore'])->name('backups.restore');
    Route::delete('backups/{backup}', [\App\Http\Controllers\Admin\BackupController::class, 'destroy'])->name('backups.destroy');
    Route::post('backups/schedule', [\App\Http\Controllers\Admin\BackupController::class, 'schedule'])->name('backups.schedule');

    // Import/Export Management
    Route::get('import-export', [\App\Http\Controllers\Admin\ImportExportController::class, 'index'])->name('import-export.index');
    Route::post('import-export/import', [\App\Http\Controllers\Admin\ImportExportController::class, 'import'])->name('import-export.import');
    Route::post('import-export/export', [\App\Http\Controllers\Admin\ImportExportController::class, 'export'])->name('import-export.export');
    Route::delete('import-export/{job}', [\App\Http\Controllers\Admin\ImportExportController::class, 'destroy'])->name('import-export.destroy');

    // System Health
    Route::get('health', [\App\Http\Controllers\Admin\HealthController::class, 'index'])->name('health.index');
    Route::get('health/status', [\App\Http\Controllers\Admin\HealthController::class, 'status'])->name('health.status');
    Route::post('health/check', [\App\Http\Controllers\Admin\HealthController::class, 'check'])->name('health.check');
    Route::post('health/optimize', [\App\Http\Controllers\Admin\HealthController::class, 'optimize'])->name('health.optimize');

    // Permissions Management
    Route::get('permissions', [\App\Http\Controllers\Admin\PermissionController::class, 'index'])->name('permissions.index');
    Route::post('permissions', [\App\Http\Controllers\Admin\PermissionController::class, 'store'])->name('permissions.store');
    Route::put('permissions/{permission}', [\App\Http\Controllers\Admin\PermissionController::class, 'update'])->name('permissions.update');
    Route::delete('permissions/{permission}', [\App\Http\Controllers\Admin\PermissionController::class, 'destroy'])->name('permissions.destroy');

    // Roles Management
    Route::get('roles', [\App\Http\Controllers\Admin\RoleController::class, 'index'])->name('roles.index');
    Route::get('roles/create', [\App\Http\Controllers\Admin\RoleController::class, 'create'])->name('roles.create');
    Route::post('roles', [\App\Http\Controllers\Admin\RoleController::class, 'store'])->name('roles.store');
    Route::get('roles/{role}/edit', [\App\Http\Controllers\Admin\RoleController::class, 'edit'])->name('roles.edit');
    Route::put('roles/{role}', [\App\Http\Controllers\Admin\RoleController::class, 'update'])->name('roles.update');
    Route::delete('roles/{role}', [\App\Http\Controllers\Admin\RoleController::class, 'destroy'])->name('roles.destroy');

    // API Logs
    Route::get('api-logs', [\App\Http\Controllers\Admin\ApiLogController::class, 'index'])->name('api-logs.index');
    Route::get('api-logs/{log}', [\App\Http\Controllers\Admin\ApiLogController::class, 'show'])->name('api-logs.show');
    Route::delete('api-logs/{log}', [\App\Http\Controllers\Admin\ApiLogController::class, 'destroy'])->name('api-logs.destroy');
    Route::post('api-logs/clear', [\App\Http\Controllers\Admin\ApiLogController::class, 'clear'])->name('api-logs.clear');

    // Error Logs
    Route::get('error-logs', [\App\Http\Controllers\Admin\ErrorLogController::class, 'index'])->name('error-logs.index');
    Route::get('error-logs/{log}', [\App\Http\Controllers\Admin\ErrorLogController::class, 'show'])->name('error-logs.show');
    Route::delete('error-logs/{log}', [\App\Http\Controllers\Admin\ErrorLogController::class, 'destroy'])->name('error-logs.destroy');
    Route::post('error-logs/clear', [\App\Http\Controllers\Admin\ErrorLogController::class, 'clear'])->name('error-logs.clear');

    // System Logs
    Route::get('system-logs', [\App\Http\Controllers\Admin\SystemLogController::class, 'index'])->name('system-logs.index');
    Route::get('system-logs/{log}', [\App\Http\Controllers\Admin\SystemLogController::class, 'show'])->name('system-logs.show');
    Route::delete('system-logs/{log}', [\App\Http\Controllers\Admin\SystemLogController::class, 'destroy'])->name('system-logs.destroy');
    Route::post('system-logs/clear', [\App\Http\Controllers\Admin\SystemLogController::class, 'clear'])->name('system-logs.clear');

    // ==================== ROUTES MANQUANTES IDENTIFIÉES ====================

    // Dashboard alias
    Route::get('/', [\App\Http\Controllers\Admin\DashboardController::class, 'index'])->name('home');

    // Backups Download
    Route::get('backups/{backup}/download', [\App\Http\Controllers\Admin\BackupController::class, 'download'])->name('backups.download');

    // Health Environment
    Route::get('health/env', [\App\Http\Controllers\Admin\HealthController::class, 'env'])->name('health.env');

    // Maintenance
    Route::get('maintenance', [\App\Http\Controllers\Admin\MaintenanceController::class, 'index'])->name('maintenance.index');
    Route::post('maintenance/toggle', [\App\Http\Controllers\Admin\MaintenanceController::class, 'toggle'])->name('maintenance.toggle');
    Route::put('maintenance', [\App\Http\Controllers\Admin\MaintenanceController::class, 'update'])->name('maintenance.update');
    Route::post('maintenance/schedule', [\App\Http\Controllers\Admin\MaintenanceController::class, 'schedule'])->name('maintenance.schedule');

    // Menus CRUD
    Route::get('menus', [\App\Http\Controllers\Admin\MenuController::class, 'index'])->name('menus.index');
    Route::get('menus/create', [\App\Http\Controllers\Admin\MenuController::class, 'create'])->name('menus.create');
    Route::post('menus', [\App\Http\Controllers\Admin\MenuController::class, 'store'])->name('menus.store');
    Route::get('menus/{menu}', [\App\Http\Controllers\Admin\MenuController::class, 'show'])->name('menus.show');
    Route::get('menus/{menu}/edit', [\App\Http\Controllers\Admin\MenuController::class, 'edit'])->name('menus.edit');
    Route::put('menus/{menu}', [\App\Http\Controllers\Admin\MenuController::class, 'update'])->name('menus.update');
    Route::delete('menus/{menu}', [\App\Http\Controllers\Admin\MenuController::class, 'destroy'])->name('menus.destroy');
    // Menu Items
    Route::post('menus/{menu}/items', [\App\Http\Controllers\Admin\MenuController::class, 'storeItem'])->name('menus.items.store');
    Route::delete('menus/{menu}/items/{item}', [\App\Http\Controllers\Admin\MenuController::class, 'destroyItem'])->name('menus.items.destroy');

    // Blog Categories CRUD complet
    Route::get('blog-categories/create', [\App\Http\Controllers\Admin\BlogCategoryController::class, 'create'])->name('blog-categories.create');
    Route::get('blog-categories/{category}', [\App\Http\Controllers\Admin\BlogCategoryController::class, 'show'])->name('blog-categories.show');
    Route::get('blog-categories/{category}/edit', [\App\Http\Controllers\Admin\BlogCategoryController::class, 'edit'])->name('blog-categories.edit');

    // Tags CRUD complet
    Route::get('tags/create', [\App\Http\Controllers\Admin\TagController::class, 'create'])->name('tags.create');
    Route::get('tags/{tag}', [\App\Http\Controllers\Admin\TagController::class, 'show'])->name('tags.show');
    Route::get('tags/{tag}/edit', [\App\Http\Controllers\Admin\TagController::class, 'edit'])->name('tags.edit');

    // Pages show
    Route::get('pages/{page}', [\App\Http\Controllers\Admin\PageController::class, 'show'])->name('pages.show');

    // Permissions CRUD complet
    Route::get('permissions/create', [\App\Http\Controllers\Admin\PermissionController::class, 'create'])->name('permissions.create');
    Route::get('permissions/{permission}', [\App\Http\Controllers\Admin\PermissionController::class, 'show'])->name('permissions.show');
    Route::get('permissions/{permission}/edit', [\App\Http\Controllers\Admin\PermissionController::class, 'edit'])->name('permissions.edit');

    // Roles show
    Route::get('roles/{role}', [\App\Http\Controllers\Admin\RoleController::class, 'show'])->name('roles.show');

    // Loyalty edit
    Route::get('loyalty/{user}/edit', [\App\Http\Controllers\Admin\LoyaltyController::class, 'edit'])->name('loyalty.edit');
    Route::put('loyalty/{user}', [\App\Http\Controllers\Admin\LoyaltyController::class, 'update'])->name('loyalty.update');

    // SEO routes complets
    Route::get('seo/edit', [\App\Http\Controllers\Admin\SeoController::class, 'edit'])->name('seo.edit');
    Route::get('seo/robots', [\App\Http\Controllers\Admin\SeoController::class, 'robots'])->name('seo.robots');
    Route::put('seo/robots', [\App\Http\Controllers\Admin\SeoController::class, 'updateRobots'])->name('seo.update-robots');
    Route::get('seo/sitemap', [\App\Http\Controllers\Admin\SeoController::class, 'sitemap'])->name('seo.sitemap-view');
    Route::put('seo/sitemap', [\App\Http\Controllers\Admin\SeoController::class, 'updateSitemap'])->name('seo.update-sitemap');
    Route::post('seo/regenerate-sitemap', [\App\Http\Controllers\Admin\SeoController::class, 'regenerateSitemap'])->name('seo.regenerate-sitemap');
    Route::put('seo', [\App\Http\Controllers\Admin\SeoController::class, 'updateGlobal'])->name('seo.update-global');

    // Settings edit
    Route::get('settings/edit', [SettingController::class, 'edit'])->name('settings.edit');

    // Error logs destroy all
    Route::delete('error-logs', [\App\Http\Controllers\Admin\ErrorLogController::class, 'clear'])->name('error-logs.destroy-all');

    // Features initialize
    Route::post('features/initialize', [\App\Http\Controllers\Admin\FeatureToggleController::class, 'initialize'])->name('features.initialize');

    // Import/Export download
    Route::get('import-export/download/{filename}', [\App\Http\Controllers\Admin\ImportExportController::class, 'download'])->name('import-export.download');

    // Reports
    Route::get('reports', [\App\Http\Controllers\Admin\ReportController::class, 'index'])->name('reports.index');
    Route::get('reports/sales', [\App\Http\Controllers\Admin\ReportController::class, 'sales'])->name('reports.sales');
    Route::get('reports/users', [\App\Http\Controllers\Admin\ReportController::class, 'users'])->name('reports.users');
    Route::get('reports/commissions', [\App\Http\Controllers\Admin\ReportController::class, 'commissions'])->name('reports.commissions');
    Route::get('reports/products', [\App\Http\Controllers\Admin\ReportController::class, 'products'])->name('reports.products');
    Route::get('reports/export/{type}', [\App\Http\Controllers\Admin\ReportController::class, 'export'])->name('reports.export');

    // Logs (alias for system-logs)
    Route::get('logs', [\App\Http\Controllers\Admin\SystemLogController::class, 'index'])->name('logs.index');
    Route::get('logs/{log}', [\App\Http\Controllers\Admin\SystemLogController::class, 'show'])->name('logs.show');
    Route::delete('logs/{log}', [\App\Http\Controllers\Admin\SystemLogController::class, 'destroy'])->name('logs.destroy');
    Route::post('logs/clear', [\App\Http\Controllers\Admin\SystemLogController::class, 'clear'])->name('logs.clear');
});

// ==================== ESPACES BACK-OFFICE ====================

// Comptabilité Dashboard
Route::middleware(['auth', 'comptabilite'])->prefix('comptabilite')->name('comptabilite.')->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\Comptabilite\DashboardController::class, 'index'])->name('dashboard');
    Route::get('/export', [\App\Http\Controllers\Comptabilite\DashboardController::class, 'export'])->name('export');
});

// Marketing Dashboard
Route::middleware(['auth', 'marketing'])->prefix('marketing')->name('marketing.')->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\Marketing\DashboardController::class, 'index'])->name('dashboard');
});

// Community Manager Dashboard
Route::middleware(['auth', 'community_manager'])->prefix('community')->name('community.')->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\CommunityManager\DashboardController::class, 'index'])->name('dashboard');
});

// Verifier (Vérificateur) Dashboard
Route::middleware(['auth', 'verifier'])->prefix('verifier')->name('verifier.')->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\Verifier\DashboardController::class, 'index'])->name('dashboard');
});

// ==================== ESPACE MEMBRE ====================

Route::middleware('member')->prefix('member')->name('member.')->group(function () {
    Route::get('/dashboard', [MemberDashboardController::class, 'index'])->name('dashboard');
    
    // Route Alias for withdrawals
    Route::redirect('withdrawals', '/member/wallet/withdrawals', 301)->name('withdrawals');
    
    // MLM features gated by subscription
    Route::middleware('subscription')->group(function () {
        Route::get('/network', [NetworkController::class, 'index'])->name('network');
        Route::get('/commissions', [MemberCommissionController::class, 'index'])->name('commissions');
    });
    Route::get('/commissions/{id}/receipt', [MemberCommissionController::class, 'downloadReceipt'])->name('commissions.receipt');
    Route::get('/wallet/transactions/{id}/receipt', [MemberCommissionController::class, 'downloadTransactionReceipt'])->name('wallet.transaction-receipt');
    Route::get('/products', [MemberProductController::class, 'index'])->name('products');
    Route::get('/products/{id}', [MemberProductController::class, 'show'])->name('products.show');
    Route::get('/profile', [ProfileController::class, 'index'])->name('profile');
    Route::put('/profile', [ProfileController::class, 'update'])->name('profile.update');
    
    Route::get('/addresses', [\App\Http\Controllers\Member\AddressController::class, 'index'])->name('addresses.index');
    Route::get('/addresses/create', [\App\Http\Controllers\Member\AddressController::class, 'create'])->name('addresses.create');
    Route::post('/addresses', [\App\Http\Controllers\Member\AddressController::class, 'store'])->name('addresses.store');
    Route::get('/addresses/{address}/edit', [\App\Http\Controllers\Member\AddressController::class, 'edit'])->name('addresses.edit');
    Route::put('/addresses/{address}', [\App\Http\Controllers\Member\AddressController::class, 'update'])->name('addresses.update');
    Route::delete('/addresses/{address}', [\App\Http\Controllers\Member\AddressController::class, 'destroy'])->name('addresses.destroy');
    Route::post('/addresses/{address}/set-default', [\App\Http\Controllers\Member\AddressController::class, 'setDefault'])->name('addresses.set-default');
    
    // Commandes
    Route::get('/orders', [\App\Http\Controllers\Member\OrderController::class, 'index'])->name('orders.index');
    Route::get('/orders/{order}', [\App\Http\Controllers\Member\OrderController::class, 'show'])->name('orders.show');

    // Wallet & Retraits (request actions gated by subscription)
    Route::get('/wallet', [\App\Http\Controllers\Member\WalletController::class, 'index'])->name('wallet.index');
    Route::middleware('subscription')->group(function () {
        Route::get('/wallet/withdrawals', [\App\Http\Controllers\Member\WalletController::class, 'withdrawals'])->name('wallet.withdrawals');
        Route::get('/wallet/withdrawals/{withdrawal}', [\App\Http\Controllers\Member\WalletController::class, 'showWithdrawal'])->name('withdrawals.show');
        Route::post('/wallet/request-withdrawal', [\App\Http\Controllers\Member\WalletController::class, 'requestWithdrawal'])->name('wallet.request-withdrawal');
    });

    // Avis & Notes produits
    Route::get('/reviews', [\App\Http\Controllers\Member\ReviewController::class, 'index'])->name('reviews.index');
    Route::get('/reviews/create/{product}', [\App\Http\Controllers\Member\ReviewController::class, 'create'])->name('reviews.create');
    Route::post('/reviews', [\App\Http\Controllers\Member\ReviewController::class, 'store'])->name('reviews.store');
    Route::get('/reviews/{review}/edit', [\App\Http\Controllers\Member\ReviewController::class, 'edit'])->name('reviews.edit');
    Route::put('/reviews/{review}', [\App\Http\Controllers\Member\ReviewController::class, 'update'])->name('reviews.update');
    Route::delete('/reviews/{review}', [\App\Http\Controllers\Member\ReviewController::class, 'destroy'])->name('reviews.destroy');

    // Litiges
    Route::get('/disputes', [\App\Http\Controllers\Member\DisputeController::class, 'index'])->name('disputes.index');
    Route::get('/disputes/create', [\App\Http\Controllers\Member\DisputeController::class, 'create'])->name('disputes.create');
    Route::post('/disputes', [\App\Http\Controllers\Member\DisputeController::class, 'store'])->name('disputes.store');
    Route::get('/disputes/{dispute}', [\App\Http\Controllers\Member\DisputeController::class, 'show'])->name('disputes.show');
    Route::post('/disputes/{dispute}/message', [\App\Http\Controllers\Member\DisputeController::class, 'addMessage'])->name('disputes.message');
    Route::patch('/disputes/{dispute}/close', [\App\Http\Controllers\Member\DisputeController::class, 'close'])->name('disputes.close');

    // Badges (gated)
    Route::middleware('subscription')->group(function () {
        Route::get('/badges', [\App\Http\Controllers\Member\BadgeController::class, 'index'])->name('badges.index');
    });

    // Classements (gated)
    Route::middleware('subscription')->group(function () {
        Route::get('/leaderboards', [\App\Http\Controllers\Member\LeaderboardController::class, 'index'])->name('leaderboards.index');
    });

    // Notifications (accessible sans abonnement)
    Route::get('/notifications', [\App\Http\Controllers\Member\NotificationController::class, 'index'])->name('notifications.index');
    Route::get('/notifications/{notification}', [\App\Http\Controllers\Member\NotificationController::class, 'show'])->name('notifications.show');
    Route::post('/notifications/{notification}/mark-read', [\App\Http\Controllers\Member\NotificationController::class, 'markAsRead'])->name('notifications.mark-read');
    Route::post('/notifications/mark-all-read', [\App\Http\Controllers\Member\NotificationController::class, 'markAllAsRead'])->name('notifications.mark-all-read');

    // Fidélité (gated)
    Route::middleware('subscription')->group(function () {
        Route::get('/loyalty', [\App\Http\Controllers\Member\LoyaltyController::class, 'index'])->name('loyalty.index');
    });

    // Pool de Partage (gated)
    Route::middleware('subscription')->group(function () {
        Route::get('/pool', [\App\Http\Controllers\Member\PoolController::class, 'index'])->name('pool.index');
    });

    // PDF abonnement
    Route::get('/subscription/pdf', [\App\Http\Controllers\Member\DashboardController::class, 'downloadSubscriptionPdf'])->name('subscription.pdf');
    
    // AMM (Achat Mensuel Minimum)
    Route::get('/amm/status', [\App\Http\Controllers\Member\DashboardController::class, 'getAmmStatus'])->name('amm.status');
    Route::post('/amm/advance-pay', [\App\Http\Controllers\Member\DashboardController::class, 'payAdvanceAmm'])->name('amm.advance-pay');
    
    // Wallet d'épargne
    Route::get('/savings', [\App\Http\Controllers\Member\SavingsController::class, 'index'])->name('savings.index');
    Route::post('/savings/transfer-to', [\App\Http\Controllers\Member\SavingsController::class, 'transferToSavings'])->name('savings.transfer-to');
    Route::post('/savings/lock-plan', [\App\Http\Controllers\Member\SavingsController::class, 'createLockedSavings'])->name('savings.lock-plan');
    Route::post('/savings/transfer-from', [\App\Http\Controllers\Member\SavingsController::class, 'transferFromSavings'])->name('savings.transfer-from');
    Route::post('/savings/lock', [\App\Http\Controllers\Member\SavingsController::class, 'lockSavingsWallet'])->name('savings.lock');
    Route::post('/savings/early-unlock', [\App\Http\Controllers\Member\SavingsController::class, 'earlyUnlock'])->name('savings.early-unlock');
    Route::post('/savings/request-unlock', [\App\Http\Controllers\Member\SavingsController::class, 'requestUnlock'])->name('savings.request-unlock');
    Route::get('/savings/transfers', [\App\Http\Controllers\Member\SavingsController::class, 'transfers'])->name('savings.transfers');

});

// ==================== PAIEMENT ABONNEMENT MLM ====================
// Routes hors du prefix member pour éviter member.subscription.callback
Route::middleware('member')->group(function () {
    Route::post('/member/subscription/pay', [PaymentController::class, 'initSubscription'])->name('member.subscription.pay');
});
Route::get('/subscription/callback', [PaymentController::class, 'subscriptionCallback'])->name('subscription.callback');

// ==================== PAIEMENTS VIA WALLET ====================

use App\Http\Controllers\WalletPaymentController;

Route::middleware('auth')->group(function () {
    Route::post('/wallet/pay-shop-order', [WalletPaymentController::class, 'payShopOrder'])->name('wallet.pay.shop');
    Route::post('/wallet/pay-subscription', [WalletPaymentController::class, 'paySubscription'])->name('wallet.pay.subscription');
    Route::post('/wallet/pay-investment', [WalletPaymentController::class, 'payInvestmentProduct'])->name('wallet.pay.investment');
});

// ==================== ROUTES DE FALLBACK ====================

// ROUTE MANQUANTE AJOUTÉE
Route::fallback(function () {
    abort(404);
});
// ==================== ESPACE SELLER ====================

Route::middleware('seller')->prefix('seller')->name('seller.')->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\Seller\DashboardController::class, 'index'])->name('dashboard');

    // Produits
    Route::get('/products', [\App\Http\Controllers\Seller\ProductController::class, 'index'])->name('products.index');
    Route::get('/products/create', [\App\Http\Controllers\Seller\ProductController::class, 'create'])->name('products.create');
    Route::post('/products', [\App\Http\Controllers\Seller\ProductController::class, 'store'])->name('products.store');
    Route::post('/products/generate-description-ajax', [\App\Http\Controllers\Seller\ProductController::class, 'generateDescriptionAjax'])->name('products.generate-description-ajax');
    Route::get('/products/{product}', [\App\Http\Controllers\Seller\ProductController::class, 'show'])->name('products.show');
    Route::get('/products/{product}/edit', [\App\Http\Controllers\Seller\ProductController::class, 'edit'])->name('products.edit');
    Route::put('/products/{product}', [\App\Http\Controllers\Seller\ProductController::class, 'update'])->name('products.update');
    Route::delete('/products/{product}', [\App\Http\Controllers\Seller\ProductController::class, 'destroy'])->name('products.destroy');
    
    // Gestion des images de produits
    Route::post('/products/{product}/images', [\App\Http\Controllers\Seller\ProductController::class, 'uploadImages'])->name('products.images.upload');
    Route::delete('/products/{product}/images/{image}', [\App\Http\Controllers\Seller\ProductController::class, 'deleteImage'])->name('products.images.delete');
    Route::post('/products/{product}/images/{image}/primary', [\App\Http\Controllers\Seller\ProductController::class, 'setPrimaryImage'])->name('products.images.primary');
    Route::post('/products/{product}/images/reorder', [\App\Http\Controllers\Seller\ProductController::class, 'reorderImages'])->name('products.images.reorder');

    // Commandes
    Route::get('/orders', [\App\Http\Controllers\Seller\OrderController::class, 'index'])->name('orders.index');
    Route::post('/orders/bulk-status', [\App\Http\Controllers\Seller\OrderController::class, 'bulkUpdateStatus'])->name('orders.bulk-status');
    Route::get('/orders/{order}', [\App\Http\Controllers\Seller\OrderController::class, 'show'])->name('orders.show');
    Route::put('/orders/{order}/status', [\App\Http\Controllers\Seller\OrderController::class, 'updateStatus'])->name('orders.update-status');
    Route::post('/orders/{order}/delivery-proof', [\App\Http\Controllers\Seller\OrderController::class, 'uploadDeliveryProof'])->name('orders.upload-delivery-proof');

    // KYC
    Route::get('/kyc', [\App\Http\Controllers\Seller\KycController::class, 'index'])->name('kyc.index');
    Route::post('/kyc', [\App\Http\Controllers\Seller\KycController::class, 'store'])->name('kyc.store');
    Route::post('/kyc/message', [\App\Http\Controllers\Seller\KycController::class, 'sendMessage'])->name('kyc.message');

    // Wallet & Retraits
    Route::get('/wallet', [\App\Http\Controllers\Seller\WalletController::class, 'index'])->name('wallet.index');
    Route::get('/wallet/withdrawals', [\App\Http\Controllers\Seller\WalletController::class, 'withdrawals'])->name('wallet.withdrawals');
    Route::post('/wallet/request-withdrawal', [\App\Http\Controllers\Seller\WalletController::class, 'requestWithdrawal'])->name('wallet.request-withdrawal');

    // Commissions
    Route::get('/commissions', [\App\Http\Controllers\Seller\CommissionController::class, 'index'])->name('commissions.index');
    Route::get('/commissions/export', [\App\Http\Controllers\Seller\CommissionController::class, 'export'])->name('commissions.export');

    // Avis
    Route::get('/reviews', [\App\Http\Controllers\Seller\ReviewController::class, 'index'])->name('reviews.index');

    // Litiges
    Route::get('/disputes', [\App\Http\Controllers\Seller\DisputeController::class, 'index'])->name('disputes.index');
    Route::get('/disputes/{dispute}', [\App\Http\Controllers\Seller\DisputeController::class, 'show'])->name('disputes.show');
    Route::post('/disputes/{dispute}/message', [\App\Http\Controllers\Seller\DisputeController::class, 'addMessage'])->name('disputes.message');

    // Notifications
    Route::get('/notifications', [\App\Http\Controllers\Seller\NotificationController::class, 'index'])->name('notifications.index');
    Route::get('/notifications/unread-count', [\App\Http\Controllers\Seller\NotificationController::class, 'getUnreadCount'])->name('notifications.unread-count');
    Route::get('/notifications/latest', [\App\Http\Controllers\Seller\NotificationController::class, 'getLatest'])->name('notifications.latest');
    Route::post('/notifications/read-all', [\App\Http\Controllers\Seller\NotificationController::class, 'markAllAsRead'])->name('notifications.read-all');
    Route::delete('/notifications/delete-read', [\App\Http\Controllers\Seller\NotificationController::class, 'deleteAllRead'])->name('notifications.delete-read');
    Route::post('/notifications/{notification}/read', [\App\Http\Controllers\Seller\NotificationController::class, 'markAsRead'])->name('notifications.read');
    Route::delete('/notifications/{notification}', [\App\Http\Controllers\Seller\NotificationController::class, 'destroy'])->name('notifications.destroy');

    // Coupons
    Route::get('/coupons', [\App\Http\Controllers\Seller\CouponController::class, 'index'])->name('coupons.index');
    Route::get('/coupons/create', [\App\Http\Controllers\Seller\CouponController::class, 'create'])->name('coupons.create');
    Route::post('/coupons', [\App\Http\Controllers\Seller\CouponController::class, 'store'])->name('coupons.store');
    Route::post('/coupons/{coupon}/toggle', [\App\Http\Controllers\Seller\CouponController::class, 'toggle'])->name('coupons.toggle');
    Route::delete('/coupons/{coupon}', [\App\Http\Controllers\Seller\CouponController::class, 'destroy'])->name('coupons.destroy');

    // Profil
    Route::get('/profile', [\App\Http\Controllers\Seller\ProfileController::class, 'index'])->name('profile.index');
    Route::put('/profile', [\App\Http\Controllers\Seller\ProfileController::class, 'update'])->name('profile.update');
    Route::put('/profile/password', [\App\Http\Controllers\Seller\ProfileController::class, 'updatePassword'])->name('profile.password');
    Route::put('/profile/payment', [\App\Http\Controllers\Seller\ProfileController::class, 'updatePayment'])->name('profile.update-payment');
    
    // Adresses
    Route::get('/addresses', [\App\Http\Controllers\Seller\ProfileController::class, 'addresses'])->name('addresses.index');
    Route::post('/addresses', [\App\Http\Controllers\Seller\ProfileController::class, 'storeAddress'])->name('addresses.store');
    Route::put('/addresses/{address}', [\App\Http\Controllers\Seller\ProfileController::class, 'updateAddress'])->name('addresses.update');
    Route::delete('/addresses/{address}', [\App\Http\Controllers\Seller\ProfileController::class, 'deleteAddress'])->name('addresses.destroy');
    Route::post('/addresses/{address}/default', [\App\Http\Controllers\Seller\ProfileController::class, 'setDefaultAddress'])->name('addresses.default');
});

// ==================== API ROUTES ====================

use App\Http\Controllers\FeatureToggleController;
use App\Http\Controllers\AiController;
use App\Http\Controllers\LanguageController;
use App\Http\Controllers\CurrencyController;
use App\Http\Controllers\LeaderboardController;
use App\Http\Controllers\BlogController;

// Public API Routes
Route::prefix('api')->name('api.')->group(function () {
    // Language & Currency
    Route::get('/languages', [LanguageController::class, 'index'])->name('languages.index');
    Route::post('/languages/set', [LanguageController::class, 'set'])->name('languages.set');
    Route::get('/currencies', [CurrencyController::class, 'index'])->name('currencies.index');
    Route::post('/currencies/set', [CurrencyController::class, 'set'])->name('currencies.set');
    Route::post('/currencies/convert', [CurrencyController::class, 'convert'])->name('currencies.convert');
    Route::get('/currencies/rates', [CurrencyController::class, 'rates'])->name('currencies.rates');
    
    // Feature Status (public)
    Route::get('/features/status', [FeatureToggleController::class, 'status'])->name('features.status');
    
    // Blog Public
    Route::get('/blog', [BlogController::class, 'index'])->name('blog.index');
    Route::get('/blog/categories', [BlogController::class, 'categories'])->name('blog.categories');
    Route::get('/blog/{slug}', [BlogController::class, 'show'])->name('blog.show');
    
    // Newsletter
    Route::post('/newsletter/subscribe', [NewsletterController::class, 'subscribe'])->name('newsletter.subscribe');
    Route::get('/newsletter/confirm/{token}', [NewsletterController::class, 'confirm'])->name('newsletter.confirm');
    Route::get('/newsletter/unsubscribe/{token}', [NewsletterController::class, 'unsubscribe'])->name('newsletter.unsubscribe');
    
    // Leaderboards Public
    Route::get('/leaderboards', [LeaderboardController::class, 'index'])->name('leaderboards.index');
    Route::get('/leaderboards/types', [LeaderboardController::class, 'types'])->name('leaderboards.types');
    Route::get('/leaderboards/badges/recent', [LeaderboardController::class, 'recentBadges'])->name('leaderboards.badges.recent');
});

// ==================== ESPACE VERIFICATEUR SELLERS ====================

Route::middleware('verifier')->prefix('verifier')->name('verifier.')->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\Verifier\DashboardController::class, 'index'])->name('dashboard');
    
    // KYC Management
    Route::get('/kyc', [\App\Http\Controllers\Verifier\KycController::class, 'index'])->name('kyc.index');
    Route::get('/kyc/{seller}', [\App\Http\Controllers\Verifier\KycController::class, 'show'])->name('kyc.show');
    Route::post('/kyc/{seller}/approve', [\App\Http\Controllers\Verifier\KycController::class, 'approve'])->name('kyc.approve');
    Route::post('/kyc/{seller}/reject', [\App\Http\Controllers\Verifier\KycController::class, 'reject'])->name('kyc.reject');
    Route::post('/kyc/{seller}/message', [\App\Http\Controllers\Verifier\KycController::class, 'sendMessage'])->name('kyc.message');
    
    // Delivery Proofs
    Route::get('/delivery', [\App\Http\Controllers\Verifier\DeliveryController::class, 'index'])->name('delivery.index');
    Route::get('/delivery/{order}', [\App\Http\Controllers\Verifier\DeliveryController::class, 'show'])->name('delivery.show');
    Route::post('/delivery/{order}/confirm', [\App\Http\Controllers\Verifier\DeliveryController::class, 'confirmDelivery'])->name('delivery.confirm');
    Route::post('/delivery/{order}/reject', [\App\Http\Controllers\Verifier\DeliveryController::class, 'rejectProof'])->name('delivery.reject');
    Route::post('/delivery/{order}/flag', [\App\Http\Controllers\Verifier\DeliveryController::class, 'flagIssue'])->name('delivery.flag');
});

// ==================== ESPACE COMMUNITY MANAGER ====================

Route::middleware('community')->prefix('community')->name('community.')->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\CommunityManager\DashboardController::class, 'index'])->name('dashboard');
    
    // Newsletter
    Route::get('/newsletter', [\App\Http\Controllers\CommunityManager\NewsletterController::class, 'index'])->name('newsletter.index');
    Route::get('/newsletter/compose', [\App\Http\Controllers\CommunityManager\NewsletterController::class, 'compose'])->name('newsletter.compose');
    Route::post('/newsletter/send', [\App\Http\Controllers\CommunityManager\NewsletterController::class, 'send'])->name('newsletter.send');
    Route::get('/newsletter/subscribers', [\App\Http\Controllers\CommunityManager\NewsletterController::class, 'subscribers'])->name('newsletter.subscribers');
    Route::delete('/newsletter/{newsletter}', [\App\Http\Controllers\CommunityManager\NewsletterController::class, 'removeSubscriber'])->name('newsletter.remove');
    Route::get('/newsletter/export', [\App\Http\Controllers\CommunityManager\NewsletterController::class, 'export'])->name('newsletter.export');
    Route::post('/newsletter/{subscriber}/unsubscribe', [\App\Http\Controllers\CommunityManager\NewsletterController::class, 'unsubscribe'])->name('newsletter.unsubscribe');
    
    // Blog
    Route::get('/blog', [\App\Http\Controllers\CommunityManager\BlogController::class, 'index'])->name('blog.index');
    Route::get('/blog/create', [\App\Http\Controllers\CommunityManager\BlogController::class, 'create'])->name('blog.create');
    Route::post('/blog', [\App\Http\Controllers\CommunityManager\BlogController::class, 'store'])->name('blog.store');
    Route::get('/blog/{post}/edit', [\App\Http\Controllers\CommunityManager\BlogController::class, 'edit'])->name('blog.edit');
    Route::put('/blog/{post}', [\App\Http\Controllers\CommunityManager\BlogController::class, 'update'])->name('blog.update');
    Route::delete('/blog/{post}', [\App\Http\Controllers\CommunityManager\BlogController::class, 'destroy'])->name('blog.destroy');
    Route::post('/blog/{post}/toggle', [\App\Http\Controllers\CommunityManager\BlogController::class, 'togglePublish'])->name('blog.toggle');
    
    // Reviews Moderation
    Route::get('/reviews', [\App\Http\Controllers\CommunityManager\ReviewController::class, 'index'])->name('reviews.index');
    Route::post('/reviews/{review}/approve', [\App\Http\Controllers\CommunityManager\ReviewController::class, 'approve'])->name('reviews.approve');
    Route::post('/reviews/{review}/reject', [\App\Http\Controllers\CommunityManager\ReviewController::class, 'reject'])->name('reviews.reject');
    Route::delete('/reviews/{review}', [\App\Http\Controllers\CommunityManager\ReviewController::class, 'destroy'])->name('reviews.destroy');
});

// ==================== ESPACE COMPTABLE ====================

Route::middleware('accountant')->prefix('accountant')->name('accountant.')->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\Accountant\DashboardController::class, 'index'])->name('dashboard');
    
    // Withdrawals
    Route::get('/withdrawals', [\App\Http\Controllers\Accountant\WithdrawalController::class, 'index'])->name('withdrawals.index');
    Route::get('/withdrawals/{withdrawal}', [\App\Http\Controllers\Accountant\WithdrawalController::class, 'show'])->name('withdrawals.show');
    Route::post('/withdrawals/{withdrawal}/approve', [\App\Http\Controllers\Accountant\WithdrawalController::class, 'approve'])->name('withdrawals.approve');
    Route::post('/withdrawals/{withdrawal}/reject', [\App\Http\Controllers\Accountant\WithdrawalController::class, 'reject'])->name('withdrawals.reject');
    Route::get('/withdrawals/export', [\App\Http\Controllers\Accountant\WithdrawalController::class, 'export'])->name('withdrawals.export');
    
    // Reports
    Route::get('/reports', [\App\Http\Controllers\Accountant\ReportController::class, 'index'])->name('reports.index');
    Route::get('/reports/financial', [\App\Http\Controllers\Accountant\ReportController::class, 'financial'])->name('reports.financial');
    Route::get('/reports/commissions', [\App\Http\Controllers\Accountant\ReportController::class, 'commissions'])->name('reports.commissions');
    Route::get('/reports/transactions', [\App\Http\Controllers\Accountant\ReportController::class, 'transactions'])->name('reports.transactions');
    Route::get('/reports/export-pdf', [\App\Http\Controllers\Accountant\ReportController::class, 'exportPdf'])->name('reports.export-pdf');
    Route::get('/reports/pdf', [\App\Http\Controllers\Accountant\ReportController::class, 'generatePdf'])->name('reports.pdf');
});

// ==================== ESPACE MARKETING ====================

Route::middleware('marketing')->prefix('marketing')->name('marketing.')->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\Marketing\DashboardController::class, 'index'])->name('dashboard');
    
    // Campagnes
    Route::get('/campaigns', [\App\Http\Controllers\Marketing\CampaignController::class, 'index'])->name('campaigns.index');
    Route::get('/campaigns/create', [\App\Http\Controllers\Marketing\CampaignController::class, 'create'])->name('campaigns.create');
    Route::post('/campaigns', [\App\Http\Controllers\Marketing\CampaignController::class, 'store'])->name('campaigns.store');
    
    // Analytics
    Route::get('/analytics', [\App\Http\Controllers\Marketing\AnalyticsController::class, 'index'])->name('analytics.index');
    Route::get('/analytics/users', [\App\Http\Controllers\Marketing\AnalyticsController::class, 'users'])->name('analytics.users');
    Route::get('/analytics/products', [\App\Http\Controllers\Marketing\AnalyticsController::class, 'products'])->name('analytics.products');
});

// ==================== ESPACE COMPTABILITÉ ====================

Route::middleware('comptabilite')->prefix('comptabilite')->name('comptabilite.')->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\Comptabilite\DashboardController::class, 'index'])->name('dashboard');
    
    // Retraits (si pas géré par accountant)
    Route::get('/withdrawals', [\App\Http\Controllers\Comptabilite\WithdrawalController::class, 'index'])->name('withdrawals.index');
    Route::get('/withdrawals/{withdrawal}', [\App\Http\Controllers\Comptabilite\WithdrawalController::class, 'show'])->name('withdrawals.show');
    
    // Rapports
    Route::get('/reports', [\App\Http\Controllers\Comptabilite\ReportController::class, 'index'])->name('reports.index');
    Route::get('/reports/export', [\App\Http\Controllers\Comptabilite\ReportController::class, 'export'])->name('reports.export');
});

// Authenticated API Routes
Route::prefix('api')->name('api.')->middleware('auth')->group(function () {
    // AI Features
    Route::get('/ai/status', [AiController::class, 'status'])->name('ai.status');
    Route::get('/ai/recommendations', [AiController::class, 'recommendations'])->name('ai.recommendations');
    Route::get('/leaderboards/my-rank', [LeaderboardController::class, 'myRank'])->name('leaderboards.my-rank');
    Route::get('/leaderboards/badges', [LeaderboardController::class, 'badges'])->name('leaderboards.badges');
});

// Admin API Routes
Route::prefix('api/admin')->name('api.admin.')->middleware(['auth', 'admin'])->group(function () {
    // Feature Toggles
    Route::get('/features', [FeatureToggleController::class, 'index'])->name('features.index');
    Route::get('/features/{key}', [FeatureToggleController::class, 'show'])->name('features.show');
    Route::post('/features/{key}/toggle', [FeatureToggleController::class, 'toggle'])->name('features.toggle');
    Route::put('/features/{key}/config', [FeatureToggleController::class, 'updateConfig'])->name('features.config');
    
    // AI Admin Features
    Route::post('/ai/generate-description/{productId}', [AiController::class, 'generateDescription'])->name('ai.generate-description');
    Route::post('/ai/moderate', [AiController::class, 'moderate'])->name('ai.moderate');
    Route::get('/ai/stagnant-leaders', [AiController::class, 'detectStagnantLeaders'])->name('ai.stagnant-leaders');
    Route::get('/ai/sales-summary', [AiController::class, 'salesSummary'])->name('ai.sales-summary');
    Route::get('/ai/suggest-pricing/{productId}', [AiController::class, 'suggestPricing'])->name('ai.suggest-pricing');
    Route::post('/ai/generate-report', [AiController::class, 'generateReport'])->name('ai.generate-report');
    Route::get('/ai/reports', [AiController::class, 'reports'])->name('ai.reports');
    Route::get('/ai/tasks', [AiController::class, 'tasks'])->name('ai.tasks');
    
    // Leaderboard Admin
    Route::post('/leaderboards/calculate', [LeaderboardController::class, 'calculate'])->name('leaderboards.calculate');
    
    // Currency Admin
    Route::post('/currencies/update-rates', [CurrencyController::class, 'updateRates'])->name('currencies.update-rates');
    
    // Blog Admin
    Route::post('/blog', [BlogController::class, 'store'])->name('blog.store');
    Route::put('/blog/{id}', [BlogController::class, 'update'])->name('blog.update');
    Route::delete('/blog/{id}', [BlogController::class, 'destroy'])->name('blog.destroy');
    
    // Newsletter Admin
    Route::get('/newsletter/subscribers', [NewsletterController::class, 'subscribers'])->name('newsletter.subscribers');
    Route::get('/newsletter/stats', [NewsletterController::class, 'stats'])->name('newsletter.stats');
});
