<?php

namespace App\Domains\UserManagement\Controllers;

use App\Providers\InertiaProvider;
use App\Scopes\CommonController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends CommonController {
    public function loginForm(Request $request) {
        $errors = [];

        if ($request->session()->has('errors')) {
            $errors = $request->session()->get('errors')->getBag('default')->getMessages();
        }


        $inertiaProvider = new InertiaProvider('UserManagement/Login', ['errors' => $errors, 'appName' => app('tenant')->name]);
        return $inertiaProvider->render();
    }

    public function doLogin(Request $request)
    {

        $credentials = $request->validate([
            'username' => ['required', 'string'],
            'password' => ['required'],
        ],
        [
            'username.required' => 'Bitte gib deinen Anmeldenamen ein.',
            'username.string' => 'Der Anmeldename muss eine E-Mail-Adresse sein.',
            'password.required' => 'Bitte gib dein Passwort ein.',
        ]);

        $user = $this->users->findByUsername($request->get('username'));
        if ($user !== null && $user->password === null) {
            return redirect()->intended('/register/verifyEmail');
        }


        #$credentials =  ['username' => 'development', 'password' => 'development'];

        if (!Auth::attempt($credentials)) {
            return back()->withErrors([
                'username' => 'Diese Zugangsdaten sind ungültig.',
            ]);
        }

        $request->session()->regenerate();
        $user = Auth::user();


#        dd($user->firstname . ' ' . $user->lastname);

        return redirect()->intended('/');
    }
}
