<?php

use App\Http\Controllers\Auth\FirstLoginPasswordController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\Settings\DealerController;
use App\Http\Controllers\Settings\BrandingController;
use App\Http\Controllers\Settings\BranchController;
use App\Http\Controllers\Settings\UserController;
use App\Http\Controllers\Settings\DepartmentController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| 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!
|
*/

Route::redirect('/', '/login');

// Friendly page for users whose dealer is inactive (no auth required)
Route::get('/dealer-inactive', fn () => view('auth.dealer-inactive'))->name('dealer.inactive');

// First-login set password (guest; token-based, no auth)
Route::get('/first-login/set-password/{token}', [FirstLoginPasswordController::class, 'show'])->name('first-login.password.show');
Route::post('/first-login/set-password/{token}', [FirstLoginPasswordController::class, 'update'])->name('first-login.password.update');

// Order: auth -> user.enabled (disabled users) -> dealer (SetCurrentDealer) -> dealer.active (inactive dealer) -> branch.active (inactive branch) -> force_password_change
Route::middleware(['auth', 'user.enabled', 'dealer', 'dealer.active', 'branch.active', 'force_password_change'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index'])
        ->middleware('permission:dashboard.index.view')
        ->name('dashboard.index');

    Route::get('/dashboard/executive', [DashboardController::class, 'executive'])
        ->middleware('permission:dashboard.executive.view')
        ->name('dashboard.executive');

    Route::get('/dashboard/sales', [DashboardController::class, 'sales'])
        ->middleware('permission:dashboard.sales.view')
        ->name('dashboard.sales');

    Route::get('/dashboard/buyers', [DashboardController::class, 'buyers'])
        ->middleware('permission:dashboard.buyers.view')
        ->name('dashboard.buyers');

    Route::get('/dashboard/financial', [DashboardController::class, 'financial'])
        ->middleware('permission:dashboard.financial.view')
        ->name('dashboard.financial');

    // Use a unique URL to avoid clashing with the Recon module route (/dashboard/recon).
    Route::get('/dashboard/recon-dashboard', [DashboardController::class, 'reconDepartment'])
        ->middleware('permission:dashboard.recon_department.view')
        ->name('dashboard.recon_department');

    Route::get('/dashboard/marketing-dashboard', [DashboardController::class, 'marketingDepartment'])
        ->middleware('permission:dashboard.marketing_department.view')
        ->name('dashboard.marketing_department');

    Route::get('/dashboard/fi-dashboard', [DashboardController::class, 'fiDepartment'])
        ->middleware('permission:dashboard.fi_department.view')
        ->name('dashboard.fi_department');

    Route::get('/dashboard/inventory', [DashboardController::class, 'inventory'])
        ->middleware('permission:dashboard.inventory_department.view')
        ->name('dashboard.inventory_department');

    Route::get('/dashboard/operations', [DashboardController::class, 'operations'])
        ->middleware('permission:dashboard.operations.view')
        ->name('dashboard.operations');

    $registerMenuRoutes = function (array $items, string $basePath = '/dashboard', array $breadcrumb = []) use (&$registerMenuRoutes) {
        foreach ($items as $item) {
            $key = $item['key'] ?? null;
            $routeName = $item['route_name'] ?? null;
            $isGroup = (bool) ($item['is_group'] ?? false);
            $children = $item['children'] ?? [];
            $defaultDealerOnly = (bool) ($item['default_dealer_only'] ?? false);

            if ($routeName === 'dashboard.index') {
                continue;
            }

            $currentPath = $basePath;
            if (is_string($key) && $key !== '') {
                $currentPath .= '/'.$key;
            }

            $currentBreadcrumb = array_values(array_filter(array_merge($breadcrumb, [$item['label'] ?? null])));

            if (
                !$isGroup
                && is_string($routeName)
                && $routeName !== ''
                && str_starts_with($routeName, 'dashboard.')
            ) {
                // If a route name already exists (e.g. explicitly defined department dashboards),
                // do not override it here.
                if (!Route::has($routeName)) {
                    $route = Route::get($currentPath, function () use ($item, $currentBreadcrumb) {
                        if (($item['route_name'] ?? null) === 'dashboard.recon.dashboard') {
                            return view('recon.dashboard', [
                                'title' => $item['label'],
                                'breadcrumb' => $currentBreadcrumb,
                                'children' => $item['children'] ?? [],
                            ]);
                        }

                        return view('placeholders.submodule', [
                            'title' => $item['label'],
                            'breadcrumb' => $currentBreadcrumb,
                        ]);
                    })->name($routeName);

                    $middlewares = [];
                    if (!empty($item['permission_key'])) {
                        $middlewares[] = 'permission:'.$item['permission_key'];
                    }
                    if ($defaultDealerOnly) {
                        $middlewares[] = 'default.dealer.only';
                    }
                    if ($middlewares !== []) {
                        $route->middleware($middlewares);
                    }
                }
            }

            if (!empty($children)) {
                $registerMenuRoutes($children, $currentPath, $currentBreadcrumb);
            }
        }
    };

    $registerMenuRoutes(config('mtt_dashboard_menu', []));

    Route::prefix('settings/dealers')
        ->name('settings.dealers.')
        ->controller(DealerController::class)
        ->middleware('default.dealer.only')
        ->group(function () {
            Route::get('/', 'index')
                ->middleware('permission:settings.dealers.view')
                ->name('index');

            Route::get('/create', 'create')
                ->middleware('permission:settings.dealers.manage')
                ->name('create');

            Route::post('/', 'store')
                ->middleware('permission:settings.dealers.manage')
                ->name('store');

            Route::get('/{dealer}/edit', 'edit')
                ->middleware('permission:settings.dealers.manage')
                ->name('edit');

            Route::put('/{dealer}', 'update')
                ->middleware('permission:settings.dealers.manage')
                ->name('update');

            Route::patch('/{dealer}/toggle-active', 'toggleActive')
                ->middleware('permission:settings.dealers.manage')
                ->name('toggle-active');

            Route::delete('/{dealer}', 'destroy')
                ->middleware('permission:settings.dealers.manage')
                ->name('destroy');

            Route::patch('/{dealer}/restore', 'restore')
                ->middleware('permission:settings.dealers.manage')
                ->name('restore');

            Route::get('/{dealer}/provisioning-summary', 'provisioningSummary')
                ->middleware('permission:settings.dealers.manage')
                ->name('provisioning-summary');

            Route::post('/{dealer}/reprovision', 'reprovision')
                ->middleware('permission:settings.dealers.manage')
                ->name('reprovision');
        });

    Route::prefix('settings/users')
        ->name('settings.users.')
        ->controller(UserController::class)
        ->group(function () {
            Route::get('/', 'index')
                ->middleware('permission:settings.users.view')
                ->name('index');

            Route::get('/create', 'create')
                ->middleware('permission:settings.users.manage')
                ->name('create');

            Route::post('/', 'store')
                ->middleware('permission:settings.users.manage')
                ->name('store');

            Route::get('/{user}/edit', 'edit')
                ->middleware('permission:settings.users.manage')
                ->name('edit');

            Route::put('/{user}', 'update')
                ->middleware('permission:settings.users.manage')
                ->name('update');

            Route::patch('/{user}/toggle-disabled', 'toggleDisabled')
                ->middleware('permission:settings.users.security')
                ->name('toggle-disabled');

            Route::post('/{user}/reset-password', 'resetPassword')
                ->middleware('permission:settings.users.security')
                ->name('reset-password');

            Route::delete('/{user}', 'destroy')
                ->middleware('permission:settings.users.security')
                ->name('destroy');

            Route::patch('/{user}/restore', 'restore')
                ->middleware('permission:settings.users.security')
                ->name('restore');
        });

    Route::prefix('settings/departments')
        ->name('settings.departments.')
        ->controller(DepartmentController::class)
        ->middleware('permission:settings.departments.manage')
        ->group(function () {
            Route::get('/', 'index')->name('index');
            Route::get('/create', 'create')->name('create');
            Route::post('/', 'store')->name('store');
            Route::get('/{department}/edit', 'edit')->name('edit');
            Route::put('/{department}', 'update')->name('update');
            Route::delete('/{department}', 'destroy')->name('destroy');
            Route::patch('/{department}/restore', 'restore')->name('restore');
            Route::post('/{department}/members/add', 'addMembers')->name('members.add');
            Route::post('/{department}/members/remove', 'removeMembers')->name('members.remove');
            Route::get('/{department}/members/search', 'searchMembers')->name('members.search');
        });

    Route::prefix('settings/branding')
        ->name('settings.branding.')
        ->controller(BrandingController::class)
        ->middleware('permission:settings.branding.manage')
        ->group(function () {
            Route::get('/', 'edit')->name('edit');
            Route::put('/', 'update')->name('update');
        });

    Route::prefix('settings/dealers')
        ->name('settings.dealers.')
        ->controller(DealerController::class)
        ->middleware('permission:settings.dealers.manage')
        ->group(function () {
            Route::get('/', 'index')->name('index');
            Route::get('/create', 'create')->name('create');
            Route::post('/', 'store')->name('store');
            Route::get('/{dealer}', 'show')->name('show');
            Route::get('/{dealer}/edit', 'edit')->name('edit');
            Route::put('/{dealer}', 'update')->name('update');
            Route::patch('/{dealer}/toggle-active', 'toggleActive')->name('toggle-active');
            Route::delete('/{dealer}', 'destroy')->name('destroy');
            Route::patch('/{dealer}/restore', 'restore')->name('restore');
            Route::get('/{dealer}/provisioning-summary', 'provisioningSummary')->name('provisioning-summary');
            Route::get('/{dealer}/documents/{document}', 'showDocument')->name('documents.show');
        });

    Route::prefix('settings/branches')
        ->name('settings.branches.')
        ->controller(BranchController::class)
        ->middleware('permission:settings.branches.manage')
        ->group(function () {
            Route::get('/', 'index')->name('index');
            Route::get('/create', 'create')->name('create');
            Route::post('/', 'store')->name('store');
            Route::get('/{branch}/edit', 'edit')->name('edit');
            Route::put('/{branch}', 'update')->name('update');
            Route::patch('/{branch}/set-default', 'setDefault')->name('set-default');
            Route::patch('/{branch}/toggle-active', 'toggleActive')->name('toggle-active');
            Route::get('/{branch}/users', 'users')->name('users.index');
            Route::post('/{branch}/users/assign', 'assignUser')->name('users.assign');
            Route::post('/{branch}/users/{user}/reassign', 'reassignUser')->name('users.reassign');
        });

    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
});

require __DIR__.'/auth.php';
