<?php

namespace App\Http\Requests\Admin\HR;

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

class EmployeeRequest extends FormRequest
{
    use CurrencyStripping;

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

    public function prepareForValidation(): void
    {
        $this->merge($this->stripCurrencyDot($this->all(), 'base_salary'));
    }

    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',
        ];
    }
}
