<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class SetLanguage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle( $request, Closure $next )
    {
        if ( $request->has( 'language' ) )
        {
            $language = $request->language;
            
            // Validate language exists
            $availableLanguages = ['en', 'id', 'pt', 'ru'];
            if ( in_array( $language, $availableLanguages ) )
            {
                // Save as users language if logged in and language column exists
                if ( Auth::user() )
                {
                    try {
                        Auth::user()->language = $language;
                        Auth::user()->save();
                    } catch ( \Exception $e ) {
                        // Language column doesn't exist, store in session instead
                        $request->session()->put( 'language', $language );
                    }
                }
                else
                {
                    // Store in session for guest users
                    $request->session()->put( 'language', $language );
                }

                App::setLocale( $language );
            }
        }
        elseif ( Auth::user() )
        {
            try {
                if ( Auth::user()->language ) {
                    App::setLocale( Auth::user()->language );
                }
            } catch ( \Exception $e ) {
                // Language column doesn't exist, check session
                if ( $request->session()->has( 'language' ) ) {
                    App::setLocale( $request->session()->get( 'language' ) );
                }
            }
        }
        elseif ( $request->session()->has( 'language' ) )
        {
            App::setLocale( $request->session()->get( 'language' ) );
        }
        else
        {
            // Default to English
            App::setLocale( 'en' );
        }
        
        return $next( $request );
    }
}
