<?php

namespace App\Http\Controllers;

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

class RegisterController extends Controller
{
    //
    public function register(){
        return view('register');
    }
    public function registerPost(Request $request)
    {
        // Validasi input
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'no_telp' => 'required|string|max:20',
            'password' => 'required|min:4',
        ]);

        // Cari role 'user' dari tabel roles
        $userRole = Role::where('name', 'user')->first();

        if (!$userRole) {
            return redirect()->back()->with('error', 'Role user belum dibuat di database.');
        }

        // Buat user (password tidak di-hash)
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'no_telp' => $request->no_telp,
            'password' => $request->password, // TANPA Hash::make()
            'role_id' => $userRole->id,
        ]);

        // // Login otomatis
        // Auth::login($user);

        return redirect()->route('login')->with('success', 'Registrasi berhasil!');
    }
}
