<?php

use Illuminate\Support\Facades\Route;
use AleshaCMS\Http\Controllers\Admin;
use AleshaCMS\Http\Controllers\Frontend\FrontendController;
use AleshaCMS\Http\Controllers\Auth\AuthController;

// Auth
Route::middleware('guest')->group(function () {
    Route::get('/admin/login', [AuthController::class, 'showLogin'])->name('login');
    Route::post('/admin/login', [AuthController::class, 'login']);
});
Route::post('/admin/logout', [AuthController::class, 'logout'])->name('logout')->middleware('auth');

// Admin Panel
Route::prefix('admin')
    ->name('admin.')
    ->middleware(['auth', 'can.access.admin'])
    ->group(function () {
        Route::get('/', [Admin\DashboardController::class, 'index'])->name('dashboard');
        Route::get('stats', [Admin\StatsController::class, 'index'])->name('stats');

        // Posts / Content Types
        Route::get('posts/{type?}', [Admin\PostController::class, 'index'])->name('posts.index');
        Route::get('posts/{type}/create', [Admin\PostController::class, 'create'])->name('posts.create');
        Route::post('posts/{type}', [Admin\PostController::class, 'store'])->name('posts.store');
        Route::get('posts/{type}/{post}/edit', [Admin\PostController::class, 'edit'])->name('posts.edit');
        Route::put('posts/{type}/{post}', [Admin\PostController::class, 'update'])->name('posts.update');
        Route::delete('posts/{type}/{post}', [Admin\PostController::class, 'destroy'])->name('posts.destroy');

        // Media
        Route::get('media', [Admin\MediaController::class, 'index'])->name('media.index');
        Route::post('media', [Admin\MediaController::class, 'store'])->name('media.store');
        Route::patch('media/{media}', [Admin\MediaController::class, 'update'])->name('media.update');
        Route::delete('media/{media}', [Admin\MediaController::class, 'destroy'])->name('media.destroy');
        Route::get('media/browse', [Admin\MediaController::class, 'browse'])->name('media.browse');

        // Themes
        Route::get('themes', [Admin\ThemeController::class, 'index'])->name('themes.index');
        Route::post('themes/activate', [Admin\ThemeController::class, 'activate'])->name('themes.activate');
        Route::get('themes/colors', [Admin\ThemeController::class, 'getColors'])->name('themes.colors.get');
        Route::post('themes/colors', [Admin\ThemeController::class, 'saveColors'])->name('themes.colors.save');

        // Plugins
        Route::get('plugins', [Admin\PluginController::class, 'index'])->name('plugins.index');
        Route::post('plugins/toggle', [Admin\PluginController::class, 'toggle'])->name('plugins.toggle');

        // Sliders
        Route::resource('sliders', Admin\SliderController::class)->except(['show']);

        // Menus
        Route::resource('menus', Admin\MenuController::class)->except(['show']);

        // Users
        Route::resource('users', Admin\UserController::class)->except(['show']);

        // Content Types
        Route::resource('content-types', Admin\ContentTypeController::class)->except(['show']);

        // Taxonomies (categories, tags, custom)
        Route::get('taxonomies/{type?}', [Admin\TaxonomyController::class, 'index'])->name('taxonomies.index');
        Route::post('taxonomies/{type}', [Admin\TaxonomyController::class, 'store'])->name('taxonomies.store');
        Route::get('taxonomies/{type}/{taxonomy}/edit', [Admin\TaxonomyController::class, 'edit'])->name('taxonomies.edit');
        Route::put('taxonomies/{type}/{taxonomy}', [Admin\TaxonomyController::class, 'update'])->name('taxonomies.update');
        Route::delete('taxonomies/{type}/{taxonomy}', [Admin\TaxonomyController::class, 'destroy'])->name('taxonomies.destroy');

        // Settings
        Route::get('settings/{group?}', [Admin\SettingsController::class, 'index'])->name('settings.index');
        Route::post('settings/{group?}', [Admin\SettingsController::class, 'update'])->name('settings.update');

        // Audit Logs
        Route::get('logs', function (\Illuminate\Http\Request $request) {
            $search = $request->search;
            $logs = \AleshaCMS\Models\CMS\AuditLog::with('user')
                ->when($search, fn($q) => $q->where(fn($q2) =>
                    $q2->where('action', 'like', "%{$search}%")
                       ->orWhere('ip_address', 'like', "%{$search}%")
                       ->orWhere('user_agent', 'like', "%{$search}%")
                       ->orWhereHas('user', fn($u) => $u->where('name', 'like', "%{$search}%"))
                ))
                ->latest()
                ->paginate(20);

            if ($request->wantsJson()) {
                return response()->json([
                    'data' => $logs->map(fn($log) => [
                        'action'     => $log->action,
                        'user'       => $log->user?->name ?? 'System',
                        'model'      => $log->model_type ? class_basename($log->model_type) . ' #' . $log->model_id : null,
                        'ip'         => $log->ip_address,
                        'user_agent' => $log->user_agent,
                        'time'       => $log->created_at->diffForHumans(),
                        'time_full'  => $log->created_at->format('d M Y H:i:s'),
                    ]),
                    'meta' => [
                        'current_page' => $logs->currentPage(),
                        'last_page'    => $logs->lastPage(),
                        'total'        => $logs->total(),
                    ],
                ]);
            }

            return view('admin.logs.index');
        })->name('logs.index');
    });

// Frontend taxonomy archives
Route::get('/category/{slug}', [FrontendController::class, 'taxonomyArchive'])->name('frontend.category');
Route::get('/tag/{slug}', [FrontendController::class, 'taxonomyArchive'])->name('frontend.tag');

// Frontend — catch-all (must be last)
Route::get('/{slug?}', [FrontendController::class, 'resolve'])->where('slug', '.*');
