<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use App\Models\LoginHistory;
use App\Models\Settings;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('auth.login');
    }

    /**
     * Handle an incoming authentication request.
     *
     * @param  \App\Http\Requests\Auth\LoginRequest  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(LoginRequest $request)
    {

        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        //$ip = '37.60.48.2';

        // Input your options for this query including your optional API Key and query flags.
        $proxy_apikey = Settings::where('name', 'proxycheck')->first();
        $proxycheck_options = array(
            'API_KEY' => $proxy_apikey->value, // Your API Key.
            'ASN_DATA' => 1, // Enable ASN data response.
            'VPN_DETECTION' => 1, // Check for both VPN's and Proxies instead of just Proxies.
            'RISK_DATA' => 1, // 0 = Off, 1 = Risk Score (0-100), 2 = Risk Score & Attack History.
        );

        $result_array = \proxycheck\proxycheck::check($ip, $proxycheck_options);
        //echo $result_array['block'];

        if($result_array['status'] == "ok"){

            $block_vpnlogin = Settings::where('name', 'block_vpnlogin')->first();

            if($result_array[$ip]['proxy'] == "yes" && $block_vpnlogin->value == '1'){
                $request->authenticate();
                $request->session()->regenerate();
                LoginHistory::create([
                    'ip' => $ip,
                    'asn' => $result_array[$ip]['asn'],
                    'provider' => $result_array[$ip]['provider'],
                    'country' => $result_array[$ip]['country'],
                    'proxy' => $result_array[$ip]['proxy'],
                    'type' => $result_array[$ip]['type'],
                    'risk' => $result_array[$ip]['risk'],
                    'user_id' => Auth::user()->id
                ]);
                $request->session()->invalidate();
                $request->session()->regenerateToken();
                session()->flash('error','VPN/Proxy detected, try not use');
                return redirect('/');
            }else{
                $request->authenticate();
                $request->session()->regenerate();
                LoginHistory::create([
                    'ip' => $ip,
                    'asn' => $result_array[$ip]['asn'],
                    'provider' => $result_array[$ip]['provider'],
                    'country' => $result_array[$ip]['country'],
                    'proxy' => $result_array[$ip]['proxy'],
                    'type' => $result_array[$ip]['type'],
                    'risk' => $result_array[$ip]['risk'],
                    'user_id' => Auth::user()->id
                ]);
            }

        }else{
            $request->authenticate();
            $request->session()->regenerate();
        }

        return redirect()->intended(RouteServiceProvider::HOME);

    }

    /**
     * Destroy an authenticated session.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Request $request)
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }
}
