<?php

use App\Http\Controllers\ProfileController;
use App\Http\Controllers\WelcomeController;
use App\Http\Controllers\ManifestController;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;

/*
|--------------------------------------------------------------------------
| Public Routes
|--------------------------------------------------------------------------
*/

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

// FASE 4: Public photo sharing routes
Route::get('/share/photo/{token}', [\App\Http\Controllers\PublicPhotoController::class, 'show'])->name('public.photo.show');
Route::post('/share/photo/{token}/like', [\App\Http\Controllers\PublicPhotoController::class, 'toggleLike'])->name('public.photo.like');
Route::post('/share/photo/{token}/comment', [\App\Http\Controllers\PublicPhotoController::class, 'addComment'])->name('public.photo.comment');

// Dynamic PWA Manifest (uses admin settings)
Route::get('/manifest.webmanifest', [ManifestController::class, 'index'])->name('manifest');

// Payment diagnostics (admin only)
Route::get('/api/payment-status', function () {
    if (!Auth::check() || !Auth::user()->isAdmin()) {
        abort(403);
    }
    $paymentService = app(\App\Services\PaymentService::class);
    return response()->json([
        'config' => $paymentService->verifyConfiguration(),
        'available_methods' => $paymentService->getAvailableMethods(),
        'settings' => [
            'stripe_enabled' => \App\Models\Setting::get('stripe_enabled'),
            'paypal_enabled' => \App\Models\Setting::get('paypal_enabled'),
            'bank_transfer_enabled' => \App\Models\Setting::get('bank_transfer_enabled'),
        ],
    ]);
})->middleware('auth');

// Static pages with friendly URLs
Route::get('/about', [\App\Http\Controllers\PageController::class, 'show'])->defaults('slug', 'about')->name('page.about');
Route::get('/terms', [\App\Http\Controllers\PageController::class, 'show'])->defaults('slug', 'terms')->name('page.terms');
Route::get('/privacy', [\App\Http\Controllers\PageController::class, 'show'])->defaults('slug', 'privacy')->name('page.privacy');
Route::get('/cookies', [\App\Http\Controllers\PageController::class, 'show'])->defaults('slug', 'cookies')->name('page.cookies');
Route::get('/refund', [\App\Http\Controllers\PageController::class, 'show'])->defaults('slug', 'refund')->name('page.refund');
Route::get('/faq', [\App\Http\Controllers\PageController::class, 'show'])->defaults('slug', 'faq')->name('page.faq');

// Legacy redirects from /page/{slug} to friendly URLs
Route::get('/page/about', fn() => redirect('/about', 301));
Route::get('/page/terms', fn() => redirect('/terms', 301));
Route::get('/page/privacy', fn() => redirect('/privacy', 301));
Route::get('/page/cookies', fn() => redirect('/cookies', 301));
Route::get('/page/refund', fn() => redirect('/refund', 301));
Route::get('/page/faq', fn() => redirect('/faq', 301));

// Fallback for page.show route (used in some existing links)
Route::get('/page/{slug}', [\App\Http\Controllers\PageController::class, 'show'])
    ->where('slug', 'about|terms|privacy|cookies|refund|faq')
    ->name('page.show');

// Dynamic pages (user-created)
Route::get('/p/{slug}', [\App\Http\Controllers\DynamicPageController::class, 'show'])->name('dynamic-page.show');

// Contact page with form
Route::get('/contacto', [\App\Http\Controllers\ContactController::class, 'index'])->name('contact');
Route::post('/contacto', [\App\Http\Controllers\ContactController::class, 'submit'])->name('contact.submit');

// Public Subscription Plans
Route::get('/planes/{plan:slug}', [\App\Http\Controllers\PlanController::class, 'show'])->name('plans.show');

// Plan purchase intent (for non-authenticated users)
Route::get('/plan-intent/{plan:slug}', [\App\Http\Controllers\PlanController::class, 'intent'])->name('plan.intent');

// Referral Code Validation (Public AJAX)
Route::post('/referral/validate', [\App\Http\Controllers\PlanController::class, 'validateReferralCode'])
    ->middleware('feature:feature_referrals')
    ->name('referral.validate');

// Blog (Public)
Route::prefix('blog')->name('blog.')->group(function () {
    Route::get('/', [\App\Http\Controllers\BlogController::class, 'index'])->name('index');
    Route::get('/categoria/{slug}', [\App\Http\Controllers\BlogController::class, 'category'])->name('category');
    Route::get('/etiqueta/{slug}', [\App\Http\Controllers\BlogController::class, 'tag'])->name('tag');
    Route::get('/{slug}', [\App\Http\Controllers\BlogController::class, 'show'])->name('show');
});

// Public Coach Plans (para que clientes compren planes)
Route::prefix('plan')->name('public.')->group(function () {
    Route::get('/{slug}', [\App\Http\Controllers\PublicCoachPlanController::class, 'show'])->name('coach-plan');
    Route::get('/{slug}/resultados', [\App\Http\Controllers\PublicCoachPlanController::class, 'results'])->name('coach-plan.results');
    Route::get('/{slug}/purchase', [\App\Http\Controllers\PublicCoachPlanController::class, 'purchase'])->name('coach-plan.purchase')->middleware('auth');
    Route::post('/{slug}/purchase', [\App\Http\Controllers\PublicCoachPlanController::class, 'processPurchase'])->name('coach-plan.process')->middleware('auth');
    Route::get('/{slug}/status/{purchase}', [\App\Http\Controllers\PublicCoachPlanController::class, 'purchaseStatus'])->name('coach-plan.status')->middleware('auth');
});

// Checkout routes (multi-payment)
Route::prefix('checkout')->name('checkout.')->group(function () {
    Route::get('/plan/{slug}/{tierId?}', [\App\Http\Controllers\CheckoutController::class, 'show'])->name('plan');
    Route::post('/plan/{slug}/purchase', [\App\Http\Controllers\CheckoutController::class, 'createPurchase'])->name('purchase');
    Route::post('/receipt', [\App\Http\Controllers\CheckoutController::class, 'uploadReceipt'])->name('receipt');
    Route::get('/status/{purchaseId}', [\App\Http\Controllers\CheckoutController::class, 'checkStatus'])->name('status');
    Route::get('/thank-you/{slug}', [\App\Http\Controllers\CheckoutController::class, 'thankYou'])->name('thank-you');
});

// Subscription expired page
Route::get('/subscription/expired', function () {
    $user = Auth::user();
    $subscription = $user?->subscriptions()
        ->with('plan')
        ->latest('end_date')
        ->first();

    $gracePeriodDays = (int) \App\Models\Setting::get('subscription_grace_period_days', 3);

    return Inertia::render('Subscription/Expired', [
        'subscription' => $subscription ? [
            'id' => $subscription->id,
            'plan_name' => $subscription->plan?->name,
            'end_date' => $subscription->end_date?->toDateString(),
            'status' => $subscription->status,
        ] : null,
        'gracePeriodDays' => $gracePeriodDays,
    ]);
})->middleware('auth')->name('subscription.expired');

// Plan Subscription Routes (para nuevos coaches)
Route::middleware(['auth', 'verified'])->prefix('subscription')->name('subscription.')->group(function () {
    Route::post('/plans/{plan:slug}/stripe', [\App\Http\Controllers\PlanController::class, 'createStripeSession'])->name('stripe.session');
    Route::post('/plans/{plan:slug}/paypal/create', [\App\Http\Controllers\PlanController::class, 'createPayPalOrder'])->name('paypal.create');
    Route::post('/plans/{plan:slug}/paypal/capture', [\App\Http\Controllers\PlanController::class, 'capturePayPalOrder'])->name('paypal.capture');
    Route::get('/success', [\App\Http\Controllers\PlanController::class, 'success'])->name('success');
    Route::get('/cancel', [\App\Http\Controllers\PlanController::class, 'cancel'])->name('cancel');
});

// Payment Webhooks (no authentication required)
Route::post('/webhooks/stripe/subscription', [\App\Http\Controllers\PlanController::class, 'handleStripeWebhook'])
    ->withoutMiddleware(['web'])
    ->name('webhooks.stripe.subscription');

// Notifications fetch endpoint (no auth required, returns empty for guests)
Route::get('/notifications/fetch', [\App\Http\Controllers\NotificationController::class, 'fetch'])->name('notifications.fetch');

// Pending approval page for coaches awaiting activation
Route::get('/pending-approval', function () {
    return Inertia::render('Auth/PendingApproval');
})->middleware('auth')->name('pending.approval');

/*
|--------------------------------------------------------------------------
| Authenticated Routes
|--------------------------------------------------------------------------
*/

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

    // Stop impersonation (available to any authenticated user when impersonating)
    Route::post('/stop-impersonating', [\App\Http\Controllers\Admin\UserController::class, 'stopImpersonating'])
        ->name('impersonate.stop');

    // Dashboard - redirects based on role
    Route::get('/dashboard', function () {
        $user = Auth::user();

        if ($user->isAdmin()) {
            return redirect()->route('admin.dashboard');
        }

        if ($user->isClient()) {
            return redirect()->route('client.dashboard');
        }

        // Coach - redirect to coach dashboard
        return redirect()->route('coach.dashboard');
    })->name('dashboard');

    // Profile routes
    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');

    // Notification routes (fetch is defined outside auth middleware)
    Route::prefix('notifications')->name('notifications.')->group(function () {
        Route::get('/', [\App\Http\Controllers\NotificationController::class, 'index'])->name('index');
        Route::post('/{id}/read', [\App\Http\Controllers\NotificationController::class, 'markAsRead'])->name('read');
        Route::post('/mark-all-read', [\App\Http\Controllers\NotificationController::class, 'markAllAsRead'])->name('read-all');
        Route::delete('/{id}', [\App\Http\Controllers\NotificationController::class, 'destroy'])->name('destroy');
        Route::delete('/', [\App\Http\Controllers\NotificationController::class, 'clearAll'])->name('clear-all');
    });

    // API: Featured Products for dashboard widgets
    Route::get('/api/products/featured', function () {
        $products = \App\Models\Product::query()
            ->where('is_active', '=', true)
            ->where('is_featured', '=', true)
            ->with('category')
            ->orderBy('sales_count', 'desc')
            ->limit(6)
            ->get();
        return response()->json(['products' => $products]);
    })->name('api.products.featured');

    // API: Products for Sale widget (random products, featured highlighted)
    Route::get('/api/products/sale', function () {
        $products = \App\Models\Product::query()
            ->where('is_active', '=', true)
            ->with('category')
            ->inRandomOrder()
            ->limit(6)
            ->get();
        return response()->json(['products' => $products]);
    })->name('api.products.sale');
});

/*
|--------------------------------------------------------------------------
| Admin Routes
|--------------------------------------------------------------------------
*/

Route::middleware(['auth', 'verified', 'role:admin'])->prefix('admin')->name('admin.')->group(function () {

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

    // Admin Chat
    Route::get('/chat', [\App\Http\Controllers\Admin\ChatController::class, 'index'])->name('chat.index');
    Route::post('/chat', [\App\Http\Controllers\Admin\ChatController::class, 'store'])->name('chat.store');

    // Settings
    Route::get('/settings', [\App\Http\Controllers\Admin\SettingsController::class, 'index'])->name('settings.index');
    Route::post('/settings/general', [\App\Http\Controllers\Admin\SettingsController::class, 'updateGeneral'])->name('settings.update.general');
    Route::post('/settings/seo', [\App\Http\Controllers\Admin\SettingsController::class, 'updateSeo'])->name('settings.update.seo');
    Route::post('/settings/email', [\App\Http\Controllers\Admin\SettingsController::class, 'updateEmail'])->name('settings.update.email');
    Route::post('/settings/pdf', [\App\Http\Controllers\Admin\SettingsController::class, 'updatePdf'])->name('settings.update.pdf');
    Route::post('/settings/payment', [\App\Http\Controllers\Admin\SettingsController::class, 'updatePayment'])->name('settings.update.payment');
    Route::post('/settings/security', [\App\Http\Controllers\Admin\SettingsController::class, 'updateSecurity'])->name('settings.update.security');
    Route::post('/settings/notifications', [\App\Http\Controllers\Admin\SettingsController::class, 'updateNotifications'])->name('settings.update.notifications');
    Route::post('/settings/cron', [\App\Http\Controllers\Admin\SettingsController::class, 'updateCron'])->name('settings.update.cron');
    Route::post('/settings/logo', [\App\Http\Controllers\Admin\SettingsController::class, 'uploadLogo'])->name('settings.logo');
    Route::post('/settings/favicon', [\App\Http\Controllers\Admin\SettingsController::class, 'uploadFavicon'])->name('settings.favicon');
    Route::post('/settings/og-image', [\App\Http\Controllers\Admin\SettingsController::class, 'uploadOgImage'])->name('settings.upload-og-image');
    Route::post('/settings/test-email', [\App\Http\Controllers\Admin\SettingsController::class, 'testEmail'])->name('settings.test-email');

    // OAuth Settings (Google Login)
    Route::get('/settings/oauth', [\App\Http\Controllers\Admin\OAuthSettingsController::class, 'index'])->name('settings.oauth');
    Route::post('/settings/oauth/google', [\App\Http\Controllers\Admin\OAuthSettingsController::class, 'updateGoogle'])->name('settings.oauth.google');
    Route::post('/settings/oauth/google/test', [\App\Http\Controllers\Admin\OAuthSettingsController::class, 'testGoogle'])->name('settings.oauth.google.test');
    Route::delete('/settings/oauth/google', [\App\Http\Controllers\Admin\OAuthSettingsController::class, 'removeGoogle'])->name('settings.oauth.google.remove');

    // PDF Settings (Advanced)
    Route::get('/settings/pdf', [\App\Http\Controllers\Admin\PdfSettingsController::class, 'index'])->name('pdf-settings.index');
    Route::post('/settings/pdf/{documentType}', [\App\Http\Controllers\Admin\PdfSettingsController::class, 'update'])->name('pdf-settings.update');
    Route::post('/settings/pdf/{documentType}/logo', [\App\Http\Controllers\Admin\PdfSettingsController::class, 'uploadLogo'])->name('pdf-settings.logo');
    Route::delete('/settings/pdf/{documentType}/logo', [\App\Http\Controllers\Admin\PdfSettingsController::class, 'removeLogo'])->name('pdf-settings.logo.remove');
    Route::post('/settings/pdf/{documentType}/reset', [\App\Http\Controllers\Admin\PdfSettingsController::class, 'reset'])->name('pdf-settings.reset');
    Route::post('/settings/pdf/copy', [\App\Http\Controllers\Admin\PdfSettingsController::class, 'copy'])->name('pdf-settings.copy');
    Route::get('/settings/pdf/{documentType}/preview', [\App\Http\Controllers\Admin\PdfSettingsController::class, 'preview'])->name('pdf-settings.preview');
    Route::get('/settings/pdf/{documentType}/sample', [\App\Http\Controllers\Admin\PdfSettingsController::class, 'sample'])->name('pdf-settings.sample');

    // Users (Coaches)
    Route::get('/users', [\App\Http\Controllers\Admin\UserController::class, 'index'])->name('users.index');
    Route::get('/users/create', [\App\Http\Controllers\Admin\UserController::class, 'create'])->name('users.create');
    Route::post('/users', [\App\Http\Controllers\Admin\UserController::class, 'store'])->name('users.store');
    Route::get('/users/{user}', [\App\Http\Controllers\Admin\UserController::class, 'show'])->name('users.show');
    Route::get('/users/{user}/edit', [\App\Http\Controllers\Admin\UserController::class, 'edit'])->name('users.edit');
    Route::put('/users/{user}', [\App\Http\Controllers\Admin\UserController::class, 'update'])->name('users.update');
    Route::get('/users/{user}/clients', [\App\Http\Controllers\Admin\UserController::class, 'clients'])->name('users.clients');
    Route::post('/users/{user}/approve', [\App\Http\Controllers\Admin\UserController::class, 'approve'])->name('users.approve');
    Route::post('/users/{user}/suspend', [\App\Http\Controllers\Admin\UserController::class, 'suspend'])->name('users.suspend');
    Route::post('/users/{user}/reactivate', [\App\Http\Controllers\Admin\UserController::class, 'reactivate'])->name('users.reactivate');
    Route::post('/users/{user}/assign-plan', [\App\Http\Controllers\Admin\UserController::class, 'assignPlan'])->name('users.assign-plan');
    Route::post('/users/{user}/impersonate', [\App\Http\Controllers\Admin\UserController::class, 'impersonate'])->name('users.impersonate');
    Route::delete('/users/{user}', [\App\Http\Controllers\Admin\UserController::class, 'destroy'])->name('users.destroy');

    // Moderators (Admin Users)
    Route::resource('moderators', \App\Http\Controllers\Admin\ModeratorController::class)->except(['show']);

    // Plans
    Route::resource('plans', \App\Http\Controllers\Admin\PlanController::class);
    Route::post('/plans/{plan}/toggle', [\App\Http\Controllers\Admin\PlanController::class, 'toggleActiveStatus'])->name('plans.toggle');
    Route::post('/plans/{plan}/toggle-featured', [\App\Http\Controllers\Admin\PlanController::class, 'toggleFeatured'])->name('plans.toggle-featured');

    // Foods - Import/Export routes MUST be before resource to avoid conflict with {food} parameter
    Route::post('/foods/import', [\App\Http\Controllers\Admin\FoodController::class, 'import'])->name('foods.import');
    Route::get('/foods/export', [\App\Http\Controllers\Admin\FoodController::class, 'export'])->name('foods.export');
    Route::resource('foods', \App\Http\Controllers\Admin\FoodController::class);

    // Email Templates
    Route::get('/email-templates', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'index'])->name('email-templates.index');
    Route::get('/email-templates/{emailTemplate}/edit', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'edit'])->name('email-templates.edit');
    Route::put('/email-templates/{emailTemplate}', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'update'])->name('email-templates.update');
    Route::get('/email-templates/{emailTemplate}/preview', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'preview'])->name('email-templates.preview');
    Route::post('/email-templates/{emailTemplate}/test', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'sendTest'])->name('email-templates.test');
    Route::post('/email-templates/reset', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'reset'])->name('email-templates.reset');

    // Static Pages (legacy)
    Route::get('/pages', [\App\Http\Controllers\Admin\DynamicPageController::class, 'index'])->name('pages.index');

    // Static pages editing
    Route::get('/pages/static/{slug}/edit', [\App\Http\Controllers\Admin\DynamicPageController::class, 'editStatic'])->name('static-pages.edit');
    Route::put('/pages/static/{slug}', [\App\Http\Controllers\Admin\DynamicPageController::class, 'updateStatic'])->name('static-pages.update');

    // Dynamic pages CRUD
    Route::get('/pages/create', [\App\Http\Controllers\Admin\DynamicPageController::class, 'create'])->name('dynamic-pages.create');
    Route::post('/pages', [\App\Http\Controllers\Admin\DynamicPageController::class, 'store'])->name('dynamic-pages.store');
    Route::get('/pages/{page}/edit', [\App\Http\Controllers\Admin\DynamicPageController::class, 'edit'])->name('dynamic-pages.edit');
    Route::put('/pages/{page}', [\App\Http\Controllers\Admin\DynamicPageController::class, 'update'])->name('dynamic-pages.update');
    Route::post('/pages/{page}/toggle', [\App\Http\Controllers\Admin\DynamicPageController::class, 'toggle'])->name('dynamic-pages.toggle');
    Route::post('/pages/{page}/toggle-visibility', [\App\Http\Controllers\Admin\DynamicPageController::class, 'toggleVisibility'])->name('dynamic-pages.toggle-visibility');
    Route::delete('/pages/{page}', [\App\Http\Controllers\Admin\DynamicPageController::class, 'destroy'])->name('dynamic-pages.destroy');
    Route::post('/pages/reorder', [\App\Http\Controllers\Admin\DynamicPageController::class, 'reorder'])->name('dynamic-pages.reorder');

    // Banks (Pago Offline RD)
    Route::resource('banks', \App\Http\Controllers\Admin\BankController::class);
    Route::post('/banks/{bank}/toggle', [\App\Http\Controllers\Admin\BankController::class, 'toggleStatus'])->name('banks.toggle');
    Route::post('/banks/order', [\App\Http\Controllers\Admin\BankController::class, 'updateOrder'])->name('banks.order');

    // Landing Page Editor
    Route::prefix('landing')->name('landing.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\LandingController::class, 'index'])->name('index');
        Route::post('/settings', [\App\Http\Controllers\Admin\LandingController::class, 'updateSettings'])->name('settings.update');
        Route::post('/upload-image', [\App\Http\Controllers\Admin\LandingController::class, 'uploadImage'])->name('upload-image');
        Route::get('/preview', [\App\Http\Controllers\Admin\LandingController::class, 'preview'])->name('preview');

        // Features CRUD
        Route::post('/features', [\App\Http\Controllers\Admin\LandingController::class, 'storeFeature'])->name('features.store');
        Route::put('/features/{feature}', [\App\Http\Controllers\Admin\LandingController::class, 'updateFeature'])->name('features.update');
        Route::delete('/features/{feature}', [\App\Http\Controllers\Admin\LandingController::class, 'destroyFeature'])->name('features.destroy');
        Route::post('/features/reorder', [\App\Http\Controllers\Admin\LandingController::class, 'reorderFeatures'])->name('features.reorder');

        // Testimonials CRUD (admin created)
        Route::post('/testimonials', [\App\Http\Controllers\Admin\LandingController::class, 'storeTestimonial'])->name('testimonials.store');
        Route::put('/testimonials/{testimonial}', [\App\Http\Controllers\Admin\LandingController::class, 'updateTestimonial'])->name('testimonials.update');
        Route::delete('/testimonials/{testimonial}', [\App\Http\Controllers\Admin\LandingController::class, 'destroyTestimonial'])->name('testimonials.destroy');
        Route::post('/testimonials/{testimonial}/approve', [\App\Http\Controllers\Admin\LandingController::class, 'approveTestimonial'])->name('testimonials.approve');
        Route::post('/testimonials/{testimonial}/reject', [\App\Http\Controllers\Admin\LandingController::class, 'rejectTestimonial'])->name('testimonials.reject');

        // Stats CRUD
        Route::post('/stats', [\App\Http\Controllers\Admin\LandingController::class, 'storeStat'])->name('stats.store');
        Route::put('/stats/{stat}', [\App\Http\Controllers\Admin\LandingController::class, 'updateStat'])->name('stats.update');
        Route::delete('/stats/{stat}', [\App\Http\Controllers\Admin\LandingController::class, 'destroyStat'])->name('stats.destroy');

        // Social Links CRUD
        Route::post('/social-links', [\App\Http\Controllers\Admin\LandingController::class, 'storeSocialLink'])->name('social-links.store');
        Route::put('/social-links/{socialLink}', [\App\Http\Controllers\Admin\LandingController::class, 'updateSocialLink'])->name('social-links.update');
        Route::delete('/social-links/{socialLink}', [\App\Http\Controllers\Admin\LandingController::class, 'destroySocialLink'])->name('social-links.destroy');
    });

    // Testimonials Approval (from coaches)
    Route::prefix('testimonials-approval')->name('testimonials-approval.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\TestimonialApprovalController::class, 'index'])->name('index');
        Route::post('/{testimonial}/approve', [\App\Http\Controllers\Admin\TestimonialApprovalController::class, 'approve'])->name('approve');
        Route::post('/{testimonial}/reject', [\App\Http\Controllers\Admin\TestimonialApprovalController::class, 'reject'])->name('reject');
        Route::post('/{testimonial}/toggle', [\App\Http\Controllers\Admin\TestimonialApprovalController::class, 'toggleActive'])->name('toggle');
        Route::post('/reorder', [\App\Http\Controllers\Admin\TestimonialApprovalController::class, 'reorder'])->name('reorder');
        Route::delete('/{testimonial}', [\App\Http\Controllers\Admin\TestimonialApprovalController::class, 'destroy'])->name('destroy');
    });

    // Broadcast Notifications
    Route::get('/broadcast', [\App\Http\Controllers\Admin\BroadcastController::class, 'index'])->name('broadcast.index');
    Route::post('/broadcast', [\App\Http\Controllers\Admin\BroadcastController::class, 'send'])->name('broadcast.send');

    // PWA & Features Settings
    Route::post('/settings/pwa', [\App\Http\Controllers\Admin\SettingsController::class, 'updatePwa'])->name('settings.update.pwa');
    Route::post('/settings/pwa-icon', [\App\Http\Controllers\Admin\SettingsController::class, 'uploadPwaIcon'])->name('settings.pwa-icon');
    Route::post('/settings/pwa-apple-icon', [\App\Http\Controllers\Admin\SettingsController::class, 'uploadAppleTouchIcon'])->name('settings.pwa-apple-icon');
    Route::post('/settings/pwa-splash', [\App\Http\Controllers\Admin\SettingsController::class, 'uploadPwaSplash'])->name('settings.pwa-splash');
    Route::post('/settings/features', [\App\Http\Controllers\Admin\SettingsController::class, 'updateFeatures'])->name('settings.update.features');

    // Blog Management
    Route::resource('posts', \App\Http\Controllers\Admin\PostController::class);
    Route::post('/posts/upload-image', [\App\Http\Controllers\Admin\PostController::class, 'uploadImage'])->name('posts.upload-image');
    Route::resource('categories', \App\Http\Controllers\Admin\CategoryController::class)->except(['show', 'create', 'edit']);
    Route::resource('tags', \App\Http\Controllers\Admin\TagController::class)->except(['show', 'create', 'edit']);

    // Subscriptions Management
    Route::prefix('subscriptions')->name('subscriptions.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\SubscriptionController::class, 'index'])->name('index');
        Route::get('/{subscription}', [\App\Http\Controllers\Admin\SubscriptionController::class, 'show'])->name('show');
        Route::post('/{subscription}/update-status', [\App\Http\Controllers\Admin\SubscriptionController::class, 'updateStatus'])->name('update-status');
        Route::post('/{subscription}/confirm-payment', [\App\Http\Controllers\Admin\SubscriptionController::class, 'confirmPayment'])->name('confirm-payment');
        Route::post('/{subscription}/change-plan', [\App\Http\Controllers\Admin\SubscriptionController::class, 'changePlan'])->name('change-plan');
        Route::post('/{subscription}/extend', [\App\Http\Controllers\Admin\SubscriptionController::class, 'extend'])->name('extend');
        Route::post('/{subscription}/cancel', [\App\Http\Controllers\Admin\SubscriptionController::class, 'cancel'])->name('cancel');
        Route::get('/{subscription}/audit-logs', [\App\Http\Controllers\Admin\SubscriptionController::class, 'auditLogs'])->name('audit-logs');
    });

    // Invoices/Payments Management
    Route::prefix('invoices')->name('invoices.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\InvoiceController::class, 'index'])->name('index');
        Route::get('/export', [\App\Http\Controllers\Admin\InvoiceController::class, 'export'])->name('export');
        Route::delete('/bulk-delete', [\App\Http\Controllers\Admin\InvoiceController::class, 'bulkDelete'])->name('bulk-delete');
        Route::get('/{invoice}', [\App\Http\Controllers\Admin\InvoiceController::class, 'show'])->name('show');
        Route::get('/{invoice}/download', [\App\Http\Controllers\Admin\InvoiceController::class, 'download'])->name('download');
        Route::post('/{invoice}/mark-paid', [\App\Http\Controllers\Admin\InvoiceController::class, 'markAsPaid'])->name('mark-paid');
        Route::post('/{invoice}/cancel', [\App\Http\Controllers\Admin\InvoiceController::class, 'cancel'])->name('cancel');
        Route::delete('/{invoice}', [\App\Http\Controllers\Admin\InvoiceController::class, 'destroy'])->name('destroy');
    });

    // Referral Program Management
    Route::prefix('referrals')->name('referrals.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\ReferralController::class, 'index'])->name('index');
        Route::get('/settings', [\App\Http\Controllers\Admin\ReferralController::class, 'settings'])->name('settings');
        Route::post('/settings', [\App\Http\Controllers\Admin\ReferralController::class, 'updateSettings'])->name('settings.update');
        Route::get('/{referral}', [\App\Http\Controllers\Admin\ReferralController::class, 'show'])->name('show');
        Route::post('/{referral}/approve', [\App\Http\Controllers\Admin\ReferralController::class, 'approve'])->name('approve');
        Route::post('/{referral}/reject', [\App\Http\Controllers\Admin\ReferralController::class, 'reject'])->name('reject');
    });

    // Wallet Transactions Management
    Route::prefix('wallets')->name('wallets.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\WalletController::class, 'index'])->name('index');
        Route::get('/{wallet}', [\App\Http\Controllers\Admin\WalletController::class, 'show'])->name('show');
        Route::post('/transactions/{transaction}/approve', [\App\Http\Controllers\Admin\WalletController::class, 'approveTransaction'])->name('transactions.approve');
        Route::post('/transactions/{transaction}/reject', [\App\Http\Controllers\Admin\WalletController::class, 'rejectTransaction'])->name('transactions.reject');
    });

    // Support Settings (Email and FAQs)
    Route::prefix('support')->name('support.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\SupportSettingsController::class, 'index'])->name('index');
        Route::put('/email', [\App\Http\Controllers\Admin\SupportSettingsController::class, 'updateEmail'])->name('update-email');
        Route::post('/faq', [\App\Http\Controllers\Admin\SupportSettingsController::class, 'storeFaq'])->name('faq.store');
        Route::put('/faq/{faq}', [\App\Http\Controllers\Admin\SupportSettingsController::class, 'updateFaq'])->name('faq.update');
        Route::delete('/faq/{faq}', [\App\Http\Controllers\Admin\SupportSettingsController::class, 'destroyFaq'])->name('faq.destroy');
        Route::post('/faq/reorder', [\App\Http\Controllers\Admin\SupportSettingsController::class, 'reorderFaqs'])->name('faq.reorder');
    });

    // Admin Delete Functions for Coach Data
    Route::prefix('coaches/{user}')->name('coaches.')->group(function () {
        Route::delete('/invoices', [\App\Http\Controllers\Admin\UserController::class, 'deleteInvoices'])->name('delete-invoices');
        Route::delete('/messages', [\App\Http\Controllers\Admin\UserController::class, 'deleteMessages'])->name('delete-messages');
        Route::delete('/transactions', [\App\Http\Controllers\Admin\UserController::class, 'deleteTransactions'])->name('delete-transactions');
    });

    // Store Management
    Route::prefix('store')->name('store.')->group(function () {
        // Products
        Route::get('/products', [\App\Http\Controllers\Admin\ProductController::class, 'index'])->name('products.index');
        Route::get('/products/create', [\App\Http\Controllers\Admin\ProductController::class, 'create'])->name('products.create');
        Route::post('/products', [\App\Http\Controllers\Admin\ProductController::class, 'store'])->name('products.store');
        Route::get('/products/{product}/edit', [\App\Http\Controllers\Admin\ProductController::class, 'edit'])->name('products.edit');
        Route::put('/products/{product}', [\App\Http\Controllers\Admin\ProductController::class, 'update'])->name('products.update');
        Route::delete('/products/{product}', [\App\Http\Controllers\Admin\ProductController::class, 'destroy'])->name('products.destroy');
        Route::post('/products/{product}/toggle', [\App\Http\Controllers\Admin\ProductController::class, 'toggleStatus'])->name('products.toggle');
        Route::post('/products/{product}/featured', [\App\Http\Controllers\Admin\ProductController::class, 'toggleFeatured'])->name('products.featured');

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

        // Coupons
        Route::get('/coupons', [\App\Http\Controllers\Admin\CouponController::class, 'index'])->name('coupons.index');
        Route::post('/coupons', [\App\Http\Controllers\Admin\CouponController::class, 'store'])->name('coupons.store');
        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');

        // Orders
        Route::get('/orders', [\App\Http\Controllers\Admin\OrderController::class, 'index'])->name('orders.index');
        Route::post('/orders/bulk-cancel', [\App\Http\Controllers\Admin\OrderController::class, 'bulkCancel'])->name('orders.bulk-cancel');
        Route::delete('/orders/bulk-delete', [\App\Http\Controllers\Admin\OrderController::class, 'bulkDelete'])->name('orders.bulk-delete');
        Route::get('/orders/{order}', [\App\Http\Controllers\Admin\OrderController::class, 'show'])->name('orders.show');
        Route::post('/orders/{order}/status', [\App\Http\Controllers\Admin\OrderController::class, 'updateStatus'])->name('orders.status');
        Route::post('/orders/{order}/paid', [\App\Http\Controllers\Admin\OrderController::class, 'markAsPaid'])->name('orders.paid');
        Route::delete('/orders/{order}', [\App\Http\Controllers\Admin\OrderController::class, 'destroy'])->name('orders.destroy');

        // Store Settings
        Route::get('/settings', [\App\Http\Controllers\Admin\StoreSettingsController::class, 'index'])->name('settings.index');
        Route::put('/settings/general', [\App\Http\Controllers\Admin\StoreSettingsController::class, 'updateGeneral'])->name('settings.general');
        Route::put('/settings/shipping', [\App\Http\Controllers\Admin\StoreSettingsController::class, 'updateShipping'])->name('settings.shipping');
        Route::put('/settings/tax', [\App\Http\Controllers\Admin\StoreSettingsController::class, 'updateTax'])->name('settings.tax');

        // Shipping Zones
        Route::post('/settings/shipping-zones', [\App\Http\Controllers\Admin\StoreSettingsController::class, 'addShippingZone'])->name('settings.shipping-zones.store');
        Route::put('/settings/shipping-zones/{shippingZone}', [\App\Http\Controllers\Admin\StoreSettingsController::class, 'updateShippingZone'])->name('settings.shipping-zones.update');
        Route::delete('/settings/shipping-zones/{shippingZone}', [\App\Http\Controllers\Admin\StoreSettingsController::class, 'deleteShippingZone'])->name('settings.shipping-zones.destroy');
    });
});

/*
|--------------------------------------------------------------------------
| Coach Routes - Payment & Subscription (No subscription required)
|--------------------------------------------------------------------------
| These routes are accessible to authenticated coaches WITHOUT active subscription
| This allows new users to purchase plans after registration
*/

Route::middleware(['auth', 'role:coach'])->prefix('coach')->name('coach.')->group(function () {
    // Payment Routes - No subscription or email verification required
    Route::get('/subscription/plans/{plan:slug}/checkout', [\App\Http\Controllers\Coach\PaymentController::class, 'checkout'])->name('subscription.show');
    Route::post('/subscription/plans/{plan:slug}/process', [\App\Http\Controllers\Coach\PaymentController::class, 'process'])->name('subscription.process');
    Route::get('/payment/stripe/success/{payment}', [\App\Http\Controllers\Coach\PaymentController::class, 'stripeSuccess'])->name('payment.stripe.success');
    Route::get('/payment/stripe/cancel/{payment}', [\App\Http\Controllers\Coach\PaymentController::class, 'stripeCancel'])->name('payment.stripe.cancel');
    Route::get('/payment/paypal/success/{payment}', [\App\Http\Controllers\Coach\PaymentController::class, 'paypalSuccess'])->name('payment.paypal.success');
    Route::get('/payment/paypal/cancel/{payment}', [\App\Http\Controllers\Coach\PaymentController::class, 'paypalCancel'])->name('payment.paypal.cancel');
});

/*
|--------------------------------------------------------------------------
| Coach Routes - Main (Subscription required)
|--------------------------------------------------------------------------
*/

Route::middleware(['auth', 'verified', 'role:coach', 'subscription'])->prefix('coach')->name('coach.')->group(function () {

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

    // Clients
    Route::resource('clients', \App\Http\Controllers\Coach\ClientController::class);
    Route::post('/clients/{client}/toggle', [\App\Http\Controllers\Coach\ClientController::class, 'toggleActive'])->name('clients.toggle');
    Route::middleware(['feature:feature_client_portal'])->group(function () {
        Route::post('/clients/{client}/portal/activate', [\App\Http\Controllers\Coach\ClientPortalController::class, 'activate'])->name('clients.portal.activate');
        Route::post('/clients/{client}/portal/deactivate', [\App\Http\Controllers\Coach\ClientPortalController::class, 'deactivate'])->name('clients.portal.deactivate');
        Route::post('/clients/{client}/portal/resend', [\App\Http\Controllers\Coach\ClientPortalController::class, 'resendCredentials'])->name('clients.portal.resend');
    });

    // Workouts (nested under clients)
    Route::resource('clients.workouts', \App\Http\Controllers\Coach\WorkoutController::class);
    Route::post('/clients/{client}/workouts/{workout}/toggle', [\App\Http\Controllers\Coach\WorkoutController::class, 'toggleActive'])->name('clients.workouts.toggle');
    Route::post('/clients/{client}/workouts/{workout}/duplicate', [\App\Http\Controllers\Coach\WorkoutController::class, 'duplicate'])->name('clients.workouts.duplicate');

    // Workout Templates (coach-level, not client-specific)
    Route::get('/workouts', [\App\Http\Controllers\Coach\WorkoutTemplateController::class, 'index'])->name('workouts.index');
    Route::get('/workouts/create', [\App\Http\Controllers\Coach\WorkoutTemplateController::class, 'create'])->name('workouts.create');
    Route::post('/workouts', [\App\Http\Controllers\Coach\WorkoutTemplateController::class, 'store'])->name('workouts.store');
    Route::get('/workouts/{workout}/edit', [\App\Http\Controllers\Coach\WorkoutTemplateController::class, 'edit'])->name('workouts.edit');
    Route::put('/workouts/{workout}', [\App\Http\Controllers\Coach\WorkoutTemplateController::class, 'update'])->name('workouts.update');
    Route::delete('/workouts/{workout}', [\App\Http\Controllers\Coach\WorkoutTemplateController::class, 'destroy'])->name('workouts.destroy');

    // Meal Plans (nested under clients)
    Route::resource('clients.meal-plans', \App\Http\Controllers\Coach\MealPlanController::class);
    Route::post('/clients/{client}/meal-plans/{meal_plan}/toggle', [\App\Http\Controllers\Coach\MealPlanController::class, 'toggleActive'])->name('clients.meal-plans.toggle');
    Route::post('/clients/{client}/meal-plans/{meal_plan}/duplicate', [\App\Http\Controllers\Coach\MealPlanController::class, 'duplicate'])->name('clients.meal-plans.duplicate');
    Route::post('/clients/{client}/meal-plans/{meal_plan}/add-diet-plan', [\App\Http\Controllers\Coach\MealPlanController::class, 'addDietPlan'])->name('clients.meal-plans.add-diet-plan');
    Route::delete('/clients/{client}/meal-plans/{meal_plan}/diet-plans/{diet_plan}', [\App\Http\Controllers\Coach\MealPlanController::class, 'deleteDietPlan'])->name('clients.meal-plans.diet-plans.destroy');

    // Meal Plan Templates (coach-level, not client-specific)
    Route::get('/meal-plans', [\App\Http\Controllers\Coach\MealPlanTemplateController::class, 'index'])->name('meal-plans.index');
    Route::get('/meal-plans/create', [\App\Http\Controllers\Coach\MealPlanTemplateController::class, 'create'])->name('meal-plans.create');
    Route::post('/meal-plans', [\App\Http\Controllers\Coach\MealPlanTemplateController::class, 'store'])->name('meal-plans.store');
    Route::get('/meal-plans/{mealPlan}/edit', [\App\Http\Controllers\Coach\MealPlanTemplateController::class, 'edit'])->name('meal-plans.edit');
    Route::put('/meal-plans/{mealPlan}', [\App\Http\Controllers\Coach\MealPlanTemplateController::class, 'update'])->name('meal-plans.update');
    Route::delete('/meal-plans/{mealPlan}', [\App\Http\Controllers\Coach\MealPlanTemplateController::class, 'destroy'])->name('meal-plans.destroy');

    // Exercises Library
    Route::get('/exercises', [\App\Http\Controllers\Coach\ExerciseController::class, 'index'])->name('exercises.index');
    Route::get('/exercises/create', [\App\Http\Controllers\Coach\ExerciseController::class, 'create'])->name('exercises.create');
    Route::post('/exercises', [\App\Http\Controllers\Coach\ExerciseController::class, 'store'])->name('exercises.store');
    Route::get('/exercises/{exercise_library}/edit', [\App\Http\Controllers\Coach\ExerciseController::class, 'edit'])->name('exercises.edit');
    Route::put('/exercises/{exercise_library}', [\App\Http\Controllers\Coach\ExerciseController::class, 'update'])->name('exercises.update');
    Route::delete('/exercises/{exercise_library}', [\App\Http\Controllers\Coach\ExerciseController::class, 'destroy'])->name('exercises.destroy');

    // Foods Library
    Route::middleware(['feature:feature_custom_foods'])->group(function () {
        Route::get('/foods', [\App\Http\Controllers\Coach\FoodController::class, 'index'])->name('foods.index');
        Route::get('/foods/create', [\App\Http\Controllers\Coach\FoodController::class, 'create'])->name('foods.create');
        Route::post('/foods', [\App\Http\Controllers\Coach\FoodController::class, 'store'])->name('foods.store');
        Route::get('/foods/{food}/edit', [\App\Http\Controllers\Coach\FoodController::class, 'edit'])->name('foods.edit');
        Route::put('/foods/{food}', [\App\Http\Controllers\Coach\FoodController::class, 'update'])->name('foods.update');
        Route::delete('/foods/{food}', [\App\Http\Controllers\Coach\FoodController::class, 'destroy'])->name('foods.destroy');
    });

    // Subscription Management (requires active subscription for viewing invoices)
    Route::get('/subscription', [\App\Http\Controllers\Coach\SubscriptionController::class, 'index'])->name('subscription.index');
    Route::get('/subscription/invoices', [\App\Http\Controllers\Coach\SubscriptionController::class, 'invoices'])->name('subscription.invoices');
    Route::get('/subscription/invoices/{invoice}/download', [\App\Http\Controllers\Coach\PdfController::class, 'invoice'])->name('subscription.invoice.download');
    Route::get('/subscription/pending/{invoice}', [\App\Http\Controllers\Coach\SubscriptionController::class, 'paymentPending'])->name('subscription.payment-pending');

    // PDF Downloads
    Route::middleware(['feature:feature_pdf_export'])->group(function () {
        Route::get('/clients/{client}/workouts/{workout}/pdf', [\App\Http\Controllers\Coach\PdfController::class, 'workout'])->name('clients.workouts.pdf');
        Route::get('/clients/{client}/meal-plans/{meal_plan}/pdf', [\App\Http\Controllers\Coach\PdfController::class, 'mealPlan'])->name('clients.meal-plans.pdf');

        // PDF Preview (inline viewing)
        Route::get('/clients/{client}/workouts/{workout}/pdf/preview', [\App\Http\Controllers\Coach\PdfController::class, 'previewWorkout'])->name('clients.workouts.pdf.preview');
        Route::get('/clients/{client}/meal-plans/{meal_plan}/pdf/preview', [\App\Http\Controllers\Coach\PdfController::class, 'previewMealPlan'])->name('clients.meal-plans.pdf.preview');
    });


    // Chat
    Route::middleware(['feature:feature_chat'])->group(function () {
        Route::get('/chat', [\App\Http\Controllers\Coach\ChatController::class, 'index'])->name('chat.index');
        Route::post('/chat', [\App\Http\Controllers\Coach\ChatController::class, 'store'])->name('chat.store');
    });

    // Wallet
    Route::middleware(['feature:feature_wallet'])->group(function () {
        Route::get('/wallet', [\App\Http\Controllers\Coach\WalletController::class, 'index'])->name('wallet.index');
        Route::post('/wallet/withdraw', [\App\Http\Controllers\Coach\WalletController::class, 'withdraw'])->name('wallet.withdraw');
        Route::post('/wallet/recharge', [\App\Http\Controllers\Coach\WalletController::class, 'recharge'])->name('wallet.recharge');
        Route::get('/wallet/recharge/stripe/success', [\App\Http\Controllers\Coach\WalletController::class, 'stripeSuccess'])->name('wallet.stripe.success');
        Route::get('/wallet/recharge/stripe/cancel', [\App\Http\Controllers\Coach\WalletController::class, 'stripeCancel'])->name('wallet.stripe.cancel');
        Route::get('/wallet/recharge/paypal/success', [\App\Http\Controllers\Coach\WalletController::class, 'paypalSuccess'])->name('wallet.paypal.success');
        Route::get('/wallet/recharge/paypal/cancel', [\App\Http\Controllers\Coach\WalletController::class, 'paypalCancel'])->name('wallet.paypal.cancel');
    });

    // Coach Plans (planes para vender a clientes)
    Route::get('/my-plans', [\App\Http\Controllers\Coach\CoachPlanController::class, 'index'])->name('plans.index');
    Route::get('/my-plans/create', [\App\Http\Controllers\Coach\CoachPlanController::class, 'create'])->name('plans.create');
    Route::post('/my-plans', [\App\Http\Controllers\Coach\CoachPlanController::class, 'store'])->name('plans.store');
    Route::get('/my-plans/{plan}', [\App\Http\Controllers\Coach\CoachPlanController::class, 'show'])->name('plans.show');
    Route::get('/my-plans/{plan}/edit', [\App\Http\Controllers\Coach\CoachPlanController::class, 'edit'])->name('plans.edit');
    Route::put('/my-plans/{plan}', [\App\Http\Controllers\Coach\CoachPlanController::class, 'update'])->name('plans.update');
    Route::delete('/my-plans/{plan}', [\App\Http\Controllers\Coach\CoachPlanController::class, 'destroy'])->name('plans.destroy');
    Route::get('/my-plans/{plan}/public-link', [\App\Http\Controllers\Coach\CoachPlanController::class, 'publicLink'])->name('plans.public-link');
    Route::post('/my-plans/{plan}/results', [\App\Http\Controllers\Coach\CoachPlanController::class, 'uploadResultImage'])->name('plans.results.upload');
    Route::post('/my-plans/{plan}/results/{index}/after', [\App\Http\Controllers\Coach\CoachPlanController::class, 'updateResultAfterImage'])->name('plans.results.after');
    Route::put('/my-plans/{plan}/results/{resultId}', [\App\Http\Controllers\Coach\CoachPlanController::class, 'updateResult'])->name('plans.results.update');
    Route::delete('/my-plans/{plan}/results/{resultId}', [\App\Http\Controllers\Coach\CoachPlanController::class, 'deleteResult'])->name('plans.results.delete');
    Route::post('/my-plans/{plan}/results/reorder', [\App\Http\Controllers\Coach\CoachPlanController::class, 'reorderResults'])->name('plans.results.reorder');
    Route::post('/my-plans/{plan}/autosave', [\App\Http\Controllers\Coach\CoachPlanController::class, 'autosave'])->name('plans.autosave');
    Route::get('/my-plans/{plan}/audit-logs', [\App\Http\Controllers\Coach\CoachPlanController::class, 'auditLogs'])->name('plans.audit-logs');
    // Bulk purchase actions (must be before {purchase} routes to avoid conflict)
    Route::post('/my-plans/purchases/bulk-confirm', [\App\Http\Controllers\Coach\CoachPlanController::class, 'bulkConfirmPurchases'])->name('plans.purchases.bulk-confirm');
    Route::post('/my-plans/purchases/bulk-cancel', [\App\Http\Controllers\Coach\CoachPlanController::class, 'bulkCancelPurchases'])->name('plans.purchases.bulk-cancel');
    Route::delete('/my-plans/purchases/bulk-delete', [\App\Http\Controllers\Coach\CoachPlanController::class, 'bulkDeletePurchases'])->name('plans.purchases.bulk-delete');

    // Individual purchase actions
    Route::post('/my-plans/purchases/{purchase}/confirm', [\App\Http\Controllers\Coach\CoachPlanController::class, 'markPurchasePaid'])->name('plans.purchases.confirm');
    Route::post('/my-plans/purchases/{purchase}/cancel', [\App\Http\Controllers\Coach\CoachPlanController::class, 'cancelPurchase'])->name('plans.purchases.cancel');
    Route::post('/my-plans/purchases/{purchase}/suspend', [\App\Http\Controllers\Coach\CoachPlanController::class, 'suspendPurchase'])->name('plans.purchases.suspend');
    Route::post('/my-plans/purchases/{purchase}/reactivate', [\App\Http\Controllers\Coach\CoachPlanController::class, 'reactivatePurchase'])->name('plans.purchases.reactivate');
    Route::post('/my-plans/purchases/{purchase}/send-reminder', [\App\Http\Controllers\Coach\CoachPlanController::class, 'sendPaymentReminder'])->name('plans.purchases.send-reminder');
    Route::put('/my-plans/purchases/{purchase}', [\App\Http\Controllers\Coach\CoachPlanController::class, 'updatePurchase'])->name('plans.purchases.update');
    Route::post('/my-plans/purchases/{purchase}/refund', [\App\Http\Controllers\Coach\CoachPlanController::class, 'refundPurchase'])->name('plans.purchases.refund');
    Route::delete('/my-plans/purchases/{purchase}', [\App\Http\Controllers\Coach\CoachPlanController::class, 'deletePurchase'])->name('plans.purchases.delete');

    // PayPal Settings
    Route::get('/paypal-settings', [\App\Http\Controllers\Coach\CoachPlanController::class, 'paypalSettings'])->name('paypal.settings');
    Route::put('/paypal-settings', [\App\Http\Controllers\Coach\CoachPlanController::class, 'updatePaypalSettings'])->name('paypal.update');

    // Email Templates
    Route::prefix('email-templates')->name('email-templates.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Coach\EmailTemplateController::class, 'index'])->name('index');
        Route::get('/{type}/edit', [\App\Http\Controllers\Coach\EmailTemplateController::class, 'edit'])->name('edit');
        Route::put('/{type}', [\App\Http\Controllers\Coach\EmailTemplateController::class, 'update'])->name('update');
        Route::post('/{type}/reset', [\App\Http\Controllers\Coach\EmailTemplateController::class, 'reset'])->name('reset');
        Route::post('/{type}/send-test', [\App\Http\Controllers\Coach\EmailTemplateController::class, 'sendTest'])->name('send-test');
    });

    // Payment Methods
    Route::prefix('payment-methods')->name('payment-methods.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Coach\PaymentMethodController::class, 'index'])->name('index');
        Route::get('/list', [\App\Http\Controllers\Coach\PaymentMethodController::class, 'list'])->name('list');
        Route::post('/paypal', [\App\Http\Controllers\Coach\PaymentMethodController::class, 'storePaypal'])->name('paypal.store');
        Route::post('/bank-dominican', [\App\Http\Controllers\Coach\PaymentMethodController::class, 'storeDominicanBank'])->name('bank-dominican.store');
        Route::post('/bank-international', [\App\Http\Controllers\Coach\PaymentMethodController::class, 'storeInternationalBank'])->name('bank-international.store');
        Route::post('/western-union', [\App\Http\Controllers\Coach\PaymentMethodController::class, 'storeWesternUnion'])->name('western-union.store');
        Route::put('/{paymentMethod}', [\App\Http\Controllers\Coach\PaymentMethodController::class, 'update'])->name('update');
        Route::post('/{paymentMethod}/toggle', [\App\Http\Controllers\Coach\PaymentMethodController::class, 'toggleActive'])->name('toggle');
        Route::post('/{paymentMethod}/verify', [\App\Http\Controllers\Coach\PaymentMethodController::class, 'verifyPaypal'])->name('verify');
        Route::post('/priorities', [\App\Http\Controllers\Coach\PaymentMethodController::class, 'updatePriorities'])->name('priorities');
        Route::delete('/{paymentMethod}', [\App\Http\Controllers\Coach\PaymentMethodController::class, 'destroy'])->name('destroy');
    });
    Route::get('/verify-payment-method/{token}', [\App\Http\Controllers\Coach\PaymentMethodController::class, 'verifyToken'])->name('payment-methods.verify-token');

    // Results
    Route::resource('results', \App\Http\Controllers\Coach\ResultController::class);

    // Support / Contact
    Route::get('/support', [\App\Http\Controllers\Coach\SupportController::class, 'index'])->name('support.index');
    Route::post('/support', [\App\Http\Controllers\Coach\SupportController::class, 'send'])->name('support.send');

    // Testimonials (enviar testimonios para la landing)
    Route::prefix('testimonials')->name('testimonials.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Coach\TestimonialController::class, 'index'])->name('index');
        Route::post('/', [\App\Http\Controllers\Coach\TestimonialController::class, 'store'])->name('store');
        Route::delete('/{testimonial}', [\App\Http\Controllers\Coach\TestimonialController::class, 'destroy'])->name('destroy');
    });

    // Store
    Route::prefix('store')->name('store.')->group(function () {
        Route::get('/', [\App\Http\Controllers\StoreController::class, 'index'])->name('index');
        Route::get('/product/{product}', [\App\Http\Controllers\StoreController::class, 'show'])->name('show');
        Route::get('/cart', [\App\Http\Controllers\StoreController::class, 'cart'])->name('cart');
        Route::post('/cart/add', [\App\Http\Controllers\StoreController::class, 'addToCart'])->name('cart.add');
        Route::post('/cart/update', [\App\Http\Controllers\StoreController::class, 'updateCart'])->name('cart.update');
        Route::post('/cart/remove', [\App\Http\Controllers\StoreController::class, 'removeFromCart'])->name('cart.remove');
        Route::get('/checkout', [\App\Http\Controllers\StoreController::class, 'checkout'])->name('checkout');
        Route::post('/checkout', [\App\Http\Controllers\StoreController::class, 'processCheckout'])->name('checkout.process');
        Route::post('/coupon/apply', [\App\Http\Controllers\StoreController::class, 'applyCoupon'])->name('coupon.apply');
        Route::post('/coupon/remove', [\App\Http\Controllers\StoreController::class, 'removeCoupon'])->name('coupon.remove');
        Route::get('/orders', [\App\Http\Controllers\StoreController::class, 'orders'])->name('orders.index');
        Route::get('/orders/{order}', [\App\Http\Controllers\StoreController::class, 'showOrder'])->name('orders.show');
        Route::post('/orders/{order}/change-payment-method', [\App\Http\Controllers\StoreController::class, 'changePaymentMethod'])->name('orders.change-payment-method');

        // Product Reviews
        Route::post('/product/{product}/reviews', [\App\Http\Controllers\StoreController::class, 'submitReview'])->name('reviews.store');
    });
});

/*
|--------------------------------------------------------------------------
| Client Routes
|--------------------------------------------------------------------------
| Accessible by clients, coaches (to view client portal), and admins
*/

Route::middleware(['auth', 'verified', 'role:client,coach,admin'])->prefix('client')->name('client.')->group(function () {
    // Redirect /client to /client/dashboard
    Route::get('/', fn() => redirect()->route('client.dashboard'));

    Route::get('/dashboard', [\App\Http\Controllers\Client\DashboardController::class, 'index'])->name('dashboard');
    Route::post('/metrics', [\App\Http\Controllers\Client\DashboardController::class, 'updateMetrics'])->name('metrics.update');

    // Workout
    Route::get('/workout', [\App\Http\Controllers\Client\WorkoutController::class, 'index'])->name('workout.index');
    Route::get('/workout-redirect', fn() => redirect()->route('client.workout.index'))->name('workout');
    Route::get('/workout/{workout}/pdf', [\App\Http\Controllers\Client\WorkoutController::class, 'pdf'])->name('workout.pdf');

    // Meal Plan
    Route::get('/meal-plan', [\App\Http\Controllers\Client\MealPlanController::class, 'index'])->name('meal-plan.index');
    Route::get('/meal-plan-redirect', fn() => redirect()->route('client.meal-plan.index'))->name('meal-plan');
    Route::get('/meal-plan/{mealPlan}/pdf', [\App\Http\Controllers\Client\MealPlanController::class, 'pdf'])->name('meal-plan.pdf');
    Route::post('/meal-plan/{mealPlan}/email', [\App\Http\Controllers\Client\MealPlanController::class, 'emailMealPlan'])->name('meal-plan.email');

    // Progress Tracking
    Route::middleware(['feature:feature_compliance_tracking'])->group(function () {
        Route::get('/progress', [\App\Http\Controllers\Client\ProgressController::class, 'index'])->name('progress.index');
        Route::get('/progress-redirect', fn() => redirect()->route('client.progress.index'))->name('progress');
        Route::post('/compliance', [\App\Http\Controllers\Client\ProgressController::class, 'logCompliance'])->name('compliance.log');
    });

    // Photos
    Route::middleware(['feature:feature_progress_photos'])->group(function () {
        Route::get('/photos', [\App\Http\Controllers\Client\PhotoController::class, 'index'])->name('photos.index');
        Route::get('/photos-redirect', fn() => redirect()->route('client.photos.index'))->name('photos');
        Route::post('/photos', [\App\Http\Controllers\Client\PhotoController::class, 'upload'])->name('photos.upload');
        Route::post('/photos/{photo}/watermark', [\App\Http\Controllers\Client\PhotoController::class, 'watermark'])->name('photos.watermark');
        Route::post('/photos/{photo}/generate-combined', [\App\Http\Controllers\Client\PhotoController::class, 'generateCombined'])->name('photos.generate-combined');
        Route::post('/photos/{photo}/make-public', [\App\Http\Controllers\PublicPhotoController::class, 'makePublic'])->name('photos.make-public');
        Route::delete('/photos/{photo}', [\App\Http\Controllers\Client\PhotoController::class, 'destroy'])->name('photos.destroy');
    });

    // Profile
    Route::get('/profile', [\App\Http\Controllers\Client\ProfileController::class, 'index'])->name('profile.index');
    Route::get('/profile-redirect', fn() => redirect()->route('client.profile.index'))->name('profile');
    Route::put('/profile', [\App\Http\Controllers\Client\ProfileController::class, 'update'])->name('profile.update');
    Route::put('/password', [\App\Http\Controllers\Client\ProfileController::class, 'updatePassword'])->name('password.update');
    Route::post('/avatar', [\App\Http\Controllers\Client\ProfileController::class, 'updateAvatar'])->name('avatar.update');

    // Chat
    Route::middleware(['feature:feature_chat'])->group(function () {
        Route::get('/chat', [\App\Http\Controllers\Client\ChatController::class, 'index'])->name('chat.index');
        Route::post('/chat', [\App\Http\Controllers\Client\ChatController::class, 'store'])->name('chat.store');
    });

    // Store
    Route::prefix('store')->name('store.')->group(function () {
        Route::get('/', [\App\Http\Controllers\StoreController::class, 'index'])->name('index');
        Route::get('/product/{product}', [\App\Http\Controllers\StoreController::class, 'show'])->name('show');
        Route::get('/cart', [\App\Http\Controllers\StoreController::class, 'cart'])->name('cart');
        Route::post('/cart/add', [\App\Http\Controllers\StoreController::class, 'addToCart'])->name('cart.add');
        Route::post('/cart/update', [\App\Http\Controllers\StoreController::class, 'updateCart'])->name('cart.update');
        Route::post('/cart/remove', [\App\Http\Controllers\StoreController::class, 'removeFromCart'])->name('cart.remove');
        Route::get('/checkout', [\App\Http\Controllers\StoreController::class, 'checkout'])->name('checkout');
        Route::post('/checkout', [\App\Http\Controllers\StoreController::class, 'processCheckout'])->name('checkout.process');
        Route::post('/coupon/apply', [\App\Http\Controllers\StoreController::class, 'applyCoupon'])->name('coupon.apply');
        Route::post('/coupon/remove', [\App\Http\Controllers\StoreController::class, 'removeCoupon'])->name('coupon.remove');
        Route::get('/orders', [\App\Http\Controllers\StoreController::class, 'orders'])->name('orders.index');
        Route::get('/orders/{order}', [\App\Http\Controllers\StoreController::class, 'showOrder'])->name('orders.show');
        Route::post('/orders/{order}/change-payment-method', [\App\Http\Controllers\StoreController::class, 'changePaymentMethod'])->name('orders.change-payment-method');

        // Product Reviews
        Route::post('/product/{product}/reviews', [\App\Http\Controllers\StoreController::class, 'submitReview'])->name('reviews.store');
    });
});

/*
|--------------------------------------------------------------------------
| Store Payment Routes
|--------------------------------------------------------------------------
*/

Route::middleware(['auth', 'verified'])->prefix('store/payment')->name('store.payment.')->group(function () {
    // PayPal
    Route::get('/paypal/{order}', [\App\Http\Controllers\StorePaymentController::class, 'paypalCreate'])->name('paypal');
    Route::get('/paypal/{order}/success', [\App\Http\Controllers\StorePaymentController::class, 'paypalSuccess'])->name('paypal.success');
    Route::get('/paypal/{order}/cancel', [\App\Http\Controllers\StorePaymentController::class, 'paypalCancel'])->name('paypal.cancel');

    // Stripe
    Route::get('/stripe/{order}', [\App\Http\Controllers\StorePaymentController::class, 'stripeCreate'])->name('stripe');
    Route::get('/stripe/{order}/success', [\App\Http\Controllers\StorePaymentController::class, 'stripeSuccess'])->name('stripe.success');
    Route::get('/stripe/{order}/cancel', [\App\Http\Controllers\StorePaymentController::class, 'stripeCancel'])->name('stripe.cancel');
});

/*
|--------------------------------------------------------------------------
| API Routes (for AJAX calls)
|--------------------------------------------------------------------------
*/

Route::middleware('auth')->group(function () {
    // Get foods by meal type (for trainers creating diets)
    Route::get('/api/foods', [\App\Http\Controllers\Admin\FoodController::class, 'getByMealType'])->name('api.foods.by-meal-type');

    // Push notification subscriptions
    Route::prefix('api/push')->group(function () {
        Route::get('/vapid-public-key', [\App\Http\Controllers\Api\PushSubscriptionController::class, 'vapidPublicKey']);
        Route::post('/subscribe', [\App\Http\Controllers\Api\PushSubscriptionController::class, 'store']);
        Route::post('/unsubscribe', [\App\Http\Controllers\Api\PushSubscriptionController::class, 'destroy']);
        Route::post('/test', [\App\Http\Controllers\Api\PushSubscriptionController::class, 'test']);
    });
});

// Broadcasting authentication
Broadcast::routes(['middleware' => ['web', 'auth']]);

require __DIR__.'/auth.php';
