<?php

namespace Mnv\Core\Validations;

use Mnv\Core\Validations\Exceptions\InvalidPhoneException;

/**
 * Class ValidatePhone
 * @package Mnv\Core\Validations
 */
final class ValidatePhone
{
    private string $phone;

    private string $replacement = '+$1 ($2) $3-$4-$5';

    /**
     * @throws InvalidPhoneException
     */
    private function __construct(string $phone)
    {
        $this->ensureIsValidPhoneNumber($phone);

        $this->phone = $phone;
    }

    /**
     * @throws InvalidPhoneException
     */
    public static function fromString(string $phone): self
    {
        return new self($phone);
    }

    public function __toString(): string
    {
        return $this->phone;
    }

    /**
     * @throws InvalidPhoneException
     */
    private function ensureIsValidPhoneNumber(string $phone)
    {
        if (empty($phone)) {
            throw new InvalidPhoneException('empty phone number');
        }

        $phone =  preg_replace('/[^0-9]/', '', $phone);

        // Разрешить +, - в номере телефона
        $filtered_phone_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
        // Проверить длину номера replacement
        if (strlen($filtered_phone_number) === 12) {
            return preg_replace('/([0-9]{3})([0-9]{2})([0-9]{3})([0-9]{2})([0-9]{2})/', $this->replacement, $phone);
        } else {
            throw new InvalidPhoneException('incorrect number of characters in the phone number');
        }
    }
}