<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    public function create() {
        
        return view('user.create');
    }
    
    public function store(Request $request) {
        
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed',
        ]);
        
        //dd($request->all());
        session()->flash('success', 'Successful registration');
        
        
        $user = User::create([
            'name' => $request->name, // || 'name' => $request->input('name'),
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
        
        session()->flash('success', 'Successful registration');
        Auth::login($user);
        return redirect()->route('home'); // || redirect()->home(); || redirect('/');
    }
    
    public function loginForm() {
        return view('user.login');
    }
    
    public function login(Request $request) {
        
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);
        
        //dd($request->all());
        
        if (Auth::attempt([
            'email' => $request->email,
            'password' => $request->password,
        ])) {
            return redirect()->route('home');
        }
        return redirect()->back()->with('error', 'Incorrect login or password');
    }
    
    public function logout(Request $request) {
        Auth::logout();
        return redirect()->route('login.create');
    }
    
    public function settings() {
        
        if (Auth::check()) {
            return view('user.settings');
        } else {
            $message = 'Пользователь не авторизован!';
            return view('errors.error', compact('message'));
        }
        
        
        
        
    }
    
    
    
}
