<?php
namespace App\Utils;

/**
 * Phone Number Normalizer
 */
class PhoneNormalizer
{
    /**
     * Normalize phone number to standard format (11 digits with leading 0 for Iranian mobiles)
     * @param string $phone Phone number in any format
     * @return string Normalized phone number
     */
    public static function normalize($phone)
    {
        // Remove all non-digits
        $cleaned = preg_replace('/\D/', '', $phone);
        
        // If empty, return as is
        if (empty($cleaned)) {
            return $cleaned;
        }
        
        // If 10 digits and starts with 9, add 0 at the beginning (Iranian mobile)
        if (strlen($cleaned) === 10 && substr($cleaned, 0, 1) === '9') {
            return '0' . $cleaned;
        }
        
        // If 11 digits and starts with 0, return as is
        if (strlen($cleaned) === 11 && substr($cleaned, 0, 1) === '0') {
            return $cleaned;
        }
        
        // Otherwise return as is
        return $cleaned;
    }

    /**
     * Return possible normalized variants for a phone number.
     * We keep both 10-digit (without leading zero) and 11-digit (with leading zero) forms.
     * This helps matching data that may have been stored in either format.
     */
    public static function normalizeCandidates(string $phone): array
    {
        $digits = preg_replace('/\D/', '', $phone);
        if ($digits === '') {
            return [];
        }

        $candidates = [];
        $len = strlen($digits);

        if ($len === 11 && substr($digits, 0, 1) === '0') {
            // Leading-zero form; also store without leading zero
            $candidates[] = $digits;
            $candidates[] = substr($digits, 1);
        } elseif ($len === 10) {
            // Already trimmed form; if starts with 9 also add leading-zero variant
            $candidates[] = $digits;
            if (substr($digits, 0, 1) === '9') {
                $candidates[] = '0' . $digits;
            }
        } else {
            // Fallback: keep the cleaned digits as-is
            $candidates[] = $digits;
        }

        // Return unique, non-empty
        return array_values(array_unique(array_filter($candidates, fn($p) => $p !== '')));
    }
}

