<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\User;

class RegistrasiController extends Controller
{
    public function index()
    {
        return view('website.auth.registrasi');
    }

    public function registrasi(Request $request)
    {
        // Validasi data input
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|unique:users,email',
            'name' => 'required|string|max:255',
            'username' => 'required|string|max:100|unique:users,username',
            'password' => 'required|min:6',
            'role' => 'required|in:user,admin',
        ]);

        // Jika validasi gagal
        if ($validator->fails()) {
            if ($validator->errors()->has('email')) {
                toast('Email sudah digunakan, silakan gunakan email lain!', 'error');
            } else if ($validator->errors()->has('username')) {
                toast('Username sudah digunakan, silakan gunakan username lain!', 'error');
            } else {
                toast('Gagal, silahkan cek kembali!', 'error');
            }
            return redirect()->back();
        }

        // Simpan pengguna ke database
        User::create([
            'name' => $request->name,
            'username' => $request->username,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'jenis_kelamin' => $request->jenis_kelamin,
            'status' => 'tidak aktif',
            'role' => $request->role,
        ]);

        toast('Anda berhasil melakukan registrasi!', 'success');
        return redirect()->route('login.index');
    }
}
