<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Dotenv\Dotenv;

class LoadEnvironmentByDomain
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $hostname = $request->getHost();
        
        // Custom mapping of hostname to env files
        $envFiles = [
            'gamedev1.site' => '.env.dewabet303',
            'gamedev2.site' => '.env.shio338',
            'gamedev3.site' => '.env.totoslot99',
        ];

        if (array_key_exists($hostname, $envFiles)) {
            $envPath = base_path('env/' . $envFiles[$hostname]);
            if (file_exists($envPath)) {
                $dotenv = Dotenv::createImmutable(base_path('env'), $envFiles[$hostname]);
                $dotenv->load();
            }
        }

        return $next($request);
    }
}
