<?php
 namespace App\Http\Middleware; use App\Models\Brand; use App\Services\Store\BrandContext; use App\Services\ThemeManager; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\View; use Symfony\Component\HttpFoundation\Response; class ResolveBrand { public function handle(Request $request, Closure $next): Response { if ($request->is('.well-known/*')) { return $next($request); } $host = strtolower($request->getHost()); $host = preg_replace('/^www\./', '', $host); $record = Brand::where('domain', $host)->with('reseller')->first(); $servable = $record && $record->is_active && $record->domain_verified && $record->reseller?->status === 'active'; if ($record && ! $servable) { return response()->view('errors.brand-unavailable', [], 503); } $brand = $servable ? $record : null; app(BrandContext::class)->set($brand); app()->instance('brand', $brand); View::share('brand', $brand); if ($brand) { $this->applyBrandTheme($brand->theme); View::share('appName', $brand->name); View::share('companyLogo', $brand->logo ?: ''); } return $next($request); } private function applyBrandTheme(?string $theme): void { if ($theme === null || $theme === '') { return; } $themeManager = app(ThemeManager::class); if (! $themeManager->exists($theme)) { Log::warning('Brand theme not found, falling back to active theme', ['theme' => $theme]); return; } if ($theme === $themeManager->getActive()) { return; } View::getFinder()->prependLocation($themeManager->getViewsPath($theme)); View::share('activeTheme', $theme); View::share('themeAssets', $themeManager->getAssets($theme)); } } 