<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UpdateUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    protected function prepareForValidation(): void
    {
        // Merge first_name and last_name into name if name is not provided
        if (! $this->has('name') && ($this->has('first_name') || $this->has('last_name'))) {
            $firstName = $this->input('first_name', '');
            $lastName = $this->input('last_name', '');
            $name = trim($firstName.' '.$lastName);
            $this->merge([
                'name' => $name,
            ]);
        }
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $userId = $this->user()->id;

        return [
            'name' => 'required_without:first_name|string|max:255',
            'first_name' => 'required_without:name|string|max:255',
            'last_name' => 'nullable|string|max:255',
            'email' => 'sometimes|email|unique:users,email,'.$userId,
            'phone' => 'sometimes|string|unique:users,phone,'.$userId,
        ];
    }
}
