<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\Admin;
use App\Models\AdminLoginLog;
use Illuminate\Support\Facades\Auth;
use App\Models\AdminCookie as AdminCookieModel;
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 AdminCookie
{
    /**
     * 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::guard('admin')->check() == true) return false;
        if (CookieHelper::has('admin') == false) return false;
        $check_data = AdminCookieModel::where('value', CookieHelper::get('admin'))->first();
        if ($check_data == false) return false;
        $check_admin = Admin::findOrFail($check_data->admin_id);
        $login = Auth::guard('admin')->loginUsingId($check_admin->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()).')';
            }
            AdminLoginLog::create([
                'admin_id' => $check_data->admin_id,
                'ip_address' => request()->ip(),
                'location'   => $input_data['location']
            ]);
            return session()->flash('result', [
                'alert'   => 'success', 
                'title'   => 'Berhasil', 
                'message' => 'Selamat datang '.$check_admin->full_name.'.',
                'timeout' => 5000,
                'size'    => 'col-lg-12'
            ]);
            return true;
        }
        return false;
    }
}

