<?php

namespace App\Libraries;

/**
 * Normalizes Ghanaian phone numbers to a single consistent format
 * (+233XXXXXXXXX) at the point of guest creation/edit — not just on
 * display — so duplicate detection and, later, WhatsApp/SMS sending
 * (Phase 3) can trust the stored value without re-parsing it.
 *
 * Accepts the common ways staff will actually type a number: local
 * 0XXXXXXXXX, with or without spaces/dashes, with or without a country
 * code, with or without a leading +.
 */
class PhoneNumber
{
    /**
     * @return string|null Normalized +233XXXXXXXXX, or null if the input
     *                      doesn't look like a valid Ghanaian mobile number.
     */
    public static function normalize(?string $raw): ?string
    {
        if ($raw === null || trim($raw) === '') {
            return null;
        }

        $digits = preg_replace('/\D/', '', $raw) ?? '';

        // 0XXXXXXXXX (10 digits, local format)
        if (strlen($digits) === 10 && $digits[0] === '0') {
            $digits = '233' . substr($digits, 1);
        }

        // 233XXXXXXXXX (12 digits, country code without +)
        if (strlen($digits) === 12 && str_starts_with($digits, '233')) {
            return '+' . $digits;
        }

        return null;
    }

    public static function isValid(?string $raw): bool
    {
        return self::normalize($raw) !== null;
    }
}
