<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Siswa;
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
{
    /**
     * Display the registration view.
     */
    public function create(): View
    {
        return view('auth.register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'username' => ['required', 'string', 'lowercase', 'max:255', 'unique:' . User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'nis' => ['required', 'string', 'max:50'],
            'tempat_lahir' => ['required', 'string', 'max:50'],
            'tanggal' => ['required', 'date'],
            'jenis_kelamin' => ['required'],
            'agama' => ['required', 'string', 'max:10'],
            'alamat' => ['required', 'string', 'max:255'],
            'kelas' => ['required', 'string', 'max:25'],
            'tahun_pelajaran' => ['required', 'string', 'max:4'],
        ]);

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

        $user->assignRole('Siswa');

        Siswa::create([
            'id_user' => $user->id,
            'nama_siswa' => $request->name,
            'nis' => $request->nis,
            'tempat_lahir' => $request->tempat_lahir,
            'tanggal' => $request->tanggal,
            'jenis_kelamin' => $request->jenis_kelamin,
            'agama' => $request->agama,
            'alamat' => $request->alamat,
            'kelas' => $request->kelas,
            'tahun_pelajaran' => $request->tahun_pelajaran,
        ]);

        event(new Registered($user));

        Auth::login($user);

        return redirect(route('dashboard', absolute: false));
    }
}
