<?php
namespace App\Http\Middleware;

use Closure;
use App\Models\Lang;
use Torann\GeoIP\Facades\GeoIP;

class Frontend
{
    use \App\Traits\ContentTrait;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $setting = self::model('setting')::where('lang', 'single')->orWhere('lang', config('lang'))->lists('value', 'name');

        if (isset($setting['access_denied']) && $setting['access_denied'] == 1) {
            $location = GeoIP::getLocation(request()->getClientIp())->toArray();
            if (!empty($location) && $location['iso_code'] == 'CN') {
                abort(500);
            }
        }

        $host = explode('.', $request->server('HTTP_HOST'));

        $domain = str_replace('www.', '', $request->server('HTTP_HOST'));
        $data = Lang::where('buy', 1)->where('enabled', 1)->flag()->where('domain', $domain)->orWhere('domain', 'www.' . $domain)->first();

        if ($data) {
            $lang = $data->slug;
        } else {
            $lang = in_array($host[0], config('langs')) ? $host[0] : config('setting.lang');
        }

        \App::setLocale($lang);

        config(['lang' => $lang, 'visit' => 'frontend']);

        if (isset($setting['open_browser']) && $setting['open_browser'] == 1 && !session('frontendLang') && $request->server('HTTP_ACCEPT_LANGUAGE') && !str_contains($request->server('HTTP_USER_AGENT'), 'Googlebot')) {

            $langs = explode(',', explode(';', $request->server('HTTP_ACCEPT_LANGUAGE'))[0]);

            foreach (config('langs') as $val) {
                $newLang = $val == 'cn' ? 'zh' : $val;
                if (in_array($newLang, $langs) && $val != config('setting.lang')) {
                    session(['frontendLang' => $val]);
                    if ($data) {
                        $redirectUrl = $request->getScheme().'://'.$data->domain.$request->getRequestUri();
                    } else {
                        $newDataDomain = Lang::where('buy', 1)->where('enabled', 1)->flag()->where('slug', $val)->value('domain');
                        $redirectUrl = $newDataDomain ? $request->getScheme().'://'.$data->domain.$request->getRequestUri() : preg_replace('/\/\/\w+\./', "//{$val}.", $request->url());
                    }
                    return redirect($redirectUrl);
                }
            }
        }
        
        if (isset($setting['status']) && $setting['status'] == 0) {
            return view('theme::close', compact('setting'));
        }

        return $next($request);
    }

   

}
