<?php

namespace App\Domains\Auth\Services;

use App\Domains\Auth\Models\User;
use Illuminate\Support\Facades\Hash;

class ProfileService
{
    /**
     * Update the given user's profile information.
     *
     * @param User $user
     * @param array $data
     * @return User
     */
    public function update(User $user, array $data): User
    {
        // Handle password hashing if a new password is provided
        if (!empty($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        } else {
            // Remove password from array if empty so we don't overwrite it with null
            unset($data['password']);
        }

        // Standardize phone number (strip all but numbers and leading '+')
        if (!empty($data['telefono'])) {
            $data['telefono'] = preg_replace('/[^\+0-9]/', '', $data['telefono']);
        }

        // DNI is already validated as numbers only, but we can do a quick strip just in case
        if (!empty($data['dni'])) {
            $data['dni'] = preg_replace('/[^0-9]/', '', $data['dni']);
        }

        $user->update($data);

        return $user;
    }
}
