<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class RegisterRequest 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
    {
        return [
            'name' => 'required_without:first_name|string|max:255',
            'first_name' => 'required_without:name|string|max:255',
            'last_name' => 'nullable|string|max:255',
            'email' => 'nullable|email|unique:users,email|required_without:phone',
            'phone' => 'nullable|string|unique:users,phone|required_without:email',
            'password' => 'required|string|min:8|confirmed',
            'gender' => 'nullable|string|in:male,female,other',
            'birth_date' => 'nullable|date|before:today',
            'city' => 'nullable|string|max:255',
            'interests' => 'nullable|array',
            'interests.*' => 'integer|exists:categories,id',
            'settings' => 'nullable|array',
        ];
    }

    public function messages(): array
    {
        return [
            'email.required_without' => 'Either email or phone is required.',
            'phone.required_without' => 'Either email or phone is required.',
            'password.confirmed' => 'The password confirmation does not match.',
        ];
    }
}
