<?php

use App\Http\Controllers\ProfileController;
use App\Http\Controllers\MarketingController;
use Illuminate\Support\Facades\Route;

// Marketing routes
Route::get('/', [MarketingController::class, 'home'])->name('marketing.home');
Route::get('/pricing', [MarketingController::class, 'pricing'])->name('marketing.pricing');
Route::get('/features', [MarketingController::class, 'features'])->name('marketing.features');
Route::get('/demo', [MarketingController::class, 'demo'])->name('marketing.demo');
Route::get('/help', [MarketingController::class, 'help'])->name('marketing.help');
Route::post('/contact-sales', [MarketingController::class, 'contactSales'])->name('marketing.contact-sales');

// Onboarding routes
Route::get('/onboarding/brand', [MarketingController::class, 'onboardingBrand'])->name('marketing.onboarding.brand');
Route::get('/onboarding/creator', [MarketingController::class, 'onboardingCreator'])->name('marketing.onboarding.creator');
Route::get('/onboarding/agency', [MarketingController::class, 'onboardingAgency'])->name('marketing.onboarding.agency');

Route::get('/dashboard', function () {
    // Redirect to appropriate dashboard based on user role
    if (auth()->check()) {
        $user = auth()->user();
        
        // Check roles in priority order
        if ($user->hasRole('superadmin')) {
            return redirect()->route('superadmin.dashboard');
        } elseif ($user->hasRole('brand_admin')) {
            return redirect()->route('brand.dashboard');
        } elseif ($user->hasRole('agency')) {
            return redirect()->route('agency.dashboard');
        } elseif ($user->hasRole('creator')) {
            return redirect()->route('creator.dashboard');
        } elseif ($user->hasRole('user')) {
            // Regular users get a basic dashboard
            return view('dashboard');
        }
        
        // Fallback: If user has no recognized role, show error
        abort(403, 'No valid role assigned to your account. Please contact support.');
    }
    
    // Not authenticated - should not reach here due to auth middleware
    return redirect()->route('login');
})->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

// SuperAdmin routes
Route::prefix('superadmin')->middleware(['auth', 'role:superadmin'])->group(function () {
    // Dashboard
    Route::get('/', function () {
        return view('superadmin.dashboard');
    })->name('superadmin.dashboard');
    
    // Tenants (Brands)
    Route::resource('tenants', App\Http\Controllers\SuperAdmin\TenantController::class)->names([
        'index' => 'superadmin.tenants.index',
        'create' => 'superadmin.tenants.create',
        'store' => 'superadmin.tenants.store',
        'show' => 'superadmin.tenants.show',
        'edit' => 'superadmin.tenants.edit',
        'update' => 'superadmin.tenants.update',
        'destroy' => 'superadmin.tenants.destroy',
    ]);
    
    // Registration requests management
    Route::prefix('requests')->group(function () {
        Route::get('/', [App\Http\Controllers\SuperAdmin\RegistrationRequestController::class, 'index'])->name('superadmin.requests.index');
        Route::post('/{registrationRequest}/approve', [App\Http\Controllers\SuperAdmin\RegistrationRequestController::class, 'approve'])->name('superadmin.requests.approve');
        Route::post('/{registrationRequest}/reject', [App\Http\Controllers\SuperAdmin\RegistrationRequestController::class, 'reject'])->name('superadmin.requests.reject');
    });
    
    // Agencies
    Route::prefix('agencies')->group(function () {
        Route::get('/', [App\Http\Controllers\SuperAdmin\AgencyController::class, 'index'])->name('superadmin.agencies.index');
        Route::get('/create', [App\Http\Controllers\SuperAdmin\AgencyController::class, 'create'])->name('superadmin.agencies.create');
        Route::post('/', [App\Http\Controllers\SuperAdmin\AgencyController::class, 'store'])->name('superadmin.agencies.store');
        Route::get('/{agency}', [App\Http\Controllers\SuperAdmin\AgencyController::class, 'show'])->name('superadmin.agencies.show');
        Route::get('/{agency}/edit', [App\Http\Controllers\SuperAdmin\AgencyController::class, 'edit'])->name('superadmin.agencies.edit');
        Route::put('/{agency}', [App\Http\Controllers\SuperAdmin\AgencyController::class, 'update'])->name('superadmin.agencies.update');
        Route::delete('/{agency}', [App\Http\Controllers\SuperAdmin\AgencyController::class, 'destroy'])->name('superadmin.agencies.destroy');
    });
    
    // Users
    Route::prefix('users')->group(function () {
        Route::get('/', [App\Http\Controllers\SuperAdmin\UserController::class, 'index'])->name('superadmin.users.index');
        Route::get('/create', [App\Http\Controllers\SuperAdmin\UserController::class, 'create'])->name('superadmin.users.create');
        Route::post('/', [App\Http\Controllers\SuperAdmin\UserController::class, 'store'])->name('superadmin.users.store');
        Route::get('/{user}', [App\Http\Controllers\SuperAdmin\UserController::class, 'show'])->name('superadmin.users.show');
        Route::get('/{user}/edit', [App\Http\Controllers\SuperAdmin\UserController::class, 'edit'])->name('superadmin.users.edit');
        Route::put('/{user}', [App\Http\Controllers\SuperAdmin\UserController::class, 'update'])->name('superadmin.users.update');
        Route::delete('/{user}', [App\Http\Controllers\SuperAdmin\UserController::class, 'destroy'])->name('superadmin.users.destroy');
        Route::get('/impersonate', [App\Http\Controllers\SuperAdmin\UserController::class, 'impersonate'])->name('superadmin.users.impersonate');
        Route::post('/{user}/impersonate', [App\Http\Controllers\SuperAdmin\UserController::class, 'startImpersonation'])->name('superadmin.users.impersonate.start');
        Route::post('/stop-impersonation', [App\Http\Controllers\SuperAdmin\UserController::class, 'stopImpersonation'])->name('superadmin.users.impersonate.stop');
    });
    
    // Roles & Permissions
    Route::prefix('roles')->group(function () {
        Route::get('/', [App\Http\Controllers\SuperAdmin\RoleController::class, 'index'])->name('superadmin.roles.index');
        Route::get('/create', [App\Http\Controllers\SuperAdmin\RoleController::class, 'create'])->name('superadmin.roles.create');
        Route::post('/', [App\Http\Controllers\SuperAdmin\RoleController::class, 'store'])->name('superadmin.roles.store');
        Route::get('/{role}/edit', [App\Http\Controllers\SuperAdmin\RoleController::class, 'edit'])->name('superadmin.roles.edit');
        Route::put('/{role}', [App\Http\Controllers\SuperAdmin\RoleController::class, 'update'])->name('superadmin.roles.update');
        Route::delete('/{role}', [App\Http\Controllers\SuperAdmin\RoleController::class, 'destroy'])->name('superadmin.roles.destroy');
    });
    
    Route::prefix('permissions')->group(function () {
        Route::get('/', [App\Http\Controllers\SuperAdmin\PermissionController::class, 'index'])->name('superadmin.permissions.index');
        Route::get('/create', [App\Http\Controllers\SuperAdmin\PermissionController::class, 'create'])->name('superadmin.permissions.create');
        Route::post('/', [App\Http\Controllers\SuperAdmin\PermissionController::class, 'store'])->name('superadmin.permissions.store');
        Route::get('/{permission}/edit', [App\Http\Controllers\SuperAdmin\PermissionController::class, 'edit'])->name('superadmin.permissions.edit');
        Route::put('/{permission}', [App\Http\Controllers\SuperAdmin\PermissionController::class, 'update'])->name('superadmin.permissions.update');
        Route::delete('/{permission}', [App\Http\Controllers\SuperAdmin\PermissionController::class, 'destroy'])->name('superadmin.permissions.destroy');
    });
    
    // Campaigns
    Route::prefix('campaigns')->group(function () {
        Route::get('/', [App\Http\Controllers\SuperAdmin\CampaignController::class, 'index'])->name('superadmin.campaigns.index');
        Route::get('/active', [App\Http\Controllers\SuperAdmin\CampaignController::class, 'active'])->name('superadmin.campaigns.active');
        Route::get('/{campaign}', [App\Http\Controllers\SuperAdmin\CampaignController::class, 'show'])->name('superadmin.campaigns.show');
    });
    
    // Proposals
    Route::prefix('proposals')->group(function () {
        Route::get('/', [App\Http\Controllers\SuperAdmin\ProposalController::class, 'index'])->name('superadmin.proposals.index');
        Route::get('/pending', [App\Http\Controllers\SuperAdmin\ProposalController::class, 'pending'])->name('superadmin.proposals.pending');
        Route::get('/{proposal}', [App\Http\Controllers\SuperAdmin\ProposalController::class, 'show'])->name('superadmin.proposals.show');
    });
    
    // AI Jobs (additional routes)
    Route::prefix('ai-jobs')->group(function () {
        Route::get('/failed', [App\Http\Controllers\Admin\AiJobController::class, 'failed'])->name('superadmin.ai-jobs.failed');
    });
    
    // Queue & Workers
    Route::prefix('queue')->group(function () {
        Route::get('/status', [App\Http\Controllers\SuperAdmin\QueueController::class, 'status'])->name('superadmin.queue.status');
        Route::get('/failed', [App\Http\Controllers\SuperAdmin\QueueController::class, 'failed'])->name('superadmin.queue.failed');
        Route::get('/workers', [App\Http\Controllers\SuperAdmin\QueueController::class, 'workers'])->name('superadmin.queue.workers');
        Route::post('/failed/{id}/retry', [App\Http\Controllers\SuperAdmin\QueueController::class, 'retry'])->name('superadmin.queue.retry');
        Route::delete('/failed/{id}', [App\Http\Controllers\SuperAdmin\QueueController::class, 'delete'])->name('superadmin.queue.delete');
    });
    
    // Reels / Media Processor
    Route::prefix('reels')->group(function () {
        Route::get('/', [App\Http\Controllers\SuperAdmin\ReelController::class, 'index'])->name('superadmin.reels.index');
        Route::get('/processing', [App\Http\Controllers\SuperAdmin\ReelController::class, 'processing'])->name('superadmin.reels.processing');
        Route::get('/failed', [App\Http\Controllers\SuperAdmin\ReelController::class, 'failed'])->name('superadmin.reels.failed');
        Route::post('/{reel}/retry', [App\Http\Controllers\SuperAdmin\ReelController::class, 'retry'])->name('superadmin.reels.retry');
    });
    
    // Integrations
    Route::prefix('integrations')->group(function () {
        Route::get('/social', [App\Http\Controllers\SuperAdmin\IntegrationController::class, 'social'])->name('superadmin.integrations.social');
        Route::get('/ai', [App\Http\Controllers\SuperAdmin\IntegrationController::class, 'ai'])->name('superadmin.integrations.ai');
        Route::get('/reels', [App\Http\Controllers\SuperAdmin\IntegrationController::class, 'reels'])->name('superadmin.integrations.reels');
        Route::get('/api-keys', [App\Http\Controllers\SuperAdmin\IntegrationController::class, 'apiKeys'])->name('superadmin.integrations.api-keys');
        Route::post('/api-keys', [App\Http\Controllers\SuperAdmin\IntegrationController::class, 'storeApiKey'])->name('superadmin.integrations.api-keys.store');
        Route::put('/api-keys/{key}', [App\Http\Controllers\SuperAdmin\IntegrationController::class, 'updateApiKey'])->name('superadmin.integrations.api-keys.update');
        Route::delete('/api-keys/{key}', [App\Http\Controllers\SuperAdmin\IntegrationController::class, 'deleteApiKey'])->name('superadmin.integrations.api-keys.delete');
    });
    
    // Billing & Subscriptions
    Route::prefix('billing')->group(function () {
        Route::get('/dashboard', [App\Http\Controllers\SuperAdmin\BillingController::class, 'dashboard'])->name('superadmin.billing.dashboard');
        Route::get('/subscriptions', [App\Http\Controllers\SuperAdmin\BillingController::class, 'subscriptions'])->name('superadmin.billing.subscriptions');
        Route::get('/invoices', [App\Http\Controllers\SuperAdmin\BillingController::class, 'invoices'])->name('superadmin.billing.invoices');
        Route::get('/failed', [App\Http\Controllers\SuperAdmin\BillingController::class, 'failed'])->name('superadmin.billing.failed');
        Route::get('/plans', [App\Http\Controllers\SuperAdmin\BillingController::class, 'plans'])->name('superadmin.billing.plans');
        Route::post('/plans', [App\Http\Controllers\SuperAdmin\BillingController::class, 'storePlan'])->name('superadmin.billing.plans.store');
        Route::put('/plans/{plan}', [App\Http\Controllers\SuperAdmin\BillingController::class, 'updatePlan'])->name('superadmin.billing.plans.update');
    });
    
    // System Logs
    Route::prefix('logs')->group(function () {
        Route::get('/application', [App\Http\Controllers\SuperAdmin\LogController::class, 'application'])->name('superadmin.logs.application');
        Route::get('/audit', [App\Http\Controllers\SuperAdmin\LogController::class, 'audit'])->name('superadmin.logs.audit');
        Route::get('/errors', [App\Http\Controllers\SuperAdmin\LogController::class, 'errors'])->name('superadmin.logs.errors');
        Route::get('/export', [App\Http\Controllers\SuperAdmin\LogController::class, 'export'])->name('superadmin.logs.export');
        Route::post('/clear', [App\Http\Controllers\SuperAdmin\LogController::class, 'clear'])->name('superadmin.logs.clear');
    });
    
    // Alerts & Incidents
    Route::prefix('alerts')->group(function () {
        Route::get('/active', [App\Http\Controllers\SuperAdmin\AlertController::class, 'active'])->name('superadmin.alerts.active');
        Route::get('/incidents', [App\Http\Controllers\SuperAdmin\AlertController::class, 'incidents'])->name('superadmin.alerts.incidents');
        Route::get('/rules', [App\Http\Controllers\SuperAdmin\AlertController::class, 'rules'])->name('superadmin.alerts.rules');
        Route::post('/rules', [App\Http\Controllers\SuperAdmin\AlertController::class, 'storeRule'])->name('superadmin.alerts.rules.store');
        Route::post('/{alert}/resolve', [App\Http\Controllers\SuperAdmin\AlertController::class, 'resolve'])->name('superadmin.alerts.resolve');
        Route::post('/{alert}/acknowledge', [App\Http\Controllers\SuperAdmin\AlertController::class, 'acknowledge'])->name('superadmin.alerts.acknowledge');
    });
    
    // Settings
    Route::prefix('settings')->group(function () {
        Route::get('/global', [App\Http\Controllers\SuperAdmin\SettingsController::class, 'global'])->name('superadmin.settings.global');
        Route::post('/global', [App\Http\Controllers\SuperAdmin\SettingsController::class, 'updateGlobal'])->name('superadmin.settings.global.update');
        Route::get('/email', [App\Http\Controllers\SuperAdmin\SettingsController::class, 'email'])->name('superadmin.settings.email');
        Route::post('/email', [App\Http\Controllers\SuperAdmin\SettingsController::class, 'updateEmail'])->name('superadmin.settings.email.update');
        Route::get('/security', [App\Http\Controllers\SuperAdmin\SettingsController::class, 'security'])->name('superadmin.settings.security');
        Route::post('/security', [App\Http\Controllers\SuperAdmin\SettingsController::class, 'updateSecurity'])->name('superadmin.settings.security.update');
        Route::get('/backup', [App\Http\Controllers\SuperAdmin\SettingsController::class, 'backup'])->name('superadmin.settings.backup');
        Route::post('/backup', [App\Http\Controllers\SuperAdmin\SettingsController::class, 'updateBackup'])->name('superadmin.settings.backup.update');
        Route::get('/rate-limits', [App\Http\Controllers\SuperAdmin\SettingsController::class, 'rateLimits'])->name('superadmin.settings.rate-limits');
        Route::post('/rate-limits', [App\Http\Controllers\SuperAdmin\SettingsController::class, 'updateRateLimits'])->name('superadmin.settings.rate-limits.update');
    });
    
    // Tools
    Route::prefix('tools')->group(function () {
        Route::get('/maintenance', [App\Http\Controllers\SuperAdmin\ToolsController::class, 'maintenance'])->name('superadmin.tools.maintenance');
        Route::post('/maintenance/enable', [App\Http\Controllers\SuperAdmin\ToolsController::class, 'enableMaintenance'])->name('superadmin.tools.maintenance.enable');
        Route::post('/maintenance/disable', [App\Http\Controllers\SuperAdmin\ToolsController::class, 'disableMaintenance'])->name('superadmin.tools.maintenance.disable');
        Route::get('/scheduler', [App\Http\Controllers\SuperAdmin\ToolsController::class, 'scheduler'])->name('superadmin.tools.scheduler');
        Route::get('/migrations', [App\Http\Controllers\SuperAdmin\ToolsController::class, 'migrations'])->name('superadmin.tools.migrations');
        Route::post('/migrations/run', [App\Http\Controllers\SuperAdmin\ToolsController::class, 'runMigrations'])->name('superadmin.tools.migrations.run');
        Route::get('/cache', [App\Http\Controllers\SuperAdmin\ToolsController::class, 'cache'])->name('superadmin.tools.cache');
        Route::post('/cache/clear', [App\Http\Controllers\SuperAdmin\ToolsController::class, 'clearCache'])->name('superadmin.tools.cache.clear');
        Route::get('/backup', [App\Http\Controllers\SuperAdmin\ToolsController::class, 'backup'])->name('superadmin.tools.backup');
        Route::post('/backup/create', [App\Http\Controllers\SuperAdmin\ToolsController::class, 'createBackup'])->name('superadmin.tools.backup.create');
    });
    
    // Help & Docs
    Route::prefix('help')->group(function () {
        Route::get('/docs', [App\Http\Controllers\SuperAdmin\HelpController::class, 'docs'])->name('superadmin.help.docs');
        Route::get('/api', [App\Http\Controllers\SuperAdmin\HelpController::class, 'api'])->name('superadmin.help.api');
        Route::get('/system-info', [App\Http\Controllers\SuperAdmin\HelpController::class, 'systemInfo'])->name('superadmin.help.system-info');
    });
    
    // Global Search API
    Route::get('/search', [App\Http\Controllers\SuperAdmin\SearchController::class, 'search'])->name('superadmin.search');
    
    // Subscription Plans Management
    Route::resource('plans', App\Http\Controllers\SuperAdmin\PlanController::class)->names('superadmin.plans');
    Route::post('plans/{plan}/toggle-status', [App\Http\Controllers\SuperAdmin\PlanController::class, 'toggleStatus'])->name('superadmin.plans.toggle-status');
    
    // Razorpay Settings
    Route::get('razorpay/settings', [App\Http\Controllers\SuperAdmin\RazorpaySettingController::class, 'index'])->name('superadmin.razorpay.settings');
    Route::put('razorpay/settings', [App\Http\Controllers\SuperAdmin\RazorpaySettingController::class, 'update'])->name('superadmin.razorpay.update');
    Route::post('razorpay/test', [App\Http\Controllers\SuperAdmin\RazorpaySettingController::class, 'test'])->name('superadmin.razorpay.test');
    
    // Subscription Management
    Route::prefix('subscriptions')->group(function () {
        Route::get('/', [App\Http\Controllers\SuperAdmin\SubscriptionManagementController::class, 'index'])->name('superadmin.subscriptions.index');
        Route::get('/create', [App\Http\Controllers\SuperAdmin\SubscriptionManagementController::class, 'create'])->name('superadmin.subscriptions.create');
        Route::post('/', [App\Http\Controllers\SuperAdmin\SubscriptionManagementController::class, 'store'])->name('superadmin.subscriptions.store');
        Route::get('/{subscription}', [App\Http\Controllers\SuperAdmin\SubscriptionManagementController::class, 'show'])->name('superadmin.subscriptions.show');
        Route::post('/{subscription}/change-plan', [App\Http\Controllers\SuperAdmin\SubscriptionManagementController::class, 'changePlan'])->name('superadmin.subscriptions.change-plan');
        Route::post('/{subscription}/cancel', [App\Http\Controllers\SuperAdmin\SubscriptionManagementController::class, 'cancel'])->name('superadmin.subscriptions.cancel');
        Route::post('/{subscription}/cancel-immediately', [App\Http\Controllers\SuperAdmin\SubscriptionManagementController::class, 'cancelImmediately'])->name('superadmin.subscriptions.cancel-immediately');
        Route::post('/{subscription}/resume', [App\Http\Controllers\SuperAdmin\SubscriptionManagementController::class, 'resume'])->name('superadmin.subscriptions.resume');
    });
    
    Route::get('subscriptions-transactions', [App\Http\Controllers\SuperAdmin\SubscriptionManagementController::class, 'transactions'])->name('superadmin.subscriptions.transactions');
    Route::get('subscriptions-analytics', [App\Http\Controllers\SuperAdmin\SubscriptionManagementController::class, 'analytics'])->name('superadmin.subscriptions.analytics');
});

// Invite registration routes
Route::get('/register/invite/{token}', [App\Http\Controllers\Auth\InviteController::class, 'showRegistrationForm'])->name('invite.register');
// Route::post('/register/invite/{token}', [App\Http\Controllers\Auth\InviteController::class, 'register']); // Handled by RegisteredUserController

// Signup request routes
Route::get('/signup/request', [App\Http\Controllers\Auth\SignupRequestController::class, 'create'])->name('signup.request');
Route::post('/signup/request', [App\Http\Controllers\Auth\SignupRequestController::class, 'store'])->name('signup.request.store');

// Invite creation route (API endpoint)
Route::post('/invites', [App\Http\Controllers\Auth\InviteController::class, 'store'])->middleware(['auth', 'role:superadmin|brand_admin'])->name('invites.store');

// BrandAdmin routes
Route::prefix('brand')->middleware(['auth', 'role:brand_admin|superadmin', 'IdentifyTenant'])->group(function () {
    Route::get('/dashboard', [App\Http\Controllers\Brand\DashboardController::class, 'index'])->name('brand.dashboard');
    
    // Sidebar API routes
    Route::get('/api/sidebar/badges', [App\Http\Controllers\Brand\SidebarController::class, 'getBadges'])->name('brand.sidebar.badges');
    Route::get('/api/sidebar/search', [App\Http\Controllers\Brand\SidebarController::class, 'quickSearch'])->name('brand.sidebar.search');
    
    // User management routes
    Route::get('/users', [App\Http\Controllers\Brand\UserController::class, 'index'])->name('brand.users.index');
    Route::post('/users/invite', [App\Http\Controllers\Brand\UserController::class, 'store'])->name('brand.users.invite');
    Route::delete('/users/{id}', [App\Http\Controllers\Brand\UserController::class, 'destroy'])->name('brand.users.destroy');
    
    // Content approval routes
    Route::get('/content/pending', [App\Http\Controllers\Brand\ContentController::class, 'pending'])->name('brand.content.pending');
    Route::post('/content/{id}/approve', [App\Http\Controllers\Brand\ContentController::class, 'approve'])->name('brand.content.approve');
    Route::post('/content/{id}/reject', [App\Http\Controllers\Brand\ContentController::class, 'reject'])->name('brand.content.reject');
    
    // Social connections routes
    Route::get('/connections', [App\Http\Controllers\Brand\SocialController::class, 'index'])->name('brand.connections.index');
    Route::get('/connections/connect/{provider}', [App\Http\Controllers\Brand\SocialController::class, 'connect'])->name('brand.connections.connect');
    Route::get('/connections/callback/{provider}', [App\Http\Controllers\Brand\SocialController::class, 'callback'])->name('brand.connections.callback');
    Route::post('/connections/manual', [App\Http\Controllers\Brand\SocialController::class, 'manualStore'])->name('brand.connections.manual');
    Route::delete('/connections/{id}', [App\Http\Controllers\Brand\SocialController::class, 'destroy'])->name('brand.connections.destroy');
    
    // Creators routes
    Route::get('/creators', [App\Http\Controllers\Brand\CreatorController::class, 'index'])->name('brand.creators.index');
    Route::get('/creators/{creator}', [App\Http\Controllers\Brand\CreatorController::class, 'show'])->name('brand.creators.show');
    Route::get('/creators/{creator}/proposal/create', [App\Http\Controllers\Brand\CreatorController::class, 'createProposal'])->name('brand.creators.proposal.create');
    Route::post('/creators/{creator}/proposal', [App\Http\Controllers\Brand\CreatorController::class, 'storeProposal'])->name('brand.creators.proposal.store');
    Route::get('/creators/data', [App\Http\Controllers\Brand\CreatorController::class, 'data'])->name('brand.creators.data');
    
    // Dashboard routes with social features
    Route::get('/dashboard/stats', [App\Http\Controllers\Brand\DashboardController::class, 'stats'])->name('brand.dashboard.stats');
    Route::post('/dashboard/sync-now', [App\Http\Controllers\Brand\DashboardController::class, 'syncNow'])->name('brand.dashboard.sync');
    
    // AI Tasks routes
        Route::post('/ai-tasks/generate-proposal', [App\Http\Controllers\Brand\DashboardController::class, 'generateAiProposal'])->name('brand.ai-tasks.generate-proposal');
        Route::get('/ai-tasks', [App\Http\Controllers\Brand\DashboardController::class, 'aiTasks'])->name('brand.ai-tasks.index');
        
        // Content Ideas routes
        Route::get('/content-ideas', [App\Http\Controllers\Brand\ContentIdeaController::class, 'index'])->name('brand.content-ideas.index');
        Route::get('/content-ideas/create', [App\Http\Controllers\Brand\ContentIdeaController::class, 'create'])->name('brand.content-ideas.create');
        Route::post('/content-ideas', [App\Http\Controllers\Brand\ContentIdeaController::class, 'store'])->name('brand.content-ideas.store')
            ->middleware('content_idea_rate_limit');
        Route::post('/content-ideas/{id}/save-to-draft', [App\Http\Controllers\Brand\ContentIdeaController::class, 'saveToDraft'])->name('brand.content-ideas.save-to-draft');
        Route::post('/content-ideas/{id}/copy', [App\Http\Controllers\Brand\ContentIdeaController::class, 'copy'])->name('brand.content-ideas.copy');
        Route::post('/content-ideas/{id}/schedule-post', [App\Http\Controllers\Brand\ContentIdeaController::class, 'schedulePost'])->name('brand.content-ideas.schedule-post');
        
        // Provider-specific routes
        Route::get('/provider/{provider}', [App\Http\Controllers\Brand\DashboardController::class, 'providerShow'])->name('brand.provider.show');
    
    // Marketplace routes
    Route::get('/marketplace', [App\Http\Controllers\Brand\MarketplaceController::class, 'index'])->name('brand.marketplace.index');
    Route::get('/marketplace/shortlists', [App\Http\Controllers\Brand\MarketplaceController::class, 'shortlists'])->name('brand.marketplace.shortlists.index');
    Route::get('/marketplace/recommendations', [App\Http\Controllers\Brand\MarketplaceController::class, 'recommendations'])->name('brand.marketplace.recommendations.index');
    
    // Proposals routes
    Route::get('/proposals', [App\Http\Controllers\Brand\ProposalController::class, 'index'])->name('brand.proposals.index');
    Route::get('/proposals/create', [App\Http\Controllers\Brand\ProposalController::class, 'create'])->name('brand.proposals.create');
    Route::get('/proposals/{proposal}', [App\Http\Controllers\Brand\ProposalController::class, 'show'])->name('brand.proposals.show');
    Route::post('/proposals', [App\Http\Controllers\Brand\ProposalController::class, 'store'])->name('brand.proposals.store');
    Route::put('/proposals/{proposal}/accept', [App\Http\Controllers\Brand\ProposalController::class, 'accept'])->name('brand.proposals.accept');
   Route::put('/proposals/{proposal}/reject', [App\Http\Controllers\Brand\ProposalController::class, 'reject'])->name('brand.proposals.reject');
   Route::post('/proposals/{proposal}/send-contract', [App\Http\Controllers\Brand\ProposalController::class, 'sendContract'])->name('brand.proposals.send-contract');
   Route::post('/proposals/{proposal}/contract-signed', [App\Http\Controllers\Brand\ProposalController::class, 'contractSigned'])->name('brand.proposals.contract-signed');
   Route::post('/proposals/{proposal}/process-payment', [App\Http\Controllers\Brand\ProposalController::class, 'processPayment'])->name('brand.proposals.process-payment');
   Route::post('/proposals/{proposal}/mark-delivered', [App\Http\Controllers\Brand\ProposalController::class, 'markDelivered'])->name('brand.proposals.mark-delivered');
   Route::post('/proposals/{proposal}/comments', [App\Http\Controllers\Brand\ProposalController::class, 'storeComment'])->name('brand.proposals.comments.store');
   Route::get('/proposals/{proposal}/comments', [App\Http\Controllers\Brand\ProposalController::class, 'comments'])->name('brand.proposals.comments.index');
   
   // AI Proposal routes
   Route::get('/ai-proposals/create/{creatorId?}', [App\Http\Controllers\Brand\AiProposalController::class, 'create'])->name('brand.ai-proposals.create');
   Route::post('/ai-proposals', [App\Http\Controllers\Brand\AiProposalController::class, 'store'])->name('brand.ai-proposals.store');
   Route::get('/ai-proposals/{jobId}', [App\Http\Controllers\Brand\AiProposalController::class, 'show'])->name('brand.ai-proposals.show');
   Route::put('/ai-proposals/{jobId}', [App\Http\Controllers\Brand\AiProposalController::class, 'update'])->name('brand.ai-proposals.update');
   
   // Agency proposal approval routes
   Route::get('/agency-proposals/pending', [App\Http\Controllers\Brand\AiProposalController::class, 'pendingAgencyProposals'])->name('brand.agency-proposals.pending');
   Route::get('/agency-proposals/{proposal}', [App\Http\Controllers\Brand\AiProposalController::class, 'showAgencyProposal'])->name('brand.agency-proposals.show');
   Route::post('/agency-proposals/{proposal}/approve', [App\Http\Controllers\Brand\AiProposalController::class, 'approveAgencyProposal'])->name('brand.agency-proposals.approve');
   Route::post('/agency-proposals/{proposal}/reject', [App\Http\Controllers\Brand\AiProposalController::class, 'rejectAgencyProposal'])->name('brand.agency-proposals.reject');
    
    // Campaigns routes
    Route::get('/campaigns', [App\Http\Controllers\Brand\CampaignController::class, 'index'])->name('brand.campaigns.index');
    Route::get('/campaigns/create', [App\Http\Controllers\Brand\CampaignController::class, 'create'])->name('brand.campaigns.create');
    Route::get('/campaigns/{campaign}', [App\Http\Controllers\Brand\CampaignController::class, 'show'])->name('brand.campaigns.show');
    Route::get('/campaigns/{campaign}/plan', [App\Http\Controllers\Brand\CampaignController::class, 'plan'])->name('brand.campaigns.plan');
    Route::post('/campaigns', [App\Http\Controllers\Brand\CampaignController::class, 'store'])->name('brand.campaigns.store');
    Route::put('/campaigns/{campaign}', [App\Http\Controllers\Brand\CampaignController::class, 'update'])->name('brand.campaigns.update');
    
    // Campaign Planner routes
    Route::get('/campaigns/{campaign}/planner', [App\Http\Controllers\Brand\CampaignPlannerController::class, 'show'])->name('brand.campaigns.planner.show');
    Route::post('/campaigns/{campaign}/milestones', [App\Http\Controllers\Brand\CampaignPlannerController::class, 'storeMilestone'])->name('brand.campaigns.milestones.store');
    Route::put('/milestones/{milestone}', [App\Http\Controllers\Brand\CampaignPlannerController::class, 'updateMilestone'])->name('brand.campaigns.milestones.update');
    Route::delete('/milestones/{milestone}', [App\Http\Controllers\Brand\CampaignPlannerController::class, 'deleteMilestone'])->name('brand.campaigns.milestones.delete');
    Route::post('/campaigns/{campaign}/budget-allocations', [App\Http\Controllers\Brand\CampaignPlannerController::class, 'storeBudgetAllocation'])->name('brand.campaigns.budget-allocations.store');
    Route::put('/budget-allocations/{allocation}', [App\Http\Controllers\Brand\CampaignPlannerController::class, 'updateBudgetAllocation'])->name('brand.campaigns.budget-allocations.update');
    Route::delete('/budget-allocations/{allocation}', [App\Http\Controllers\Brand\CampaignPlannerController::class, 'deleteBudgetAllocation'])->name('brand.campaigns.budget-allocations.delete');
    Route::post('/campaigns/{campaign}/ai-planning', [App\Http\Controllers\Brand\CampaignPlannerController::class, 'requestAiPlanning'])->name('brand.campaigns.ai-planning.request');
    Route::get('/campaigns/{campaign}/export', [App\Http\Controllers\Brand\CampaignPlannerController::class, 'exportCampaign'])->name('brand.campaigns.export');
    
    // Analytics routes
    Route::get('/analytics', [App\Http\Controllers\Brand\AnalyticsController::class, 'index'])->name('brand.analytics.index');
    Route::get('/analytics/data', [App\Http\Controllers\Brand\AnalyticsController::class, 'data'])->name('brand.analytics.data');
    
    // Messages routes
        Route::get('/messages', [App\Http\Controllers\Brand\MessageController::class, 'index'])->name('brand.messages.index');
        Route::get('/messages/{thread}', [App\Http\Controllers\Brand\MessageController::class, 'show'])->name('brand.messages.show');
        Route::post('/messages', [App\Http\Controllers\Brand\MessageController::class, 'store'])->name('brand.messages.store');
        Route::post('/messages/{thread}/reply', [App\Http\Controllers\Brand\MessageController::class, 'reply'])->name('brand.messages.reply');
        
        // Content Ideas routes
        Route::get('/content-ideas', [App\Http\Controllers\Brand\ContentIdeaController::class, 'index'])->name('brand.content-ideas.index');
        Route::get('/content-ideas/create', [App\Http\Controllers\Brand\ContentIdeaController::class, 'create'])->name('brand.content-ideas.create');
        Route::post('/content-ideas', [App\Http\Controllers\Brand\ContentIdeaController::class, 'store'])->name('brand.content-ideas.store');
        Route::post('/content-ideas/{id}/save-to-draft', [App\Http\Controllers\Brand\ContentIdeaController::class, 'saveToDraft'])->name('brand.content-ideas.save-to-draft');
        Route::post('/content-ideas/{id}/copy', [App\Http\Controllers\Brand\ContentIdeaController::class, 'copy'])->name('brand.content-ideas.copy');
        Route::post('/content-ideas/{id}/schedule-post', [App\Http\Controllers\Brand\ContentIdeaController::class, 'schedulePost'])->name('brand.content-ideas.schedule-post');
        
        // Reels routes
        Route::get('/reels', [App\Http\Controllers\Brand\ReelController::class, 'index'])->name('brand.reels.index');
        Route::get('/reels/create', [App\Http\Controllers\Brand\ReelController::class, 'create'])->name('brand.reels.create');
        Route::post('/reels', [App\Http\Controllers\Brand\ReelController::class, 'store'])->name('brand.reels.store');
        Route::get('/reels/{reel}', [App\Http\Controllers\Brand\ReelController::class, 'show'])->name('brand.reels.show');
        Route::post('/reels/{reel}/retry', [App\Http\Controllers\Brand\ReelController::class, 'retry'])->name('brand.reels.retry');
        Route::get('/reels/{reel}/download', [App\Http\Controllers\Brand\ReelController::class, 'download'])->name('brand.reels.download');
        
        // Auto-reply routes
        Route::middleware(['ensure_brand_admin'])->group(function () {
            Route::get('/auto-replies', [App\Http\Controllers\Brand\AutoReplyController::class, 'index'])->name('brand.auto-replies.index');
            Route::get('/auto-replies/approved', [App\Http\Controllers\Brand\AutoReplyController::class, 'approved'])->name('brand.auto-replies.approved');
            Route::get('/auto-replies/posted', [App\Http\Controllers\Brand\AutoReplyController::class, 'posted'])->name('brand.auto-replies.posted');
            Route::post('/auto-replies/{id}/approve', [App\Http\Controllers\Brand\AutoReplyController::class, 'approve'])->name('brand.auto-replies.approve');
            Route::post('/auto-replies/{id}/edit', [App\Http\Controllers\Brand\AutoReplyController::class, 'edit'])->name('brand.auto-replies.edit');
            Route::post('/auto-replies/{id}/post', [App\Http\Controllers\Brand\AutoReplyController::class, 'post'])->name('brand.auto-replies.post');
            Route::post('/auto-replies/{id}/skip', [App\Http\Controllers\Brand\AutoReplyController::class, 'skip'])->name('brand.auto-replies.skip');
            
            // Auto-reply settings routes
            Route::get('/auto-replies/settings', [App\Http\Controllers\Brand\AutoReplyController::class, 'settings'])->name('brand.auto-replies.settings');
            Route::post('/auto-replies/settings', [App\Http\Controllers\Brand\AutoReplyController::class, 'updateSettings'])->name('brand.auto-replies.settings.update');
        });
        
        // Scheduled Posts routes
        Route::get('/scheduled-posts', [App\Http\Controllers\Brand\ScheduledPostController::class, 'index'])->name('brand.scheduled-posts.index');
        Route::get('/scheduled-posts/create', [App\Http\Controllers\Brand\ScheduledPostController::class, 'create'])->name('brand.scheduled-posts.create');
        Route::post('/scheduled-posts', [App\Http\Controllers\Brand\ScheduledPostController::class, 'store'])
            ->name('brand.scheduled-posts.store')
            ->middleware('throttle_social_publishing');
        Route::get('/scheduled-posts/{scheduledPost}', [App\Http\Controllers\Brand\ScheduledPostController::class, 'show'])->name('brand.scheduled-posts.show');
        Route::get('/scheduled-posts/{scheduledPost}/edit', [App\Http\Controllers\Brand\ScheduledPostController::class, 'edit'])->name('brand.scheduled-posts.edit');
        Route::put('/scheduled-posts/{scheduledPost}', [App\Http\Controllers\Brand\ScheduledPostController::class, 'update'])->name('brand.scheduled-posts.update');
        Route::delete('/scheduled-posts/{scheduledPost}', [App\Http\Controllers\Brand\ScheduledPostController::class, 'destroy'])->name('brand.scheduled-posts.destroy');
        Route::post('/scheduled-posts/{scheduledPost}/publish-now', [App\Http\Controllers\Brand\ScheduledPostController::class, 'publishNow'])->name('brand.scheduled-posts.publish-now');
        Route::post('/scheduled-posts/{scheduledPost}/reschedule', [App\Http\Controllers\Brand\ScheduledPostController::class, 'reschedule'])->name('brand.scheduled-posts.reschedule');
        Route::post('/scheduled-posts/{scheduledPost}/cancel', [App\Http\Controllers\Brand\ScheduledPostController::class, 'cancel'])->name('brand.scheduled-posts.cancel');
        Route::post('/scheduled-posts/{scheduledPost}/approve', [App\Http\Controllers\Brand\ScheduledPostController::class, 'approve'])->name('brand.scheduled-posts.approve');
        Route::post('/scheduled-posts/{scheduledPost}/deny', [App\Http\Controllers\Brand\ScheduledPostController::class, 'deny'])->name('brand.scheduled-posts.deny');
        Route::post('/scheduled-posts/{scheduledPost}/retry', [App\Http\Controllers\Brand\ScheduledPostController::class, 'retry'])->name('brand.scheduled-posts.retry');
    // Ad Manager routes
    Route::prefix('ads')->group(function () {
        Route::get('/', [App\Http\Controllers\Brand\AdManagerController::class, 'index'])->name('brand.ads.index');
        Route::get('/create', [App\Http\Controllers\Brand\AdManagerController::class, 'create'])->name('brand.ads.create');
        Route::post('/', [App\Http\Controllers\Brand\AdManagerController::class, 'store'])->name('brand.ads.store');
        Route::get('/{ad}', [App\Http\Controllers\Brand\AdManagerController::class, 'show'])->name('brand.ads.show');
        Route::get('/{ad}/edit', [App\Http\Controllers\Brand\AdManagerController::class, 'edit'])->name('brand.ads.edit');
        Route::put('/{ad}', [App\Http\Controllers\Brand\AdManagerController::class, 'update'])->name('brand.ads.update');
        Route::delete('/{ad}', [App\Http\Controllers\Brand\AdManagerController::class, 'destroy'])->name('brand.ads.destroy');
        
        // A/B Testing routes
        Route::get('/{ad}/ab-test', [App\Http\Controllers\Brand\AdManagerController::class, 'abTestDashboard'])->name('brand.ads.ab-test');
        Route::post('/{ad}/launch-variants', [App\Http\Controllers\Brand\AdManagerController::class, 'launchVariants'])->name('brand.ads.launch-variants');
        Route::post('/{ad}/pause-variants', [App\Http\Controllers\Brand\AdManagerController::class, 'pauseVariants'])->name('brand.ads.pause-variants');
        Route::post('/{ad}/regenerate-variants', [App\Http\Controllers\Brand\AdManagerController::class, 'regenerateVariants'])->name('brand.ads.regenerate-variants');
        
        // Variant management routes
        Route::post('/variants/{variant}/duplicate', [App\Http\Controllers\Brand\AdManagerController::class, 'duplicateVariant'])->name('brand.ads.variants.duplicate');
        Route::post('/variants/{variant}/promote', [App\Http\Controllers\Brand\AdManagerController::class, 'promoteWinner'])->name('brand.ads.variants.promote');
        
        // Export and metrics routes
        Route::get('/{ad}/export', [App\Http\Controllers\Brand\AdManagerController::class, 'exportResults'])->name('brand.ads.export');
        Route::get('/{ad}/metrics', [App\Http\Controllers\Brand\AdManagerController::class, 'getMetrics'])->name('brand.ads.metrics');
    });
    
    // Performance Forecasting routes
    Route::prefix('forecasts')->group(function () {
        Route::get('/', [App\Http\Controllers\Brand\PerformanceForecastController::class, 'index'])->name('brand.forecasts.index');
        Route::get('/create', [App\Http\Controllers\Brand\PerformanceForecastController::class, 'create'])->name('brand.forecasts.create');
        Route::post('/', [App\Http\Controllers\Brand\PerformanceForecastController::class, 'store'])->name('brand.forecasts.store');
        Route::get('/{forecast}', [App\Http\Controllers\Brand\PerformanceForecastController::class, 'show'])->name('brand.forecasts.show');
        Route::delete('/{forecast}', [App\Http\Controllers\Brand\PerformanceForecastController::class, 'destroy'])->name('brand.forecasts.destroy');
        
        // API endpoints for forecast data
        Route::get('/{forecast}/data', [App\Http\Controllers\Brand\PerformanceForecastController::class, 'data'])->name('brand.forecasts.data');
        Route::get('/{forecast}/status', [App\Http\Controllers\Brand\PerformanceForecastController::class, 'status'])->name('brand.forecasts.status');
        Route::get('/{forecast}/comparison', [App\Http\Controllers\Brand\PerformanceForecastController::class, 'comparison'])->name('brand.forecasts.comparison');
        Route::get('/{forecast}/export', [App\Http\Controllers\Brand\PerformanceForecastController::class, 'export'])->name('brand.forecasts.export');
        
        // Scenario comparison
        Route::post('/compare-scenarios', [App\Http\Controllers\Brand\PerformanceForecastController::class, 'compareScenarios'])->name('brand.forecasts.compare-scenarios');
    });
    
    // Competitor Insights routes
    Route::prefix('competitor-insights')->group(function () {
        Route::get('/', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'index'])->name('brand.competitor-insights.index');
        Route::get('/competitors', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'competitors'])->name('brand.competitor-insights.competitors');
        Route::post('/competitors', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'storeCompetitor'])->name('brand.competitor-insights.competitors.store');
        Route::put('/competitors/{competitor}', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'updateCompetitor'])->name('brand.competitor-insights.competitors.update');
        Route::delete('/competitors/{competitor}', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'destroyCompetitor'])->name('brand.competitor-insights.competitors.destroy');
        
        Route::get('/competitors/{competitor}', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'show'])->name('brand.competitor-insights.show');
        Route::get('/competitors/{competitor}/data', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'insightsData'])->name('brand.competitor-insights.data');
        Route::post('/competitors/{competitor}/sync', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'syncCompetitor'])->name('brand.competitor-insights.sync');
        Route::get('/competitors/{competitor}/export', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'exportInsights'])->name('brand.competitor-insights.export');
        
        Route::get('/alerts', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'alerts'])->name('brand.competitor-insights.alerts');
        Route::post('/alerts/{alert}/read', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'markAlertRead'])->name('brand.competitor-insights.alerts.read');
        Route::post('/alerts/{alert}/dismiss', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'dismissAlert'])->name('brand.competitor-insights.alerts.dismiss');
        Route::post('/alerts/bulk-read', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'bulkMarkRead'])->name('brand.competitor-insights.alerts.bulk-read');
        
        Route::get('/compare', [App\Http\Controllers\Brand\CompetitorInsightsController::class, 'compare'])->name('brand.competitor-insights.compare');
    });
    
    // Localization routes
    Route::prefix('localization')->group(function () {
        Route::get('/', [App\Http\Controllers\Brand\LocalizationController::class, 'index'])->name('brand.localization.index');
        Route::post('/', [App\Http\Controllers\Brand\LocalizationController::class, 'store'])->name('brand.localization.store');
        Route::get('/{localizedContent}', [App\Http\Controllers\Brand\LocalizationController::class, 'show'])->name('brand.localization.show');
        Route::put('/{localizedContent}', [App\Http\Controllers\Brand\LocalizationController::class, 'update'])->name('brand.localization.update');
        Route::delete('/{localizedContent}', [App\Http\Controllers\Brand\LocalizationController::class, 'destroy'])->name('brand.localization.destroy');
        
        Route::post('/{localizedContent}/approve', [App\Http\Controllers\Brand\LocalizationController::class, 'approve'])->name('brand.localization.approve');
        Route::post('/{localizedContent}/reject', [App\Http\Controllers\Brand\LocalizationController::class, 'reject'])->name('brand.localization.reject');
        Route::get('/{localizedContent}/export', [App\Http\Controllers\Brand\LocalizationController::class, 'export'])->name('brand.localization.export');
        
        Route::get('/content/localizations', [App\Http\Controllers\Brand\LocalizationController::class, 'getContentLocalizations'])->name('brand.localization.content');
        Route::get('/stats/{brand}', [App\Http\Controllers\Brand\LocalizationController::class, 'stats'])->name('brand.localization.stats');
        Route::get('/supported-locales', [App\Http\Controllers\Brand\LocalizationController::class, 'supportedLocales'])->name('brand.localization.supported-locales');
        Route::get('/supported-tones', [App\Http\Controllers\Brand\LocalizationController::class, 'supportedTones'])->name('brand.localization.supported-tones');
    
    // Customer Support Bot routes
    Route::prefix('support')->group(function () {
        // Knowledge Base Management
        Route::get('/knowledge-base', [App\Http\Controllers\Brand\KnowledgeBaseController::class, 'index'])->name('brand.support.knowledge-base.index');
        Route::post('/knowledge-base', [App\Http\Controllers\Brand\KnowledgeBaseController::class, 'store'])->name('brand.support.knowledge-base.store');
        Route::get('/knowledge-base/{document}', [App\Http\Controllers\Brand\KnowledgeBaseController::class, 'show'])->name('brand.support.knowledge-base.show');
        Route::put('/knowledge-base/{document}', [App\Http\Controllers\Brand\KnowledgeBaseController::class, 'update'])->name('brand.support.knowledge-base.update');
        Route::delete('/knowledge-base/{document}', [App\Http\Controllers\Brand\KnowledgeBaseController::class, 'destroy'])->name('brand.support.knowledge-base.destroy');
        Route::post('/knowledge-base/batch-index', [App\Http\Controllers\Brand\KnowledgeBaseController::class, 'batchIndex'])->name('brand.support.knowledge-base.batch-index');
        Route::post('/knowledge-base/{document}/reindex', [App\Http\Controllers\Brand\KnowledgeBaseController::class, 'reindex'])->name('brand.support.knowledge-base.reindex');
        Route::get('/knowledge-base/{document}/download', [App\Http\Controllers\Brand\KnowledgeBaseController::class, 'download'])->name('brand.support.knowledge-base.download');
        
        // Support Dashboard
        Route::get('/dashboard', [App\Http\Controllers\Brand\SupportDashboardController::class, 'index'])->name('brand.support.dashboard');
        Route::get('/statistics', [App\Http\Controllers\Brand\SupportDashboardController::class, 'statistics'])->name('brand.support.statistics');
        Route::get('/conversations/{conversation}', [App\Http\Controllers\Brand\SupportDashboardController::class, 'showConversation'])->name('brand.support.conversations.show');
        Route::post('/conversations/{conversation}/assign', [App\Http\Controllers\Brand\SupportDashboardController::class, 'assignAgent'])->name('brand.support.conversations.assign');
        Route::post('/conversations/{conversation}/message', [App\Http\Controllers\Brand\SupportDashboardController::class, 'sendAgentMessage'])->name('brand.support.conversations.message');
        Route::post('/conversations/{conversation}/resolve', [App\Http\Controllers\Brand\SupportDashboardController::class, 'resolveConversation'])->name('brand.support.conversations.resolve');
        
        // Bot Settings
        Route::get('/settings', [App\Http\Controllers\Brand\SupportDashboardController::class, 'getSettings'])->name('brand.support.settings');
        Route::put('/settings', [App\Http\Controllers\Brand\SupportDashboardController::class, 'updateSettings'])->name('brand.support.settings.update');
        
        // Analytics
        Route::get('/analytics', [App\Http\Controllers\Brand\SupportDashboardController::class, 'analytics'])->name('brand.support.analytics');
        Route::get('/low-confidence-topics', [App\Http\Controllers\Brand\SupportDashboardController::class, 'lowConfidenceTopics'])->name('brand.support.low-confidence-topics');
    });
    
    // Provider Credentials / Integrations routes
    Route::prefix('integrations')->group(function () {
        Route::get('/', [App\Http\Controllers\Brand\ProviderCredentialController::class, 'index'])->name('brand.integrations.index');
        Route::get('/create', [App\Http\Controllers\Brand\ProviderCredentialController::class, 'create'])->name('brand.integrations.create');
        Route::post('/', [App\Http\Controllers\Brand\ProviderCredentialController::class, 'store'])->name('brand.integrations.store');
        Route::get('/providers', [App\Http\Controllers\Brand\ProviderCredentialController::class, 'providers'])->name('brand.integrations.providers');
        Route::get('/{credential}', [App\Http\Controllers\Brand\ProviderCredentialController::class, 'show'])->name('brand.integrations.show');
        Route::put('/{credential}', [App\Http\Controllers\Brand\ProviderCredentialController::class, 'update'])->name('brand.integrations.update');
        Route::delete('/{credential}', [App\Http\Controllers\Brand\ProviderCredentialController::class, 'destroy'])->name('brand.integrations.destroy');
        Route::post('/{credential}/test', [App\Http\Controllers\Brand\ProviderCredentialController::class, 'testConnection'])->name('brand.integrations.test');
        Route::post('/{credential}/refresh-token', [App\Http\Controllers\Brand\ProviderCredentialController::class, 'refreshToken'])->name('brand.integrations.refresh-token');
    });
    });
});

// Admin routes for AI jobs
Route::prefix('admin')->middleware(['auth', 'role:superadmin'])->group(function () {
    Route::get('/ai-jobs', [App\Http\Controllers\Admin\AiJobController::class, 'index'])->name('admin.ai-jobs.index');
    Route::get('/ai-jobs/{jobId}', [App\Http\Controllers\Admin\AiJobController::class, 'show'])->name('admin.ai-jobs.show');
    Route::post('/ai-jobs/{jobId}/rerun', [App\Http\Controllers\Admin\AiJobController::class, 'rerun'])->name('admin.ai-jobs.rerun');
    Route::get('/ai-jobs/{jobId}/logs', [App\Http\Controllers\Admin\AiJobController::class, 'logs'])->name('admin.ai-jobs.logs');
});

// SuperAdmin routes for AI proposal generation
Route::prefix('superadmin')->middleware(['auth', 'role:superadmin'])->group(function () {
    Route::get('/ai-proposals', [App\Http\Controllers\SuperAdmin\AiProposalController::class, 'index'])->name('superadmin.ai-proposals.index');
    Route::get('/ai-proposals/create', [App\Http\Controllers\SuperAdmin\AiProposalController::class, 'create'])->name('superadmin.ai-proposals.create');
    Route::post('/ai-proposals', [App\Http\Controllers\SuperAdmin\AiProposalController::class, 'store'])->name('superadmin.ai-proposals.store');
    Route::post('/ai-proposals/{jobId}/rerun', [App\Http\Controllers\SuperAdmin\AiProposalController::class, 'rerun'])->name('superadmin.ai-proposals.rerun');
    Route::post('/ai-proposals/{jobId}/force-refresh', [App\Http\Controllers\SuperAdmin\AiProposalController::class, 'forceRefresh'])->name('superadmin.ai-proposals.force-refresh');
    Route::get('/ai-proposals/token-usage', [App\Http\Controllers\SuperAdmin\AiProposalController::class, 'tokenUsage'])->name('superadmin.ai-proposals.token-usage');
});

// Unified messaging routes for both brand and creator
Route::middleware(['auth', 'role:brand_admin|creator'])->group(function () {
    Route::get('/messages', [App\Http\Controllers\MessagingController::class, 'index'])->name('messages.index');
    Route::get('/messages/{thread}', [App\Http\Controllers\MessagingController::class, 'show'])->name('messages.show');
    Route::post('/messages/{thread}/send', [App\Http\Controllers\MessagingController::class, 'send'])->name('messages.send');
    Route::post('/threads/create', [App\Http\Controllers\MessagingController::class, 'createThread'])->name('threads.create');
});

// User panel routes
Route::prefix('user')->middleware(['auth', 'role:user'])->group(function () {
    Route::get('/profile', [App\Http\Controllers\User\ProfileController::class, 'show'])->name('user.profile.show');
    Route::patch('/profile', [App\Http\Controllers\User\ProfileController::class, 'edit'])->name('user.profile.edit');
    
    Route::get('/subscriptions', [App\Http\Controllers\User\SubscriptionController::class, 'index'])->name('user.subscriptions.index');
    Route::post('/subscriptions/subscribe', [App\Http\Controllers\User\SubscriptionController::class, 'subscribe'])->name('user.subscriptions.subscribe');
    
    Route::get('/library', [App\Http\Controllers\User\LibraryController::class, 'index'])->name('user.library.index');
});

// Creator panel routes
Route::prefix('creator')->middleware(['auth', 'role:creator', 'IdentifyTenant'])->group(function () {
    // Sidebar API routes
    Route::get('/api/sidebar/badges', [App\Http\Controllers\Creator\SidebarController::class, 'getBadges'])->name('creator.sidebar.badges');
    Route::get('/api/sidebar/search', [App\Http\Controllers\Creator\SidebarController::class, 'quickSearch'])->name('creator.sidebar.search');
    Route::get('/api/sidebar/stats', [App\Http\Controllers\Creator\SidebarController::class, 'getDashboardStats'])->name('creator.sidebar.stats');
    Route::post('/api/notifications/{notification}/read', [App\Http\Controllers\Creator\SidebarController::class, 'markNotificationRead'])->name('creator.notifications.read');
    Route::post('/api/notifications/read-all', [App\Http\Controllers\Creator\SidebarController::class, 'markAllNotificationsRead'])->name('creator.notifications.read-all');
    
    // Profile routes
    Route::get('/profile', [App\Http\Controllers\Creator\ProfileController::class, 'show'])->name('creator.profile.show');
    Route::get('/profile/edit', [App\Http\Controllers\Creator\ProfileController::class, 'edit'])->name('creator.profile.edit');
    Route::patch('/profile', [App\Http\Controllers\Creator\ProfileController::class, 'update'])->name('creator.profile.update');
    
    // Social Accounts routes (for sidebar navigation)
    Route::get('/social-accounts', [App\Http\Controllers\Creator\SocialConnectionController::class, 'index'])->name('creator.social-accounts.index');
    
    // Earnings routes
    Route::get('/earnings', [App\Http\Controllers\Creator\EarningsController::class, 'index'])->name('creator.earnings.index');
    Route::get('/earnings/contracts', [App\Http\Controllers\Creator\EarningsController::class, 'contracts'])->name('creator.earnings.contracts');
    Route::get('/earnings/payments', [App\Http\Controllers\Creator\EarningsController::class, 'payments'])->name('creator.earnings.payments');
    
    // Support routes
    Route::get('/support/dashboard', [App\Http\Controllers\Creator\SupportController::class, 'dashboard'])->name('creator.support.dashboard');
    Route::get('/support/tickets', [App\Http\Controllers\Creator\SupportController::class, 'tickets'])->name('creator.support.tickets');
    Route::post('/support/tickets', [App\Http\Controllers\Creator\SupportController::class, 'createTicket'])->name('creator.support.tickets.create');
    
    // Settings routes
    Route::get('/niche/edit', [App\Http\Controllers\Creator\ProfileController::class, 'editNiche'])->name('creator.niche.edit');
    Route::patch('/niche', [App\Http\Controllers\Creator\ProfileController::class, 'updateNiche'])->name('creator.niche.update');
    Route::get('/api-keys', [App\Http\Controllers\Creator\ApiKeyController::class, 'index'])->name('creator.api-keys.index');
    Route::get('/privacy/edit', [App\Http\Controllers\Creator\ProfileController::class, 'editPrivacy'])->name('creator.privacy.edit');
    Route::patch('/privacy', [App\Http\Controllers\Creator\ProfileController::class, 'updatePrivacy'])->name('creator.privacy.update');
    
    // Audit logs
    Route::get('/audit-logs', [App\Http\Controllers\Creator\AuditLogController::class, 'index'])->name('creator.audit-logs');
    
    // Existing content routes
    Route::get('/content', [App\Http\Controllers\Creator\ContentController::class, 'index'])->name('creator.content.index');
    Route::get('/content/create', [App\Http\Controllers\Creator\ContentController::class, 'create'])->name('creator.content.create');
    Route::post('/content', [App\Http\Controllers\Creator\ContentController::class, 'store'])->name('creator.content.store');
    Route::get('/content/{content}', [App\Http\Controllers\Creator\ContentController::class, 'show'])->name('creator.content.show');
    Route::get('/content/{content}/edit', [App\Http\Controllers\Creator\ContentController::class, 'edit'])->name('creator.content.edit');
    Route::put('/content/{content}', [App\Http\Controllers\Creator\ContentController::class, 'update'])->name('creator.content.update');
    Route::delete('/content/{content}', [App\Http\Controllers\Creator\ContentController::class, 'destroy'])->name('creator.content.destroy');
    
    // Social connections routes (legacy)
    Route::get('/connections', [App\Http\Controllers\Creator\SocialController::class, 'index'])->name('creator.connections.index');
    Route::get('/connections/connect/{provider}', [App\Http\Controllers\Creator\SocialController::class, 'connect'])->name('creator.connections.connect');
    Route::get('/connections/callback/{provider}', [App\Http\Controllers\Creator\SocialController::class, 'callback'])->name('creator.connections.callback');
    Route::post('/connections/manual', [App\Http\Controllers\Creator\SocialController::class, 'manualStore'])->name('creator.connections.manual');
    Route::delete('/connections/{id}', [App\Http\Controllers\Creator\SocialController::class, 'destroy'])->name('creator.connections.destroy');
    
    // New Social Connections Management routes
    Route::prefix('social-connections')->group(function () {
        Route::get('/', [App\Http\Controllers\Creator\SocialConnectionController::class, 'index'])->name('creator.social-connections.index');
        Route::get('/create', [App\Http\Controllers\Creator\SocialConnectionController::class, 'create'])->name('creator.social-connections.create');
        Route::post('/', [App\Http\Controllers\Creator\SocialConnectionController::class, 'store'])->name('creator.social-connections.store');
        Route::get('/{connection}', [App\Http\Controllers\Creator\SocialConnectionController::class, 'show'])->name('creator.social-connections.show');
        Route::put('/{connection}', [App\Http\Controllers\Creator\SocialConnectionController::class, 'update'])->name('creator.social-connections.update');
        Route::delete('/{connection}', [App\Http\Controllers\Creator\SocialConnectionController::class, 'destroy'])->name('creator.social-connections.destroy');
        
        // Connection actions
        Route::post('/{connection}/test', [App\Http\Controllers\Creator\SocialConnectionController::class, 'test'])->name('creator.social-connections.test');
        Route::post('/{connection}/refresh-token', [App\Http\Controllers\Creator\SocialConnectionController::class, 'refreshToken'])->name('creator.social-connections.refresh-token');
        
        // OAuth flow
        Route::get('/oauth/{platform}', [App\Http\Controllers\Creator\SocialConnectionController::class, 'oauth'])->name('creator.social-connections.oauth');
        Route::get('/oauth/{platform}/callback', [App\Http\Controllers\Creator\SocialConnectionController::class, 'oauthCallback'])->name('creator.social-connections.oauth.callback');
        
        // Sharing with brands
        Route::post('/{connection}/share', [App\Http\Controllers\Creator\SocialConnectionController::class, 'share'])->name('creator.social-connections.share');
        Route::post('/shared-access/{sharedAccess}/revoke', [App\Http\Controllers\Creator\SocialConnectionController::class, 'revokeAccess'])->name('creator.social-connections.revoke-access');
    });
    
    // Dashboard routes
    Route::get('/dashboard', [App\Http\Controllers\Creator\DashboardController::class, 'index'])->name('creator.dashboard');
    Route::get('/dashboard/stats', [App\Http\Controllers\Creator\DashboardController::class, 'stats'])->name('creator.dashboard.stats');
    Route::post('/dashboard/sync-now', [App\Http\Controllers\Creator\DashboardController::class, 'syncNow'])->name('creator.dashboard.sync');
    
    // Provider-specific routes
    Route::get('/provider/{provider}', [App\Http\Controllers\Creator\DashboardController::class, 'providerShow'])->name('creator.provider.show');
    
    // Providers list route
    Route::get('/providers', function () {
        // Get all providers for the current user
        $providers = App\Services\SocialProviders\ProviderFactory::getSupportedProviders();
        $userProviders = App\Models\SocialAccount::where('user_id', auth()->id())
            ->pluck('provider')
            ->toArray();
        
        return view('creator.providers.index', compact('providers', 'userProviders'));
    })->name('creator.providers.index');
    
    // Settings routes
    Route::get('/settings/social', function () {
        return view('creator.settings.social');
    })->name('creator.settings.social');
    
    Route::get('/settings/account', function () {
       return view('creator.settings.account');
   })->name('creator.settings.account');
   
   // Content Ideas routes
   Route::get('/content-ideas', [App\Http\Controllers\Creator\ContentIdeaController::class, 'index'])->name('creator.content-ideas.index');
   Route::get('/content-ideas/create', [App\Http\Controllers\Creator\ContentIdeaController::class, 'create'])->name('creator.content-ideas.create');
   Route::post('/content-ideas', [App\Http\Controllers\Creator\ContentIdeaController::class, 'store'])->name('creator.content-ideas.store')
       ->middleware('content_idea_rate_limit');
   Route::post('/content-ideas/{id}/favorite', [App\Http\Controllers\Creator\ContentIdeaController::class, 'favorite'])->name('creator.content-ideas.favorite');
   Route::post('/content-ideas/{id}/copy', [App\Http\Controllers\Creator\ContentIdeaController::class, 'copy'])->name('creator.content-ideas.copy');
   Route::post('/content-ideas/{id}/save-to-draft', [App\Http\Controllers\Creator\ContentIdeaController::class, 'saveToDraft'])->name('creator.content-ideas.save-to-draft');
   Route::post('/content-ideas/{id}/export-to-proposal', [App\Http\Controllers\Creator\ContentIdeaController::class, 'exportToProposal'])->name('creator.content-ideas.export-to-proposal');
   
   // Scheduled Posts routes
   Route::get('/scheduled-posts', [App\Http\Controllers\Creator\ScheduledPostController::class, 'index'])->name('creator.scheduled-posts.index');
   Route::get('/scheduled-posts/create', [App\Http\Controllers\Creator\ScheduledPostController::class, 'create'])->name('creator.scheduled-posts.create');
   Route::post('/scheduled-posts', [App\Http\Controllers\Creator\ScheduledPostController::class, 'store'])->name('creator.scheduled-posts.store');
   Route::get('/scheduled-posts/{scheduledPost}', [App\Http\Controllers\Creator\ScheduledPostController::class, 'show'])->name('creator.scheduled-posts.show');
   Route::get('/scheduled-posts/{scheduledPost}/edit', [App\Http\Controllers\Creator\ScheduledPostController::class, 'edit'])->name('creator.scheduled-posts.edit');
   Route::put('/scheduled-posts/{scheduledPost}', [App\Http\Controllers\Creator\ScheduledPostController::class, 'update'])->name('creator.scheduled-posts.update');
   Route::delete('/scheduled-posts/{scheduledPost}', [App\Http\Controllers\Creator\ScheduledPostController::class, 'destroy'])->name('creator.scheduled-posts.destroy');
   Route::post('/scheduled-posts/{scheduledPost}/publish-now', [App\Http\Controllers\Creator\ScheduledPostController::class, 'publishNow'])->name('creator.scheduled-posts.publish-now');
   Route::post('/scheduled-posts/{scheduledPost}/reschedule', [App\Http\Controllers\Creator\ScheduledPostController::class, 'reschedule'])->name('creator.scheduled-posts.reschedule');
   Route::post('/scheduled-posts/{scheduledPost}/cancel', [App\Http\Controllers\Creator\ScheduledPostController::class, 'cancel'])->name('creator.scheduled-posts.cancel');
   Route::post('/scheduled-posts/{scheduledPost}/duplicate', [App\Http\Controllers\Creator\ScheduledPostController::class, 'duplicate'])->name('creator.scheduled-posts.duplicate');
   Route::post('/scheduled-posts/{scheduledPost}/retry', [App\Http\Controllers\Creator\ScheduledPostController::class, 'retry'])->name('creator.scheduled-posts.retry');
   Route::post('/scheduled-posts/bulk-publish', [App\Http\Controllers\Creator\ScheduledPostController::class, 'bulkPublish'])->name('creator.scheduled-posts.bulk-publish');
});

// Agency panel routes
Route::prefix('agency')->middleware(['auth', 'role:agency'])->group(function () {
    Route::get('/', [App\Http\Controllers\Agency\DashboardController::class, 'index'])->name('agency.dashboard');
    
    // Sidebar API routes
    Route::get('/api/sidebar/badges', [App\Http\Controllers\Agency\SidebarController::class, 'getBadges'])->name('agency.sidebar.badges');
    Route::get('/api/sidebar/search', [App\Http\Controllers\Agency\SidebarController::class, 'quickSearch'])->name('agency.sidebar.search');
    Route::get('/api/sidebar/kpis', [App\Http\Controllers\Agency\SidebarController::class, 'getDashboardKPIs'])->name('agency.sidebar.kpis');
    Route::get('/api/sidebar/activity', [App\Http\Controllers\Agency\SidebarController::class, 'getRecentActivity'])->name('agency.sidebar.activity');
    
    // Managed Brands routes
    Route::get('/brands', [App\Http\Controllers\Agency\BrandController::class, 'index'])->name('agency.brands.index');
    Route::get('/brands/{brand}', [App\Http\Controllers\Agency\BrandController::class, 'show'])->name('agency.brands.show');
    Route::post('/brands/{brand}/invite', [App\Http\Controllers\Agency\BrandController::class, 'inviteBrand'])->name('agency.brands.invite');
    Route::delete('/brands/{brand}', [App\Http\Controllers\Agency\BrandController::class, 'removeBrand'])->name('agency.brands.remove');
    
    // Campaigns routes
    Route::get('/campaigns', [App\Http\Controllers\Agency\CampaignController::class, 'index'])->name('agency.campaigns.index');
    Route::get('/campaigns/create', [App\Http\Controllers\Agency\CampaignController::class, 'create'])->name('agency.campaigns.create');
    Route::post('/campaigns', [App\Http\Controllers\Agency\CampaignController::class, 'store'])->name('agency.campaigns.store');
    Route::get('/campaigns/{campaign}', [App\Http\Controllers\Agency\CampaignController::class, 'show'])->name('agency.campaigns.show');
    Route::put('/campaigns/{campaign}', [App\Http\Controllers\Agency\CampaignController::class, 'update'])->name('agency.campaigns.update');
    Route::delete('/campaigns/{campaign}', [App\Http\Controllers\Agency\CampaignController::class, 'destroy'])->name('agency.campaigns.destroy');
    
    // Proposals routes
    Route::get('/proposals', [App\Http\Controllers\Agency\ProposalController::class, 'index'])->name('agency.proposals.index');
    Route::get('/proposals/{proposal}', [App\Http\Controllers\Agency\ProposalController::class, 'show'])->name('agency.proposals.show');
    Route::post('/proposals/{proposal}/approve', [App\Http\Controllers\Agency\ProposalController::class, 'approve'])->name('agency.proposals.approve');
    Route::post('/proposals/{proposal}/reject', [App\Http\Controllers\Agency\ProposalController::class, 'reject'])->name('agency.proposals.reject');
    
    // Creators routes
    Route::get('/creators', [App\Http\Controllers\Agency\CreatorController::class, 'index'])->name('agency.creators.index');
    Route::get('/creators/{creator}', [App\Http\Controllers\Agency\CreatorController::class, 'show'])->name('agency.creators.show');
    Route::post('/creators/{creator}/invite', [App\Http\Controllers\Agency\CreatorController::class, 'invite'])->name('agency.creators.invite');
    
    // Messaging routes
    Route::get('/messages', [App\Http\Controllers\Agency\MessageController::class, 'index'])->name('agency.messages.index');
    Route::get('/messages/{thread}', [App\Http\Controllers\Agency\MessageController::class, 'show'])->name('agency.messages.show');
    Route::post('/messages', [App\Http\Controllers\Agency\MessageController::class, 'store'])->name('agency.messages.store');
    Route::post('/messages/{thread}/reply', [App\Http\Controllers\Agency\MessageController::class, 'reply'])->name('agency.messages.reply');
    
    // Analytics & Reports routes
    Route::get('/analytics', [App\Http\Controllers\Agency\AnalyticsController::class, 'index'])->name('agency.analytics.index');
    Route::get('/analytics/data', [App\Http\Controllers\Agency\AnalyticsController::class, 'data'])->name('agency.analytics.data');
    Route::get('/analytics/export', [App\Http\Controllers\Agency\AnalyticsController::class, 'export'])->name('agency.analytics.export');
    Route::get('/reports', [App\Http\Controllers\Agency\ReportsController::class, 'index'])->name('agency.reports.index');
    
    // Billing routes
    Route::get('/billing', [App\Http\Controllers\Agency\BillingController::class, 'index'])->name('agency.billing.index');
    Route::get('/billing/invoices', [App\Http\Controllers\Agency\BillingController::class, 'invoices'])->name('agency.billing.invoices');
    Route::get('/billing/payments', [App\Http\Controllers\Agency\BillingController::class, 'payments'])->name('agency.billing.payments');
    
    // Support routes
    Route::get('/support/dashboard', [App\Http\Controllers\Agency\SupportController::class, 'dashboard'])->name('agency.support.dashboard');
    Route::get('/support/tickets', [App\Http\Controllers\Agency\SupportController::class, 'tickets'])->name('agency.support.tickets');
    Route::post('/support/tickets', [App\Http\Controllers\Agency\SupportController::class, 'createTicket'])->name('agency.support.tickets.create');
    
    // Settings routes
    Route::get('/profile/edit', [App\Http\Controllers\Agency\ProfileController::class, 'edit'])->name('agency.profile.edit');
    Route::put('/profile', [App\Http\Controllers\Agency\ProfileController::class, 'update'])->name('agency.profile.update');
    Route::get('/team', [App\Http\Controllers\Agency\TeamController::class, 'index'])->name('agency.team.index');
    Route::post('/team/invite', [App\Http\Controllers\Agency\TeamController::class, 'invite'])->name('agency.team.invite');
    Route::delete('/team/{member}', [App\Http\Controllers\Agency\TeamController::class, 'remove'])->name('agency.team.remove');
    Route::get('/api-keys', [App\Http\Controllers\Agency\ApiKeyController::class, 'index'])->name('agency.api-keys.index');
    Route::post('/api-keys', [App\Http\Controllers\Agency\ApiKeyController::class, 'store'])->name('agency.api-keys.store');
    Route::delete('/api-keys/{key}', [App\Http\Controllers\Agency\ApiKeyController::class, 'destroy'])->name('agency.api-keys.destroy');
    
    // Audit logs
    Route::get('/audit-logs', [App\Http\Controllers\Agency\AuditLogController::class, 'index'])->name('agency.audit-logs.index');
    
    // AI Proposal routes
    Route::get('/ai-proposals/create/{brandId?}', [App\Http\Controllers\Agency\AiProposalController::class, 'create'])->name('agency.ai-proposals.create');
    Route::post('/ai-proposals', [App\Http\Controllers\Agency\AiProposalController::class, 'store'])->name('agency.ai-proposals.store');
    Route::get('/ai-proposals/{jobId}', [App\Http\Controllers\Agency\AiProposalController::class, 'show'])->name('agency.ai-proposals.show');
    Route::put('/ai-proposals/{jobId}', [App\Http\Controllers\Agency\AiProposalController::class, 'update'])->name('agency.ai-proposals.update');
});

// Creator panel routes for marketplace
Route::prefix('creator')->middleware(['auth', 'role:creator', 'IdentifyTenant'])->group(function () {
    // Marketplace routes
    Route::get('/marketplace', [App\Http\Controllers\Creator\MarketplaceController::class, 'index'])->name('creator.marketplace.index');
    Route::get('/marketplace/opportunities', [App\Http\Controllers\Creator\MarketplaceController::class, 'opportunities'])->name('creator.marketplace.opportunities.index');
    
    // Proposals routes
    Route::get('/proposals', [App\Http\Controllers\Creator\ProposalController::class, 'index'])->name('creator.proposals.index');
    Route::get('/proposals/create', [App\Http\Controllers\Creator\ProposalController::class, 'create'])->name('creator.proposals.create');
    Route::get('/proposals/{proposal}', [App\Http\Controllers\Creator\ProposalController::class, 'show'])->name('creator.proposals.show');
    Route::post('/proposals', [App\Http\Controllers\Creator\ProposalController::class, 'store'])->name('creator.proposals.store');
    Route::post('/proposals/{proposal}/comments', [App\Http\Controllers\Creator\ProposalController::class, 'storeComment'])->name('creator.proposals.comments.store');
    Route::get('/proposals/{proposal}/comments', [App\Http\Controllers\Creator\ProposalController::class, 'comments'])->name('creator.proposals.comments.index');
    
    // Campaigns routes
    Route::get('/campaigns', [App\Http\Controllers\Creator\CampaignController::class, 'index'])->name('creator.campaigns.index');
    Route::get('/campaigns/invitations', [App\Http\Controllers\Creator\CampaignController::class, 'invitations'])->name('creator.campaigns.invitations.index');
    Route::get('/campaigns/{campaign}', [App\Http\Controllers\Creator\CampaignController::class, 'show'])->name('creator.campaigns.show');
    
    // Campaign Planner routes
    Route::get('/campaigns/{campaign}/planner', [App\Http\Controllers\Creator\CampaignPlannerController::class, 'show'])->name('creator.campaigns.planner.show');
    Route::post('/campaigns/{campaign}/milestones', [App\Http\Controllers\Creator\CampaignPlannerController::class, 'storeMilestone'])->name('creator.campaigns.milestones.store');
    Route::put('/milestones/{milestone}', [App\Http\Controllers\Creator\CampaignPlannerController::class, 'updateMilestone'])->name('creator.campaigns.milestones.update');
    Route::delete('/milestones/{milestone}', [App\Http\Controllers\Creator\CampaignPlannerController::class, 'deleteMilestone'])->name('creator.campaigns.milestones.delete');
    Route::post('/campaigns/{campaign}/ai-planning', [App\Http\Controllers\Creator\CampaignPlannerController::class, 'requestAiPlanning'])->name('creator.campaigns.ai-planning.request');
    Route::get('/campaigns/{campaign}/export', [App\Http\Controllers\Creator\CampaignPlannerController::class, 'exportCampaign'])->name('creator.campaigns.export');
    Route::post('/campaigns/create', [App\Http\Controllers\Creator\CampaignPlannerController::class, 'createCampaign'])->name('creator.campaigns.create');
    
    // Analytics routes
    Route::get('/analytics', [App\Http\Controllers\Creator\AnalyticsController::class, 'index'])->name('creator.analytics.index');
    Route::get('/analytics/data', [App\Http\Controllers\Creator\AnalyticsController::class, 'data'])->name('creator.analytics.data');
    
    // Messages routes
    Route::get('/messages', [App\Http\Controllers\Creator\MessageController::class, 'index'])->name('creator.messages.index');
    Route::get('/messages/{thread}', [App\Http\Controllers\Creator\MessageController::class, 'show'])->name('creator.messages.show');
    Route::post('/messages', [App\Http\Controllers\Creator\MessageController::class, 'store'])->name('creator.messages.store');
    Route::post('/messages/{thread}/reply', [App\Http\Controllers\Creator\MessageController::class, 'reply'])->name('creator.messages.reply');
    
    // Reels routes
    Route::get('/reels', [App\Http\Controllers\Creator\ReelController::class, 'index'])->name('creator.reels.index');
    Route::get('/reels/create', [App\Http\Controllers\Creator\ReelController::class, 'create'])->name('creator.reels.create');
    Route::post('/reels', [App\Http\Controllers\Creator\ReelController::class, 'store'])->name('creator.reels.store');
    Route::get('/reels/{reel}', [App\Http\Controllers\Creator\ReelController::class, 'show'])->name('creator.reels.show');
    Route::post('/reels/{reel}/retry', [App\Http\Controllers\Creator\ReelController::class, 'retry'])->name('creator.reels.retry');
    Route::get('/reels/{reel}/download', [App\Http\Controllers\Creator\ReelController::class, 'download'])->name('creator.reels.download');
    
    // Auto-Replies routes
    Route::get('/auto-replies', [App\Http\Controllers\Creator\AutoReplyController::class, 'index'])->name('creator.auto-replies.index');
    Route::get('/auto-replies/settings', [App\Http\Controllers\Creator\AutoReplyController::class, 'settings'])->name('creator.auto-replies.settings');
    Route::post('/auto-replies/settings', [App\Http\Controllers\Creator\AutoReplyController::class, 'updateSettings'])->name('creator.auto-replies.settings.update');
    Route::get('/auto-replies/approved', [App\Http\Controllers\Creator\AutoReplyController::class, 'approved'])->name('creator.auto-replies.approved');
    Route::get('/auto-replies/posted', [App\Http\Controllers\Creator\AutoReplyController::class, 'posted'])->name('creator.auto-replies.posted');
    Route::post('/auto-replies/{id}/approve', [App\Http\Controllers\Creator\AutoReplyController::class, 'approve'])->name('creator.auto-replies.approve');
    Route::post('/auto-replies/{id}/edit', [App\Http\Controllers\Creator\AutoReplyController::class, 'edit'])->name('creator.auto-replies.edit');
    Route::post('/auto-replies/{id}/post', [App\Http\Controllers\Creator\AutoReplyController::class, 'post'])->name('creator.auto-replies.post');
    Route::post('/auto-replies/{id}/skip', [App\Http\Controllers\Creator\AutoReplyController::class, 'skip'])->name('creator.auto-replies.skip');
    Route::post('/auto-replies/{id}/favorite', [App\Http\Controllers\Creator\AutoReplyController::class, 'favorite'])->name('creator.auto-replies.favorite');

// Public API routes for Customer Support Bot
Route::prefix('api/support')->group(function () {
    Route::post('/conversations/start', [App\Http\Controllers\SupportBotController::class, 'startConversation'])->name('api.support.conversations.start');
    Route::get('/conversations/{conversationId}', [App\Http\Controllers\SupportBotController::class, 'getConversation'])->name('api.support.conversations.show');
    Route::post('/conversations/{conversationId}/messages', [App\Http\Controllers\SupportBotController::class, 'sendMessage'])->name('api.support.conversations.messages');
    Route::post('/messages/{messageId}/feedback', [App\Http\Controllers\SupportBotController::class, 'provideFeedback'])->name('api.support.messages.feedback');
    Route::post('/conversations/{conversationId}/request-human', [App\Http\Controllers\SupportBotController::class, 'requestHuman'])->name('api.support.conversations.request-human');
    Route::post('/conversations/{conversationId}/rate', [App\Http\Controllers\SupportBotController::class, 'rateConversation'])->name('api.support.conversations.rate');
    Route::post('/conversations/{conversationId}/close', [App\Http\Controllers\SupportBotController::class, 'closeConversation'])->name('api.support.conversations.close');
});
});

// Global messaging routes
Route::middleware(['auth', 'role:brand_admin|creator'])->group(function () {
    Route::get('/messages', [App\Http\Controllers\MessagingController::class, 'index'])->name('messages.index');
    Route::get('/messages/{thread}', [App\Http\Controllers\MessagingController::class, 'show'])->name('messages.show');
    Route::post('/messages/{thread}/send', [App\Http\Controllers\MessagingController::class, 'send'])->name('messages.send');
    Route::post('/threads/create', [App\Http\Controllers\MessagingController::class, 'createThread'])->name('threads.create');
});

// Include reels routes
require __DIR__.'/reels.php';

// API routes for reel processing callbacks
Route::post('/api/reels/callback', [App\Http\Controllers\Api\ReelController::class, 'callback'])->name('api.reels.callback');

// API routes for AI tasks
Route::get('/api/ai-tasks', [App\Http\Controllers\Api\AiTaskController::class, 'index'])->name('api.ai-tasks.index');

// API routes for scheduled posts
Route::prefix('api/scheduled-posts')->middleware(['auth', 'role:brand_admin|superadmin'])->group(function () {
    Route::get('/', [App\Http\Controllers\Api\ScheduledPostController::class, 'index'])->name('api.scheduled-posts.index');
    Route::get('/{scheduledPost}', [App\Http\Controllers\Api\ScheduledPostController::class, 'show'])->name('api.scheduled-posts.show');
    Route::post('/', [App\Http\Controllers\Api\ScheduledPostController::class, 'store'])->name('api.scheduled-posts.store');
    Route::put('/{scheduledPost}', [App\Http\Controllers\Api\ScheduledPostController::class, 'update'])->name('api.scheduled-posts.update');
    Route::delete('/{scheduledPost}', [App\Http\Controllers\Api\ScheduledPostController::class, 'destroy'])->name('api.scheduled-posts.destroy');
    Route::post('/{scheduledPost}/publish-now', [App\Http\Controllers\Api\ScheduledPostController::class, 'publishNow'])->name('api.scheduled-posts.publish-now');
    Route::post('/{scheduledPost}/reschedule', [App\Http\Controllers\Api\ScheduledPostController::class, 'reschedule'])->name('api.scheduled-posts.reschedule');
    Route::post('/{scheduledPost}/cancel', [App\Http\Controllers\Api\ScheduledPostController::class, 'cancel'])->name('api.scheduled-posts.cancel');
});

// User Subscription Routes
Route::middleware(['auth'])->group(function () {
    Route::get('subscription/plans', [App\Http\Controllers\SubscriptionController::class, 'index'])->name('subscription.plans');
    Route::get('subscription/checkout/{plan}', [App\Http\Controllers\SubscriptionController::class, 'checkout'])->name('subscription.checkout');
    Route::post('subscription/process-payment', [App\Http\Controllers\SubscriptionController::class, 'processPayment'])->name('subscription.process-payment');
    Route::get('subscription/success', [App\Http\Controllers\SubscriptionController::class, 'success'])->name('subscription.success');
    Route::get('subscription/cancel', [App\Http\Controllers\SubscriptionController::class, 'cancel'])->name('subscription.cancel');
    
    Route::middleware(['subscription'])->group(function () {
        Route::get('subscription/manage', [App\Http\Controllers\SubscriptionController::class, 'manage'])->name('subscription.manage');
        Route::post('subscription/change-plan/{plan}', [App\Http\Controllers\SubscriptionController::class, 'changePlan'])->name('subscription.change-plan');
        Route::post('subscription/cancel-subscription', [App\Http\Controllers\SubscriptionController::class, 'cancelSubscription'])->name('subscription.cancel-subscription');
        Route::post('subscription/resume-subscription', [App\Http\Controllers\SubscriptionController::class, 'resumeSubscription'])->name('subscription.resume-subscription');
        
        // Invoices
        Route::get('subscription/invoices', [App\Http\Controllers\InvoiceController::class, 'index'])->name('subscription.invoices');
        Route::get('subscription/invoices/{invoice}', [App\Http\Controllers\InvoiceController::class, 'show'])->name('subscription.invoices.show');
        Route::get('subscription/invoices/{invoice}/download', [App\Http\Controllers\InvoiceController::class, 'download'])->name('subscription.invoices.download');
    });
});

// Razorpay Webhook (no auth required)
Route::post('webhooks/razorpay', [App\Http\Controllers\WebhookController::class, 'handle'])->name('webhooks.razorpay');

require __DIR__.'/auth.php';
