<?php

namespace App\Helpers;

use libphonenumber\PhoneNumberUtil;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\NumberParseException;

class Formatter
{
    /**
     * Parse and format a phone number to international WhatsApp format (E.164)
     * Supports all countries in the world with auto-detection
     * 
     * @param string $phone Phone number to format
     * @param string|null $defaultRegion ISO 3166-1 alpha-2 country code (e.g., 'US', 'NG', 'GB')
     * @return string Formatted phone number without '+' prefix
     */
    public static function pf($phone, $defaultRegion = null)
    {
        // Handle null or empty phone numbers
        if (empty($phone)) {
            return '';
        }
        
        // Clean the phone number
        $phone = trim($phone);
        
        // Auto-detect default region from app settings or use Nigeria as fallback
        if (empty($defaultRegion)) {
            $defaultRegion = config('app.default_country_code', 'NG');
        }
        
        $phoneUtil = PhoneNumberUtil::getInstance();

        try {
            // If phone starts with '+' or country code, try international format first
            if (str_starts_with($phone, '+')) {
                $numberProto = $phoneUtil->parse($phone, null);
            } else {
                // Try to detect country from phone number prefix
                $detectedRegion = self::detectCountryFromPhone($phone);
                $regionToUse = $detectedRegion ?: strtoupper($defaultRegion);
                
                // Parse with detected or default country
                $numberProto = $phoneUtil->parse($phone, $regionToUse);
            }

            // Validate the number
            if (!$phoneUtil->isValidNumber($numberProto)) {
                // Try with default region as fallback
                try {
                    $numberProto = $phoneUtil->parse($phone, strtoupper($defaultRegion));
                    if (!$phoneUtil->isValidNumber($numberProto)) {
                        return preg_replace('/\D/', '', $phone); // fallback to digits only
                    }
                } catch (NumberParseException $e) {
                    return preg_replace('/\D/', '', $phone);
                }
            }

            // Format to E.164 (e.g., +2348012345678)
            $formatted = $phoneUtil->format($numberProto, PhoneNumberFormat::E164);

            // Remove '+' for WhatsApp use
            return ltrim($formatted, '+');

        } catch (NumberParseException $e) {
            // Final fallback: just return digits
            return preg_replace('/\D/', '', $phone);
        }
    }
    
    /**
     * Detect country from phone number prefix
     * Supports major country codes worldwide
     * 
     * @param string $phone Phone number
     * @return string|null Country code or null if not detected
     */
    private static function detectCountryFromPhone($phone)
    {
        // Remove all non-digits
        $digits = preg_replace('/\D/', '', $phone);
        
        // Country code mapping (prefix => ISO code)
        $countryPrefixes = [
            // Africa
            '234' => 'NG', // Nigeria
            '27' => 'ZA',  // South Africa
            '254' => 'KE', // Kenya
            '233' => 'GH', // Ghana
            '251' => 'ET', // Ethiopia
            '255' => 'TZ', // Tanzania
            '256' => 'UG', // Uganda
            '20' => 'EG',  // Egypt
            '212' => 'MA', // Morocco
            '213' => 'DZ', // Algeria
            '216' => 'TN', // Tunisia
            '218' => 'LY', // Libya
            '220' => 'GM', // Gambia
            '221' => 'SN', // Senegal
            '222' => 'MR', // Mauritania
            '223' => 'ML', // Mali
            '224' => 'GN', // Guinea
            '225' => 'CI', // Ivory Coast
            '226' => 'BF', // Burkina Faso
            '227' => 'NE', // Niger
            '228' => 'TG', // Togo
            '229' => 'BJ', // Benin
            '230' => 'MU', // Mauritius
            '231' => 'LR', // Liberia
            '232' => 'SL', // Sierra Leone
            '235' => 'TD', // Chad
            '236' => 'CF', // Central African Republic
            '237' => 'CM', // Cameroon
            '238' => 'CV', // Cape Verde
            '239' => 'ST', // São Tomé and Príncipe
            '240' => 'GQ', // Equatorial Guinea
            '241' => 'GA', // Gabon
            '242' => 'CG', // Republic of the Congo
            '243' => 'CD', // DR Congo
            '244' => 'AO', // Angola
            '245' => 'GW', // Guinea-Bissau
            '246' => 'IO', // British Indian Ocean Territory
            '248' => 'SC', // Seychelles
            '249' => 'SD', // Sudan
            '250' => 'RW', // Rwanda
            '252' => 'SO', // Somalia
            '253' => 'DJ', // Djibouti
            '257' => 'BI', // Burundi
            '258' => 'MZ', // Mozambique
            '260' => 'ZM', // Zambia
            '261' => 'MG', // Madagascar
            '262' => 'RE', // Réunion
            '263' => 'ZW', // Zimbabwe
            '264' => 'NA', // Namibia
            '265' => 'MW', // Malawi
            '266' => 'LS', // Lesotho
            '267' => 'BW', // Botswana
            '268' => 'SZ', // Eswatini
            '269' => 'KM', // Comoros
            
            // North America
            '1' => 'US',   // USA/Canada (needs area code detection)
            
            // Europe
            '44' => 'GB',  // United Kingdom
            '33' => 'FR',  // France
            '49' => 'DE',  // Germany
            '39' => 'IT',  // Italy
            '34' => 'ES',  // Spain
            '31' => 'NL',  // Netherlands
            '32' => 'BE',  // Belgium
            '41' => 'CH',  // Switzerland
            '43' => 'AT',  // Austria
            '45' => 'DK',  // Denmark
            '46' => 'SE',  // Sweden
            '47' => 'NO',  // Norway
            '48' => 'PL',  // Poland
            '351' => 'PT', // Portugal
            '353' => 'IE', // Ireland
            '354' => 'IS', // Iceland
            '355' => 'AL', // Albania
            '356' => 'MT', // Malta
            '357' => 'CY', // Cyprus
            '358' => 'FI', // Finland
            '359' => 'BG', // Bulgaria
            '36' => 'HU',  // Hungary
            '370' => 'LT', // Lithuania
            '371' => 'LV', // Latvia
            '372' => 'EE', // Estonia
            '373' => 'MD', // Moldova
            '374' => 'AM', // Armenia
            '375' => 'BY', // Belarus
            '376' => 'AD', // Andorra
            '377' => 'MC', // Monaco
            '378' => 'SM', // San Marino
            '380' => 'UA', // Ukraine
            '381' => 'RS', // Serbia
            '382' => 'ME', // Montenegro
            '383' => 'XK', // Kosovo
            '385' => 'HR', // Croatia
            '386' => 'SI', // Slovenia
            '387' => 'BA', // Bosnia and Herzegovina
            '389' => 'MK', // North Macedonia
            '30' => 'GR',  // Greece
            '40' => 'RO',  // Romania
            '420' => 'CZ', // Czech Republic
            '421' => 'SK', // Slovakia
            '423' => 'LI', // Liechtenstein
            
            // Asia
            '86' => 'CN',   // China
            '91' => 'IN',   // India
            '81' => 'JP',   // Japan
            '82' => 'KR',   // South Korea
            '65' => 'SG',   // Singapore
            '60' => 'MY',   // Malaysia
            '62' => 'ID',   // Indonesia
            '63' => 'PH',   // Philippines
            '66' => 'TH',   // Thailand
            '84' => 'VN',   // Vietnam
            '852' => 'HK',  // Hong Kong
            '853' => 'MO',  // Macau
            '886' => 'TW',  // Taiwan
            '880' => 'BD',  // Bangladesh
            '92' => 'PK',   // Pakistan
            '93' => 'AF',   // Afghanistan
            '94' => 'LK',   // Sri Lanka
            '95' => 'MM',   // Myanmar
            '960' => 'MV',  // Maldives
            '961' => 'LB',  // Lebanon
            '962' => 'JO',  // Jordan
            '963' => 'SY',  // Syria
            '964' => 'IQ',  // Iraq
            '965' => 'KW',  // Kuwait
            '966' => 'SA',  // Saudi Arabia
            '967' => 'YE',  // Yemen
            '968' => 'OM',  // Oman
            '970' => 'PS',  // Palestine
            '971' => 'AE',  // UAE
            '972' => 'IL',  // Israel
            '973' => 'BH',  // Bahrain
            '974' => 'QA',  // Qatar
            '975' => 'BT',  // Bhutan
            '976' => 'MN',  // Mongolia
            '977' => 'NP',  // Nepal
            '98' => 'IR',   // Iran
            '992' => 'TJ',  // Tajikistan
            '993' => 'TM',  // Turkmenistan
            '994' => 'AZ',  // Azerbaijan
            '995' => 'GE',  // Georgia
            '996' => 'KG',  // Kyrgyzstan
            '998' => 'UZ',  // Uzbekistan
            '850' => 'KP',  // North Korea
            '855' => 'KH',  // Cambodia
            '856' => 'LA',  // Laos
            '673' => 'BN',  // Brunei
            '670' => 'TL',  // Timor-Leste
            
            // Middle East
            '90' => 'TR',   // Turkey
            '7' => 'RU',    // Russia/Kazakhstan
            
            // Oceania
            '61' => 'AU',   // Australia
            '64' => 'NZ',   // New Zealand
            '675' => 'PG',  // Papua New Guinea
            '676' => 'TO',  // Tonga
            '677' => 'SB',  // Solomon Islands
            '678' => 'VU',  // Vanuatu
            '679' => 'FJ',  // Fiji
            '680' => 'PW',  // Palau
            '681' => 'WF',  // Wallis and Futuna
            '682' => 'CK',  // Cook Islands
            '683' => 'NU',  // Niue
            '685' => 'WS',  // Samoa
            '686' => 'KI',  // Kiribati
            '687' => 'NC',  // New Caledonia
            '688' => 'TV',  // Tuvalu
            '689' => 'PF',  // French Polynesia
            '690' => 'TK',  // Tokelau
            '691' => 'FM',  // Micronesia
            '692' => 'MH',  // Marshall Islands
            
            // South America
            '55' => 'BR',   // Brazil
            '54' => 'AR',   // Argentina
            '56' => 'CL',   // Chile
            '57' => 'CO',   // Colombia
            '58' => 'VE',   // Venezuela
            '51' => 'PE',   // Peru
            '52' => 'MX',   // Mexico
            '53' => 'CU',   // Cuba
            '591' => 'BO',  // Bolivia
            '592' => 'GY',  // Guyana
            '593' => 'EC',  // Ecuador
            '594' => 'GF',  // French Guiana
            '595' => 'PY',  // Paraguay
            '596' => 'MQ',  // Martinique
            '597' => 'SR',  // Suriname
            '598' => 'UY',  // Uruguay
            '599' => 'CW',  // Curaçao
            
            // Central America & Caribbean
            '501' => 'BZ',  // Belize
            '502' => 'GT',  // Guatemala
            '503' => 'SV',  // El Salvador
            '504' => 'HN',  // Honduras
            '505' => 'NI',  // Nicaragua
            '506' => 'CR',  // Costa Rica
            '507' => 'PA',  // Panama
            '509' => 'HT',  // Haiti
            '590' => 'GP',  // Guadeloupe
            '1242' => 'BS', // Bahamas
            '1246' => 'BB', // Barbados
            '1264' => 'AI', // Anguilla
            '1268' => 'AG', // Antigua and Barbuda
            '1284' => 'VG', // British Virgin Islands
            '1340' => 'VI', // US Virgin Islands
            '1345' => 'KY', // Cayman Islands
            '1441' => 'BM', // Bermuda
            '1473' => 'GD', // Grenada
            '1649' => 'TC', // Turks and Caicos
            '1664' => 'MS', // Montserrat
            '1670' => 'MP', // Northern Mariana Islands
            '1671' => 'GU', // Guam
            '1684' => 'AS', // American Samoa
            '1721' => 'SX', // Sint Maarten
            '1758' => 'LC', // Saint Lucia
            '1767' => 'DM', // Dominica
            '1784' => 'VC', // Saint Vincent and the Grenadines
            '1787' => 'PR', // Puerto Rico
            '1809' => 'DO', // Dominican Republic
            '1868' => 'TT', // Trinidad and Tobago
            '1869' => 'KN', // Saint Kitts and Nevis
            '1876' => 'JM', // Jamaica
        ];
        
        // Check prefixes from longest to shortest (to match 4-digit codes before 3-digit)
        $sortedPrefixes = array_keys($countryPrefixes);
        usort($sortedPrefixes, function($a, $b) {
            return strlen($b) - strlen($a);
        });
        
        foreach ($sortedPrefixes as $prefix) {
            if (str_starts_with($digits, $prefix)) {
                return $countryPrefixes[$prefix];
            }
        }
        
        return null;
    }

    /**
     * WhatsApp single user format
     */
    public static function s_wa($phone, $defaultRegion = null)
    {
        return self::pf($phone, $defaultRegion) . '@s.whatsapp.net';
    }

    /**
     * WhatsApp group format
     */
    public static function g_us($phone, $defaultRegion = null)
    {
        return self::pf($phone, $defaultRegion) . '@g.us';
    }

    /**
     * WhatsApp contact format
     */
    public static function c_us($phone, $defaultRegion = null)
    {
        return self::pf($phone, $defaultRegion) . '@c.us';
    }
    
    /**
     * Get supported countries with their codes
     * 
     * @return array Associative array of country codes and names
     */
    public static function getSupportedCountries()
    {
        return [
            // Africa
            'DZ' => 'Algeria', 'AO' => 'Angola', 'BJ' => 'Benin', 'BW' => 'Botswana',
            'BF' => 'Burkina Faso', 'BI' => 'Burundi', 'CM' => 'Cameroon', 'CV' => 'Cape Verde',
            'CF' => 'Central African Republic', 'TD' => 'Chad', 'KM' => 'Comoros', 'CG' => 'Congo',
            'CD' => 'DR Congo', 'CI' => 'Ivory Coast', 'DJ' => 'Djibouti', 'EG' => 'Egypt',
            'GQ' => 'Equatorial Guinea', 'ER' => 'Eritrea', 'ET' => 'Ethiopia', 'GA' => 'Gabon',
            'GM' => 'Gambia', 'GH' => 'Ghana', 'GN' => 'Guinea', 'GW' => 'Guinea-Bissau',
            'KE' => 'Kenya', 'LS' => 'Lesotho', 'LR' => 'Liberia', 'LY' => 'Libya',
            'MG' => 'Madagascar', 'MW' => 'Malawi', 'ML' => 'Mali', 'MR' => 'Mauritania',
            'MU' => 'Mauritius', 'MA' => 'Morocco', 'MZ' => 'Mozambique', 'NA' => 'Namibia',
            'NE' => 'Niger', 'NG' => 'Nigeria', 'RW' => 'Rwanda', 'ST' => 'São Tomé and Príncipe',
            'SN' => 'Senegal', 'SC' => 'Seychelles', 'SL' => 'Sierra Leone', 'SO' => 'Somalia',
            'ZA' => 'South Africa', 'SD' => 'Sudan', 'SZ' => 'Eswatini', 'TZ' => 'Tanzania',
            'TG' => 'Togo', 'TN' => 'Tunisia', 'UG' => 'Uganda', 'ZM' => 'Zambia', 'ZW' => 'Zimbabwe',
            
            // Americas
            'AR' => 'Argentina', 'BS' => 'Bahamas', 'BB' => 'Barbados', 'BZ' => 'Belize',
            'BO' => 'Bolivia', 'BR' => 'Brazil', 'CA' => 'Canada', 'CL' => 'Chile',
            'CO' => 'Colombia', 'CR' => 'Costa Rica', 'CU' => 'Cuba', 'DO' => 'Dominican Republic',
            'EC' => 'Ecuador', 'SV' => 'El Salvador', 'GD' => 'Grenada', 'GT' => 'Guatemala',
            'GY' => 'Guyana', 'HT' => 'Haiti', 'HN' => 'Honduras', 'JM' => 'Jamaica',
            'MX' => 'Mexico', 'NI' => 'Nicaragua', 'PA' => 'Panama', 'PY' => 'Paraguay',
            'PE' => 'Peru', 'KN' => 'Saint Kitts and Nevis', 'LC' => 'Saint Lucia',
            'VC' => 'Saint Vincent', 'SR' => 'Suriname', 'TT' => 'Trinidad and Tobago',
            'US' => 'United States', 'UY' => 'Uruguay', 'VE' => 'Venezuela',
            
            // Asia
            'AF' => 'Afghanistan', 'AM' => 'Armenia', 'AZ' => 'Azerbaijan', 'BH' => 'Bahrain',
            'BD' => 'Bangladesh', 'BT' => 'Bhutan', 'BN' => 'Brunei', 'KH' => 'Cambodia',
            'CN' => 'China', 'GE' => 'Georgia', 'IN' => 'India', 'ID' => 'Indonesia',
            'IR' => 'Iran', 'IQ' => 'Iraq', 'IL' => 'Israel', 'JP' => 'Japan',
            'JO' => 'Jordan', 'KZ' => 'Kazakhstan', 'KW' => 'Kuwait', 'KG' => 'Kyrgyzstan',
            'LA' => 'Laos', 'LB' => 'Lebanon', 'MY' => 'Malaysia', 'MV' => 'Maldives',
            'MN' => 'Mongolia', 'MM' => 'Myanmar', 'NP' => 'Nepal', 'KP' => 'North Korea',
            'OM' => 'Oman', 'PK' => 'Pakistan', 'PS' => 'Palestine', 'PH' => 'Philippines',
            'QA' => 'Qatar', 'SA' => 'Saudi Arabia', 'SG' => 'Singapore', 'KR' => 'South Korea',
            'LK' => 'Sri Lanka', 'SY' => 'Syria', 'TW' => 'Taiwan', 'TJ' => 'Tajikistan',
            'TH' => 'Thailand', 'TL' => 'Timor-Leste', 'TR' => 'Turkey', 'TM' => 'Turkmenistan',
            'AE' => 'UAE', 'UZ' => 'Uzbekistan', 'VN' => 'Vietnam', 'YE' => 'Yemen',
            
            // Europe
            'AL' => 'Albania', 'AD' => 'Andorra', 'AT' => 'Austria', 'BY' => 'Belarus',
            'BE' => 'Belgium', 'BA' => 'Bosnia', 'BG' => 'Bulgaria', 'HR' => 'Croatia',
            'CY' => 'Cyprus', 'CZ' => 'Czech Republic', 'DK' => 'Denmark', 'EE' => 'Estonia',
            'FI' => 'Finland', 'FR' => 'France', 'DE' => 'Germany', 'GR' => 'Greece',
            'HU' => 'Hungary', 'IS' => 'Iceland', 'IE' => 'Ireland', 'IT' => 'Italy',
            'LV' => 'Latvia', 'LI' => 'Liechtenstein', 'LT' => 'Lithuania', 'LU' => 'Luxembourg',
            'MT' => 'Malta', 'MD' => 'Moldova', 'MC' => 'Monaco', 'ME' => 'Montenegro',
            'NL' => 'Netherlands', 'MK' => 'North Macedonia', 'NO' => 'Norway', 'PL' => 'Poland',
            'PT' => 'Portugal', 'RO' => 'Romania', 'RU' => 'Russia', 'SM' => 'San Marino',
            'RS' => 'Serbia', 'SK' => 'Slovakia', 'SI' => 'Slovenia', 'ES' => 'Spain',
            'SE' => 'Sweden', 'CH' => 'Switzerland', 'UA' => 'Ukraine', 'GB' => 'United Kingdom',
            'VA' => 'Vatican City',
            
            // Oceania
            'AU' => 'Australia', 'FJ' => 'Fiji', 'KI' => 'Kiribati', 'MH' => 'Marshall Islands',
            'FM' => 'Micronesia', 'NR' => 'Nauru', 'NZ' => 'New Zealand', 'PW' => 'Palau',
            'PG' => 'Papua New Guinea', 'WS' => 'Samoa', 'SB' => 'Solomon Islands', 'TO' => 'Tonga',
            'TV' => 'Tuvalu', 'VU' => 'Vanuatu',
        ];
    }
    
    /**
     * Format phone number with country name
     * 
     * @param string $phone Phone number
     * @param string|null $defaultRegion Country code
     * @return array ['formatted' => '2348012345678', 'country' => 'Nigeria', 'country_code' => 'NG']
     */
    public static function formatWithCountry($phone, $defaultRegion = null)
    {
        $formatted = self::pf($phone, $defaultRegion);
        
        if (empty($formatted)) {
            return [
                'formatted' => '',
                'country' => 'Unknown',
                'country_code' => null
            ];
        }
        
        $detectedCode = self::detectCountryFromPhone($phone);
        $countries = self::getSupportedCountries();
        
        return [
            'formatted' => $formatted,
            'country' => $detectedCode ? ($countries[$detectedCode] ?? 'Unknown') : 'Unknown',
            'country_code' => $detectedCode
        ];
    }
}
