<?php

namespace App\Http\Controllers\Auth;

use App\Helpers\Alert;
use App\Http\Requests\Auth\LoginRequest;
use App\Models\User;
use App\Http\Controllers\Controller;
use App\Notifications\VerifyUser;
use App\Services\Hashid;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class LoginController extends Controller
{
    protected $redirectTo = '/';

    public function __construct()
    {
        $this->middleware("guest")->except('logout');
    }

    public function showLogin()
    {
        return view("auth.login");
    }

    public function login(LoginRequest $request, Hashid $hashid)
    {
        $user = User::whereUsername($request->username)->first();

        if (is_null($user)) {
            Alert::flash("Please check your credentials", "error");
            return redirect()->route("auth.login");
        }

        if (!$user->is_active) {
            Alert::flash("Your account is blocked or its not confirmed yet. Please contact with your system administrator or check your email.", "error");
            return redirect()->route("auth.login");
        }

        if (!Hash::check($request->password, $user->password)) {
            Alert::flash("Your password is incorrect", "error");
            return redirect()->route("auth.login");
        }

        $user->security_code = rand(10000, 99999);
        if ($user->is_forgot_password) {
            $user->is_forgot_password = false;
        }

            //$user->security_code = 1234;
            $user->verify_token = Str::uuid();
            $user->is_online = true;
            $user->save();

            $user->notify(new VerifyUser($user));

            return redirect()->route("verify-login.index", [
                "id" => $hashid->encode($user->id),
                "token" => $user->verify_token
            ]);
    }

    public function logout()
    {

        $user = auth()->user();
        $user->is_online = false;
        $user->save();

        auth()->logout();

        return redirect("/auth/login");
    }
}
