<?php

namespace App\Http\Middleware;

use App\Facades\General;
use App\Models\Account;
use App\Models\UserSetting;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;

class CheckAccountDomain
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        preg_match('/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i', $request->server('HTTP_HOST'), $match);
        $subDomain = isset($match[1]) ? $match[1] : '';

        $accountModel = new Account();
        $objAccount   = $accountModel->where("domain_alias", $subDomain)->first();

        // If basic information not exit in Database it will redirect to main portal
        if (!is_null($objAccount) && isset($objAccount->id) && !is_null($objAccount->domain_alias) && $subDomain != '') {
            if ($objAccount->domain_alias == $subDomain) {
                Config::set('account.subDomain', $objAccount->domain_alias);
                Config::set('account.id', $objAccount->id);
                Config::set('account.name', $objAccount->name);
                Config::set('account.logo', $objAccount->logo);
            }
        }

        /*if (General::isSuperAdmin()) {
            $defaultAccountId = UserSetting::getOptionValueByName('default_account_id');
            if (!is_null($defaultAccountId)) {
                $objSuperAccount = $accountModel->where("id", $defaultAccountId->option_value)->first();
                if (!is_null($objSuperAccount) && isset($objSuperAccount->id) && !is_null($objSuperAccount->domain_alias)) {
                    Config::set('account.subDomain', $objSuperAccount->domain_alias);
                    Config::set('account.id', $objSuperAccount->id);
                    Config::set('account.name', $objSuperAccount->name);
                }
            }
        }*/


        if ($subDomain == '') {
            return $next($request);
        }

        if ($objAccount == null && $subDomain != 'www') {
           // return redirect($request->server('HTTP_HOST') == Config::get('app.url') ? Config::get('app.url') : 'http://test.dgtalclass.com/auth/login');
        }

        return $next($request);
    }
}
