<?php

use App\Http\Controllers\Admin\BlockAdminController;
use App\Http\Controllers\Admin\BlockLayoutWizardController;
use App\Http\Controllers\Admin\CacheAdminController;
use App\Http\Controllers\Admin\CarController;
use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\Admin\LeadController;
use App\Http\Controllers\Admin\LoginController;
use App\Http\Controllers\Admin\ManualController;
use App\Http\Controllers\Admin\PageAdminController;
use App\Http\Controllers\Admin\PageSectionController;
use App\Http\Controllers\Admin\ReviewAdminController;
use App\Http\Controllers\Admin\ServiceAdminController;
use App\Http\Controllers\Admin\SettingAdminController;
use App\Http\Controllers\Admin\UserAdminController;
use App\Http\Controllers\Admin\WebFormController;
use App\Http\Controllers\CatalogController;
use App\Http\Controllers\FavoritesController;
use App\Http\Controllers\FormSubmitController;
use App\Http\Controllers\PageController;
use App\Http\Controllers\ServiceController;
use Illuminate\Support\Facades\Route;

/*
 * routes/web.php — веб-маршруты приложения.
 *
 * Изменён: 2026-05-06 (добавлены admin-маршруты)
 * Структура:
 *   GET /                       → страница приветствия (стандартная Laravel)
 *   /admin/*                    → группа административной панели (prefix 'admin', name 'admin.')
 *     login/logout              → LoginController (без middleware)
 *     middleware('admin')       → EnsureUserIsAdmin; всё что ниже — только для admin
 *       GET /admin/             → DashboardController
 *       resource /admin/cars    → CarController (CRUD)
 *       /admin/manuals/*        → ManualController (справочники: разделы и значения)
 */

// Публичные страницы: middleware maintenance блокирует доступ если сайт на обслуживании
// (пропускает только role=admin|superadmin, остальным показывает заглушку)
Route::middleware('maintenance')->group(function () {
    Route::get('/', [PageController::class, 'home'])->name('home');
    Route::get('/services', [PageController::class, 'services'])->name('services');
    Route::get('/services/{slug}', [ServiceController::class, 'show'])->name('services.show');
    Route::get('/contacts', [PageController::class, 'contacts'])->name('contacts');
    Route::get('/catalog', [CatalogController::class, 'index'])->name('catalog');
    Route::get('/catalog/{id}', [CatalogController::class, 'show'])->name('catalog.show')->where('id', '[0-9]+');
    Route::get('/privacy', [PageController::class, 'privacy'])->name('privacy');
    Route::get('/offer', [PageController::class, 'offer'])->name('offer');

    // Избранное
    Route::get('/favorites', [FavoritesController::class, 'index'])->name('favorites');
    Route::post('/favorites/load', [FavoritesController::class, 'load'])->name('favorites.load');

    // Отправка веб-форм
    Route::post('/forms/{slug}/submit', [FormSubmitController::class, 'submit'])->name('forms.submit');
});

// Группа административной панели: все маршруты с префиксом /admin и именем admin.*
Route::prefix('admin')->name('admin.')->group(function () {
    Route::get('login', [LoginController::class, 'showLoginForm'])->name('login');
    Route::post('login', [LoginController::class, 'login']);
    Route::post('logout', [LoginController::class, 'logout'])->name('logout');

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

        // Страницы сайта (редактирование без создания/удаления)
        Route::get('pages', [PageAdminController::class, 'index'])->name('pages.index');
        Route::get('pages/{page}/edit', [PageAdminController::class, 'edit'])->name('pages.edit');
        Route::put('pages/{page}', [PageAdminController::class, 'update'])->name('pages.update');

        // Блоки контента
        // Маршруты визарда должны быть ДО resource чтобы 'blocks/wizard' не трактовался как {block}
        Route::get('blocks/wizard',          [BlockLayoutWizardController::class, 'index'])->name('blocks.wizard');
        Route::post('blocks/wizard/analyze', [BlockLayoutWizardController::class, 'analyze'])->name('blocks.wizard.analyze');
        Route::post('blocks/wizard/generate',[BlockLayoutWizardController::class, 'generate'])->name('blocks.wizard.generate');
        Route::resource('blocks', BlockAdminController::class)->except(['show']);

        // Page-builder: управление секциями страницы (встроен в edit)
        Route::post('pages/{page}/sections/reorder', [PageSectionController::class, 'reorder'])->name('pages.sections.reorder');
        Route::post('pages/{page}/sections/attach-block', [PageSectionController::class, 'attachBlock'])->name('pages.sections.attach-block');
        Route::post('pages/{page}/sections/add-content', [PageSectionController::class, 'addContent'])->name('pages.sections.add-content');
        Route::put('pages/{page}/sections/{section}', [PageSectionController::class, 'updateContent'])->name('pages.sections.update');
        Route::delete('pages/{page}/sections/{section}', [PageSectionController::class, 'destroy'])->name('pages.sections.destroy');

        // Настройки сайта
        Route::get('settings', [SettingAdminController::class, 'index'])->name('settings.index');
        Route::post('settings', [SettingAdminController::class, 'update'])->name('settings.update');

        // Пользователи и права
        Route::get('users', [UserAdminController::class, 'index'])->name('users.index');
        Route::get('users/create', [UserAdminController::class, 'create'])->name('users.create');
        Route::post('users', [UserAdminController::class, 'store'])->name('users.store');
        Route::get('users/{user}/edit', [UserAdminController::class, 'edit'])->name('users.edit');
        Route::put('users/{user}', [UserAdminController::class, 'update'])->name('users.update');
        Route::delete('users/{user}', [UserAdminController::class, 'destroy'])->name('users.destroy');

        // Конструктор форм
        Route::resource('forms', WebFormController::class)->except(['show']);

        // Заявки
        Route::get('leads', [LeadController::class, 'index'])->name('leads.index');
        Route::get('leads/{lead}', [LeadController::class, 'show'])->name('leads.show');
        Route::delete('leads/{lead}', [LeadController::class, 'destroy'])->name('leads.destroy');

        // Услуги компании
        Route::resource('services', ServiceAdminController::class)->except(['show']);

        // Отзывы клиентов
        Route::resource('reviews', ReviewAdminController::class)->except(['show']);
        Route::post('reviews/{review}/toggle', [ReviewAdminController::class, 'toggle'])->name('reviews.toggle');

        // Очистка кеша
        Route::post('cache/clear', [CacheAdminController::class, 'clear'])->name('cache.clear');

        // Cars
        Route::resource('cars', CarController::class);

        // Manuals — sections
        Route::prefix('manuals')->name('manuals.')->group(function () {
            Route::get('/', [ManualController::class, 'index'])->name('index');

            Route::get('sections/create', [ManualController::class, 'sectionCreate'])->name('section.create');
            Route::post('sections', [ManualController::class, 'sectionStore'])->name('section.store');
            Route::get('sections/{section}/edit', [ManualController::class, 'sectionEdit'])->name('section.edit');
            Route::put('sections/{section}', [ManualController::class, 'sectionUpdate'])->name('section.update');
            Route::delete('sections/{section}', [ManualController::class, 'sectionDestroy'])->name('section.destroy');

            // Manuals — values
            Route::get('{section}/values', [ManualController::class, 'values'])->name('values');
            Route::get('{section}/values/create', [ManualController::class, 'valueCreate'])->name('value.create');
            Route::post('{section}/values', [ManualController::class, 'valueStore'])->name('value.store');
            Route::get('{section}/values/{value}/edit', [ManualController::class, 'valueEdit'])->name('value.edit');
            Route::put('{section}/values/{value}', [ManualController::class, 'valueUpdate'])->name('value.update');
            Route::delete('{section}/values/{value}', [ManualController::class, 'valueDestroy'])->name('value.destroy');
        });
    });
});
