<?php

function http_post_form(string $url, array $fields, array $headers = []): array
{
    $ch = curl_init($url);

    $headers = array_merge([
        'Accept: application/json',
        'Content-Type: application/x-www-form-urlencoded',
    ], $headers);

    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => http_build_query($fields),
        CURLOPT_TIMEOUT => 60,
    ]);

    $raw = curl_exec($ch);
    $err = curl_error($ch);
    $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return [
        'ok' => ($err === '' && $status >= 200 && $status < 300),
        'status' => $status,
        'error' => $err,
        'raw' => $raw,
        'json' => json_decode((string)$raw, true),
    ];
}

function http_post_json(string $url, array $payload, array $headers = []): array
{
    $ch = curl_init($url);

    $headers = array_merge([
        'Accept: application/json',
        'Content-Type: application/json',
    ], $headers);

    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        CURLOPT_TIMEOUT => 60,
    ]);

    $raw = curl_exec($ch);
    $err = curl_error($ch);
    $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return [
        'ok' => ($err === '' && $status >= 200 && $status < 300),
        'status' => $status,
        'error' => $err,
        'raw' => $raw,
        'payload' => $payload,
        'json' => json_decode((string)$raw, true),
    ];
}

function dhl_get_token(): array
{
    $url = DHL_BASE_URL . '/parcel/de/account/auth/ropc/v1/token';

    $resp = http_post_form($url, [
        'grant_type' => 'password',
        'username' => DHL_USERNAME,
        'password' => DHL_PASSWORD,
        'client_id' => DHL_API_KEY,
        'client_secret' => DHL_API_SECRET,
    ]);

    if (!$resp['ok']) {
        return [
            'ok' => false,
            'message' => 'Token request failed',
            'response' => $resp,
        ];
    }

    $token = $resp['json']['access_token'] ?? '';

    if ($token === '') {
        return [
            'ok' => false,
            'message' => 'No access_token returned',
            'response' => $resp,
        ];
    }

    return [
        'ok' => true,
        'token' => $token,
        'response' => $resp['json'],
    ];
}

function dhl_create_order(string $token,array $orderRow): array
{
$url = DHL_BASE_URL . '/parcel/de/shipping/v2/orders?mustEncode=true&docFormat=PDF&printFormat=910-300-710';


$address = $orderRow['payload_json']['shippingAddress'];


/*$payload = [
    'profile' => 'STANDARD_GRUPPENPROFIL',
    'shipments' => [
        [
            'product' => 'V01PAK',
            'billingNumber' => '33333333330101',
            'shipmentRefNo' => '#NFK307069RVG0',

            'shipper' => [
                'name1' => 'Rift Valley Germany GmbH',
                'name2' => 'Halle 12a',
                'addressStreet' => 'Hofstrasse',
                'addressHouse' => '64',
                'postalCode' => '40723',
                'city' => 'Hilden',
                'country' => 'DEU',
                'email' => 'souhail@riftvalleyfarms.com',
            ],

            'consignee' => [
                'name1' => 'Brigitte Uhl',
                'name2' => '41856363',
                'addressStreet' => 'Packstation',
                'addressHouse' => '125',
                'postalCode' => '90429',
                'city' => 'Nuernberg',
                'country' => 'DEU',
            ],

            'details' => [
                'weight' => [
                    'uom' => 'kg',
                    'value' => 1.2,
                ],
            ],
        ]
    ]
];*/

$splitAddress = dhl_split_street_house($address['address1']);



$payload = [
                        'profile' => 'STANDARD_GRUPPENPROFIL',
                        'shipments' => [
                            [
                                'product' => 'V01PAK',
                                'billingNumber' => '33333333330101',
                                'shipmentRefNo' => '#NFK307069RVG0',
                    
                                'shipper' => [
                                    'name1' => 'Rift Valley Germany GmbH',
                                    'name2' => 'Halle 12a',
                                    'addressStreet' => 'Hofstrasse',
                                    'addressHouse' => '64',
                                    'postalCode' => '40723',
                                    'city' => 'Hilden',
                                    'country' => 'DEU',
                                    'email' => 'souhail@riftvalleyfarms.com',
                                ],
                    
                                'consignee' => [
                                'name1' => $address['firstName'],
                                'name2' => $address['lastName'],
                                'name3' => trim((string)$address['address2']),
                                'addressStreet' => $splitAddress['street'],
                                'addressHouse' => $splitAddress['house'],
                                'postalCode' => $address['zip'],
                                'city' => $address['city'],
                                'country' => normalize_netsuite_country($address['country']),
                                ],
                    
                                'details' => [
                                    'weight' => [
                                        'uom' => 'kg',
                                        'value' => $orderRow['order_weight'],
                                    ],
                                ],
                            ]
                        ]
                    ];
                    
                    

    return http_post_json($url, $payload, [
        'Authorization: Bearer ' . $token,
    ]);
}

function extract_tracking_number(array $json): ?string
{
    $paths = [
        ['shipments', 0, 'shipmentNo'],
        ['items', 0, 'shipmentNo'],
        ['shipmentNo'],
    ];

    foreach ($paths as $path) {
        $value = $json;
        $found = true;

        foreach ($path as $segment) {
            if (is_array($value) && array_key_exists($segment, $value)) {
                $value = $value[$segment];
            } else {
                $found = false;
                break;
            }
        }

        if ($found && is_string($value) && $value !== '') {
            return $value;
        }
    }

    return null;
}

function normalize_netsuite_country($country)
{
    $map = array(
        'Afghanistan' => 'AFG',
        'Aland Islands' => 'ALA',
        'Åland Islands' => 'ALA',
        'Albania' => 'ALB',
        'Algeria' => 'DZA',
        'American Samoa' => 'ASM',
        'Andorra' => 'AND',
        'Angola' => 'AGO',
        'Anguilla' => 'AIA',
        'Antarctica' => 'ATA',
        'Antigua and Barbuda' => 'ATG',
        'Argentina' => 'ARG',
        'Armenia' => 'ARM',
        'Aruba' => 'ABW',
        'Australia' => 'AUS',
        'Austria' => 'AUT',
        'Azerbaijan' => 'AZE',

        'Bahamas' => 'BHS',
        'Bahrain' => 'BHR',
        'Bangladesh' => 'BGD',
        'Barbados' => 'BRB',
        'Belarus' => 'BLR',
        'Belgium' => 'BEL',
        'Belize' => 'BLZ',
        'Benin' => 'BEN',
        'Bermuda' => 'BMU',
        'Bhutan' => 'BTN',
        'Bolivia' => 'BOL',
        'Bolivia, Plurinational State of' => 'BOL',
        'Bonaire, Sint Eustatius and Saba' => 'BES',
        'Bosnia and Herzegovina' => 'BIH',
        'Botswana' => 'BWA',
        'Bouvet Island' => 'BVT',
        'Brazil' => 'BRA',
        'British Indian Ocean Territory' => 'IOT',
        'Brunei' => 'BRN',
        'Brunei Darussalam' => 'BRN',
        'Bulgaria' => 'BGR',
        'Burkina Faso' => 'BFA',
        'Burundi' => 'BDI',

        'Cabo Verde' => 'CPV',
        'Cape Verde' => 'CPV',
        'Cambodia' => 'KHM',
        'Cameroon' => 'CMR',
        'Canada' => 'CAN',
        'Cayman Islands' => 'CYM',
        'Central African Republic' => 'CAF',
        'Chad' => 'TCD',
        'Chile' => 'CHL',
        'China' => 'CHN',
        'Christmas Island' => 'CXR',
        'Cocos (Keeling) Islands' => 'CCK',
        'Colombia' => 'COL',
        'Comoros' => 'COM',
        'Congo' => 'COG',
        'Congo, The Democratic Republic of the' => 'COD',
        'Democratic Republic of the Congo' => 'COD',
        'Cook Islands' => 'COK',
        'Costa Rica' => 'CRI',
        "Côte d'Ivoire" => 'CIV',
        "Cote d'Ivoire" => 'CIV',
        'Ivory Coast' => 'CIV',
        'Croatia' => 'HRV',
        'Cuba' => 'CUB',
        'Curaçao' => 'CUW',
        'Curacao' => 'CUW',
        'Cyprus' => 'CYP',
        'Czechia' => 'CZE',
        'Czech Republic' => 'CZE',

        'Denmark' => 'DNK',
        'Djibouti' => 'DJI',
        'Dominica' => 'DMA',
        'Dominican Republic' => 'DOM',

        'Ecuador' => 'ECU',
        'Egypt' => 'EGY',
        'El Salvador' => 'SLV',
        'Equatorial Guinea' => 'GNQ',
        'Eritrea' => 'ERI',
        'Estonia' => 'EST',
        'Eswatini' => 'SWZ',
        'Swaziland' => 'SWZ',
        'Ethiopia' => 'ETH',

        'Falkland Islands' => 'FLK',
        'Falkland Islands (Malvinas)' => 'FLK',
        'Faroe Islands' => 'FRO',
        'Fiji' => 'FJI',
        'Finland' => 'FIN',
        'France' => 'FRA',
        'French Guiana' => 'GUF',
        'French Polynesia' => 'PYF',
        'French Southern Territories' => 'ATF',

        'Gabon' => 'GAB',
        'Gambia' => 'GMB',
        'Georgia' => 'GEO',
        'Germany' => 'DEU',
        'Ghana' => 'GHA',
        'Gibraltar' => 'GIB',
        'Greece' => 'GRC',
        'Greenland' => 'GRL',
        'Grenada' => 'GRD',
        'Guadeloupe' => 'GLP',
        'Guam' => 'GUM',
        'Guatemala' => 'GTM',
        'Guernsey' => 'GGY',
        'Guinea' => 'GIN',
        'Guinea-Bissau' => 'GNB',
        'Guyana' => 'GUY',

        'Haiti' => 'HTI',
        'Heard Island and McDonald Islands' => 'HMD',
        'Holy See' => 'VAT',
        'Vatican City' => 'VAT',
        'Honduras' => 'HND',
        'Hong Kong' => 'HKG',
        'Hungary' => 'HUN',

        'Iceland' => 'ISL',
        'India' => 'IND',
        'Indonesia' => 'IDN',
        'Iran' => 'IRN',
        'Iran, Islamic Republic of' => 'IRN',
        'Iraq' => 'IRQ',
        'Ireland' => 'IRL',
        'Isle of Man' => 'IMN',
        'Israel' => 'ISR',
        'Italy' => 'ITA',

        'Jamaica' => 'JAM',
        'Japan' => 'JPN',
        'Jersey' => 'JEY',
        'Jordan' => 'JOR',

        'Kazakhstan' => 'KAZ',
        'Kenya' => 'KEN',
        'Kiribati' => 'KIR',
        'Korea, Democratic People\'s Republic of' => 'PRK',
        'North Korea' => 'PRK',
        'Korea, Republic of' => 'KOR',
        'South Korea' => 'KOR',
        'Kuwait' => 'KWT',
        'Kyrgyzstan' => 'KGZ',

        'Lao People\'s Democratic Republic' => 'LAO',
        'Laos' => 'LAO',
        'Latvia' => 'LVA',
        'Lebanon' => 'LBN',
        'Lesotho' => 'LSO',
        'Liberia' => 'LBR',
        'Libya' => 'LBY',
        'Liechtenstein' => 'LIE',
        'Lithuania' => 'LTU',
        'Luxembourg' => 'LUX',

        'Macao' => 'MAC',
        'Macau' => 'MAC',
        'Madagascar' => 'MDG',
        'Malawi' => 'MWI',
        'Malaysia' => 'MYS',
        'Maldives' => 'MDV',
        'Mali' => 'MLI',
        'Malta' => 'MLT',
        'Marshall Islands' => 'MHL',
        'Martinique' => 'MTQ',
        'Mauritania' => 'MRT',
        'Mauritius' => 'MUS',
        'Mayotte' => 'MYT',
        'Mexico' => 'MEX',
        'Micronesia' => 'FSM',
        'Micronesia, Federated States of' => 'FSM',
        'Moldova' => 'MDA',
        'Moldova, Republic of' => 'MDA',
        'Monaco' => 'MCO',
        'Mongolia' => 'MNG',
        'Montenegro' => 'MNE',
        'Montserrat' => 'MSR',
        'Morocco' => 'MAR',
        'Mozambique' => 'MOZ',
        'Myanmar' => 'MMR',
        'Burma' => 'MMR',

        'Namibia' => 'NAM',
        'Nauru' => 'NRU',
        'Nepal' => 'NPL',
        'Netherlands' => 'NLD',
        'Netherlands, Kingdom of the' => 'NLD',
        'New Caledonia' => 'NCL',
        'New Zealand' => 'NZL',
        'Nicaragua' => 'NIC',
        'Niger' => 'NER',
        'Nigeria' => 'NGA',
        'Niue' => 'NIU',
        'Norfolk Island' => 'NFK',
        'North Macedonia' => 'MKD',
        'Macedonia' => 'MKD',
        'Northern Mariana Islands' => 'MNP',
        'Norway' => 'NOR',

        'Oman' => 'OMN',

        'Pakistan' => 'PAK',
        'Palau' => 'PLW',
        'Palestine' => 'PSE',
        'Palestine, State of' => 'PSE',
        'State of Palestine' => 'PSE',
        'Palestinian Territories' => 'PSE',
        'Occupied Palestinian Territory' => 'PSE',
        'Panama' => 'PAN',
        'Papua New Guinea' => 'PNG',
        'Paraguay' => 'PRY',
        'Peru' => 'PER',
        'Philippines' => 'PHL',
        'Pitcairn' => 'PCN',
        'Poland' => 'POL',
        'Portugal' => 'PRT',
        'Puerto Rico' => 'PRI',

        'Qatar' => 'QAT',

        'Réunion' => 'REU',
        'Reunion' => 'REU',
        'Romania' => 'ROU',
        'Russian Federation' => 'RUS',
        'Russia' => 'RUS',
        'Rwanda' => 'RWA',

        'Saint Barthélemy' => 'BLM',
        'Saint Barthelemy' => 'BLM',
        'Saint Helena, Ascension and Tristan da Cunha' => 'SHN',
        'Saint Kitts and Nevis' => 'KNA',
        'Saint Lucia' => 'LCA',
        'Saint Martin (French part)' => 'MAF',
        'Saint Pierre and Miquelon' => 'SPM',
        'Saint Vincent and the Grenadines' => 'VCT',
        'Samoa' => 'WSM',
        'San Marino' => 'SMR',
        'Sao Tome and Principe' => 'STP',
        'São Tomé and Príncipe' => 'STP',
        'Saudi Arabia' => 'SAU',
        'Senegal' => 'SEN',
        'Serbia' => 'SRB',
        'Seychelles' => 'SYC',
        'Sierra Leone' => 'SLE',
        'Singapore' => 'SGP',
        'Sint Maarten' => 'SXM',
        'Sint Maarten (Dutch part)' => 'SXM',
        'Slovakia' => 'SVK',
        'Slovenia' => 'SVN',
        'Solomon Islands' => 'SLB',
        'Somalia' => 'SOM',
        'South Africa' => 'ZAF',
        'South Georgia and the South Sandwich Islands' => 'SGS',
        'South Sudan' => 'SSD',
        'Spain' => 'ESP',
        'Sri Lanka' => 'LKA',
        'Sudan' => 'SDN',
        'Suriname' => 'SUR',
        'Svalbard and Jan Mayen' => 'SJM',
        'Sweden' => 'SWE',
        'Switzerland' => 'CHE',
        'Syrian Arab Republic' => 'SYR',
        'Syria' => 'SYR',

        'Taiwan' => 'TWN',
        'Taiwan, Province of China' => 'TWN',
        'Tajikistan' => 'TJK',
        'Tanzania' => 'TZA',
        'Tanzania, United Republic of' => 'TZA',
        'Thailand' => 'THA',
        'Timor-Leste' => 'TLS',
        'East Timor' => 'TLS',
        'Togo' => 'TGO',
        'Tokelau' => 'TKL',
        'Tonga' => 'TON',
        'Trinidad and Tobago' => 'TTO',
        'Tunisia' => 'TUN',
        'Turkey' => 'TUR',
        'Türkiye' => 'TUR',
        'Turkiye' => 'TUR',
        'Turkmenistan' => 'TKM',
        'Turks and Caicos Islands' => 'TCA',
        'Tuvalu' => 'TUV',

        'Uganda' => 'UGA',
        'Ukraine' => 'UKR',
        'United Arab Emirates' => 'ARE',
        'United Kingdom' => 'GBR',
        'United Kingdom of Great Britain and Northern Ireland' => 'GBR',
        'UK' => 'GBR',
        'Great Britain' => 'GBR',
        'United States' => 'USA',
        'United States of America' => 'USA',
        'USA' => 'USA',
        'U.S.A.' => 'USA',
        'US' => 'USA',
        'United States Minor Outlying Islands' => 'UMI',
        'Uruguay' => 'URY',
        'Uzbekistan' => 'UZB',

        'Vanuatu' => 'VUT',
        'Venezuela' => 'VEN',
        'Venezuela, Bolivarian Republic of' => 'VEN',
        'Viet Nam' => 'VNM',
        'Vietnam' => 'VNM',
        'Virgin Islands, British' => 'VGB',
        'British Virgin Islands' => 'VGB',
        'Virgin Islands, U.S.' => 'VIR',
        'U.S. Virgin Islands' => 'VIR',

        'Wallis and Futuna' => 'WLF',
        'Western Sahara' => 'ESH',

        'Yemen' => 'YEM',

        'Zambia' => 'ZMB',
        'Zimbabwe' => 'ZWE',
    );

    $alpha2ToAlpha3 = array(
        'AF' => 'AFG', 'AX' => 'ALA', 'AL' => 'ALB', 'DZ' => 'DZA', 'AS' => 'ASM',
        'AD' => 'AND', 'AO' => 'AGO', 'AI' => 'AIA', 'AQ' => 'ATA', 'AG' => 'ATG',
        'AR' => 'ARG', 'AM' => 'ARM', 'AW' => 'ABW', 'AU' => 'AUS', 'AT' => 'AUT',
        'AZ' => 'AZE', 'BS' => 'BHS', 'BH' => 'BHR', 'BD' => 'BGD', 'BB' => 'BRB',
        'BY' => 'BLR', 'BE' => 'BEL', 'BZ' => 'BLZ', 'BJ' => 'BEN', 'BM' => 'BMU',
        'BT' => 'BTN', 'BO' => 'BOL', 'BQ' => 'BES', 'BA' => 'BIH', 'BW' => 'BWA',
        'BV' => 'BVT', 'BR' => 'BRA', 'IO' => 'IOT', 'BN' => 'BRN', 'BG' => 'BGR',
        'BF' => 'BFA', 'BI' => 'BDI', 'CV' => 'CPV', 'KH' => 'KHM', 'CM' => 'CMR',
        'CA' => 'CAN', 'KY' => 'CYM', 'CF' => 'CAF', 'TD' => 'TCD', 'CL' => 'CHL',
        'CN' => 'CHN', 'CX' => 'CXR', 'CC' => 'CCK', 'CO' => 'COL', 'KM' => 'COM',
        'CG' => 'COG', 'CD' => 'COD', 'CK' => 'COK', 'CR' => 'CRI', 'CI' => 'CIV',
        'HR' => 'HRV', 'CU' => 'CUB', 'CW' => 'CUW', 'CY' => 'CYP', 'CZ' => 'CZE',
        'DK' => 'DNK', 'DJ' => 'DJI', 'DM' => 'DMA', 'DO' => 'DOM', 'EC' => 'ECU',
        'EG' => 'EGY', 'SV' => 'SLV', 'GQ' => 'GNQ', 'ER' => 'ERI', 'EE' => 'EST',
        'SZ' => 'SWZ', 'ET' => 'ETH', 'FK' => 'FLK', 'FO' => 'FRO', 'FJ' => 'FJI',
        'FI' => 'FIN', 'FR' => 'FRA', 'GF' => 'GUF', 'PF' => 'PYF', 'TF' => 'ATF',
        'GA' => 'GAB', 'GM' => 'GMB', 'GE' => 'GEO', 'DE' => 'DEU', 'GH' => 'GHA',
        'GI' => 'GIB', 'GR' => 'GRC', 'GL' => 'GRL', 'GD' => 'GRD', 'GP' => 'GLP',
        'GU' => 'GUM', 'GT' => 'GTM', 'GG' => 'GGY', 'GN' => 'GIN', 'GW' => 'GNB',
        'GY' => 'GUY', 'HT' => 'HTI', 'HM' => 'HMD', 'VA' => 'VAT', 'HN' => 'HND',
        'HK' => 'HKG', 'HU' => 'HUN', 'IS' => 'ISL', 'IN' => 'IND', 'ID' => 'IDN',
        'IR' => 'IRN', 'IQ' => 'IRQ', 'IE' => 'IRL', 'IM' => 'IMN', 'IL' => 'ISR',
        'IT' => 'ITA', 'JM' => 'JAM', 'JP' => 'JPN', 'JE' => 'JEY', 'JO' => 'JOR',
        'KZ' => 'KAZ', 'KE' => 'KEN', 'KI' => 'KIR', 'KP' => 'PRK', 'KR' => 'KOR',
        'KW' => 'KWT', 'KG' => 'KGZ', 'LA' => 'LAO', 'LV' => 'LVA', 'LB' => 'LBN',
        'LS' => 'LSO', 'LR' => 'LBR', 'LY' => 'LBY', 'LI' => 'LIE', 'LT' => 'LTU',
        'LU' => 'LUX', 'MO' => 'MAC', 'MG' => 'MDG', 'MW' => 'MWI', 'MY' => 'MYS',
        'MV' => 'MDV', 'ML' => 'MLI', 'MT' => 'MLT', 'MH' => 'MHL', 'MQ' => 'MTQ',
        'MR' => 'MRT', 'MU' => 'MUS', 'YT' => 'MYT', 'MX' => 'MEX', 'FM' => 'FSM',
        'MD' => 'MDA', 'MC' => 'MCO', 'MN' => 'MNG', 'ME' => 'MNE', 'MS' => 'MSR',
        'MA' => 'MAR', 'MZ' => 'MOZ', 'MM' => 'MMR', 'NA' => 'NAM', 'NR' => 'NRU',
        'NP' => 'NPL', 'NL' => 'NLD', 'NC' => 'NCL', 'NZ' => 'NZL', 'NI' => 'NIC',
        'NE' => 'NER', 'NG' => 'NGA', 'NU' => 'NIU', 'NF' => 'NFK', 'MK' => 'MKD',
        'MP' => 'MNP', 'NO' => 'NOR', 'OM' => 'OMN', 'PK' => 'PAK', 'PW' => 'PLW',
        'PS' => 'PSE', 'PA' => 'PAN', 'PG' => 'PNG', 'PY' => 'PRY', 'PE' => 'PER',
        'PH' => 'PHL', 'PN' => 'PCN', 'PL' => 'POL', 'PT' => 'PRT', 'PR' => 'PRI',
        'QA' => 'QAT', 'RE' => 'REU', 'RO' => 'ROU', 'RU' => 'RUS', 'RW' => 'RWA',
        'BL' => 'BLM', 'SH' => 'SHN', 'KN' => 'KNA', 'LC' => 'LCA', 'MF' => 'MAF',
        'PM' => 'SPM', 'VC' => 'VCT', 'WS' => 'WSM', 'SM' => 'SMR', 'ST' => 'STP',
        'SA' => 'SAU', 'SN' => 'SEN', 'RS' => 'SRB', 'SC' => 'SYC', 'SL' => 'SLE',
        'SG' => 'SGP', 'SX' => 'SXM', 'SK' => 'SVK', 'SI' => 'SVN', 'SB' => 'SLB',
        'SO' => 'SOM', 'ZA' => 'ZAF', 'GS' => 'SGS', 'SS' => 'SSD', 'ES' => 'ESP',
        'LK' => 'LKA', 'SD' => 'SDN', 'SR' => 'SUR', 'SJ' => 'SJM', 'SE' => 'SWE',
        'CH' => 'CHE', 'SY' => 'SYR', 'TW' => 'TWN', 'TJ' => 'TJK', 'TZ' => 'TZA',
        'TH' => 'THA', 'TL' => 'TLS', 'TG' => 'TGO', 'TK' => 'TKL', 'TO' => 'TON',
        'TT' => 'TTO', 'TN' => 'TUN', 'TR' => 'TUR', 'TM' => 'TKM', 'TC' => 'TCA',
        'TV' => 'TUV', 'UG' => 'UGA', 'UA' => 'UKR', 'AE' => 'ARE', 'GB' => 'GBR',
        'US' => 'USA', 'UM' => 'UMI', 'UY' => 'URY', 'UZ' => 'UZB', 'VU' => 'VUT',
        'VE' => 'VEN', 'VN' => 'VNM', 'VG' => 'VGB', 'VI' => 'VIR', 'WF' => 'WLF',
        'EH' => 'ESH', 'YE' => 'YEM', 'ZM' => 'ZMB', 'ZW' => 'ZWE',
    );

    $country = trim((string)$country);
    if ($country === '') {
        return '';
    }

    if (isset($map[$country])) {
        return $map[$country];
    }

    $countryUpper = strtoupper($country);
    if (isset($alpha2ToAlpha3[$countryUpper])) {
        return $alpha2ToAlpha3[$countryUpper];
    }

    if (strlen($countryUpper) === 3) {
        return $countryUpper;
    }

    $countryLower = strtolower($country);
    foreach ($map as $name => $code) {
        if (strtolower($name) === $countryLower) {
            return $code;
        }
    }

    return $countryUpper;
}

function dhl_split_street_house($address1)
{
    $address1 = trim((string)$address1);

    $result = [
        'street' => $address1,
        'house'  => '1',
    ];

    if ($address1 === '') {
        return $result;
    }

    if (preg_match('/^(.*?)[\s,]+([0-9A-Za-z\-\/]{1,10})$/u', $address1, $m)) {
        $street = trim($m[1]);
        $house  = trim($m[2]);

        if ($street !== '') {
            $result['street'] = $street;
        }

        if ($house !== '') {
            $result['house'] = $house;
        }
    }

    return $result;
}
