<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UpdateClienteRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('update', $this->route('cliente'));
    }

    protected function prepareForValidation(): void
    {
        $merge = [];
        if ($this->exists('email')) {
            $merge['email'] = $this->filled('email') ? trim((string) $this->input('email')) : null;
        }
        if ($this->exists('telefono')) {
            $merge['telefono'] = $this->filled('telefono') ? trim((string) $this->input('telefono')) : null;
        }
        if ($this->exists('direccion')) {
            $merge['direccion'] = $this->filled('direccion') ? trim((string) $this->input('direccion')) : null;
        }
        $this->merge($merge);
    }

    public function rules(): array
    {
        return [
            'nombre' => ['sometimes', 'required', 'string', 'max:255'],
            'email' => ['nullable', 'string', 'email:rfc', 'max:255'],
            'telefono' => ['nullable', 'string', 'max:50', 'regex:/^[\d\+\-\s\(\)\.]{7,50}$/'],
            'direccion' => ['nullable', 'string'],
            'puntos_lealtad' => ['nullable', 'integer', 'min:0'],
            'cliente_categoria_id' => ['nullable', 'integer', 'exists:cliente_categorias,id'],
        ];
    }
}
