<?php
namespace App\Http\Middleware;

use Closure;
use App;
use Carbon\Carbon;

class Locale {

    /**
     * Routes locale. Not the cleanest implementation, but hey..
     * Some inspiration: https://coderwall.com/p/czumyq/easy-i18n-with-language-prefix-and-language-related-route-in-laravel-4
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        // ignore this if running inside CLI
        if (app()->runningInConsole()) {
            return $next($request);
        }

        // first segment is the locale (if avai).
        $first_segment = $request->segment(1);
        // again check if we need locale here
        if (in_array($first_segment, config('app.no_locale_namespaces'))) {
            return $next($request);
        }

        // do the redirect if no valid locale found
        if (!in_array($first_segment, config('app.available_locales'))) {
            // prepare url...
            $query = $request->getQueryString();
            $segments = $request->segments();
            
            // detect if the first segment is a locale (eg: 2 words)
            if (strlen($first_segment) == 2) {
                array_shift($segments);
            }
            
            // build full url.
            $full_url = implode('/', $segments) . ($query ? '?' . $query : '');
            
            // set default locale.
            $first_segment = config('app.default_locale');
            
            // force redirection!
            return redirect('/' . implode('/', array_filter([$first_segment, $full_url])), 301);
            //  app()->abort(301, null, [
            //          'Location' => '/' . implode('/', array_filter([$first_segment, $full_url]))
            //  ]);
        }

        // set app locale
        App::setLocale($first_segment);

        // set locale carbon (for dates transaltion!)
        if ($first_segment === 'ro') {
            setlocale(LC_TIME, 'ro_RO', 'Romanian');
        }
        Carbon::setLocale($first_segment);

        // go next
        return $next($request);
    }

}
