<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\User;
use Hash;
use App\Notifications\AuthenticateUser;
use Exception;
use Illuminate\Support\Facades\Notification;

class AdminLoginController extends Controller
{
    public function authenticate(Request $request)
    {
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $email    = $request->email;
        $password = $request->password;

        $user     = User::where('email', $email)->first();

        if ($user == null) {
            return redirect(route('admin-login'))
                ->withInput($request->only('email', 'remember'))
                ->withErrors([
                    'password' => 'Invalid Credentials',
                ]);
        }

        if ((Hash::check($password, $user->password)) && (!empty($user)) && ($user->status == 1) && (in_array($user->userType->name, ['Super Admin', 'Super User', 'Administrator']))) {
            if (config('app.env') === 'local') {
                Auth::login($user);
                return redirect('/assets');
            }

            $user->update(['email_token' => bin2hex(openssl_random_pseudo_bytes(4))]);

            try {
                Notification::send($user, new AuthenticateUser($user));
                return view('auth.login-verify', compact('email'));
            } catch (Exception $e) {
                return redirect(route('admin-login'))->withErrors([
                    'password' => 'Email sending failed. Please try again later',
                ]);
            }
        }

        return redirect(route('admin-login'))
            ->withInput($request->only('email', 'remember'))
            ->withErrors([
                'password' => 'Invalid credentials or Inactive user',
            ]);
    }
}
