<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // Check if locale is in request
        if ($request->has('locale')) {
            $locale = $request->get('locale');
            
            // Validate locale
            if (in_array($locale, ['en', 'id'])) {
                App::setLocale($locale);
                Session::put('locale', $locale);
            }
        }
        
        // Check if locale is in session
        elseif (Session::has('locale')) {
            $locale = Session::get('locale') ?? 'id';
            
            if (in_array($locale, ['en', 'id'])) {
                App::setLocale($locale);
            }
        }
        
        return $next($request);
    }
}
