<?php

namespace App\Http\Middleware;

use App\Models\Translation;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Lang;
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $locale = session('locale', 'en');
        if (! in_array($locale, ['en', 'fa', 'ps'], true)) $locale = 'en';
        app()->setLocale($locale);
        $lines = Translation::where('locale', $locale)->pluck('value', 'key')->all();

        // addLines expects "group.item" keys. Prefixing with "*." places these
        // database entries in Laravel's JSON translation group, so __('Dashboard')
        // and other plain-text keys remain both translatable and safe.
        if ($lines) {
            $jsonLines = [];
            foreach ($lines as $key => $value) {
                $jsonLines['*.'.$key] = $value;
            }
            Lang::addLines($jsonLines, $locale);
        }
        return $next($request);
    }
}
