<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Interfaces\LocationRepositoryInterface;
use App\Models\location;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;

class RegisteredUserController extends Controller
{
    protected $locationrepository;

    public function __construct(LocationRepositoryInterface $locationrepository)
    {
        $this->locationrepository = $locationrepository;
    }
    /**
     * Display the registration view.
     */
    public function create(): View
    {
        $location = $this->locationrepository->forAll();
        $role = DB::table('roles')->where('role', '!=', 'Admin')->get();
        return view('auth.register', compact('location', 'role'));
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
         $validated = request()->validate([
            "name" => "required",
            "email" => "required|email|unique:users,email", 
            "username" => "required|unique:users,username",
            "password" => "required|min:8",
            "role_id" => "required",
            "location_id" => "required",
        ]);

        $user = User::create([
            'name' => $request->name,
            'username' => $request->username,
            'email' => $request->email,
            'location_id' => $request->location_id,
            'role_id' => $request->role_id,
            'password' => Hash::make($request->password),
        ]);

        event(new Registered($user));

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