<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cookie;

class TranslationMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->method() !== 'GET') {
            return $next($request);
        }

        $locales = get_locales();
        $locale_code = get_default_language();

        if (Cookie::has('locale')) {
            $locale_code = Cookie::get('locale');

            if ($locale_code !== request()->segment(1)) {
                $segments = request()->segments();
                $segments = array_replace($segments, [0 => $locale_code]);
                app()->setLocale($locale_code);

                return redirect()->to(implode('/', $segments));
            }
            if (array_key_exists($locale_code, $locales) && array_key_exists(request()->segment(1), $locales)) {
                app()->setLocale($locale_code);
                return $next($request);
            }else{
                $segments = request()->segments();
                $segments = Arr::prepend($segments, $locale_code);

                app()->setLocale($locale_code);

                return redirect()->to(implode('/', $segments));
            }
        }

        if ( auto_redirect() == "true" ) {
            $locale_code = get_browser_lang();

            // check if the first segment is available and is not the same as the country code
            if (array_key_exists(request()->segment(1), $locales) && request()->segment(1) !== $locale_code) {
                $segments = request()->segments();
                array_shift($segments); // remove first segment
                $segments = Arr::prepend($segments, $locale_code);

                app()->setLocale($locale_code);

                return redirect()->to(implode('/', $segments));
            }
        }

        if (! array_key_exists(request()->segment(1), $locales) ) {
            $segments = request()->segments();
            $segments = Arr::prepend($segments, $locale_code);

            app()->setLocale($locale_code);

            return redirect()->to(implode('/', $segments));
        }

        return $next($request);
    }
}
