<?php

namespace App\Http\Requests\Admin\HR;

use App\Enums\EmploymentStatus;
use App\Enums\Gender;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class EmployeeRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('employees.create')
            || $this->user()->can('employees.update');
    }

    public function rules(): array
    {
        $userId = $this->route('user')?->id;
        $isOwner = $this->input('role') === 'owner';

        return [
            'email' => [
                'required',
                'email',
                'max:100',
                Rule::unique('users', 'email')->ignore($userId, 'id'),
            ],
            'username' => [
                'required',
                'string',
                'max:20',
                'alpha_dash',
                Rule::unique('users', 'username')->ignore($userId, 'id'),
            ],
            'role' => ['required', 'string', Rule::exists('roles', 'name')],
            'full_name' => ['required', 'string', 'max:200'],
            'phone_number' => ['nullable', 'string', 'max:20'],
            'gender' => ['nullable', Rule::in(Gender::values())],
            'birth_date' => ['nullable', 'date'],
            'address' => ['nullable', 'string'],
            'join_date' => [
                'date',
                Rule::requiredIf(! $isOwner),
            ],
            'resign_date' => [
                'nullable',
                'date',
                'after_or_equal:join_date',
            ],
            'employment_status' => [
                Rule::requiredIf(! $isOwner),
                Rule::in(EmploymentStatus::values()),
            ],
            'base_salary' => [
                Rule::requiredIf(! $isOwner),
                'integer',
                'min:0',
            ],
        ];
    }

    public function attributes(): array
    {
        return [
            'email' => 'Email',
            'username' => 'Username',
            'role' => 'Role',
            'full_name' => 'Nama Lengkap',
            'phone_number' => 'No. Telepon',
            'gender' => 'Jenis Kelamin',
            'birth_date' => 'Tanggal Lahir',
            'address' => 'Alamat',
            'join_date' => 'Tanggal Masuk',
            'resign_date' => 'Tanggal Keluar',
            'employment_status' => 'Status Kepegawaian',
            'base_salary' => 'Gaji Pokok',
        ];
    }
}
