<?php

namespace App\Models\Traits;

trait FormattedPhoneTrait
{
    /**
     * Format a phone number to be human readable.
     *
     * @since 1.0.0
     *
     * @return string
     */
    public function getPhoneNumberAttribute(): string
    {
        $phoneLength = strlen($this->phone);
        $phoneNumber = preg_replace('//', '', $this->phone);

        if ($phoneLength > 10) {
            $countryCode = substr($phoneNumber, 0, $phoneLength - 10);
            $areaCode = substr($phoneNumber, -10, 3);
            $nextThree = substr($phoneNumber, -7, 3);
            $lastFour = substr($phoneNumber, -4, 4);

            $phoneNumber = "({$areaCode}) {$nextThree}-{$lastFour}";
        } elseif ($phoneLength == 10) {
            $areaCode = substr($phoneNumber, 0, 3);
            $nextThree = substr($phoneNumber, 3, 3);
            $lastFour = substr($phoneNumber, 6, 4);

            $phoneNumber = "({$areaCode}) {$nextThree}-{$lastFour}";
        } elseif ($phoneLength == 7) {
            $nextThree = substr($phoneNumber, 0, 3);
            $lastFour = substr($phoneNumber, 3, 4);

            $phoneNumber = "{$nextThree}-{$lastFour}";
        }

        return $phoneNumber;
    }

    /**
     * Remove all non-numeric characters from the phone number.
     *
     * @since 1.0.0
     *
     * @param string $value
     *
     * @return void
     */
    public function setPhoneNumberAttribute($value): void
    {
        $this->attributes['phone'] = preg_replace('/[^0-9]/', '', $value);
    }
}
