<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Middleware\TrustProxies;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
            'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
            'ensure.enrolled' => \App\Http\Middleware\EnsureEnrolled::class,
        ]);
        
        // Add InjectTheme middleware to web middleware group
        $middleware->web(append: [
            \App\Http\Middleware\InjectTheme::class,
        ]);

        // Exclude external webhook/callback POST routes from CSRF verification
        $middleware->validateCsrfTokens(except: [
            'payments/momo/callback',        // Global MTN MoMo payment callback
            'mentorship/payments/callback',  // Mentorship MTN MoMo payment callback
            'membership/payments/callback',  // MTN MoMo membership payment callback (if applicable)
        ]);

        // Trust all proxy headers so Hepsia's reverse proxy passes correct
        // scheme and host to Laravel (fixes HTTP/HTTPS mismatch and URL generation).
        $middleware->trustProxies(
            at: '*',
            headers: Request::HEADER_X_FORWARDED_FOR |
                Request::HEADER_X_FORWARDED_HOST |
                Request::HEADER_X_FORWARDED_PORT |
                Request::HEADER_X_FORWARDED_PROTO
        );
    })
    ->withExceptions(function (Exceptions $exceptions) {
        // ─────────────────────────────────────────────────────────────────────
        // Custom error pages — only active when APP_DEBUG=false.
        // Covers all HTTP error codes listed in the project requirements.
        // ─────────────────────────────────────────────────────────────────────
        $exceptions->render(function (\Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e, \Illuminate\Http\Request $request) {
            // Only intercept when debug is OFF (production mode)
            if (config('app.debug')) {
                return null; // Let Laravel's default Whoops handler take over
            }

            // Only intercept HTML (browser) requests, not API/JSON requests
            if ($request->expectsJson()) {
                return null;
            }

            $statusCode = $e->getStatusCode();

            // Determine if the request is coming from a dashboard/admin area
            $isDashboard = \App\Support\ErrorPageHelper::isDashboardRequest($request);

            // Build the view data for this specific error code
            $viewData = \App\Support\ErrorPageHelper::buildViewData($statusCode, $isDashboard, $e, $request);

            return response()->view('errors.error', $viewData, $statusCode);
        });
    })->create();
