<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\User;
use App\Models\UserLoginLog;
use Illuminate\Support\Facades\Auth;
use App\Models\UserCookie;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Cookie as CookieHelper;
use Jenssegers\Agent\Agent;
use Stevebauman\Location\Facades\Location;

class Cookie
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
	public function __construct(Request $request) {
        $this->user_agent = new Agent();
        $this->location = Location::get($request->ip());
	}
    public function handle($request, Closure $next) {
        if ($this->check() == true) {
            return $next($request);
        }
        return $next($request);
    }
    private function check() {
        if (Auth::check() == true) return false;
        if (CookieHelper::has('user') == false) return false;
        $check_data = UserCookie::where('value', CookieHelper::get('user'))->first();
        if ($check_data == false) return false;
        $check_user = User::findOrFail($check_data->user_id);
        $login = Auth::loginUsingId($check_user->id);
        if ($login == true) {
            if ($this->location) {
                $input_data['location'] = $this->location->countryName.' - '.$this->location->regionName.' - '.$this->location->cityName.' ('.$this->user_agent->device().' - '.$this->user_agent->platform().'/'.$this->user_agent->version($this->user_agent->platform()).' - '.$this->user_agent->browser().'/'.$this->user_agent->version($this->user_agent->browser()).')';
            } else {
                $input_data['location'] = '('.$this->user_agent->device().' - '.$this->user_agent->platform().'/'.$this->user_agent->version($this->user_agent->platform()).' - '.$this->user_agent->browser().'/'.$this->user_agent->version($this->user_agent->browser()).')';
            }
            UserLoginLog::create([
                'user_id'    => $check_data->user_id,
                'ip_address' => request()->ip(),
                'location'   => $input_data['location']
            ]);
			Session::put('information_popup', true);
            return session()->flash('result', [
                'alert'   => 'success', 
                'title'   => 'Berhasil', 
                'message' => 'Selamat datang '.$check_user->full_name.'.',
                'timeout' => 5000,
                'size'    => 'col-lg-12'
            ]);
            return true;
        }
        return false;
    }
}
