<?php

namespace App\Http\Requests;

use App\Models\User;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class ProfileUpdateRequest extends FormRequest
{
    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation()
    {
        if ($this->filled('whatsapp')) {
            $whatsapp = preg_replace('/[^0-9]/', '', $this->whatsapp);
            if (str_starts_with($whatsapp, '0')) {
                $whatsapp = '62' . substr($whatsapp, 1);
            }
            $this->merge([
                'whatsapp' => $whatsapp,
            ]);
        }
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => [
                'required',
                'string',
                'lowercase',
                'email',
                'max:255',
                Rule::unique(User::class)->ignore($this->user()->id),
            ],
            'whatsapp' => [
                'nullable',
                'string',
                'min:8',
                'max:15',
                Rule::unique(User::class)->ignore($this->user()->id),
            ],
        ];
    }
}
