<?php

namespace App\Http\Middleware;

use App\Models\Currency;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class LoadCurrencies
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (!Auth::check()) {
            return $next($request);
        }

        $currencies = Cache::rememberForever('currencies',function(){
            return Currency::all();
        });


        foreach ($currencies as $currency) {
            config(['money.' . $currency->code . '.name' => $currency->name]);
            config(['money.' . $currency->code . '.rate' => $currency->exchange_rate]);
            if($currency->precision)config(['money.' . $currency->code . '.precision' => $currency->precision]);
            config(['money.' . $currency->code . '.symbol' => $currency->symbol]);
            if($currency->decimal_mark)config(['money.' . $currency->code . '.decimal_mark' => $currency->decimal_mark]);
            if($currency->thousands_separator)config(['money.' . $currency->code . '.thousands_separator' => $currency->thousands_separator]);
        }

        // Set currencies with new settings
        \Akaunting\Money\Currency::setCurrencies(config('money'));
        //Auth::user()->setAttribute('currency_code',Auth::user()->account->currency_code);
        return $next($request);
    }


}
