<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\MasterInduk;
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\Validation\ValidationException;
use Illuminate\View\View;

class RegisteredUserController extends Controller
{
    public function create(Request $request): View
    {
        $role = $request->query('role', 'siswa');
        return view('auth.register', ['role' => $role]);
    }

    public function store(Request $request): RedirectResponse
    {
        $role = $request->input('role');


        $rules = [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'role' => ['required', 'in:siswa,guru'],
            '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);


        $nomorInduk = ($role === 'siswa') ? $request->nisn : $request->nip;

        $isWhitelisted = MasterInduk::where('nomor_induk', $nomorInduk)
            ->where('role', $role)
            ->exists();

        if (!$isWhitelisted) {
            throw ValidationException::withMessages([
                ($role === 'siswa' ? 'nisn' : 'nip') => ['Nomor induk tidak terdaftar di Data Sekolah. Hubungi petugas.'],
            ]);
        }


        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => $role,
            'nisn' => ($role === 'siswa') ? $nomorInduk : null,
            'nip' => ($role === 'guru') ? $nomorInduk : null,
        ]);

        event(new Registered($user));

        Auth::login($user);

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