<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Models\User;

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

    public function rules()
    {
        $userId = $this->route('user'); // Get user ID from route parameter
        $rules = [
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255|unique:users,email,'.$userId,
            'alamat' => 'required|string|max:255',
            'telepon' => 'required|string|max:20',
            'keterangan' => 'required|string|max:255',
            'role' => 'required|in:admin,mahasiswa,karyawan'
        ];

        if ($this->role === 'mahasiswa') {
            $user = User::with('mahasiswa')->find($userId);
            $mahasiswaId = $user->mahasiswa ? $user->mahasiswa->user_id : 'NULL';
            
            $rules += [
                'nim' => 'required|string|max:20|unique:mahasiswas,nim,'.$mahasiswaId.',user_id',
                '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',
            'in' => ':attribute tidak valid',
            'no_hp.regex' => 'Nomor HP hanya boleh berisi angka',
            
            // Specific field messages
            'nim.required' => 'NIM wajib diisi',
            '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',
            'alamat' => 'Alamat',
            'telepon' => 'Nomor telepon',
            'keterangan' => 'Keterangan',
        ];
    }
}