<?php

namespace App\Http\Controllers\Auth;

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

class RegisterController extends Controller
{
    // Menampilkan form pendaftaran
    public function showRegistrationForm()
    {
        return view('auth.register');  // Pastikan view register ada
    }

    // Proses registrasi pengguna baru
    public function register(Request $request)
    {
        // Validasi input pendaftaran
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'no_hp' => 'required|string|max:15',
            'instansi' => 'required|string|max:255',
            'status' => 'required|string|max:50',
            'no_ktp' => 'required|string|max:20',
            'alasan' => 'required|string|max:255',
        ]);

        if ($validator->fails()) {
            return redirect()->route('register')
                             ->withErrors($validator)
                             ->withInput();
        }

        // Simpan data pengguna baru
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => 'user', 
            'no_hp' => $request->no_hp,
            'instansi' => $request->instansi,
            'status' => $request->status,
            'no_ktp' => $request->no_ktp,
            'alasan' => $request->alasan,
        ]);

        // Login otomatis setelah pendaftaran
        auth()->login($user);

        // Redirect ke dashboard pengguna
        return redirect()->route('user.dashboard');
    }
}
