<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\RegistrationRequest;
use Illuminate\Http\RedirectResponse;

class UserController extends Controller
{

    public function reg(RegistrationRequest $request)
    {
        $user = User::create([
            'fullname' => $request->fullname,
            'name' => $request->name,
            'patronymic' => $request->patronymic,
            'numberphone' => $request->numberphone,
            'email' => $request->email,
            'password' => $request->password,
            'role' => $request->role,
        ]);

        if ($user) {
            Auth::login($user);
            return redirect(route('homepage'));
        } else {
            return redirect((route('login')))->withErrors([
                'formError' => 'Произошла ошибка при регистрации пользователя'
            ]);
        }
    }

    public function log(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', ''],
        ]);

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

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


        return back()->withErrors([
            'email' => 'Пользователя с данной почтой не существует.',
            'password' => 'Неверный пароль.',
        ])->onlyInput('email', 'password');
    }

    public function out(Request $request): RedirectResponse
    {
        $request->session()->invalidate();

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

        return redirect('/');
    }
}
