<?php
// routes/web.php - Complete Fixed Routes

use App\Http\Controllers\ProfileController;
use App\Http\Controllers\PrivacyPolicyController;
use App\Http\Controllers\AdminDashboardController;
use App\Http\Controllers\VehicleDashboardController;
use App\Http\Controllers\DeliveryRecordController;
use App\Http\Controllers\Admin\UserManagementController;
use App\Http\Controllers\Admin\WarehouseController;
use App\Http\Controllers\Admin\CommissionRatesController;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

// Public Routes
Route::get('/', function () {
    return redirect()->route('login');
});

// Authentication Routes (handled by Laravel Breeze)
require __DIR__.'/auth.php';

// Protected Routes
Route::middleware(['auth', 'verified'])->group(function () {
    
    // 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');
    
    // Dashboard Redirects based on role
    Route::get('/dashboard', function () {
        $user = auth()->user();
        
        if ($user->isAdmin()) {
            return redirect()->route('admin.dashboard');
        } elseif ($user->isVehicleUser()) {
            return redirect()->route('vehicle.dashboard');
        }
        
        return redirect()->route('profile.edit');
    })->name('dashboard');
    
});

/*
|--------------------------------------------------------------------------
| Admin Routes
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'verified', 'role:admin'])->prefix('admin')->name('admin.')->group(function () {
    
    // Admin Dashboard
    Route::get('/dashboard', [AdminDashboardController::class, 'index'])->name('dashboard');
    
    // User Management Routes
    Route::prefix('users')->name('users.')->group(function () {
        Route::get('/', [UserManagementController::class, 'index'])->name('index');
        Route::get('/create', [UserManagementController::class, 'create'])->name('create');
        Route::post('/', [UserManagementController::class, 'store'])->name('store');
        Route::get('/{user}', [UserManagementController::class, 'show'])->name('show');
        Route::get('/{user}/edit', [UserManagementController::class, 'edit'])->name('edit');
        Route::put('/{user}', [UserManagementController::class, 'update'])->name('update');
        Route::delete('/{user}', [UserManagementController::class, 'destroy'])->name('destroy');
        
        // Additional User Actions
        Route::post('/{user}/reset-password', [UserManagementController::class, 'resetPassword'])->name('reset-password');
        Route::patch('/{user}/toggle', [UserManagementController::class, 'toggleUserStatus'])->name('toggle');
        Route::post('/bulk', [UserManagementController::class, 'bulk'])->name('bulk');
        Route::get('/export', [UserManagementController::class, 'export'])->name('export');
    });
    
    // Warehouse Management Routes
    Route::prefix('warehouses')->name('warehouses.')->group(function () {
        Route::get('/', [WarehouseController::class, 'index'])->name('index');
        Route::get('/create', [WarehouseController::class, 'create'])->name('create');
        Route::post('/', [WarehouseController::class, 'store'])->name('store');
        Route::get('/{warehouse}', [WarehouseController::class, 'show'])->name('show');
        Route::get('/{warehouse}/edit', [WarehouseController::class, 'edit'])->name('edit');
        Route::put('/{warehouse}', [WarehouseController::class, 'update'])->name('update');
        Route::delete('/{warehouse}', [WarehouseController::class, 'destroy'])->name('destroy');
        
        // Additional Warehouse Actions
        Route::patch('/{warehouse}/toggle', [WarehouseController::class, 'toggle'])->name('toggle');
        Route::post('/bulk', [WarehouseController::class, 'bulk'])->name('bulk');
        Route::get('/export', [WarehouseController::class, 'export'])->name('export');
        Route::get('/{warehouse}/stats', [WarehouseController::class, 'getStats'])->name('stats');
    });
    
    // Commission Rates Management Routes
    Route::prefix('commission-rates')->name('commission-rates.')->group(function () {
        Route::get('/', [CommissionRatesController::class, 'index'])->name('index');
        Route::get('/create', [CommissionRatesController::class, 'create'])->name('create');
        Route::post('/', [CommissionRatesController::class, 'store'])->name('store');
        Route::get('/{commissionRate}', [CommissionRatesController::class, 'show'])->name('show');
        Route::get('/{commissionRate}/edit', [CommissionRatesController::class, 'edit'])->name('edit');
        Route::put('/{commissionRate}', [CommissionRatesController::class, 'update'])->name('update');
        Route::delete('/{commissionRate}', [CommissionRatesController::class, 'destroy'])->name('destroy');
        
        // Additional Commission Rate Actions
        Route::patch('/{commissionRate}/toggle', [CommissionRatesController::class, 'toggle'])->name('toggle');
        Route::post('/bulk', [CommissionRatesController::class, 'bulk'])->name('bulk');
        Route::post('/import', [CommissionRatesController::class, 'import'])->name('import');
        Route::get('/export', [CommissionRatesController::class, 'export'])->name('export');
        Route::post('/calculate', [CommissionRatesController::class, 'calculate'])->name('calculate');
        Route::get('/existing-rates', [CommissionRatesController::class, 'getExistingRates'])->name('existing');
        Route::post('/check-overlap', [CommissionRatesController::class, 'checkOverlap'])->name('check-overlap');
        Route::get('/calculation-breakdown', [CommissionRatesController::class, 'getCalculationBreakdown'])->name('calculation-breakdown');
    });
    
    
    // Reports Routes (replace the placeholder routes)
Route::prefix('reports')->name('reports.')->group(function () {
    Route::get('/', [App\Http\Controllers\Admin\ReportController::class, 'index'])->name('index');
    Route::get('/delivery', [App\Http\Controllers\Admin\ReportController::class, 'delivery'])->name('delivery');
    Route::get('/commission', [App\Http\Controllers\Admin\ReportController::class, 'commission'])->name('commission');
    Route::get('/warehouse', [App\Http\Controllers\Admin\ReportController::class, 'warehouse'])->name('warehouse');
    
    // Export routes
    Route::post('/delivery/export', [App\Http\Controllers\Admin\ReportController::class, 'exportDeliveryReport'])->name('delivery.export');
    Route::post('/commission/export', [App\Http\Controllers\Admin\ReportController::class, 'exportCommissionReport'])->name('commission.export');
    Route::post('/warehouse/export', [App\Http\Controllers\Admin\ReportController::class, 'exportWarehouseReport'])->name('warehouse.export');
});
    
});

/*
|--------------------------------------------------------------------------
| Vehicle User Routes
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'verified', 'vehicle'])->prefix('vehicle')->name('vehicle.')->group(function () {
    
    // Vehicle Dashboard
    Route::get('/dashboard', [VehicleDashboardController::class, 'index'])->name('dashboard');
    Route::get('/calculator', [VehicleDashboardController::class, 'calculateCommission'])->name('calculator');
    
    // API Routes for Vehicle Dashboard
    Route::get('/api/weekly-comparison', [VehicleDashboardController::class, 'getWeeklyComparison'])->name('api.weekly-comparison');
    Route::get('/api/monthly-stats', [VehicleDashboardController::class, 'getMonthlyStats'])->name('api.monthly-stats');
    Route::get('/api/daily-chart', [VehicleDashboardController::class, 'getDailyChart'])->name('api.daily-chart');
    
    // Delivery Records Management
    Route::prefix('deliveries')->name('deliveries.')->group(function () {
        Route::get('/', [DeliveryRecordController::class, 'index'])->name('index');
        Route::get('/create', [DeliveryRecordController::class, 'create'])->name('create');
        Route::post('/', [DeliveryRecordController::class, 'store'])->name('store');
        Route::get('/{delivery}', [DeliveryRecordController::class, 'show'])->name('show');
        Route::get('/{delivery}/edit', [DeliveryRecordController::class, 'edit'])->name('edit');
        Route::put('/{delivery}', [DeliveryRecordController::class, 'update'])->name('update');
        Route::delete('/{delivery}', [DeliveryRecordController::class, 'destroy'])->name('destroy');
        
        // Additional Delivery Actions
        Route::post('/preview-commission', [DeliveryRecordController::class, 'previewCommission'])->name('preview-commission');
        Route::post('/validate-date', [DeliveryRecordController::class, 'validateDeliveryDate'])->name('validate-date');
    });
    
});

/*
|--------------------------------------------------------------------------
| Finance Management Routes
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'verified'])->prefix('finance')->name('finance.')->group(function () {
    
    // Dashboard
    Route::get('/dashboard', [App\Http\Controllers\FinanceDashboardController::class, 'index'])->name('dashboard');
    Route::get('/dashboard/chart', [App\Http\Controllers\FinanceDashboardController::class, 'getChartData'])->name('dashboard.chart');
    Route::post('/dashboard/sync', [App\Http\Controllers\FinanceDashboardController::class, 'syncDeliveryData'])->name('dashboard.sync');
    Route::get('/dashboard/export', [App\Http\Controllers\FinanceDashboardController::class, 'exportReport'])->name('dashboard.export');
    
    // Finance Records
    Route::prefix('records')->name('records.')->group(function () {
        Route::get('/', [App\Http\Controllers\FinanceRecordController::class, 'index'])->name('index');
        Route::get('/create', [App\Http\Controllers\FinanceRecordController::class, 'create'])->name('create');
        Route::post('/', [App\Http\Controllers\FinanceRecordController::class, 'store'])->name('store');
        Route::get('/{record}/edit', [App\Http\Controllers\FinanceRecordController::class, 'edit'])->name('edit');
        Route::put('/{record}', [App\Http\Controllers\FinanceRecordController::class, 'update'])->name('update');
        Route::delete('/{record}', [App\Http\Controllers\FinanceRecordController::class, 'destroy'])->name('destroy');
        Route::post('/bulk-delete', [App\Http\Controllers\FinanceRecordController::class, 'bulkDelete'])->name('bulk-delete');
        Route::post('/{record}/duplicate', [App\Http\Controllers\FinanceRecordController::class, 'duplicate'])->name('duplicate');
        Route::get('/categories', [App\Http\Controllers\FinanceRecordController::class, 'getCategories'])->name('categories');
    });
    
    // Monthly Budgets
    Route::prefix('budgets')->name('budgets.')->group(function () {
        Route::get('/', [App\Http\Controllers\MonthlyBudgetController::class, 'index'])->name('index');
        Route::get('/create', [App\Http\Controllers\MonthlyBudgetController::class, 'create'])->name('create');
        Route::post('/', [App\Http\Controllers\MonthlyBudgetController::class, 'store'])->name('store');
        Route::get('/{budget}/edit', [App\Http\Controllers\MonthlyBudgetController::class, 'edit'])->name('edit');
        Route::put('/{budget}', [App\Http\Controllers\MonthlyBudgetController::class, 'update'])->name('update');
        Route::delete('/{budget}', [App\Http\Controllers\MonthlyBudgetController::class, 'destroy'])->name('destroy');
        Route::post('/copy', [App\Http\Controllers\MonthlyBudgetController::class, 'copyFromPreviousMonth'])->name('copy');
        Route::post('/bulk-update', [App\Http\Controllers\MonthlyBudgetController::class, 'bulkUpdate'])->name('bulk-update');
    });
    
    // Saving Goals
    Route::prefix('goals')->name('goals.')->group(function () {
        Route::get('/', [App\Http\Controllers\SavingGoalController::class, 'index'])->name('index');
        Route::get('/create', [App\Http\Controllers\SavingGoalController::class, 'create'])->name('create');
        Route::post('/', [App\Http\Controllers\SavingGoalController::class, 'store'])->name('store');
        Route::get('/{goal}', [App\Http\Controllers\SavingGoalController::class, 'show'])->name('show');
        Route::get('/{goal}/edit', [App\Http\Controllers\SavingGoalController::class, 'edit'])->name('edit');
        Route::put('/{goal}', [App\Http\Controllers\SavingGoalController::class, 'update'])->name('update');
        Route::delete('/{goal}', [App\Http\Controllers\SavingGoalController::class, 'destroy'])->name('destroy');
        Route::post('/{goal}/deposit', [App\Http\Controllers\SavingGoalController::class, 'deposit'])->name('deposit');
        Route::post('/{goal}/withdraw', [App\Http\Controllers\SavingGoalController::class, 'withdraw'])->name('withdraw');
        Route::post('/{goal}/complete', [App\Http\Controllers\SavingGoalController::class, 'complete'])->name('complete');
        Route::post('/{goal}/cancel', [App\Http\Controllers\SavingGoalController::class, 'cancel'])->name('cancel');
        Route::post('/{goal}/reactivate', [App\Http\Controllers\SavingGoalController::class, 'reactivate'])->name('reactivate');
    });
    
    // Reports
    Route::prefix('reports')->name('reports.')->group(function () {
        Route::get('/', [App\Http\Controllers\FinanceReportController::class, 'index'])->name('index');
        Route::get('/monthly', [App\Http\Controllers\FinanceReportController::class, 'monthly'])->name('monthly');
        Route::get('/yearly', [App\Http\Controllers\FinanceReportController::class, 'yearly'])->name('yearly');
        Route::get('/category', [App\Http\Controllers\FinanceReportController::class, 'byCategory'])->name('category');
        Route::post('/export', [App\Http\Controllers\FinanceReportController::class, 'export'])->name('export');
    });
    
    // API endpoints for AJAX
    Route::prefix('api')->name('api.')->group(function () {
        Route::get('/stats', [App\Http\Controllers\FinanceDashboardController::class, 'getStats'])->name('stats');
        Route::get('/trends', [App\Http\Controllers\FinanceDashboardController::class, 'getTrends'])->name('trends');
        Route::get('/categories/{type}', [App\Http\Controllers\FinanceRecordController::class, 'getCategoriesByType'])->name('categories.type');
    });
});


/*
|--------------------------------------------------------------------------
| API Routes (for AJAX calls)
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'verified'])->prefix('api')->name('api.')->group(function () {
    
    // Commission calculation API (accessible by all authenticated users)
    Route::post('/commission/calculate', function (Illuminate\Http\Request $request) {
        return app(CommissionRatesController::class)->calculate($request);
    })->name('commission.calculate');
    
    // Warehouse data API
    Route::get('/warehouses', function () {
        return response()->json(
            \App\Models\Warehouse::active()->select('code', 'name', 'location')->get()
        );
    })->name('warehouses');
    
    // Commission rates API
    Route::get('/commission-rates/{warehouse}/{vehicle}', function ($warehouse, $vehicle) {
        $rates = \App\Models\CommissionRate::forWarehouseAndVehicle(null, $warehouse, $vehicle)->get();
        return response()->json($rates);
    })->name('commission-rates');
    
    // User data API
    Route::get('/users', function () {
        return response()->json(
            \App\Models\User::active()->select('id', 'first_name', 'last_name', 'email', 'role')->get()
        );
    })->name('users');
    
});

Route::get('/privacy-policy', [PrivacyPolicyController::class, 'index'])->name('privacy-policy');

/*
|--------------------------------------------------------------------------
| Health Check Route
|--------------------------------------------------------------------------
*/
Route::get('/health', function () {
    return response()->json([
        'status' => 'healthy',
        'timestamp' => now()->toISOString(),
        'version' => config('app.version', '1.0.0'),
        'database' => \DB::connection()->getPdo() ? 'connected' : 'disconnected',
        'cache' => cache()->get('health_check', true) ? 'working' : 'error',
    ]);
})->name('health');

/*
|--------------------------------------------------------------------------
| Test Route (for development)
|--------------------------------------------------------------------------
*/
if (app()->environment('local')) {
    Route::get('/test', function () {
        return response()->json([
            'message' => 'Laravel Commission System is running!',
            'user' => auth()->user() ? [
                'name' => auth()->user()->name,
                'role' => auth()->user()->role,
                'email' => auth()->user()->email
            ] : null,
            'routes' => [
                'admin' => route('admin.dashboard'),
                'vehicle' => route('vehicle.dashboard'),
                'commission_rates' => route('admin.commission-rates.index'),
            ]
        ]);
    })->name('test')->middleware(['auth']);
}

/*
|--------------------------------------------------------------------------
| Fallback Route
|--------------------------------------------------------------------------
*/
Route::fallback(function () {
    if (request()->expectsJson()) {
        return response()->json([
            'message' => 'Route not found.',
            'status' => 404,
            'available_routes' => [
                'admin' => '/admin/dashboard',
                'vehicle' => '/vehicle/dashboard',
                'commission_rates' => '/admin/commission-rates',
                'users' => '/admin/users',
                'warehouses' => '/admin/warehouses',
            ]
        ], 404);
    }
    
    return response()->view('errors.404', [], 404);
});