<?php

namespace App\Http\Controllers;

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

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',
        ]);
        
        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() {
        return view('user.settings');
    }
    
    public function loginGoogle() {
        $googleUser = Socialite::driver('google')->user();

        $user = User::where('email','=', $googleUser->email)->first();
        if (!$user) {
            $user = User::create([
                'name' => $googleUser->name,
                'email' => $googleUser->email,
                'password' => Hash::make(config('project.empty_password')),
            ]);
        }

        Auth::login($user);
        return redirect()->route('home');
    }
    
    
    
}
