<?php

namespace App\Http\Controllers\Auth;

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

class RegisterController extends Controller
{
    /**
     * Show the registration form.
     */
    public function showForm()
    {
        return view('auth.register');
    }

    /**
     * Handle the registration of a new user.
     */
    public function register(Request $request)
{
    // Validate the input data
    $validator = Validator::make($request->all(), [
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email',
        'no_telp' => 'required|string|max:20', // Example: Indonesian phone numbers starting with 08
        'password' => 'required|min:6|confirmed', // Ensure password confirmation is required
    ]);

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

    // Find the 'user' role ID (assuming the role name is 'user')
    $role = Role::where('name', 'user')->first(); // Adjust if your roles table is structured differently
    $roleId = $role ? $role->id : 2; // Default to 2 (user role) if not found

    // Create the new user (without hashing the password)
    $user = User::create([
        'name' => $request->name,
        'email' => $request->email,
        'no_telp' => $request->no_telp,
        'password' => $request->password, // Store the password as plain text
        'role_id' => $roleId, // Assign the user role by default
    ]);

    // Redirect to the login page after successful registration
    return redirect()->route('login')->with('success', 'Account created successfully. Please login.');
}


}
