<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Roleuser;
use Illuminate\Support\Facades\Crypt;

class RegisterController extends Controller
{
    public function index()
    {
        // Menampilkan form registrasi dengan pilihan role (jika diperlukan)
        $roleuser = Roleuser::all();
        return view('register', compact('roleuser'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'nama' => 'required',
            'username' => 'required|unique:users,username',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:6',
            'image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
        ]);

        $data = [
            'name' => $request->nama,
            'username' => $request->username,
            'email' => $request->email,
            'password' => Crypt::encryptString($request->password),
            'id_roleuser' => 2 // default: mahasiswa (pastikan ID role mahasiswa = 2)
        ];

        if ($request->hasFile('image')) {
            $foto = $request->file('image');
            $namaFoto = time() . '.' . $foto->getClientOriginalExtension();
            $foto->move(public_path('upload/user'), $namaFoto);
            $data['image'] = 'upload/user/' . $namaFoto;
        }

        User::create($data);

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