<?php

namespace App\Http\Controllers;

use App\Models\User;
use Exception;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{

    function __construct()
    {
        // $this->middleware("auth");
    }
    public function index()
    {
        $checkIsLogged = Auth::check();
        if ($checkIsLogged) {
            return redirect("admin/dashboard");
        }
        return view('auth');
    }

    public function signin(Request $request)
    {
        $valid = Auth::attempt(['username' => $request->username, 'password' => $request->password]);
        if ($valid) {
            return redirect('admin/dashboard');
        }
        return redirect()->back();
    }
    public function register(Request $request)
    {
        // try {
            $request->validate([
                'password_confirmation' => 'required|same:password|min:6'
            ]);
        // } catch (ValidationException $e) {
        //     return $e->errors();
        // }

        $user = User::create([
            'nama_lengkap' => $request->fullname,
            'username' => $request->username,
            'password' => Hash::make($request->password),
        ]);

        // event(new Registered($user));

        // Auth::login($user);

        return redirect('admin/dashboard');
    }
}
