<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreUserRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        $rules = [
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ];
    
        if ($this->isMahasiswa()) {
            $rules = array_merge($rules, [
                'nim' => 'required|string|max:20|unique:mahasiswas,nim',
                'program_studi' => 'required|string|max:100',
                'jurusan' => 'required|string|max:100',
                'no_hp' => 'required|string|max:15|regex:/^[0-9]+$/',
            ]);
        }
    
        return $rules;
    }
    
    public function messages()
    {
        return [
            'required' => ':attribute wajib diisi',
            'email' => 'Format email tidak valid',
            'unique' => ':attribute sudah terdaftar',
            'min' => ':attribute minimal :min karakter',
            'confirmed' => 'Konfirmasi password tidak cocok',
            'no_hp.regex' => 'Nomor HP hanya boleh berisi angka',
            
            // Specific field messages
            'nim.required' => 'NIM wajib diisi',
            'nim.unique' => 'NIM sudah terdaftar',
            'program_studi.required' => 'Program studi wajib diisi',
            'jurusan.required' => 'Jurusan wajib diisi',
            'no_hp.required' => 'Nomor HP wajib diisi',
        ];
    }

    public function attributes()
    {
        return [
            'name' => 'Nama lengkap',
            'email' => 'Alamat email',
            'password' => 'Password',
        ];
    }

    protected function isMahasiswa()
    {
        return $this->input('force_mahasiswa') || $this->input('role') === 'mahasiswa';
    }
}