<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\InstallController;
use App\Http\Controllers\DocumentationController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

// Installation Routes
Route::prefix('install')->name('install.')->group(function () {
    Route::get('/', [InstallController::class, 'showWelcome'])->name('welcome');
    Route::get('/requirements', [InstallController::class, 'showRequirements'])->name('requirements');
    Route::get('/database', [InstallController::class, 'showDatabase'])->name('database');
    Route::post('/database', [InstallController::class, 'processDatabase'])->name('process_database');
    Route::get('/complete', [InstallController::class, 'showComplete'])->name('complete');
});

// Admin Authentication Routes
Route::prefix('admin')->name('admin.')->group(function () {
    Route::get('/login', [App\Http\Controllers\Admin\AuthController::class, 'showLoginForm'])->name('login');
    Route::post('/login', [App\Http\Controllers\Admin\AuthController::class, 'login']);
    Route::post('/logout', [App\Http\Controllers\Admin\AuthController::class, 'logout'])->name('logout');
});

// Admin Dashboard Routes
Route::prefix('admin')->name('admin.')->middleware([\App\Http\Middleware\CheckAdmin::class])->group(function () {
    Route::get('/', [DashboardController::class, 'index'])->name('dashboard');
    Route::get('/dashboard/users-by-plan-data', [DashboardController::class, 'getUsersByPlanData'])->name('dashboard.users_by_plan_data');
    Route::get('/dashboard/user-locations', [DashboardController::class, 'getUserLocationData'])->name('dashboard.user_locations');
    
    // Support System Routes
    Route::prefix('support')->name('support.')->group(function () {
        Route::get('/settings', [App\Http\Controllers\Admin\SupportController::class, 'settings'])->name('settings');
        Route::post('/settings', [App\Http\Controllers\Admin\SupportController::class, 'updateSettings'])->name('settings.update');
        
        Route::get('/tickets', [App\Http\Controllers\Admin\SupportController::class, 'tickets'])->name('tickets');
        Route::get('/tickets/{id}', [App\Http\Controllers\Admin\SupportController::class, 'showTicket'])->name('tickets.show');
        Route::post('/tickets/{id}/update', [App\Http\Controllers\Admin\SupportController::class, 'updateTicket'])->name('tickets.update');
        Route::post('/tickets/{id}/reply', [App\Http\Controllers\Admin\SupportController::class, 'replyTicket'])->name('tickets.reply');
        
        Route::get('/chats', [App\Http\Controllers\Admin\SupportController::class, 'chats'])->name('chats');
        Route::get('/chats/{id}', [App\Http\Controllers\Admin\SupportController::class, 'showChat'])->name('chats.show');
        Route::post('/chats/{id}/message', [App\Http\Controllers\Admin\SupportController::class, 'sendMessage'])->name('chats.message');
        Route::post('/chats/{id}/close', [App\Http\Controllers\Admin\SupportController::class, 'closeChat'])->name('chats.close');
    });
    
    Route::get('/users', [App\Http\Controllers\Admin\UserManagementController::class, 'index'])->name('users.index');

    Route::get('/users/{user}/details', [App\Http\Controllers\Admin\UserManagementController::class, 'getUserDetails'])->name('users.details');
    Route::put('/users/{user}', [App\Http\Controllers\Admin\UserManagementController::class, 'update'])->name('users.update');
    Route::post('/users/{user}/ban', [App\Http\Controllers\Admin\UserManagementController::class, 'banUser'])->name('users.ban');
    Route::post('/users/{user}/suspend', [App\Http\Controllers\Admin\UserManagementController::class, 'suspendUser'])->name('users.suspend');
    Route::post('/users/{user}/verify', [App\Http\Controllers\Admin\UserManagementController::class, 'verifyUser'])->name('users.verify');
    Route::post('/users/{user}/change-plan', [App\Http\Controllers\Admin\UserManagementController::class, 'changeUserPlan'])->name('users.change_plan');
    Route::post('/users/{user}/notify', [App\Http\Controllers\Admin\UserManagementController::class, 'sendUserNotification'])->name('users.notify');
    
    Route::get('/ads/create', [App\Http\Controllers\Admin\AdController::class, 'create'])->name('ads.create');
    Route::post('/ads', [App\Http\Controllers\Admin\AdController::class, 'store'])->name('ads.store');
    Route::get('/ads', [App\Http\Controllers\Admin\AdController::class, 'index'])->name('ads.index');
    
    // Admin Ads Approval Routes
    Route::prefix('ads')->name('ads.')->group(function () {
        Route::post('{id}/approve', [App\Http\Controllers\Admin\AdController::class, 'approve'])->name('approve');
        Route::post('{id}/reject', [App\Http\Controllers\Admin\AdController::class, 'reject'])->name('reject');
        Route::post('{id}/deactivate', [App\Http\Controllers\Admin\AdController::class, 'deactivate'])->name('deactivate');
        Route::post('{id}/activate', [App\Http\Controllers\Admin\AdController::class, 'activate'])->name('activate');
        Route::post('{id}/toggle-featured', [App\Http\Controllers\Admin\AdController::class, 'toggleFeatured'])->name('toggle_featured');
        Route::post('{id}/toggle-boost', [App\Http\Controllers\Admin\AdController::class, 'toggleBoost'])->name('toggle_boost');
        Route::post('bulk/approve', [App\Http\Controllers\Admin\AdController::class, 'bulkApprove'])->name('bulk_approve');
        Route::post('bulk/reject', [App\Http\Controllers\Admin\AdController::class, 'bulkReject'])->name('bulk_reject');
        Route::post('bulk/deactivate', [App\Http\Controllers\Admin\AdController::class, 'bulkDeactivate'])->name('bulk_deactivate');
        Route::get('{id}/show', [App\Http\Controllers\Admin\AdController::class, 'show'])->name('show');
        Route::get('{id}/edit', [App\Http\Controllers\Admin\AdController::class, 'edit'])->name('edit');
        Route::put('{id}', [App\Http\Controllers\Admin\AdController::class, 'update'])->name('update');
        Route::delete('{id}', [App\Http\Controllers\Admin\AdController::class, 'destroy'])->name('destroy');
        
        // Approval settings routes
        Route::get('settings/approval', [App\Http\Controllers\Admin\AdController::class, 'getApprovalSettings'])->name('settings.approval');
        Route::post('settings/approval', [App\Http\Controllers\Admin\AdController::class, 'updateApprovalSettings'])->name('settings.approval.update');
    });
    
    Route::get('/categories', [App\Http\Controllers\Admin\CategoryController::class, 'index'])->name('categories.index');
    Route::resource('categories', App\Http\Controllers\Admin\CategoryController::class)->except(['index', 'create', 'edit', 'show']);
    Route::resource('subcategories', App\Http\Controllers\Admin\SubcategoryController::class)->only(['store', 'update', 'destroy']);
    
    
    Route::get('/plans', [App\Http\Controllers\Admin\PlansController::class, 'index'])->name('plans.index');
    
    // Packages routes
    Route::resource('packages', App\Http\Controllers\Admin\PackagesController::class);
    
    // Package Pricing Tiers
    Route::post('packages/{package}/pricing', [App\Http\Controllers\Admin\PackagePricingController::class, 'store'])->name('packages.pricing.store');
    Route::delete('packages/pricing/{tier}', [App\Http\Controllers\Admin\PackagePricingController::class, 'destroy'])->name('packages.pricing.destroy');
    
    Route::get('/safety', function () {
        return view('admin.safety.index');
    })->name('safety.index');
    
    Route::get('/analytics', function () {
        return view('admin.analytics');
    })->name('analytics');
    
    Route::get('/analytics/ad-post', function () {
        return view('admin.analytics.ad_post');
    })->name('analytics.ad_post');
    
    Route::get('/analytics/ad/{adId}', [App\Http\Controllers\Admin\IndividualAdAnalyticsController::class, 'show'])->name('analytics.individual_ad');
    Route::get('/analytics/ad/{adId}/enhanced', [App\Http\Controllers\Admin\IndividualAdAnalyticsController::class, 'showEnhanced'])->name('analytics.individual_ad_enhanced');

    // Algorithm Control Panel Routes
    Route::prefix('algorithm')->group(function () {
        Route::get('/config', [App\Http\Controllers\Admin\AlgorithmController::class, 'getConfig']);
        Route::post('/config', [App\Http\Controllers\Admin\AlgorithmController::class, 'updateConfig']);
        Route::get('/performance', [App\Http\Controllers\Admin\AlgorithmController::class, 'getPerformance']);
        Route::post('/ab-test', [App\Http\Controllers\Admin\AlgorithmController::class, 'runABTest']);
        Route::get('/vip-settings', [App\Http\Controllers\Admin\AlgorithmController::class, 'getVIPSettings']);
        Route::post('/vip-settings', [App\Http\Controllers\Admin\AlgorithmController::class, 'updateVIPSettings']);
        Route::post('/reset-defaults', [App\Http\Controllers\Admin\AlgorithmController::class, 'resetDefaults']);
        Route::post('/emergency-stop', [App\Http\Controllers\Admin\AlgorithmController::class, 'emergencyStop']);
        Route::post('/clear-cache', [App\Http\Controllers\Admin\AlgorithmController::class, 'clearCache']);
        Route::post('/optimize-cache', [App\Http\Controllers\Admin\AlgorithmController::class, 'optimizeCache']);
        Route::get('/real-time-status', [App\Http\Controllers\Admin\AlgorithmController::class, 'getRealTimeStatus']);
        Route::get('/ad/{adId}/recommendations', [App\Http\Controllers\Admin\AlgorithmController::class, 'getAdRecommendations']);
        Route::get('/user/{userId}/insights', [App\Http\Controllers\Admin\AlgorithmController::class, 'getUserBehaviorInsights']);
        Route::get('/category/{categoryId}/competitive-analysis', [App\Http\Controllers\Admin\AlgorithmController::class, 'getCompetitiveAnalysis']);
        Route::post('/export-data', [App\Http\Controllers\Admin\AlgorithmController::class, 'exportData']);
        Route::get('/user-plans', [App\Http\Controllers\Admin\AlgorithmController::class, 'getUserPlans']);
        Route::get('/ad-packages', [App\Http\Controllers\Admin\AlgorithmController::class, 'getAdPackages']);
    });

    // Algorithm Control Panel Routes
    Route::get('/algorithm/control', [App\Http\Controllers\Admin\AlgorithmController::class, 'showControlPanel'])->name('algorithm.control');

    // Test route for debugging
    Route::get('/test-algorithm', function () {
        return response()->json([
            'success' => true,
            'message' => 'Algorithm API is working',
            'timestamp' => now()->toDateTimeString()
        ]);
    });

    // Plans API Routes
    Route::prefix('plans')->name('plans.')->group(function () {
        Route::get('/export', [App\Http\Controllers\Admin\PlansController::class, 'export'])->name('export');
        Route::post('/{plan}/set-default', [App\Http\Controllers\Admin\PlansController::class, 'setDefault'])->name('setDefault');
        Route::get('/{plan}/analytics', [App\Http\Controllers\Admin\PlansController::class, 'analytics'])->name('analytics');
        // Use ID parameter to match controller logic
        Route::post('/{id}/toggle-status', [App\Http\Controllers\Admin\PlansController::class, 'toggleStatus'])->name('toggle_status');
        Route::post('/{id}/toggle-default', [App\Http\Controllers\Admin\PlansController::class, 'toggleDefault'])->name('toggle_default');
        Route::post('/bulk-action', [App\Http\Controllers\Admin\PlansController::class, 'apiBulkAction'])->name('bulk_action');
        Route::post('/api-store', [App\Http\Controllers\Admin\PlansController::class, 'apiStore'])->name('api_store');
        Route::post('/api-update/{plan}', [App\Http\Controllers\Admin\PlansController::class, 'apiUpdate'])->name('api_update');
        // Wildcard route moved to bottom to prevent shadowing
        Route::get('/{plan}', [App\Http\Controllers\Admin\PlansController::class, 'apiShow'])->name('api_show');
        Route::delete('/{plan}', [App\Http\Controllers\Admin\PlansController::class, 'destroy'])->name('destroy');
    });

    // Plans CRUD Routes
    Route::prefix('plans')->name('plans.')->group(function () {
        Route::get('/', [App\Http\Controllers\Admin\PlansController::class, 'index'])->name('index');
        Route::get('/create', [App\Http\Controllers\Admin\PlansController::class, 'create'])->name('create');
        Route::post('/', [App\Http\Controllers\Admin\PlansController::class, 'store'])->name('store');
        Route::get('/{plan}/edit', [App\Http\Controllers\Admin\PlansController::class, 'edit'])->name('edit');
        Route::put('/{plan}', [App\Http\Controllers\Admin\PlansController::class, 'update'])->name('update');
        Route::delete('/{plan}', [App\Http\Controllers\Admin\PlansController::class, 'destroy'])->name('destroy');
    });

    Route::get('/safety/algorithm-settings', function () {
        return view('admin.safety.algorithm_settings');
    })->name('safety.algorithm_settings');
    
    Route::get('/safety/trust-management', function () {
        return view('admin.safety.trust_management');
    })->name('safety.trust_management');
    
    Route::get('/settings', function () {
        return view('admin.settings.index');
    })->name('settings.index');
    
    Route::get('/settings/location', function () {
        $settings = \App\Models\Setting::all()->pluck('value', 'key');
        return view('admin.settings.location', compact('settings'));
    })->name('settings.location');

    Route::prefix('settings')->name('settings.')->group(function () {
        Route::post('/general', [App\Http\Controllers\Admin\SettingsController::class, 'update'])->name('general.update');
        Route::get('/notifications', [App\Http\Controllers\Admin\PushNotificationSettingController::class, 'index'])->name('notifications');
        Route::post('/notifications', [App\Http\Controllers\Admin\PushNotificationSettingController::class, 'update'])->name('notifications.update');
        Route::post('/notifications/test', [App\Http\Controllers\Admin\PushNotificationSettingController::class, 'test'])->name('notifications.test');
        
        // Payment Gateway Settings Routes
        Route::get('/payment-gateways', [App\Http\Controllers\Admin\PaymentSettingsController::class, 'index'])->name('payment_gateways');
        Route::put('/payment-gateways/{gateway}', [App\Http\Controllers\Admin\PaymentSettingsController::class, 'update'])->name('payment_gateways.update');
        Route::post('/payment-gateways/{gateway}/test', [App\Http\Controllers\Admin\PaymentSettingsController::class, 'testConnection'])->name('payment_gateways.test');
    });

        // Payment Gateway Routes
        Route::get('/payment-gateways', [App\Http\Controllers\Admin\PaymentGatewayController::class, 'index'])->name('payment-gateways.index');
        Route::get('/payment-gateways/create', [App\Http\Controllers\Admin\PaymentGatewayController::class, 'create'])->name('payment-gateways.create');
        Route::post('/payment-gateways', [App\Http\Controllers\Admin\PaymentGatewayController::class, 'store'])->name('payment-gateways.store');
        Route::get('/payment-gateways/{paymentGateway}/edit', [App\Http\Controllers\Admin\PaymentGatewayController::class, 'edit'])->name('payment-gateways.edit');
        Route::put('/payment-gateways/{paymentGateway}', [App\Http\Controllers\Admin\PaymentGatewayController::class, 'update'])->name('payment-gateways.update');
        Route::delete('/payment-gateways/{paymentGateway}', [App\Http\Controllers\Admin\PaymentGatewayController::class, 'destroy'])->name('payment-gateways.destroy');
        Route::post('/payment-gateways/{paymentGateway}/toggle-status', [App\Http\Controllers\Admin\PaymentGatewayController::class, 'toggleStatus'])->name('payment-gateways.toggle-status');
        Route::get('/payment-gateways/{paymentGateway}/payment-methods', [App\Http\Controllers\Admin\PaymentGatewayController::class, 'paymentMethods'])->name('payment-gateways.payment-methods');
        Route::post('/payment-gateways/{paymentGateway}/payment-methods', [App\Http\Controllers\Admin\PaymentGatewayController::class, 'addPaymentMethod'])->name('payment-gateways.add-payment-method');
        Route::post('/payment-methods/{paymentMethod}/toggle', [App\Http\Controllers\Admin\PaymentGatewayController::class, 'togglePaymentMethod'])->name('payment-methods.toggle');
        Route::get('/payment-gateways/{paymentGateway}/analytics', [App\Http\Controllers\Admin\PaymentGatewayController::class, 'analytics'])->name('payment-gateways.analytics');

        // Notification Routes
        Route::get('/notifications/search/users', [App\Http\Controllers\Admin\NotificationController::class, 'searchUsers'])->name('notifications.search.users');
        Route::get('/notifications/search/ads', [App\Http\Controllers\Admin\NotificationController::class, 'searchAds'])->name('notifications.search.ads');
        Route::get('/notifications/search/cities', [App\Http\Controllers\Admin\NotificationController::class, 'searchCities'])->name('notifications.search.cities');
        Route::get('/notifications/search/states', [App\Http\Controllers\Admin\NotificationController::class, 'searchStates'])->name('notifications.search.states');
        Route::get('/notifications/search/countries', [App\Http\Controllers\Admin\NotificationController::class, 'searchCountries'])->name('notifications.search.countries');
        Route::get('/notifications', [App\Http\Controllers\Admin\NotificationController::class, 'index'])->name('notifications.index');
        Route::get('/notifications/create', [App\Http\Controllers\Admin\NotificationController::class, 'create'])->name('notifications.create');
        Route::post('/notifications', [App\Http\Controllers\Admin\NotificationController::class, 'store'])->name('notifications.store');
        Route::get('/notifications/{notification}', [App\Http\Controllers\Admin\NotificationController::class, 'show'])->name('notifications.show');
        Route::get('/notifications/{notification}/edit', [App\Http\Controllers\Admin\NotificationController::class, 'edit'])->name('notifications.edit');
        Route::put('/notifications/{notification}', [App\Http\Controllers\Admin\NotificationController::class, 'update'])->name('notifications.update');
        Route::delete('/notifications/{notification}', [App\Http\Controllers\Admin\NotificationController::class, 'destroy'])->name('notifications.destroy');
        Route::post('/notifications/{notification}/send', [App\Http\Controllers\Admin\NotificationController::class, 'send'])->name('notifications.send');
        Route::get('/notifications/{notification}/analytics', [App\Http\Controllers\Admin\NotificationController::class, 'analytics'])->name('notifications.analytics');

        // Safety & Reporting
        Route::get('/guardian/logs', [App\Http\Controllers\Admin\GuardianDashboardController::class, 'index'])->name('guardian.logs');
        Route::post('/guardian/logs/{id}/overwrite', [App\Http\Controllers\Admin\GuardianDashboardController::class, 'overwrite'])->name('guardian.overwrite');
        
        Route::get('/safety/reports', [App\Http\Controllers\Admin\AdSafetyController::class, 'index'])->name('safety.reports');
        Route::post('/safety/reports/{id}/handle', [App\Http\Controllers\Admin\AdSafetyController::class, 'handle'])->name('safety.reports.handle');
        Route::post('/safety/settings', [App\Http\Controllers\Admin\AdSafetyController::class, 'updateSettings'])->name('safety.settings.update');
        Route::post('/safety/trust-algorithm', [App\Http\Controllers\Admin\AdSafetyController::class, 'updateTrustAlgorithm'])->name('safety.algorithm.update');
        Route::get('/notifications/scheduled', [App\Http\Controllers\Admin\NotificationController::class, 'scheduled'])->name('notifications.scheduled');
        Route::get('/notifications/sent', [App\Http\Controllers\Admin\NotificationController::class, 'sent'])->name('notifications.sent');

        // Monetization Routes
        Route::prefix('monetization')->name('monetization.')->group(function () {
            Route::get('/', [App\Http\Controllers\Admin\MonetizationController::class, 'index'])->name('index');
            Route::put('/network/{id}', [App\Http\Controllers\Admin\MonetizationController::class, 'updateNetwork'])->name('network.update');
            Route::post('/ad-unit', [App\Http\Controllers\Admin\MonetizationController::class, 'storeAdUnit'])->name('ad_unit.store');
            Route::put('/ad-unit/{id}', [App\Http\Controllers\Admin\MonetizationController::class, 'updateAdUnit'])->name('ad_unit.update');
            Route::delete('/ad-unit/{id}', [App\Http\Controllers\Admin\MonetizationController::class, 'destroyAdUnit'])->name('ad_unit.destroy');
        });

    // Banner Management Routes
    Route::prefix('banners')->name('banners.')->group(function () {
        // Banner Packages
        Route::get('/packages', [App\Http\Controllers\Admin\BannerPackageController::class, 'index'])->name('packages.index');
        Route::get('/packages/create', [App\Http\Controllers\Admin\BannerPackageController::class, 'create'])->name('packages.create');
        Route::post('/packages', [App\Http\Controllers\Admin\BannerPackageController::class, 'store'])->name('packages.store');
        Route::get('/packages/{bannerPackage}/edit', [App\Http\Controllers\Admin\BannerPackageController::class, 'edit'])->name('packages.edit');
        Route::put('/packages/{bannerPackage}', [App\Http\Controllers\Admin\BannerPackageController::class, 'update'])->name('packages.update');
        Route::delete('/packages/{bannerPackage}', [App\Http\Controllers\Admin\BannerPackageController::class, 'destroy'])->name('packages.destroy');
        Route::post('/packages/{bannerPackage}/toggle', [App\Http\Controllers\Admin\BannerPackageController::class, 'toggleStatus'])->name('packages.toggle');
        
        // Banner Management
        Route::get('/', [App\Http\Controllers\Admin\BannerManagementController::class, 'index'])->name('index');
        Route::get('/create', [App\Http\Controllers\Admin\BannerManagementController::class, 'create'])->name('create');
        Route::post('/', [App\Http\Controllers\Admin\BannerManagementController::class, 'store'])->name('store');
        Route::get('/{banner}/edit', [App\Http\Controllers\Admin\BannerManagementController::class, 'edit'])->name('edit');
        Route::put('/{banner}', [App\Http\Controllers\Admin\BannerManagementController::class, 'update'])->name('update');
        Route::delete('/{banner}', [App\Http\Controllers\Admin\BannerManagementController::class, 'destroy'])->name('destroy');
        Route::post('/{banner}/approve', [App\Http\Controllers\Admin\BannerManagementController::class, 'approve'])->name('approve');
        Route::post('/{banner}/reject', [App\Http\Controllers\Admin\BannerManagementController::class, 'reject'])->name('reject');
        Route::post('/{banner}/pause', [App\Http\Controllers\Admin\BannerManagementController::class, 'pause'])->name('pause');
        Route::post('/{banner}/resume', [App\Http\Controllers\Admin\BannerManagementController::class, 'resume'])->name('resume');
        Route::post('/reorder', [App\Http\Controllers\Admin\BannerManagementController::class, 'reorder'])->name('reorder');
        Route::post('/{banner}/toggle-status', [App\Http\Controllers\Admin\BannerManagementController::class, 'toggleStatus'])->name('toggle_status');
        Route::get('/analytics', [App\Http\Controllers\Admin\BannerManagementController::class, 'analytics'])->name('analytics');
    });
    

    // Blog Management Routes
    Route::post('blogs/upload-image', [App\Http\Controllers\Admin\BlogController::class, 'uploadImage'])->name('blogs.uploadImage');
    Route::resource('blogs', App\Http\Controllers\Admin\BlogController::class);
    
    // Category Custom Fields & Global Library
    Route::get('/custom-fields-library', [App\Http\Controllers\Admin\GlobalFieldController::class, 'index'])->name('global_fields.index');
    Route::get('/api/global-fields', [App\Http\Controllers\Admin\GlobalFieldController::class, 'list'])->name('global_fields.list');
    Route::resource('global-fields', App\Http\Controllers\Admin\GlobalFieldController::class)->except(['index', 'create', 'edit', 'show']);

    Route::resource('category-fields', App\Http\Controllers\Admin\CategoryFieldController::class);
    Route::resource('blog-categories', App\Http\Controllers\Admin\BlogCategoryController::class);

    // Pages Management Routes    
    // Pages Management
    Route::post('pages/{page}/toggle-app-visibility', [App\Http\Controllers\Admin\PagesController::class, 'toggleAppVisibility'])->name('pages.toggleAppVisibility');
    Route::resource('pages', App\Http\Controllers\Admin\PagesController::class);

    // Admin Profile Routes
    Route::get('/profile', [App\Http\Controllers\Admin\ProfileController::class, 'show'])->name('profile.show');
    Route::get('/profile/edit', [App\Http\Controllers\Admin\ProfileController::class, 'edit'])->name('profile.edit');
    Route::put('/profile', [App\Http\Controllers\Admin\ProfileController::class, 'update'])->name('profile.update');
    Route::put('/profile/password', [App\Http\Controllers\Admin\ProfileController::class, 'updatePassword'])->name('profile.password.update');

});

// Installation Routes
Route::get('/install', [InstallController::class, 'showWelcome'])->name('install.welcome');
Route::get('/install/requirements', [InstallController::class, 'showRequirements'])->name('install.requirements');
Route::get('/install/database', [InstallController::class, 'showDatabase'])->name('install.database');
Route::post('/install/process', [InstallController::class, 'processDatabase'])->name('install.process');
Route::get('/install/complete', [InstallController::class, 'showComplete'])->name('install.complete');

// Documentation Routes
Route::prefix('docs')->name('docs.')->group(function () {
    Route::get('/', [DocumentationController::class, 'index'])->name('index');
    Route::get('/installation', [DocumentationController::class, 'installation'])->name('installation');
    Route::get('/admin', [DocumentationController::class, 'adminGuide'])->name('admin');
    Route::get('/notifications', [DocumentationController::class, 'pushNotifications'])->name('notifications');
    Route::get('/deployment', [DocumentationController::class, 'deployment'])->name('deployment');
    Route::get('/api', [DocumentationController::class, 'api'])->name('api');
});

// Admin API Routes (called by JS in Admin Panel)
Route::get('/api/admin/ads/stats', [App\Http\Controllers\Admin\AdController::class, 'stats'])->name('api.admin.ads.stats')->middleware([\App\Http\Middleware\CheckAdmin::class]);
Route::get('/api/admin/ads/charts', [App\Http\Controllers\Admin\AdController::class, 'charts'])->name('api.admin.ads.charts')->middleware([\App\Http\Middleware\CheckAdmin::class]);


// Home route
Route::get('/', function () {
    return view('welcome');
});

// Simple fix route for database table creation
Route::get('/simple-fix', function () {
    // Try to find database file
    $databasePath = null;
    $possiblePaths = [
        base_path('database/database.sqlite'),
        base_path('../database/database.sqlite'), 
        base_path('storage/database.sqlite'),
        base_path('database.sqlite')
    ];

    foreach ($possiblePaths as $path) {
        if (file_exists($path)) {
            $databasePath = $path;
            break;
        }
    }

    if (!$databasePath) {
        return "<h1>❌ Could not find SQLite database file!</h1>
        <p>Please check these locations:</p>
        <ul>" . implode('', array_map(fn($path) => "<li>$path</li>", $possiblePaths)) . "</ul>
        <p><strong>Manual Solution:</strong> Create a file called 'database.sqlite' in your clx_backend folder</p>";
    }

    try {
        // Connect to database
        $pdo = new PDO("sqlite:$databasePath");
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // Check if table exists
        $stmt = $pdo->query("SELECT name FROM sqlite_master WHERE type='table' AND name='user_plans';");
        $tableExists = $stmt->fetch();
        
        if (!$tableExists) {
            // Create table
            $sql = "CREATE TABLE user_plans (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                plan_name TEXT NOT NULL,
                price DECIMAL(10,2) DEFAULT 0.00,
                duration_days INTEGER DEFAULT 30,
                post_limit INTEGER NULL,
                lead_limit INTEGER NULL,
                analytics_tier TEXT DEFAULT 'basic',
                validity_days INTEGER DEFAULT 30,
                ad_free BOOLEAN DEFAULT 0,
                has_analytics BOOLEAN DEFAULT 0,
                verified_badge BOOLEAN DEFAULT 0,
                theme TEXT NULL,
                status TEXT DEFAULT 'Active',
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )";
            
            $pdo->exec($sql);
        }
        
        // Check if we have data
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM user_plans");
        $rowCount = $stmt->fetch(PDO::FETCH_ASSOC);
        $count = $rowCount['count'];
        
        if ($count == 0) {
            // Insert your exact premium plans
            $inserts = [
                "INSERT INTO user_plans (plan_name, price, duration_days, post_limit, lead_limit, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, theme, status) VALUES ('Standard', 0.00, 30, 5, 10, 'basic', 30, 0, 1, 0, 'standard', 'Active')",
                "INSERT INTO user_plans (plan_name, price, duration_days, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, badge_style, theme, halo_effect, ad_border, status) VALUES ('VIP Buyer', 19.99, 30, 'advanced', 30, 0, 1, 1, 'blue_vip', 'vip_buyer_theme', 'blue_glow', 'blue_border', 'Active')",
                "INSERT INTO user_plans (plan_name, price, duration_days, post_limit, lead_limit, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, badge_style, theme, halo_effect, ad_border, status) VALUES ('VIP Seller', 24.99, 30, 50, 100, 'premium', 30, 0, 1, 1, 'gold_vip', 'vip_seller_theme', 'gold_glow', 'gold_border', 'Active')",
                "INSERT INTO user_plans (plan_name, price, duration_days, post_limit, lead_limit, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, badge_style, theme, halo_effect, ad_border, status) VALUES ('VIP Pro', 39.99, 30, 200, 500, 'enterprise', 30, 1, 1, 1, 'purple_premium', 'vip_pro_theme', 'purple_glow', 'purple_border', 'Active')"
            ];
            
            foreach ($inserts as $sql) {
                $pdo->exec($sql);
            }
        }
        
        // Verify and display results
        $stmt = $pdo->query("SELECT plan_name, price, status FROM user_plans ORDER BY price DESC");
        $plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $html = "<!DOCTYPE html>
        <html>
        <head>
            <title>✅ SUCCESS! Premium Plans Created</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 40px; background: #f8fafc; }
                .container { max-width: 800px; margin: 0 auto; background: white; padding: 30px; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
                .success { color: #10b981; font-weight: bold; font-size: 20px; }
                .highlight { background: #fef3c7; padding: 20px; border-radius: 8px; border-left: 5px solid #f59e0b; }
                table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                th, td { border: 1px solid #e5e7eb; padding: 12px; text-align: left; }
                th { background: #f9fafb; font-weight: bold; }
                .btn { background: #7c3aed; color: white; padding: 15px 30px; border: none; border-radius: 8px; cursor: pointer; font-size: 18px; text-decoration: none; display: inline-block; margin: 15px 0; }
                .btn:hover { background: #6d28d9; }
            </style>
        </head>
        <body>
        <div class='container'>
            <h1>🎉 SUCCESS! Your Premium Plan system is now ready!</h1>
            <p class='success'>✅ Database table created and premium plans inserted successfully!</p>
            
            <h3>📋 Your Premium Plans:</h3>
            <table>
                <tr><th>Plan Name</th><th>Price</th><th>Status</th></tr>";
        
        foreach ($plans as $plan) {
            $html .= "<tr><td>{$plan['plan_name']}</td><td>₹{$plan['price']}</td><td>{$plan['status']}</td></tr>";
        }
        
        $html .= "</table>
            
            <div class='highlight'>
                <h3>✅ Your Complete Plan Structure:</h3>
                <ul>
                    <li><strong>Standard Plan</strong> (Free): Basic features with ads</li>
                    <li><strong>VIP Buyer Plan</strong> (₹19.99): Call + WhatsApp buttons, premium theme</li>
                    <li><strong>VIP Seller Plan</strong> (₹24.99): Enhanced visibility, advanced analytics</li>
                    <li><strong>VIP Pro Plan</strong> (₹39.99): All features + ad-free experience</li>
                </ul>
            </div>
            
            <p><a href='/admin/plans' class='btn'>Go to Admin Plans Dashboard →</a></p>
            <p><a href='/admin/dashboard' class='btn' style='background: #3b82f6;'>Go to Admin Dashboard</a></p>
        </div>
        </body>
        </html>";
        
        return $html;
        
    } catch (PDOException $e) {
        return "<h1>❌ Database Error: " . $e->getMessage() . "</h1>
        <p><strong>Manual Solution:</strong></p>
        <div style='background: #1f2937; color: #f9fafb; padding: 20px; border-radius: 8px; font-family: monospace; overflow-x: auto; margin: 20px 0;'>
        # 1. Create database file if it doesn't exist<br>
        # 2. Run this SQL:<br>
        CREATE TABLE user_plans (<br>
            id INTEGER PRIMARY KEY AUTOINCREMENT,<br>
            plan_name TEXT NOT NULL,<br>
            price DECIMAL(10,2) DEFAULT 0.00,<br>
            duration_days INTEGER DEFAULT 30,<br>
            post_limit INTEGER NULL,<br>
            lead_limit INTEGER NULL,<br>
            analytics_tier TEXT DEFAULT 'basic',<br>
            validity_days INTEGER DEFAULT 30,<br>
            ad_free BOOLEAN DEFAULT 0,<br>
            has_analytics BOOLEAN DEFAULT 0,<br>
            verified_badge BOOLEAN DEFAULT 0,<br>
            theme TEXT NULL,<br>
            status TEXT DEFAULT 'Active',<br>
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,<br>
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP<br>
        );<br><br>
        # 3. Insert your plans:<br>
        INSERT INTO user_plans (plan_name, price, duration_days, post_limit, lead_limit, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, theme, status) VALUES ('Standard', 0.00, 30, 5, 10, 'basic', 30, 0, 1, 0, 'standard', 'Active');<br>
        INSERT INTO user_plans (plan_name, price, duration_days, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, badge_style, theme, halo_effect, ad_border, status) VALUES ('VIP Buyer', 19.99, 30, 'advanced', 30, 0, 1, 1, 'blue_vip', 'vip_buyer_theme', 'blue_glow', 'blue_border', 'Active');<br>
        INSERT INTO user_plans (plan_name, price, duration_days, post_limit, lead_limit, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, badge_style, theme, halo_effect, ad_border, status) VALUES ('VIP Seller', 24.99, 30, 50, 100, 'premium', 30, 0, 1, 1, 'gold_vip', 'vip_seller_theme', 'gold_glow', 'gold_border', 'Active');<br>
        INSERT INTO user_plans (plan_name, price, duration_days, post_limit, lead_limit, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, badge_style, theme, halo_effect, ad_border, status) VALUES ('VIP Pro', 39.99, 30, 200, 500, 'enterprise', 30, 1, 1, 1, 'purple_premium', 'vip_pro_theme', 'purple_glow', 'purple_border', 'Active');<br>
        </div>";
    } catch (Exception $e) {
        return "<h1>❌ Error: " . $e->getMessage() . "</h1>";
    }
});

