<?php

namespace App\Http\Controllers\Auth;

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

class RegisterController extends Controller
{
    public function register(Request $request)
    {
        // Validasi data
        $validated = $request->validate([
            'nama_lengkap' => 'required|string|max:255',
            'nim'          => 'required|string|max:50|unique:users,nim',
            'semester'     => 'required|numeric|min:1',
            'angkatan'     => 'required|numeric|min:2000|max:' . date('Y'),
            'email'        => [
                'required',
                'email',
                'max:255',
                'unique:users,email',
                // Validasi regex domain email
                'regex:/^[a-zA-Z0-9._%+-]+@(polije\.ac\.id|student\.polije\.ac\.id)$/'
            ],
            'password'     => 'required|string|min:8|confirmed',
        ], [
            'email.regex' => 'Email harus menggunakan domain @polije.ac.id atau @student.polije.ac.id.',
        ]);

        // Simpan ke database
        $user = User::create([
            'nama_lengkap' => $validated['nama_lengkap'],
            'nim' => $validated['nim'],
            'semester' => $validated['semester'],
            'angkatan' => $validated['angkatan'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
            'kelas_user' => 3,
            'foto' => 'images/defaultProfile.jpg',
        ]);
        DB::table('hasil')->insert([
            'id_user' => $user->id,
            'created_at' => now(),
        ]);
        // Redirect ke halaman yang diinginkan
        return redirect()->route('login')->with('success', 'Pendaftaran berhasil!');
    }
    public function showRegistrationForm()
    {
        return view('auth.register'); // pastikan nama view sesuai
    }
}
