<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\DashboardController;
use App\Http\Controllers\WebAuthController;

use App\Http\Controllers\Admin\TenantController;
use App\Http\Controllers\Admin\UserController;
use App\Http\Controllers\Admin\SubscriptionController;
use App\Http\Controllers\Admin\RoleController;
use App\Http\Controllers\Admin\SettingController;

use App\Http\Controllers\Tenant\ProductController;
use App\Http\Controllers\Tenant\CustomerController;
use App\Http\Controllers\Tenant\PosController;
use App\Http\Controllers\Tenant\CategoryController;
use App\Http\Controllers\Tenant\BrandController;
use App\Http\Controllers\Tenant\ManufacturerController;
use App\Http\Controllers\Tenant\UnitController;
use App\Http\Controllers\Tenant\SupplierController;
use App\Http\Controllers\Tenant\StoreLocationController;

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

Route::get('/login', [WebAuthController::class, 'showLoginForm'])->name('login');
Route::post('/login', [WebAuthController::class, 'login']);
Route::post('/logout', [WebAuthController::class, 'logout'])->name('logout');

Route::get('/register', [WebAuthController::class, 'showRegisterForm'])->name('register');
Route::post('/register', [WebAuthController::class, 'register']);

// Tenant Auth
Route::get('/tenant/login', [\App\Http\Controllers\Tenant\AuthController::class, 'showLoginForm'])->name('tenant.login');
Route::post('/tenant/login', [\App\Http\Controllers\Tenant\AuthController::class, 'login']);
Route::post('/tenant/logout', [\App\Http\Controllers\Tenant\AuthController::class, 'logout'])->name('tenant.logout');

use App\Http\Controllers\Admin\TenantCategoryController;

Route::middleware(['auth', '2fa'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');

    // Admin Routes
    Route::middleware(['role:Admin|Developer'])->prefix('admin')->name('admin.')->group(function () {
        // 2FA Routes
        Route::get('2fa/setup', [\App\Http\Controllers\Admin\TwoFactorController::class, 'showSetupForm'])->name('2fa.setup');
        Route::post('2fa/confirm', [\App\Http\Controllers\Admin\TwoFactorController::class, 'confirm'])->name('2fa.confirm');
        Route::get('2fa/verify', [\App\Http\Controllers\Admin\TwoFactorController::class, 'showVerifyForm'])->name('2fa.verify');
        Route::post('2fa/verify', [\App\Http\Controllers\Admin\TwoFactorController::class, 'verify']);

        Route::resource('tenant-categories', TenantCategoryController::class);
        Route::post('ai/generate-prompt', [\App\Http\Controllers\Admin\AiController::class, 'generatePrompt'])->name('ai.generate-prompt');
        Route::resource('tenants', TenantController::class);
        Route::resource('users', UserController::class);
        Route::resource('subscriptions', SubscriptionController::class)->except(['create', 'store', 'destroy']);
        Route::post('/subscriptions/{subscription}/cancel', [SubscriptionController::class, 'cancel'])->name('subscriptions.cancel');
        Route::resource('plans', \App\Http\Controllers\Admin\PlanController::class);
        Route::resource('roles', RoleController::class);
        Route::get('/settings', [SettingController::class, 'index'])->name('settings.index');
        Route::put('/settings', [SettingController::class, 'update'])->name('settings.update');
        Route::post('/settings/test-serper', [SettingController::class, 'testSerper'])->name('settings.test-serper');
        Route::post('/settings/test-rapidapi', [SettingController::class, 'testRapidAPI'])->name('settings.test-rapidapi');
        Route::post('/settings/test-openrouter', [SettingController::class, 'testOpenRouter'])->name('settings.test-openrouter');
        Route::post('/settings/test-numverify', [SettingController::class, 'testNumverify'])->name('settings.test-numverify');
        Route::post('/settings/test-pokeapi', [SettingController::class, 'testPokeAPI'])->name('settings.test-pokeapi');
        
        // Security Settings
        Route::get('/security', [\App\Http\Controllers\Admin\SecuritySettingController::class, 'index'])->name('security.index');
        Route::put('/security', [\App\Http\Controllers\Admin\SecuritySettingController::class, 'update'])->name('security.update');
        
        // IP Blocking
        Route::resource('blocked-ips', \App\Http\Controllers\Admin\BlockedIpController::class)->only(['index', 'store', 'destroy']);

        // Login Logs
        Route::get('/login-logs', [\App\Http\Controllers\Admin\LoginLogController::class, 'index'])->name('login-logs.index');

        // Backups
        Route::resource('backups', \App\Http\Controllers\Admin\BackupController::class)->only(['index', 'store', 'destroy']);
        Route::get('backups/{fileName}/download', [\App\Http\Controllers\Admin\BackupController::class, 'download'])->name('backups.download');
    });

    // Tenant Manager Routes
    Route::middleware(['role:Manager', 'tenant.context', 'tenant.subscription'])->prefix('tenant')->name('tenant.')->group(function () {
        // Dashboard
        Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
        
        // Subscription Management
        Route::get('/subscription/plans', [\App\Http\Controllers\Tenant\SubscriptionController::class, 'index'])->name('subscription.index');
        Route::post('/subscription/subscribe/{plan}', [\App\Http\Controllers\Tenant\SubscriptionController::class, 'store'])->name('subscription.store');

        Route::post('products/import', [ProductController::class, 'import'])->name('products.import');
        Route::get('products/template', [ProductController::class, 'downloadTemplate'])->name('products.template');
        Route::resource('products', ProductController::class);
        Route::resource('pos', PosController::class)->only(['index', 'store']);
        
        // New Sell System
        Route::get('sell', [\App\Http\Controllers\Tenant\SellController::class, 'index'])->name('sell.index');
        Route::post('sell', [\App\Http\Controllers\Tenant\SellController::class, 'store'])->name('sell.store');
        Route::get('sell/products', [\App\Http\Controllers\Tenant\SellController::class, 'searchProducts'])->name('sell.products');

        // Sales Returns
        Route::resource('returns', \App\Http\Controllers\Tenant\SaleReturnController::class)->only(['index', 'create', 'store']);
        Route::post('returns/search', [\App\Http\Controllers\Tenant\SaleReturnController::class, 'search'])->name('returns.search');

        // Reports
        Route::prefix('reports')->name('reports.')->controller(\App\Http\Controllers\Tenant\ReportController::class)->group(function() {
            Route::get('/', 'index')->name('index');
            Route::get('/sales', 'sales')->name('sales');
            Route::get('/top-products', 'topProducts')->name('top-products');
            Route::get('/inventory', 'inventory')->name('inventory');
            Route::get('/detailed', 'detailed')->name('detailed');
            Route::get('/stock', 'stockReport')->name('stock');
            Route::get('/stock/export', 'exportStockReport')->name('stock.export');
            Route::get('/stock-movement', 'stockMovement')->name('stock-movement');
            Route::get('/expiring-products', 'detailed')->name('expiring_products');
        });

        // Settings
        Route::get('settings', [\App\Http\Controllers\Tenant\SettingController::class, 'index'])->name('settings.index');
        Route::put('settings', [\App\Http\Controllers\Tenant\SettingController::class, 'update'])->name('settings.update');
        Route::post('settings/generate-demo-data', [\App\Http\Controllers\Tenant\SettingController::class, 'generateDemoData'])->name('settings.generate-demo');
        Route::post('settings/clean-data', [\App\Http\Controllers\Tenant\SettingController::class, 'cleanData'])->name('settings.clean-data');

        // Profile
        Route::get('/profile', [\App\Http\Controllers\Tenant\ProfileController::class, 'edit'])->name('profile.edit');
        Route::patch('/profile', [\App\Http\Controllers\Tenant\ProfileController::class, 'update'])->name('profile.update');
        Route::put('/profile/password', [\App\Http\Controllers\Tenant\ProfileController::class, 'updatePassword'])->name('profile.password');
        
        // Catalog
        Route::resource('categories', CategoryController::class);
        Route::resource('brands', BrandController::class);
        Route::resource('manufacturers', ManufacturerController::class);
        Route::get('/manufacturers/{manufacturer}/summary', [ManufacturerController::class, 'summary'])->name('manufacturers.summary');
        Route::resource('units', UnitController::class);

        // Inventory / Operations
        Route::resource('suppliers', SupplierController::class);
        Route::resource('locations', StoreLocationController::class);
        
        // Purchase Requisitions & Purchases
        Route::resource('requisitions', App\Http\Controllers\Tenant\PurchaseRequisitionController::class);
        Route::post('/requisitions/{requisition}/approve-process', [App\Http\Controllers\Tenant\PurchaseRequisitionController::class, 'approve'])->name('requisitions.approve');
        Route::post('/requisitions/store-supplier', [App\Http\Controllers\Tenant\PurchaseRequisitionController::class, 'storeSupplier'])->name('requisitions.store-supplier');
        Route::post('/requisitions/store-product', [App\Http\Controllers\Tenant\PurchaseRequisitionController::class, 'storeProduct'])->name('requisitions.store-product');
        Route::resource('purchases', App\Http\Controllers\Tenant\PurchaseController::class);
        Route::get('/requisitions/{requisition}/convert-to-purchase', [App\Http\Controllers\Tenant\PurchaseController::class, 'createFromRequisition'])->name('requisitions.convert-to-purchase');

        Route::resource('customers', CustomerController::class);
        Route::get('/customers/{customer}/history', [CustomerController::class, 'history'])->name('customers.history');
        Route::post('/customers/{customer}/convert-points', [CustomerController::class, 'convertPoints'])->name('customers.convert-points');
        
        // Stock Management
        Route::prefix('stock')->name('stock.')->group(function() {
            Route::get('/adjustments', [\App\Http\Controllers\Tenant\StockAdjustmentController::class, 'index'])->name('adjustments.index');
            Route::post('/adjustments', [\App\Http\Controllers\Tenant\StockAdjustmentController::class, 'store'])->name('adjustments.store');
            Route::get('/adjustments/history', [\App\Http\Controllers\Tenant\StockAdjustmentController::class, 'history'])->name('adjustments.history');
            
            // Stock In
            Route::get('/in', [\App\Http\Controllers\Tenant\StockInController::class, 'index'])->name('in.index');
            Route::get('/in/search-products', [\App\Http\Controllers\Tenant\StockInController::class, 'searchProducts'])->name('in.search-products');
            Route::get('/in/search-mrrs', [\App\Http\Controllers\Tenant\StockInController::class, 'searchMrrs'])->name('in.search-mrrs');
            Route::post('/in', [\App\Http\Controllers\Tenant\StockInController::class, 'store'])->name('in.store');
            Route::get('/in/{id}/report', [\App\Http\Controllers\Tenant\StockInController::class, 'report'])->name('in.report');
            Route::post('/in/import', [\App\Http\Controllers\Tenant\StockInController::class, 'import'])->name('in.import');

            // MRR (Material Receipt Report)
            Route::get('/mrr', [\App\Http\Controllers\Tenant\StockInController::class, 'mrrIndex'])->name('mrr.index');
            Route::get('/mrr/create/{requisition?}', [\App\Http\Controllers\Tenant\StockInController::class, 'mrrCreate'])->name('mrr.create');
            Route::post('/mrr', [\App\Http\Controllers\Tenant\StockInController::class, 'mrrStore'])->name('mrr.store');
        });
        
        // Notifications
        Route::get('/notifications', [\App\Http\Controllers\Tenant\NotificationController::class, 'index'])->name('notifications.index');
        Route::get('/notifications/{id}', [\App\Http\Controllers\Tenant\NotificationController::class, 'show'])->name('notifications.show');
        Route::post('/notifications/{id}/read', [\App\Http\Controllers\Tenant\NotificationController::class, 'markAsRead'])->name('notifications.read');
        Route::post('/notifications/read-all', [\App\Http\Controllers\Tenant\NotificationController::class, 'markAllAsRead'])->name('notifications.read-all');
        Route::get('/notifications/unread-count', [\App\Http\Controllers\Tenant\NotificationController::class, 'getUnreadCount'])->name('notifications.unread-count');
        Route::get('/notifications/recent', [\App\Http\Controllers\Tenant\NotificationController::class, 'getRecentNotifications'])->name('notifications.recent');
    });
});

// Payment Routes
Route::prefix('payment')->name('payment.')->group(function () {
    Route::get('/success', [\App\Http\Controllers\PaymentController::class, 'paymentSuccess'])->name('success');
    Route::post('/callback', [\App\Http\Controllers\PaymentController::class, 'paymentCallback'])->name('callback');
});

// Admin Payment Settings
Route::middleware(['auth', 'role:Admin'])->prefix('admin')->name('admin.')->group(function () {
    Route::get('/payment', [\App\Http\Controllers\PaymentController::class, 'index'])->name('payment.index');
    Route::put('/payment', [\App\Http\Controllers\PaymentController::class, 'updateSettings'])->name('payment.update');
    Route::post('/subscriptions/{subscription}/refund', [\App\Http\Controllers\PaymentController::class, 'refund'])->name('subscriptions.refund');
    
    // Reports
    Route::get('/reports', [\App\Http\Controllers\Admin\ReportController::class, 'index'])->name('reports.index');
    Route::get('/reports/payments', [\App\Http\Controllers\Admin\ReportController::class, 'payments'])->name('reports.payments');
    Route::get('/reports/customers', [\App\Http\Controllers\Admin\ReportController::class, 'customers'])->name('reports.customers');
    Route::get('/reports/transactions', [\App\Http\Controllers\Admin\ReportController::class, 'transactions'])->name('reports.transactions');
    Route::get('/reports/customers/{id}', [\App\Http\Controllers\Admin\ReportController::class, 'customerDetails'])->name('reports.customer-details');
    Route::get('/reports/analytics', [\App\Http\Controllers\Admin\ReportController::class, 'analytics'])->name('reports.analytics');
    
    // Chat System
    Route::get('/chat', [\App\Http\Controllers\Admin\ChatController::class, 'index'])->name('chat.index');
    Route::get('/chat/{id}', [\App\Http\Controllers\Admin\ChatController::class, 'show'])->name('chat.show');
    Route::post('/chat/{id}/send', [\App\Http\Controllers\Admin\ChatController::class, 'sendMessage'])->name('chat.send');
    Route::post('/chat/start', [\App\Http\Controllers\Admin\ChatController::class, 'startChat'])->name('chat.start');
    Route::post('/chat/{id}/close', [\App\Http\Controllers\Admin\ChatController::class, 'closeSession'])->name('chat.close');
    Route::get('/chat/{id}/messages', [\App\Http\Controllers\Admin\ChatController::class, 'getMessages'])->name('chat.messages');
    Route::get('/chat/unread-count', [\App\Http\Controllers\Admin\ChatController::class, 'getUnreadCount'])->name('chat.unread-count');
    Route::get('/chat/search-tenants', [\App\Http\Controllers\Admin\ChatController::class, 'searchTenants'])->name('chat.search-tenants');
    Route::get('/chat/{id}/stream', [\App\Http\Controllers\Admin\ChatController::class, 'streamMessages'])->name('chat.stream');
    Route::post('/chat/{id}/typing', [\App\Http\Controllers\Admin\ChatController::class, 'sendTypingIndicator'])->name('chat.typing');
    
    // Notifications
    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/{id}', [\App\Http\Controllers\Admin\NotificationController::class, 'show'])->name('notifications.show');
    Route::post('/notifications/{id}/read', [\App\Http\Controllers\Admin\NotificationController::class, 'markAsRead'])->name('notifications.read');
    Route::post('/notifications/read-all', [\App\Http\Controllers\Admin\NotificationController::class, 'markAllAsRead'])->name('notifications.read-all');
    Route::delete('/notifications/{id}', [\App\Http\Controllers\Admin\NotificationController::class, 'destroy'])->name('notifications.destroy');
    Route::get('/notifications/unread-count', [\App\Http\Controllers\Admin\NotificationController::class, 'getUnreadCount'])->name('notifications.unread-count');
    Route::get('/notifications/recent', [\App\Http\Controllers\Admin\NotificationController::class, 'getRecentNotifications'])->name('notifications.recent');
});

// Tenant Payment Routes
Route::middleware(['role:Manager', 'tenant.context', 'tenant.subscription'])->prefix('tenant')->name('tenant.')->group(function () {
    Route::post('/subscriptions/{plan}/purchase', [\App\Http\Controllers\Tenant\SubscriptionController::class, 'store'])->name('subscriptions.store');
    Route::get('/payment/success', [\App\Http\Controllers\Tenant\SubscriptionController::class, 'paymentSuccess'])->name('payment.success');
    Route::post('/payment/callback', [\App\Http\Controllers\Tenant\SubscriptionController::class, 'paymentCallback'])->name('payment.callback');
    
    // Chat System
    Route::get('/chat', [\App\Http\Controllers\Tenant\ChatController::class, 'index'])->name('chat.index');
    Route::post('/chat/send', [\App\Http\Controllers\Tenant\ChatController::class, 'sendMessage'])->name('chat.send');
    Route::get('/chat/messages', [\App\Http\Controllers\Tenant\ChatController::class, 'getMessages'])->name('chat.messages');
    Route::get('/chat/unread-count', [\App\Http\Controllers\Tenant\ChatController::class, 'getUnreadCount'])->name('chat.unread-count');
    Route::post('/chat/{id}/read', [\App\Http\Controllers\Tenant\ChatController::class, 'markAsRead'])->name('chat.read');
    Route::get('/chat/stream', [\App\Http\Controllers\Tenant\ChatController::class, 'streamMessages'])->name('chat.stream');
    Route::post('/chat/typing', [\App\Http\Controllers\Tenant\ChatController::class, 'sendTypingIndicator'])->name('chat.typing');
});

// Mail Test Route
Route::get('/test-mail', [\App\Http\Controllers\TestMailController::class, 'test']);

// Developer Login Route
Route::get('/developer/login', function () {
    return view('auth.developer-login');
})->name('developer.login');

// Developer Routes
Route::prefix('developer')->middleware(['web', 'auth', 'developer'])->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\Developer\DashboardController::class, 'index'])->name('developer.dashboard');
    Route::get('/tenants', [\App\Http\Controllers\Developer\DashboardController::class, 'tenants'])->name('developer.tenants');
    Route::post('/tenants/assign-subscription', [\App\Http\Controllers\Developer\DashboardController::class, 'assignSubscription'])->name('developer.tenants.subscription.assign');
    Route::get('/tenants/{id}/activity', [\App\Http\Controllers\Developer\DashboardController::class, 'tenantActivity'])->name('developer.tenants.activity');
    Route::get('/tenants/{id}/applications', [\App\Http\Controllers\Developer\DashboardController::class, 'tenantApplications'])->name('developer.tenants.applications');
    Route::get('/monitoring', [\App\Http\Controllers\Developer\DashboardController::class, 'monitoring'])->name('developer.monitoring');
    Route::get('/monitoring/data', [\App\Http\Controllers\Developer\DashboardController::class, 'getMonitoringData'])->name('developer.monitoring.data');
    Route::get('/database', [\App\Http\Controllers\Developer\DashboardController::class, 'database'])->name('developer.database');
    Route::get('/database/tables', [\App\Http\Controllers\Developer\DashboardController::class, 'getTables'])->name('developer.database.tables');
    Route::get('/database/columns', [\App\Http\Controllers\Developer\DashboardController::class, 'getTableColumns'])->name('developer.database.columns');
    Route::post('/database/column/update', [\App\Http\Controllers\Developer\DashboardController::class, 'updateTableColumn'])->name('developer.database.column.update');
    
    // Table Data Routes
    Route::get('/database/data', [\App\Http\Controllers\Developer\DashboardController::class, 'getTableData'])->name('developer.database.data');
    Route::post('/database/data/add', [\App\Http\Controllers\Developer\DashboardController::class, 'addTableRow'])->name('developer.database.data.add');
    Route::post('/database/data/update', [\App\Http\Controllers\Developer\DashboardController::class, 'updateTableRow'])->name('developer.database.data.update');
    Route::post('/database/data/delete', [\App\Http\Controllers\Developer\DashboardController::class, 'deleteTableRow'])->name('developer.database.data.delete');

    Route::get('/logs', [\App\Http\Controllers\Developer\DashboardController::class, 'logs'])->name('developer.logs');
    Route::get('/logs/download', [\App\Http\Controllers\Developer\DashboardController::class, 'downloadLogs'])->name('developer.logs.download');
    Route::post('/logs/clear', [\App\Http\Controllers\Developer\DashboardController::class, 'clearLogs'])->name('developer.logs.clear');
    Route::get('/chat', [\App\Http\Controllers\Developer\ChatController::class, 'index'])->name('developer.chat.index');
    Route::get('/chat/{id}', [\App\Http\Controllers\Developer\ChatController::class, 'show'])->name('developer.chat.show');
    Route::post('/chat/{id}/send', [\App\Http\Controllers\Developer\ChatController::class, 'sendMessage'])->name('developer.chat.send');
    Route::post('/chat/start', [\App\Http\Controllers\Developer\ChatController::class, 'startChat'])->name('developer.chat.start');
    Route::post('/chat/{id}/close', [\App\Http\Controllers\Developer\ChatController::class, 'closeSession'])->name('developer.chat.close');
    Route::get('/analytics', [\App\Http\Controllers\Developer\ReportController::class, 'analytics'])->name('developer.reports.analytics');
    Route::resource('/users', \App\Http\Controllers\Developer\UserController::class, ['names' => 'developer.users']);
    Route::resource('/roles', \App\Http\Controllers\Developer\RoleController::class, ['names' => 'developer.roles']);
    Route::post('/database/clear-cache', [\App\Http\Controllers\Developer\DashboardController::class, 'clearCache'])->name('developer.database.clear-cache');
    Route::post('/database/optimize', [\App\Http\Controllers\Developer\DashboardController::class, 'optimizeDatabase'])->name('developer.database.optimize');
    Route::post('/database/analyze', [\App\Http\Controllers\Developer\DashboardController::class, 'analyzeQueries'])->name('developer.database.analyze');
    Route::post('/database/export', [\App\Http\Controllers\Developer\DashboardController::class, 'exportSchema'])->name('developer.database.export');
    Route::post('/database/backup', [\App\Http\Controllers\Developer\DashboardController::class, 'backupDatabase'])->name('developer.database.backup');
    Route::post('/database/upload', [\App\Http\Controllers\Developer\DashboardController::class, 'uploadDatabase'])->name('developer.database.upload');
    Route::get('/database/tables', [\App\Http\Controllers\Developer\DashboardController::class, 'getTables'])->name('developer.database.tables');
    Route::get('/database/columns', [\App\Http\Controllers\Developer\DashboardController::class, 'getTableColumns'])->name('developer.database.columns');
    Route::post('/database/column/update', [\App\Http\Controllers\Developer\DashboardController::class, 'updateTableColumn'])->name('developer.database.column.update');
    
    // Server Configuration
    Route::get('/server-config', [\App\Http\Controllers\Developer\DashboardController::class, 'serverConfig'])->name('developer.server.config');
    Route::post('/server/update-env', [\App\Http\Controllers\Developer\DashboardController::class, 'updateEnv'])->name('developer.server.update-env');
    Route::post('/server/clear-cache', [\App\Http\Controllers\Developer\DashboardController::class, 'clearAllCaches'])->name('developer.server.clear-cache');
    Route::post('/server/run-command', [\App\Http\Controllers\Developer\DashboardController::class, 'runArtisanCommand'])->name('developer.server.run-command');
    
    // Application Request Monitor
    Route::get('/requests', [\App\Http\Controllers\Developer\RequestMonitorController::class, 'index'])->name('developer.requests.index');
    Route::get('/requests/data', [\App\Http\Controllers\Developer\RequestMonitorController::class, 'getData'])->name('developer.requests.data');
    Route::post('/requests/clear', [\App\Http\Controllers\Developer\RequestMonitorController::class, 'clear'])->name('developer.requests.clear');
});


