<?php

use App\Http\Controllers\Install\InstallController;
use App\Http\Controllers\Admin\AdminDashboardController;

// Installation Routes (No middleware - accessible before installation)
Route::get('/install', [InstallController::class, 'welcome'])->name('install.welcome');
Route::get('/install/requirements', [InstallController::class, 'welcome'])->name('install.requirements');
Route::get('/install/database', [InstallController::class, 'database'])->name('install.database');
Route::post('/install/database', [InstallController::class, 'processDatabase'])->name('install.database.process');
Route::get('/install/migrations', [InstallController::class, 'migrations'])->name('install.migrations');
Route::post('/install/migrations', [InstallController::class, 'processMigrations'])->name('install.migrations.process');
Route::post('/install/migrations/run', [InstallController::class, 'runSingleMigration'])->name('install.migrations.run');
Route::get('/install/admin', [InstallController::class, 'admin'])->name('install.admin');
Route::post('/install/admin', [InstallController::class, 'processAdmin'])->name('install.admin.process');
Route::get('/install/complete', [InstallController::class, 'complete'])->name('install.complete');

// All other routes require installation check
use App\Http\Controllers\Admin\AdminVendorController;
use App\Http\Controllers\Admin\AdminCategoryController;
use App\Http\Controllers\Admin\AdminBrandController;
use App\Http\Controllers\Admin\AdminProductController;
use App\Http\Controllers\Admin\AdminOrderController;
use App\Http\Controllers\Admin\AdminCarController;
use App\Http\Controllers\Admin\AdminCouponController;
use App\Http\Controllers\Admin\AdminAnnouncementController;
use App\Http\Controllers\Admin\AdminVendorSettingsController;
use App\Http\Controllers\Admin\AdminUserController;
use App\Http\Controllers\Admin\AdminReviewController;
use App\Http\Controllers\Admin\AdminSocialAuthController;
use App\Http\Controllers\Admin\AdminPasswordResetController;
use App\Http\Controllers\Admin\AdminConversationController;
use App\Http\Controllers\Admin\AdminRoleController;
use App\Http\Controllers\Admin\AdminCurrencyController;
use App\Http\Controllers\Admin\AdminStorageController;
use App\Http\Controllers\Admin\AdminCodController;
use App\Http\Controllers\Admin\AdminCacheController;
use App\Http\Controllers\Vendor\VendorDashboardController;
use App\Http\Controllers\Vendor\VendorOnboardingController;
use App\Http\Controllers\Vendor\VendorProductController;
use App\Http\Controllers\Vendor\VendorOrderController;
use App\Http\Controllers\Vendor\VendorProfileController;
use App\Http\Controllers\Vendor\VendorCouponController;
use App\Http\Controllers\Vendor\VendorCodController;
use App\Http\Controllers\Shop\HomeController;
use App\Http\Controllers\Shop\ProductController;
use App\Http\Controllers\Shop\CartController;
use App\Http\Controllers\Shop\CheckoutController;
use App\Http\Controllers\Shop\OrderController;
use App\Http\Controllers\Shop\WishlistController;
use App\Http\Controllers\Shop\OrderTrackingController;
use App\Http\Controllers\Shop\ReviewController;
use App\Http\Controllers\Shop\CustomerOrderController;
use App\Http\Controllers\Shop\ProfileController;
use App\Http\Controllers\VendorRegistrationController;
use App\Http\Controllers\LanguageController;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\App;
use Illuminate\Http\Request;

// Dashboard redirect route
Route::get('/dashboard', function (Request $request) {
    if (auth()->check()) {
        $user = auth()->user();
        
        // Check if user has vendor role and approved vendor record
        if ($user->hasRole('vendor')) {
            $vendor = $user->vendor;
            if ($vendor && $vendor->status === 'approved') {
                return redirect()->route('vendor.dashboard');
            }
            // If vendor but not approved, go to pending page
            return redirect()->route('vendor.pending');
        }
        
        // Check if admin
        if ($user->hasRole('admin')) {
            return redirect()->route('admin.dashboard');
        }
    }
    return redirect()->route('home');
})->middleware(['auth'])->name('dashboard');

// Language Switch Route - must be within installed middleware to have session
Route::middleware(['installed', 'setlocale'])->group(function () {
    Route::post('/language/switch', [LanguageController::class, 'switch'])->name('language.switch');
    Route::get('/language/{locale}', [LanguageController::class, 'switch'])->name('language.switch.get');
});

// Public / Storefront
Route::middleware(['installed', 'setlocale'])->group(function () {
    Route::get('/', [HomeController::class, 'index'])->name('home');
    Route::get('/shop', [ProductController::class, 'index'])->name('shop.index');
    Route::get('/shop/{slug}', [ProductController::class, 'show'])->name('shop.product');
    Route::get('/category/{slug}', [ProductController::class, 'byCategory'])->name('shop.category');
    Route::get('/brand/{slug}', [ProductController::class, 'byBrand'])->name('shop.brand');
    Route::get('/store/{slug}', [ProductController::class, 'byVendor'])->name('shop.vendor');
    Route::get('/search', [ProductController::class, 'search'])->name('shop.search');
    Route::get('/car-filter', [ProductController::class, 'carFilter'])->name('shop.car-filter');
    Route::get('/api/car-models', [ProductController::class, 'getCarModels'])->name('api.car-models');
    Route::get('/api/car-years', [ProductController::class, 'getCarYears'])->name('api.car-years');

    // Cart
    Route::get('/cart', [CartController::class, 'index'])->name('cart.index');
    Route::post('/cart/add', [CartController::class, 'add'])->name('cart.add');
    Route::patch('/cart/{id}', [CartController::class, 'update'])->name('cart.update');
    Route::delete('/cart/{id}', [CartController::class, 'remove'])->name('cart.remove');
    Route::post('/cart/coupon', [CartController::class, 'applyCoupon'])->name('cart.coupon');
    Route::delete('/cart/coupon/remove', [CartController::class, 'removeCoupon'])->name('cart.coupon.remove');
});
Route::get('/debug-routes', function () {
    return [
        'vendor.profile.edit' => route('vendor.profile.edit'),
        'vendor.profile.update' => route('vendor.profile.update'),
        'profile.update' => route('profile.update'),
    ];
});

Route::get('/debug-vendor', function () {
    $user = auth()->user();
    $vendor = $user->vendor;
    return [
        'user_id' => $user->id,
        'roles' => $user->getRoleNames(),
        'vendor_exists' => (bool) $vendor,
        'vendor_status' => $vendor?->status,
        'onboarding_step' => $vendor?->onboarding_step,
    ];
})->middleware('auth');

Route::get('/debug-locale', function () {
    return [
        'session_locale' => Session::get('locale'),
        'app_locale' => App::getLocale(),
        'config_locale' => config('app.locale'),
        'user_locale' => auth()->check() ? auth()->user()->locale : null,
        'session_id' => Session::getId(),
    ];
})->middleware('installed');

Route::get('/debug-clear', function() {
    \Artisan::call('route:clear');
    \Artisan::call('config:clear');
    \Artisan::call('cache:clear');
    \Artisan::call('view:clear');
    return 'Cleared! All caches cleared successfully.';
});

Route::get('/run-car-seeder', function() {
    try {
        \Artisan::call('db:seed', [
            '--class' => 'Database\\Seeders\\CarDataSeeder',
            '--force' => true
        ]);
        $output = \Artisan::output();
        return '<pre>Car Data Success! ' . $output . '</pre>';
    } catch (\Exception $e) {
        return 'Error: ' . $e->getMessage();
    }
})->middleware('admin');

Route::get('/run-category-seeder', function() {
    try {
        \Artisan::call('db:seed', [
            '--class' => 'Database\\Seeders\\CategoryDataSeeder',
            '--force' => true
        ]);
        $output = \Artisan::output();
        return '<pre>Category Data Success! ' . $output . '</pre>';
    } catch (\Exception $e) {
        return 'Error: ' . $e->getMessage();
    }
})->middleware('admin');

// Auth Required
Route::middleware(['installed', 'auth', 'setlocale'])->group(function () {
    Route::get('/profile', [ProfileController::class, 'index'])->name('profile.index');
    Route::put('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::get('/profile/orders', [OrderTrackingController::class, 'index'])->name('shop.orders.index');
    Route::get('/profile/orders/{orderNumber}', [OrderTrackingController::class, 'show'])->name('shop.orders.show');
    Route::get('/profile/orders/{orderNumber}/track', [OrderTrackingController::class, 'track'])->name('shop.orders.track');
    Route::patch('/profile/orders/{orderNumber}/cancel', [CustomerOrderController::class, 'cancel'])->name('shop.orders.cancel');
    Route::get('/profile/addresses', [ProfileController::class, 'addresses'])->name('profile.addresses');
    Route::post('/profile/addresses', [ProfileController::class, 'storeAddress'])->name('profile.addresses.store');
    Route::delete('/profile/addresses/{id}', [ProfileController::class, 'deleteAddress'])->name('profile.addresses.delete');

    Route::get('/wishlist', [WishlistController::class, 'index'])->name('wishlist.index');
    Route::post('/wishlist/toggle', [WishlistController::class, 'toggle'])->name('wishlist.toggle');

    Route::get('/checkout', [CheckoutController::class, 'index'])->name('checkout.index');
    Route::post('/checkout', [CheckoutController::class, 'store'])->name('checkout.store');
    Route::get('/checkout/success/{orderNumber}', [CheckoutController::class, 'success'])->name('checkout.success');
    Route::post('/checkout/payment-intent', [CheckoutController::class, 'createPaymentIntent'])->name('checkout.payment-intent');

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

    Route::get('/become-vendor', [VendorRegistrationController::class, 'create'])->name('vendor.register');
    Route::post('/become-vendor', [VendorRegistrationController::class, 'store'])->name('vendor.register.store');
    Route::get('/vendor-pending', [VendorRegistrationController::class, 'pending'])->name('vendor.pending');
});

// Vendor Dashboard
Route::middleware(['installed', 'auth', 'vendor', 'setlocale'])->prefix('vendor')->name('vendor.')->group(function () {
    // Onboarding Routes (accessible to vendors pending approval)
    Route::get('/onboarding/step-1', [VendorOnboardingController::class, 'step1'])->name('onboarding.step1');
    Route::post('/onboarding/step-1', [VendorOnboardingController::class, 'processStep1'])->name('onboarding.step1.process');
    Route::get('/onboarding/step-2', [VendorOnboardingController::class, 'step2'])->name('onboarding.step2');
    Route::post('/onboarding/step-2', [VendorOnboardingController::class, 'processStep2'])->name('onboarding.step2.process');
    Route::get('/onboarding/step-3', [VendorOnboardingController::class, 'step3'])->name('onboarding.step3');
    Route::post('/onboarding/step-3', [VendorOnboardingController::class, 'processStep3'])->name('onboarding.step3.process');
    Route::get('/onboarding/pending', [VendorOnboardingController::class, 'pending'])->name('onboarding.pending');
    
    // Main Dashboard (only for approved vendors)
    Route::get('/dashboard', [VendorDashboardController::class, 'index'])->name('dashboard');
    Route::resource('products', VendorProductController::class);
    Route::get('/orders', [VendorOrderController::class, 'index'])->name('orders.index');
    Route::get('/orders/{id}', [VendorOrderController::class, 'show'])->name('orders.show');
    Route::patch('/orders/{id}/status', [VendorOrderController::class, 'updateStatus'])->name('orders.update-status');
    Route::get('/earnings', [VendorDashboardController::class, 'earnings'])->name('earnings');
    Route::get('/profile', [VendorProfileController::class, 'edit'])->name('profile.edit');
    Route::put('/profile', [VendorProfileController::class, 'update'])->name('profile.update');
    
    // Vendor Coupons
    Route::resource('coupons', VendorCouponController::class);
    
    // Vendor COD Orders
    Route::get('/cod-orders', [VendorCodController::class, 'index'])->name('cod.index');
    Route::get('/cod-orders/{order}', [VendorCodController::class, 'show'])->name('cod.show');
    Route::post('/cod-orders/{order}/mark-paid', [VendorCodController::class, 'markAsPaid'])->name('cod.mark-paid');
});

// Admin Panel
Route::middleware(['installed', 'auth', 'admin', 'setlocale'])->prefix('admin')->name('admin.')->group(function () {
    Route::get('/dashboard', [AdminDashboardController::class, 'index'])->name('dashboard');
    Route::resource('vendors', AdminVendorController::class);
    Route::patch('/vendors/{id}/status', [AdminVendorController::class, 'updateStatus'])->name('vendors.status');
    Route::patch('/vendors/{id}/approve', [AdminVendorController::class, 'updateStatus'])->name('vendors.approve');
    Route::patch('/vendors/{id}/reject', [AdminVendorController::class, 'updateStatus'])->name('vendors.reject');
    Route::patch('/vendors/{id}/suspend', [AdminVendorController::class, 'updateStatus'])->name('vendors.suspend');
    Route::resource('categories', AdminCategoryController::class);
    Route::resource('brands', AdminBrandController::class);
    Route::resource('products', AdminProductController::class);
    Route::post('/products/{product}/approve', [AdminProductController::class, 'approve'])->name('products.approve');
    Route::post('/products/{product}/reject', [AdminProductController::class, 'reject'])->name('products.reject');
    Route::post('/products/bulk-approve', [AdminProductController::class, 'bulkApprove'])->name('products.bulk-approve');
    Route::resource('orders', AdminOrderController::class)->only(['index', 'show']);
    Route::patch('/orders/{id}/status', [AdminOrderController::class, 'updateStatus'])->name('orders.status');
    Route::resource('car-makes', AdminCarController::class);
    Route::get('/car-models', [AdminCarController::class, 'models'])->name('car-models.index');
    // Note: AdminCarController::models() is the correct method name
    Route::post('/car-models', [AdminCarController::class, 'storeModel'])->name('car-models.store');
    Route::delete('/car-models/{id}', [AdminCarController::class, 'destroyModel'])->name('car-models.destroy');
    Route::resource('coupons', AdminCouponController::class);
    Route::resource('users', AdminUserController::class);
    Route::post('/users/{user}/toggle-status', [AdminUserController::class, 'toggleStatus'])->name('users.toggle-status');
    Route::post('/users/{user}/reset-password', [AdminUserController::class, 'resetPassword'])->name('users.reset-password');
    Route::post('/users/{user}/impersonate', [AdminUserController::class, 'impersonate'])->name('users.impersonate');
    Route::resource('reviews', AdminReviewController::class)->only(['index', 'update', 'destroy']);
    
    // Password Reset Management
    Route::get('/password-resets', [AdminPasswordResetController::class, 'index'])->name('password-resets.index');
    Route::get('/password-resets/{user}', [AdminPasswordResetController::class, 'show'])->name('password-resets.show');
    Route::put('/password-resets/{user}', [AdminPasswordResetController::class, 'reset'])->name('password-resets.reset');
    Route::post('/password-resets/{user}/send-link', [AdminPasswordResetController::class, 'sendResetLink'])->name('password-resets.send-link');
    
    // Conversations & Messages
    Route::get('/conversations', [AdminConversationController::class, 'index'])->name('conversations.index');
    Route::get('/conversations/create', [AdminConversationController::class, 'create'])->name('conversations.create');
    Route::post('/conversations', [AdminConversationController::class, 'store'])->name('conversations.store');
    Route::get('/conversations/{conversation}', [AdminConversationController::class, 'show'])->name('conversations.show');
    Route::post('/conversations/{conversation}/reply', [AdminConversationController::class, 'reply'])->name('conversations.reply');
    Route::patch('/conversations/{conversation}/status', [AdminConversationController::class, 'updateStatus'])->name('conversations.update-status');
    Route::delete('/conversations/{conversation}', [AdminConversationController::class, 'destroy'])->name('conversations.destroy');
    
    // Role Management
    Route::get('/roles', [AdminRoleController::class, 'index'])->name('roles.index');
    Route::post('/roles', [AdminRoleController::class, 'createRole'])->name('roles.create');
    Route::put('/roles/{role}', [AdminRoleController::class, 'updateRole'])->name('roles.update');
    Route::delete('/roles/{role}', [AdminRoleController::class, 'deleteRole'])->name('roles.delete');
    Route::get('/roles/users', [AdminRoleController::class, 'users'])->name('roles.users');
    Route::put('/roles/users/{user}', [AdminRoleController::class, 'updateUserRoles'])->name('roles.users.update');
    
    // Currency Management
    Route::get('/currencies', [AdminCurrencyController::class, 'index'])->name('currencies.index');
    Route::post('/currencies', [AdminCurrencyController::class, 'store'])->name('currencies.store');
    Route::put('/currencies/{currency}', [AdminCurrencyController::class, 'update'])->name('currencies.update');
    Route::delete('/currencies/{currency}', [AdminCurrencyController::class, 'destroy'])->name('currencies.destroy');
    Route::post('/currencies/update-rates', [AdminCurrencyController::class, 'updateRates'])->name('currencies.update-rates');
    
    // Enhanced Vendor Routes
    Route::get('/vendors/pending', [AdminVendorController::class, 'pendingApprovals'])->name('vendors.pending');
    Route::post('/vendors/bulk-action', [AdminVendorController::class, 'bulkAction'])->name('vendors.bulk-action');
    Route::post('/vendors/{vendor}/approve-with-note', [AdminVendorController::class, 'approveWithNote'])->name('vendors.approve-with-note');
    
    // Social Auth Settings
    Route::get('/social-auth', [AdminSocialAuthController::class, 'index'])->name('social-auth.index');
    Route::put('/social-auth', [AdminSocialAuthController::class, 'update'])->name('social-auth.update');
    
    // Storage Settings (Fix Images)
    Route::get('/storage-settings', [AdminStorageController::class, 'index'])->name('storage.index');
    Route::post('/storage-settings/fix', [AdminStorageController::class, 'fixStorageLink'])->name('storage.fix');
    Route::post('/storage-settings/htaccess', [AdminStorageController::class, 'createHtaccess'])->name('storage.htaccess');
    
    // COD Orders Management
    Route::get('/cod-orders', [AdminCodController::class, 'index'])->name('cod.index');
    Route::get('/cod-orders/{order}', [AdminCodController::class, 'show'])->name('cod.show');
    Route::post('/cod-orders/{order}/mark-paid', [AdminCodController::class, 'markAsPaid'])->name('cod.mark-paid');
    Route::post('/cod-orders/bulk-mark-paid', [AdminCodController::class, 'bulkMarkAsPaid'])->name('cod.bulk-paid');
    
    // Announcements
    Route::resource('announcements', AdminAnnouncementController::class)->except(['show']);
    
    // Vendor Settings (image limits, storefront customization)
    Route::get('/vendor-settings', [AdminVendorSettingsController::class, 'index'])->name('vendor-settings.index');
    Route::put('/vendor-settings', [AdminVendorSettingsController::class, 'update'])->name('vendor-settings.update');
    
    // Cache Management
    Route::get('/cache', [AdminCacheController::class, 'index'])->name('cache.index');
    Route::post('/cache/clear-all', [AdminCacheController::class, 'clearAll'])->name('cache.clear-all');
    Route::post('/cache/clear-application', [AdminCacheController::class, 'clearApplication'])->name('cache.clear-application');
    Route::post('/cache/clear-config', [AdminCacheController::class, 'clearConfig'])->name('cache.clear-config');
    Route::post('/cache/clear-route', [AdminCacheController::class, 'clearRoute'])->name('cache.clear-route');
    Route::post('/cache/clear-view', [AdminCacheController::class, 'clearView'])->name('cache.clear-view');
    Route::post('/cache/cache-config', [AdminCacheController::class, 'cacheConfig'])->name('cache.cache-config');
    Route::post('/cache/cache-route', [AdminCacheController::class, 'cacheRoute'])->name('cache.cache-route');
    Route::post('/cache/cache-view', [AdminCacheController::class, 'cacheView'])->name('cache.cache-view');
    Route::post('/cache/optimize', [AdminCacheController::class, 'optimize'])->name('cache.optimize');
    Route::get('/cache/status', [AdminCacheController::class, 'getCacheStatus'])->name('cache.status');
});

require __DIR__.'/auth.php';
