<?php

use App\Http\Middleware\LocaleMiddleware;
use App\Http\Middleware\WebsiteMiddleware;
use App\Services\WebsiteTemplateService;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Modules\Admin\App\Services\AdminTemplateService;
use \Symfony\Component\HttpKernel\Exception\HttpException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__ . '/../routes/web.php',
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(WebsiteMiddleware::class);
        $middleware->web(LocaleMiddleware::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (HttpException $exception, Request $request) {
            // Verificar si estamos en el contexto de admin
            $isAdminContext = $request->is(['admin', 'admin/*']);

            if ($isAdminContext) {
                $pageConfigs = ['myLayout' => 'blank'];
                $_admin = app(AdminTemplateService::class)->getAdminVars();  // Obtener las variables del administrador

                switch ($exception->getStatusCode()) {
                    case 400:
                        return response()->view("admin::errors.400", compact('pageConfigs', 'exception', '_admin'), 400);
                    case 401:
                        return response()->view("admin::errors.401", compact('pageConfigs', 'exception', '_admin'), 401);
                    case 403:
                        return response()->view("admin::errors.403", compact('pageConfigs', 'exception', '_admin'), 403);
                    case 404:
                        return response()->view("admin::errors.404", compact('pageConfigs', 'exception', '_admin'), 404);
                }
            }

            // Si no es el contexto admin, entonces manejar las excepciones normalmente
            $_web = app(WebsiteTemplateService::class)->getWebsiteVars();  // Obtener las variables del sitio web

            switch ($exception->getStatusCode()) {
                case 400:
                    return response()->view("errors.400", compact('exception', '_web'), 400);
                case 401:
                    return response()->view("errors.401", compact('exception', '_web'), 401);
                case 403:
                    return response()->view("errors.403", compact('exception', '_web'), 403);
                case 404:
                    return response()->view("errors.404", compact('exception', '_web'), 404);
            }
        });
    })
    ->create();
