<?php

namespace GriffinForms\Admin\Html\Elements\Submission;

class InputPhone extends \GriffinForms\Admin\Html\Elements\Submission\Format
{
    public function getHtml()
    {
        if (!$this->hasPhoneValue()) {
            echo '<div class="' . esc_attr($this->input_class) . ' text-muted">' . esc_html__('No number provided', 'griffinforms-form-builder') . '</div>';
            return;
        }

        $value = is_array($this->field_value) ? reset($this->field_value) : $this->field_value;
        $phone_data = $this->parsePhoneValue($value);

        echo '<div class="' . esc_attr($this->input_class) . ' d-flex align-items-center gap-2">';

        if (!empty($phone_data['flag'])) {
            echo '<span class="fs-5" aria-hidden="true">' . esc_html($phone_data['flag']) . '</span>';
        }

        $meta_parts = array();
        if (!empty($phone_data['country'])) {
            $meta_parts[] = $phone_data['country'];
        }
        if (!empty($phone_data['dial_code'])) {
            $meta_parts[] = $phone_data['dial_code'];
        }
        if (!empty($meta_parts)) {
            echo '<span class="text-muted small">' . esc_html(implode(' · ', $meta_parts)) . '</span>';
        }

        $tel_href = $phone_data['tel'] !== '' ? $phone_data['tel'] : $value;
        $display_number = $phone_data['number'] !== '' ? $phone_data['number'] : $value;
        echo '<a href="tel:' . esc_attr($tel_href) . '" class="ms-2">';
        echo esc_html($display_number);
        echo '</a>';

        echo '</div>';
    }

    private function hasPhoneValue()
    {
        $value = is_array($this->field_value) ? reset($this->field_value) : $this->field_value;
        if (empty($value)) {
            return false;
        }

        if (is_string($value) && strip_tags($value) === __('No value entered', 'griffinforms-form-builder')) {
            return false;
        }

        return true;
    }

    private function getFlagEmoji($digits)
    {
        $map = array(
            '1'   => '🇺🇸',
            '7'   => '🇷🇺',
            '20'  => '🇪🇬',
            '27'  => '🇿🇦',
            '30'  => '🇬🇷',
            '31'  => '🇳🇱',
            '32'  => '🇧🇪',
            '33'  => '🇫🇷',
            '34'  => '🇪🇸',
            '36'  => '🇭🇺',
            '39'  => '🇮🇹',
            '40'  => '🇷🇴',
            '41'  => '🇨🇭',
            '44'  => '🇬🇧',
            '45'  => '🇩🇰',
            '46'  => '🇸🇪',
            '47'  => '🇳🇴',
            '48'  => '🇵🇱',
            '49'  => '🇩🇪',
            '52'  => '🇲🇽',
            '55'  => '🇧🇷',
            '56'  => '🇨🇱',
            '57'  => '🇨🇴',
            '60'  => '🇲🇾',
            '61'  => '🇦🇺',
            '62'  => '🇮🇩',
            '63'  => '🇵🇭',
            '64'  => '🇳🇿',
            '65'  => '🇸🇬',
            '66'  => '🇹🇭',
            '81'  => '🇯🇵',
            '82'  => '🇰🇷',
            '84'  => '🇻🇳',
            '86'  => '🇨🇳',
            '90'  => '🇹🇷',
            '91'  => '🇮🇳',
            '92'  => '🇵🇰',
            '93'  => '🇦🇫',
            '94'  => '🇱🇰',
            '95'  => '🇲🇲',
            '98'  => '🇮🇷',
            '971' => '🇦🇪',
            '972' => '🇮🇱',
            '973' => '🇧🇭',
            '974' => '🇶🇦',
            '975' => '🇧🇹',
            '976' => '🇲🇳',
            '977' => '🇳🇵'
        );

        for ($len = 4; $len >= 1; $len--) {
            $prefix = substr($digits, 0, $len);
            if (isset($map[$prefix])) {
                return $map[$prefix];
            }
        }

        return '';
    }

    private function parsePhoneValue($value)
    {
        $value = is_string($value) ? $value : '';
        $digits = preg_replace('/\D+/', '', $value);
        $countries = \GriffinForms\Includes\Helpers\PhoneCountries::getCountries();
        $match = null;

        foreach ($countries as $country) {
            if (empty($country['dial_code'])) {
                continue;
            }
            $dial_digits = ltrim($country['dial_code'], '+');
            if ($dial_digits === '') {
                continue;
            }
            if (strpos($digits, $dial_digits) === 0) {
                if ($match === null || strlen($dial_digits) > strlen(ltrim($match['dial_code'], '+'))) {
                    $match = $country;
                }
            }
        }

        $dial_code = $match['dial_code'] ?? '';
        $number = $digits;
        if ($dial_code !== '') {
            $number = substr($digits, strlen(ltrim($dial_code, '+')));
        }

        return array(
            'dial_code' => $dial_code,
            'country' => $match['name'] ?? '',
            'flag' => $match['flag'] ?? ($digits !== '' ? $this->getFlagEmoji($digits) : ''),
            'number' => $number,
            'tel' => $digits !== '' ? '+' . $digits : '',
        );
    }
}
