<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

// ✅ IMPORTANT: Force debug mode OFF at the very beginning
$_ENV['APP_DEBUG'] = 'false';
$_SERVER['APP_DEBUG'] = 'false';

// ✅ Set PHP settings to prevent memory issues
@ini_set('memory_limit', '512M');
@ini_set('max_execution_time', '300');
@ini_set('display_errors', '0');
@ini_set('display_startup_errors', '0');
error_reporting(0);

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        // Web middleware group
        $middleware->web(append: [
            // আপনি চাইলে এখানে custom middleware যোগ করতে পারেন
        ]);
        
        // API middleware group
        $middleware->api(append: [
            // API middleware
        ]);
        
        // ✅ কাস্টম মিডলওয়্যার alias - উভয় নামে রেজিস্টার করুন
        $middleware->alias([
            'checkusertype' => \App\Http\Middleware\CheckUserType::class,
            'check.user.type' => \App\Http\Middleware\CheckUserType::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        // ✅ Custom exception handling to prevent memory issues
        $exceptions->render(function (Throwable $e, $request) {
            // For loan-related errors, return simple response
            if (str_contains($e->getMessage(), 'memory') || 
                str_contains($e->getMessage(), 'Loan') ||
                str_contains($request->path(), 'loans') ||
                str_contains($request->path(), 'approve')) {
                
                if ($request->expectsJson()) {
                    return response()->json([
                        'error' => true,
                        'message' => 'সিস্টেম ত্রুটি। দয়া করে আবার চেষ্টা করুন।'
                    ], 500);
                }
                
                // Redirect back with simple message
                return redirect()->back()
                    ->with('error', 'সিস্টেম ত্রুটি। দয়া করে আবার চেষ্টা করুন।');
            }
            
            // Default Laravel handling for other exceptions
            return null;
        });
    })->create();