<?php
namespace EasyChat\Library\Commerce;






final class OpenCartShippingResolver
{
    public function resolve($code, $method, array $mapping = array()): array
    {
        $code = $this->plain($code);
        $method = $this->plain($method);
        $key = $code !== '' ? $code : $method;
        $normalized = function_exists('mb_strtolower') ? mb_strtolower($key, 'UTF-8') : strtolower($key);

        foreach ($mapping as $mapped_key => $provider) {
            if ((string)$mapped_key === $key && $this->isProviderOrIgnored($provider)) {
                if ($provider === 'ignore') {
                    return array('provider' => '', 'carrier' => '', 'confidence' => 1.0, 'evidence' => 'admin_ignored', 'key' => $key);
                }
                return $this->result($provider, 'admin_mapping', $key, 1.0);
            }
        }

        $rules = array(
            'apiship' => '/(^|[_.:-])apiship([_.:-]|$)/iu',
            'cdek' => '/(^|[_.:-])(cdek|сдэк|сдек)([_.:-]|$)/iu',
            'russian_post' => '/(^|[_.:-])(pochta|russian.?post|почта.?россии)([_.:-]|$)/iu',
            'yandex_delivery' => '/(^|[_.:-])yandex([_.:-]|$)/iu',
        );
        foreach ($rules as $provider => $pattern) {
            if ($code !== '' && preg_match($pattern, $code)) {
                return $this->result($provider, 'shipping_code', $code, 0.98);
            }
        }

         
         
         
        foreach ($rules as $provider => $pattern) {
            if ($method !== '' && preg_match($pattern, $method)) {
                return $this->result($provider, 'shipping_method_suggestion', $method, 0.60);
            }
        }
        return array('provider' => '', 'carrier' => '', 'confidence' => 0.0, 'evidence' => '', 'key' => $key);
    }

    public function mappingFromSettings($raw): array
    {
        $decoded = is_array($raw) ? $raw : json_decode((string)$raw, true);
        if (!is_array($decoded)) return array();
        $result = array();
        foreach ($decoded as $key => $provider) {
            if (count($result) >= 48) break;
            $key = $this->plain($key);
            if ($key !== '' && $this->isProviderOrIgnored($provider)) $result[$key] = (string)$provider;
        }
        return $result;
    }

    public function label(string $provider): string
    {
        $labels = array('apiship'=>'ApiShip','cdek'=>'СДЭК','russian_post'=>'Почта России','yandex_delivery'=>'Яндекс Доставка','ignore'=>'Не отслеживать');
        return $labels[$provider] ?? '';
    }

    private function result(string $provider, string $evidence, string $key, float $confidence): array
    {
        return array('provider'=>$provider,'carrier'=>$this->label($provider), 'confidence'=>$confidence, 'evidence'=>$evidence, 'key'=>$key);
    }

    private function isProvider($provider): bool
    {
        return in_array((string)$provider, array('apiship','cdek','russian_post','yandex_delivery'), true);
    }

    private function isProviderOrIgnored($provider): bool
    {
        return $this->isProvider($provider) || (string)$provider === 'ignore';
    }

    private function plain($value): string
    {
        $value = preg_replace('/\s+/u', ' ', strip_tags((string)$value));
        return trim(function_exists('mb_substr') ? mb_substr($value, 0, 128, 'UTF-8') : substr($value, 0, 128));
    }
}
