<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;

class RegisteredUserController extends Controller
{
    /**
     * Menampilkan halaman registrasi.
     */
    public function create(Request $request): View
    {
        // Bagian Pengambilan Role dari URL
        $role = $request->query('role', 'siswa'); // Ambil 'role' dari URL, default ke 'siswa'

        // Kirim $role ke view
        return view('auth.register', ['role' => $role]);
    }

    /**
     * Menangani permintaan registrasi yang masuk.
     */
    public function store(Request $request): RedirectResponse
    {
        $role = $request->input('role');

        $rules = [
            'name' => ['required', 'string', 'max:255'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'role' => ['required', 'in:siswa,guru'],
        ];

        if ($role === 'siswa') {
            $rules['nisn'] = ['required', 'string', 'max:255', 'unique:users,nomor_induk'];
        } else {
            $rules['nip'] = ['required', 'string', 'max:255', 'unique:users,nomor_induk'];
        }

        $request->validate($rules);

        $user = User::create([
            'name' => $request->name,
            'nama_lengkap' => $request->name,
            'email' => ($request->nisn ?: $request->nip) . '@smkn1perpus.sch.id',
            'password' => Hash::make($request->password),
            'role' => $request->role,
            'nomor_induk' => $request->nisn ?: $request->nip,
        ]);

        event(new Registered($user));

        Auth::login($user);

        if ($user->role === 'penjaga perpus') {
            return redirect()->route('admin.dashboard');
        } else {
            return redirect()->route('dashboard');
        }
    }
}