<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Mail\ServletMail;
use App\Models\LoginHistory;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(Request $req): View
    {
        if ($req->has('redirect')) {
            session(['login_redirect' => $req->get('redirect')]);
        }
        
        return view('auth.login');
    }

    /**
     * Handle an incoming authentication request.
    */
     
    public function store(LoginRequest $request): RedirectResponse
    {
        
        $request->authenticate();

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

        if(auth()->user()->suspend == 0){
            $this->destroySession($request);
            return redirect('/login.py')->with('error_message' , 'Your Account has been suspended please contact support');
        }
        if (auth()->check()) {
            auth()->user()->forceFill([
                'ip_address' => request()->ip(),
                'support_pin' => random_int(11111, 99999),
            ])->save();
        }

        $this->logLogin($request);
        if(auth()->user()->googlef2_status == 1){
            session()->put('GoogleOtp' , 0);
        }else{
            $generator =  substr(md5(uniqid(rand(), true)) , 0 , 6);
            session()->put('otp' , $generator);
            Mail::send(new ServletMail($request->ip()));
            session()->put('servlet' , 0);
        }

        return redirect()->intended(route('home', absolute: false));
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
       
        $this->destroySession($request);
        return redirect('/');
    }



    protected function destroySession($request){
        Auth::guard('web')->logout();

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

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

    protected function logLogin($request){
        LoginHistory::create([
            'user_id' => auth()->user()->id,
            'date' => Carbon::now(),
            'ip_address' => $request->ip(),
            'host_name' => $request->getHost(),
            'result' => 'Success'
        ]);
    }
}
