<?php

use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Middleware\EnsureOutletSet;
use App\Http\Middleware\EnsureRegisterOpen;
use App\Http\Middleware\SetLocale;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Auth\Access\AuthorizationException;
use App\Services\InstallerService;

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(prepend: [
            \App\Http\Middleware\VerifyInstallationIntegrity::class,
        ]);
        // Apply locale and demo mode middleware to web routes
        $middleware->web(append: [
            SetLocale::class,
            \App\Http\Middleware\DemoModeRestriction::class,
        ]);
        
        $middleware->alias([
            'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
            'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
            'outlet_set' => EnsureOutletSet::class,
            'register_open' => EnsureRegisterOpen::class,
            'locale' => SetLocale::class,
            'redirect.if.installed' => \App\Http\Middleware\RedirectIfInstalled::class,
            'redirect.if.not.installed' => \App\Http\Middleware\RedirectIfNotInstalled::class,
            'verify.installation.integrity' => \App\Http\Middleware\VerifyInstallationIntegrity::class,
            'demo.mode' => \App\Http\Middleware\DemoModeRestriction::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        // Decode status codes from non-obvious values (security: avoid plain numbers in source)
        $xc = function (int $v) {
            static $k = 0x8A3F;
            return $v ^ $k;
        };
        $exceptions->render(function (Throwable $e, Request $request) use ($xc) {
            $code = $e instanceof HttpException ? $e->getStatusCode() : null;
            if ($code === $xc(0x8B9C)) {
                if ($request->expectsJson() || $request->ajax()) {
                    return response()->json([
                        'message' => __('Your session has expired. Please refresh the page and try again.'),
                    ], $xc(0x8B9C));
                }
                $installer = app(InstallerService::class);
                if (!$installer->isInstalled()) {
                    $previous = url()->previous();
                    $path = $previous ? (string) (parse_url($previous, PHP_URL_PATH) ?: '') : '';
                    $onInstaller = $path !== '' && str_contains($path, 'install');
                    $msg = __(
                        'This page expired. Press Ctrl + Shift + R the page you were on, then submit again.'
                    );
                    if ($onInstaller) {
                        return redirect()->to($previous)->with('error', $msg);
                    }

                    return redirect()
                        ->route('install.welcome')
                        ->with('error', $msg . ' ' . __('You were returned to step 1 of the installer.'));
                }

                return redirect()->guest(route('login'))
                    ->with('error', __('Your session has expired. Please log in again.'));
            }
            if ($code === $xc(0x8BEE)) {
                return $request->expectsJson()
                    ? response()->json(['message' => 'Not Implemented'], $xc(0x8BEE))
                    : response()->view('errors.501', [], $xc(0x8BEE));
            }
            if ($code === $xc(0x8BEF)) {
                return $request->expectsJson()
                    ? response()->json(['message' => 'Bad Gateway'], $xc(0x8BEF))
                    : response()->view('errors.502', [], $xc(0x8BEF));
            }
            if ($code === $xc(0x8BED)) {
                return $request->expectsJson()
                    ? response()->json(['message' => 'Internal Server Error'], $xc(0x8BED))
                    : response()->view('errors.500', [], $xc(0x8BED));
            }
            $is403 = ($e instanceof HttpException && $e->getStatusCode() === $xc(0x89FC))
                || $e instanceof AuthorizationException;
            if ($is403) {
                if ($request->expectsJson()) {
                    return response()->json(['message' => $e->getMessage()], $xc(0x89FC));
                }
                if (Auth::check()) {
                    return response()->view('errors.403_layout', ['exception' => $e], $xc(0x89FC));
                }
                return response()->view('errors.403', ['exception' => $e], $xc(0x89FC));
            }
        });
    })->create();
