<?php

use App\Http\Controllers\ActivityController;
use App\Http\Controllers\ChatConversationController;
use App\Http\Controllers\CalendarController;
use App\Http\Controllers\CompanyController;
use App\Http\Controllers\ContactController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\DealController;
use App\Http\Controllers\DiskController;
use App\Http\Controllers\DiskExplorerController;
use App\Http\Controllers\FormController;
use App\Http\Controllers\HrController;
use App\Http\Controllers\MailServiceController;
use App\Http\Controllers\ModuleController;
use App\Http\Controllers\MessengerController;
use App\Http\Controllers\NewsController;
use App\Http\Controllers\NotificationController;
use App\Http\Controllers\OneCController;
use App\Http\Controllers\PipelineController;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\ProfileAccessController;
use App\Http\Controllers\ProfileApiTokenController;
use App\Http\Controllers\ProfileAppearanceController;
use App\Http\Controllers\ProfileCompanySettingsController;
use App\Http\Controllers\ProfileMenuController;
use App\Http\Controllers\ProfileUpdateCenterController;
use App\Http\Controllers\ProfileThemeController;
use App\Http\Controllers\ProfileTwoFactorController;
use App\Http\Controllers\ProjectController;
use App\Http\Controllers\PublicFormController;
use App\Http\Controllers\ReportController;
use App\Http\Controllers\SectionAccessController;
use App\Http\Controllers\TaskController;
use App\Http\Controllers\TelephonyController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\WarehouseAddressController;
use App\Http\Controllers\WarehouseController;
use App\Support\CrmModuleManager;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return auth()->check()
        ? redirect()->route(\App\Support\UserStartPage::resolveRouteName(auth()->user()->start_page) ?? 'dashboard')
        : redirect()->route('login');
});

Route::middleware('auth')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    Route::get('/news', [NewsController::class, 'index'])->name('news.index');
    Route::get('/news/create', [NewsController::class, 'create'])->name('news.create');
    Route::post('/news', [NewsController::class, 'store'])->name('news.store');
    Route::view('/academy', 'training.index')->name('academy.index');
    Route::get('/calendar', [CalendarController::class, 'index'])->name('calendar.index')->middleware('can:viewCalendar');
    Route::get('/calendar/events', [CalendarController::class, 'events'])->name('calendar.events')->middleware('can:viewCalendar');
    Route::patch('/calendar/tasks/{task}/timing', [CalendarController::class, 'updateTaskTiming'])->name('calendar.tasks.timing')->middleware('can:viewCalendar');
    Route::get('/notifications/feed', [NotificationController::class, 'feed'])->name('notifications.feed');
    Route::get('/notifications/{key}/open', [NotificationController::class, 'open'])->name('notifications.open');

    Route::resource('companies', CompanyController::class);
    Route::resource('contacts', ContactController::class);
    Route::resource('pipelines', PipelineController::class);
    Route::patch('/pipelines/{pipeline}/stages', [PipelineController::class, 'updateStages'])->name('pipelines.update-stages');
    Route::resource('deals', DealController::class);
    Route::patch('/deals/{deal}/stage', [DealController::class, 'updateStage'])->name('deals.update-stage');
    Route::resource('products', ProductController::class);
    Route::resource('warehouses', WarehouseController::class);
    Route::patch('/warehouses/{warehouse}/map', [WarehouseController::class, 'updateMap'])->name('warehouses.map.update');
    Route::post('/warehouses/{warehouse}/addresses/generate', [WarehouseAddressController::class, 'generate'])->name('warehouses.addresses.generate');
    Route::post('/warehouses/{warehouse}/addresses', [WarehouseAddressController::class, 'store'])->name('warehouses.addresses.store');
    Route::patch('/warehouses/{warehouse}/addresses/{warehouseAddress}', [WarehouseAddressController::class, 'update'])->name('warehouses.addresses.update');
    Route::delete('/warehouses/{warehouse}/addresses/{warehouseAddress}', [WarehouseAddressController::class, 'destroy'])->name('warehouses.addresses.destroy');
    Route::get('/onec', [OneCController::class, 'index'])->name('onec.index');
    Route::patch('/onec/settings', [OneCController::class, 'updateSettings'])->name('onec.settings.update');
    Route::post('/onec/exchanges', [OneCController::class, 'storeExchange'])->name('onec.exchanges.store');
    Route::patch('/onec/exchanges/{exchange}/retry', [OneCController::class, 'retryExchange'])->name('onec.exchanges.retry');
    Route::get('/hr', [HrController::class, 'index'])->name('hr.index');
    Route::patch('/hr/settings', [HrController::class, 'updateSettings'])->name('hr.settings.update');
    Route::post('/hr/requests', [HrController::class, 'storeRequest'])->name('hr.requests.store');
    Route::patch('/hr/requests/{hrRequest}', [HrController::class, 'updateRequest'])->name('hr.requests.update');
    Route::delete('/hr/requests/{hrRequest}', [HrController::class, 'destroyRequest'])->name('hr.requests.destroy');
    Route::get('/telephony', [TelephonyController::class, 'index'])->name('telephony.index');
    Route::patch('/telephony/settings', [TelephonyController::class, 'updateSettings'])->name('telephony.settings.update');
    Route::post('/telephony/calls', [TelephonyController::class, 'storeCall'])->name('telephony.calls.store');
    Route::get('/messengers', [MessengerController::class, 'index'])->name('messengers.index');
    Route::patch('/messengers/settings', [MessengerController::class, 'updateSettings'])->name('messengers.settings.update');
    Route::post('/messengers/channels', [MessengerController::class, 'storeChannel'])->name('messengers.channels.store');
    Route::patch('/messengers/channels/{channel}', [MessengerController::class, 'updateChannel'])->name('messengers.channels.update');
    Route::post('/messengers/conversations', [MessengerController::class, 'storeConversation'])->name('messengers.conversations.store');
    Route::patch('/messengers/conversations/{conversation}/accept', [MessengerController::class, 'acceptConversation'])->name('messengers.conversations.accept');
    Route::patch('/messengers/conversations/{conversation}/contact', [MessengerController::class, 'updateConversationContact'])->name('messengers.conversations.contact.update');
    Route::post('/messengers/conversations/{conversation}/messages', [MessengerController::class, 'storeMessage'])->name('messengers.messages.store');
    Route::get('/mail', [MailServiceController::class, 'index'])->name('mail.index');
    Route::patch('/mail/settings', [MailServiceController::class, 'updateSettings'])->name('mail.settings.update');
    Route::post('/mail/mailboxes', [MailServiceController::class, 'storeMailbox'])->name('mail.mailboxes.store');
    Route::patch('/mail/mailboxes/{mailbox}', [MailServiceController::class, 'updateMailbox'])->name('mail.mailboxes.update');
    Route::delete('/mail/mailboxes/{mailbox}', [MailServiceController::class, 'destroyMailbox'])->name('mail.mailboxes.destroy');

    Route::resource('tasks', TaskController::class);
    Route::patch('/tasks/{task}/complete', [TaskController::class, 'complete'])->name('tasks.complete');
    Route::patch('/tasks/{task}/status', [TaskController::class, 'updateStatus'])->name('tasks.update-status');
    Route::patch('/tasks/kanban/preset', [TaskController::class, 'updateKanbanPreset'])->name('tasks.kanban.preset');
    Route::get('/disks', [DiskController::class, 'index'])->name('disks.index');
    Route::post('/disks', [DiskController::class, 'store'])->name('disks.store');
    Route::post('/disks/folders', [DiskController::class, 'storeFolder'])->name('disks.folders.store');
    Route::post('/disks/explorer/folders', [DiskExplorerController::class, 'createFolder'])->name('disks.explorer.folders.create');
    Route::delete('/disks/explorer/folders', [DiskExplorerController::class, 'deleteFolder'])->name('disks.explorer.folders.delete');
    Route::patch('/disks/explorer/folders/move', [DiskExplorerController::class, 'moveFolder'])->name('disks.explorer.folders.move');
    Route::post('/disks/explorer/folders/copy', [DiskExplorerController::class, 'copyFolder'])->name('disks.explorer.folders.copy');
    Route::patch('/disks/{disk}', [DiskController::class, 'update'])->name('disks.update');
    Route::delete('/disks/{disk}', [DiskController::class, 'destroy'])->name('disks.destroy');
    Route::patch('/disks/explorer/files/{disk}/move', [DiskExplorerController::class, 'moveFile'])->name('disks.explorer.files.move');
    Route::post('/disks/explorer/files/{disk}/copy', [DiskExplorerController::class, 'copyFile'])->name('disks.explorer.files.copy');
    Route::delete('/disks/explorer/files/{disk}', [DiskExplorerController::class, 'deleteFile'])->name('disks.explorer.files.delete');
    Route::get('/disks/{disk}/preview', [DiskController::class, 'preview'])->name('disks.preview');
    Route::get('/disks/{disk}/inline', [DiskController::class, 'inline'])->name('disks.inline');
    Route::get('/disks/{disk}/word-source', [DiskController::class, 'wordSource'])->name('disks.word-source');
    Route::get('/disks/{disk}/spreadsheet-source', [DiskController::class, 'spreadsheetSource'])->name('disks.spreadsheet-source');
    Route::get('/disks/{disk}/download', [DiskController::class, 'download'])->name('disks.download');
    Route::resource('forms', FormController::class)->except(['show']);

    Route::resource('projects', ProjectController::class);
    Route::patch('/projects/{project}/status', [ProjectController::class, 'updateStatus'])->name('projects.update-status');
    Route::post('/projects/{project}/stages', [ProjectController::class, 'storeStage'])->name('projects.stages.store');
    Route::delete('/projects/{project}/stages/{stage}', [ProjectController::class, 'destroyStage'])->name('projects.stages.destroy');
    Route::patch('/projects/{project}/stages', [ProjectController::class, 'updateStages'])->name('projects.update-stages');
    Route::patch('/projects/{project}/tasks/{task}/stage', [ProjectController::class, 'updateTaskStage'])->name('projects.tasks.update-stage');

    Route::resource('activities', ActivityController::class);
    Route::get('/reports', [ReportController::class, 'index'])->name('reports.index');
    Route::get('/chat/sidebar/{member}', [ChatConversationController::class, 'sidebar'])->name('chat.sidebar');
    Route::get('/chat/conversations/{member}', [ChatConversationController::class, 'show'])->name('chat.conversations.show');
    Route::post('/chat/conversations/{member}', [ChatConversationController::class, 'store'])->name('chat.conversations.store');
    Route::get('/users/{member}', [UserController::class, 'show'])->name('users.show');

    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::patch('/profile/appearance', [ProfileAppearanceController::class, 'update'])->name('profile.appearance.update');
    Route::patch('/profile/access', [ProfileAccessController::class, 'update'])->name('profile.access.update')->middleware('can:manageAccess');
    Route::post('/profile/access/groups', [ProfileAccessController::class, 'storeGroup'])->name('profile.access.groups.store')->middleware('can:manageAccess');
    Route::patch('/profile/access/groups/bulk-assign', [ProfileAccessController::class, 'bulkAssignGroup'])->name('profile.access.groups.bulk-assign')->middleware('can:manageAccess');
    Route::patch('/profile/access/groups/{group}', [ProfileAccessController::class, 'updateGroup'])->name('profile.access.groups.update')->middleware('can:manageAccess');
    Route::delete('/profile/access/groups/{group}', [ProfileAccessController::class, 'destroyGroup'])->name('profile.access.groups.destroy')->middleware('can:manageAccess');
    Route::post('/profile/users', [ProfileAccessController::class, 'storeUser'])->name('profile.users.store')->middleware('can:manageAccess');
    Route::get('/profile/users/import-template', [ProfileAccessController::class, 'downloadUsersTemplate'])->name('profile.users.template')->middleware('can:manageAccess');
    Route::post('/profile/users/import', [ProfileAccessController::class, 'importUsers'])->name('profile.users.import')->middleware('can:manageAccess');
    Route::patch('/profile/company-settings', [ProfileCompanySettingsController::class, 'update'])->name('profile.company-settings.update')->middleware('can:manageAccess');
    Route::post('/profile/access/impersonate/leave', [ProfileAccessController::class, 'leaveImpersonation'])->name('profile.access.impersonate.leave');
    Route::post('/profile/access/impersonate/{member}', [ProfileAccessController::class, 'impersonate'])->name('profile.access.impersonate')->middleware('can:manageAccess');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
    Route::patch('/profile/menu', [ProfileMenuController::class, 'update'])->name('profile.menu.update');
    Route::post('/profile/menu/custom', [ProfileMenuController::class, 'storeCustom'])->name('profile.menu.custom.store');
    Route::patch('/profile/menu/sidebar', [ProfileMenuController::class, 'updateSidebar'])->name('profile.menu.sidebar');
    Route::patch('/profile/right-rail', [ProfileMenuController::class, 'updateRightRail'])->name('profile.right-rail');
    Route::post('/profile/themes', [ProfileThemeController::class, 'store'])->name('profile.themes.store')->middleware('can:manageAccess');
    Route::patch('/profile/themes/{theme}', [ProfileThemeController::class, 'activate'])->name('profile.themes.activate')->middleware('can:manageAccess');
    Route::delete('/profile/themes/{theme}', [ProfileThemeController::class, 'destroy'])->name('profile.themes.destroy')->middleware('can:manageAccess');
    Route::post('/profile/api-tokens', [ProfileApiTokenController::class, 'store'])->name('profile.api-tokens.store');
    Route::delete('/profile/api-tokens/{token}', [ProfileApiTokenController::class, 'destroy'])->name('profile.api-tokens.destroy');
    Route::patch('/profile/updates', [ProfileUpdateCenterController::class, 'update'])->name('profile.updates.update')->middleware('can:manageAccess');
    Route::post('/profile/updates/check', [ProfileUpdateCenterController::class, 'check'])->name('profile.updates.check')->middleware('can:manageAccess');
    Route::post('/profile/updates/install', [ProfileUpdateCenterController::class, 'install'])->name('profile.updates.install')->middleware('can:manageAccess');
    Route::get('/profile/updates/installations/{installation}', [ProfileUpdateCenterController::class, 'showInstallation'])->name('profile.updates.installations.show')->middleware('can:manageAccess');
    Route::post('/profile/two-factor/setup', [ProfileTwoFactorController::class, 'setup'])->name('profile.two-factor.setup');
    Route::post('/profile/two-factor/confirm', [ProfileTwoFactorController::class, 'confirm'])->name('profile.two-factor.confirm');
    Route::post('/profile/two-factor/recovery-codes', [ProfileTwoFactorController::class, 'regenerateRecoveryCodes'])->name('profile.two-factor.recovery-codes');
    Route::delete('/profile/two-factor', [ProfileTwoFactorController::class, 'disable'])->name('profile.two-factor.disable');
    Route::post('/modules/scaffold', [ModuleController::class, 'scaffold'])->name('modules.scaffold')->middleware('can:manageAccess');
    Route::post('/modules', [ModuleController::class, 'store'])->name('modules.store')->middleware('can:manageAccess');
    Route::patch('/modules/{module}', [ModuleController::class, 'update'])->name('modules.update')->middleware('can:manageAccess');
    Route::delete('/modules/{module}', [ModuleController::class, 'destroy'])->name('modules.destroy')->middleware('can:manageAccess');
    Route::patch('/section-access/{entity}', [SectionAccessController::class, 'update'])->name('section-access.update');
    Route::get('/docs/api', static fn () => view('docs.api'))->name('docs.api.page');
    Route::get('/docs/api.md', static function () {
        $path = base_path('docs/api.md');
        abort_unless(is_file($path), 404);

        return response(file_get_contents($path), 200, [
            'Content-Type' => 'text/markdown; charset=UTF-8',
        ]);
    })->name('docs.api');
    Route::get('/docs/modules', static fn () => view('docs.modules', [
        'supportedHooks' => CrmModuleManager::supportedHooks(),
    ]))->name('docs.modules.page');
    Route::get('/docs/modules.md', static function () {
        $path = base_path('docs/modules.md');
        abort_unless(is_file($path), 404);

        return response(file_get_contents($path), 200, [
            'Content-Type' => 'text/markdown; charset=UTF-8',
        ]);
    })->name('docs.modules');
});

Route::get('/f/{form:slug}', [PublicFormController::class, 'show'])->name('public-forms.show');
Route::post('/f/{form:slug}', [PublicFormController::class, 'submit'])->name('public-forms.submit');

require __DIR__.'/auth.php';
