<?php

namespace App\Http\Middleware;

use Closure;
use DB;
use Request;
use App\User;

function newGetUser($bypass = false){
    $myUser = null;
    if(isset($_COOKIE['session'])){
        $myUser = User::where('session', $_COOKIE['session'])->first();
        if(!is_null($myUser)){
            if($myUser->sess_end <= floor(microtime(true) * 1000)){
                $myUser->session = NULL;
                $myUser->sess_end = NULL;
                $myUser->tfa_auth = 0;
                setcookie('session', '', 1000, '/');
            }else{
                if(!$bypass){
                    if($myUser->tfa_locked){
                        exit();
                    }
                    if((($myUser->tfa_enabled || $myUser->tfa_forced || $myUser->isCouncil(true)) && !$myUser->tfa_auth)){
                        if(!$myUser->tfa_enabled){
                            if($_SERVER['REQUEST_METHOD'] == 'GET'){
                                exit();
                            }
                        }else{
                            if($_SERVER['REQUEST_METHOD'] == 'GET'){
                                exit();
                            }
                        }
                        return null; // deny all post requests until they log in
                    }
                }
            }
        }
    }

    return $myUser;
}

class Maintenance
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $maintenance = DB::table('site_settings')->where('setting', 'maintenance')->get();

        if($maintenance != null && $maintenance[0]->intval == 1){
            $myUser = newGetUser();
            // isDeveloper not indicated as true as we do not want Mod to be able to view whilst in maintenance mode
            if($myUser == null || (!$myUser->isManager(true) && !$myUser->isDeveloper() && $myUser->id != 180)){ // allow admins & test account
                \View::share('maintenance_reason', $maintenance[0]->strval);
                return abort(503);
            }
        }

        
        \View::share('currentDomain', Request::getHttpHost()); // share the current domain with the website
        
        
        return $next($request);
    }
}

// made with <3 by br3nt0n xx :)