<?php
namespace EasyChat\Library\Messenger;

 
class ChannelCatalog {
    private const CHANNELS = [
        'widget' => ['label' => 'Сайт', 'short_label' => 'Сайт', 'kind' => 'owned'],
        'telegram' => ['label' => 'Telegram', 'short_label' => 'Telegram', 'kind' => 'messenger'],
        'vk' => ['label' => 'ВКонтакте', 'short_label' => 'VK', 'kind' => 'messenger'],
        'max-bot' => ['label' => 'MAX-бот', 'short_label' => 'MAX-бот', 'kind' => 'messenger'],
        'whatsapp-personal' => ['label' => 'Личный WhatsApp', 'short_label' => 'WhatsApp', 'kind' => 'messenger'],
        'sms' => ['label' => 'SMS', 'short_label' => 'SMS', 'kind' => 'owned'],
        'email' => ['label' => 'Почта', 'short_label' => 'Почта', 'kind' => 'owned'],
        'avito' => [
            'label' => 'Авито', 'short_label' => 'Авито', 'kind' => 'marketplace',
            'item_fallback' => 'Объявление Авито', 'general_fallback' => 'Общий запрос Авито',
        ],
        'youla' => [
            'label' => 'Юла', 'short_label' => 'Юла', 'kind' => 'marketplace',
            'item_fallback' => 'Объявление Юлы', 'general_fallback' => 'Общий запрос Юлы',
        ],
        'wildberries' => [
            'label' => 'Wildberries', 'short_label' => 'WB', 'kind' => 'marketplace',
            'item_fallback' => 'Товар Wildberries', 'general_fallback' => 'Общий запрос Wildberries',
        ],
        'ozon' => [
            'label' => 'Ozon', 'short_label' => 'Ozon', 'kind' => 'marketplace',
            'item_fallback' => 'Товар Ozon', 'general_fallback' => 'Общий запрос Ozon',
        ],
        'yandex_market' => [
            'label' => 'Яндекс Маркет', 'short_label' => 'Маркет', 'kind' => 'marketplace',
            'item_fallback' => 'Товар Яндекс Маркета', 'general_fallback' => 'Общий запрос Яндекс Маркета',
        ],
    ];

    public static function all(): array {
        return self::CHANNELS;
    }

    public static function get(string $provider): array {
        $provider = self::normalize($provider);
        return self::CHANNELS[$provider] ?? [
            'label' => $provider !== '' ? strtoupper($provider) : 'Сайт',
            'short_label' => $provider !== '' ? strtoupper($provider) : 'Сайт',
            'kind' => 'custom',
        ];
    }

    public static function label(string $provider, bool $short = false): string {
        $channel = self::get($provider);
        return (string)$channel[$short ? 'short_label' : 'label'];
    }

    public static function isMarketplace(string $provider): bool {
        return (string)(self::get($provider)['kind'] ?? '') === 'marketplace';
    }

    



    public static function marketplaceContextFallbacks(): array {
        $result = [];
        foreach (self::CHANNELS as $provider => $channel) {
            if (($channel['kind'] ?? '') !== 'marketplace') {
                continue;
            }
            $result[$provider] = [
                'item' => (string)($channel['item_fallback'] ?? ('Товар ' . $channel['label'])),
                'general' => (string)($channel['general_fallback'] ?? ('Общий запрос ' . $channel['label'])),
            ];
        }
        return $result;
    }

    public static function filterOrder(): array {
         
         
         
        return [
            'widget', 'email', 'avito', 'youla', 'wildberries', 'ozon',
            'yandex_market', 'max-bot', 'whatsapp-personal', 'sms',
            'telegram', 'vk',
        ];
    }

    public static function isConfigured(string $provider, array $settings, $registry = null): bool {
        $provider = self::normalize($provider);
        if ($provider === '' || $provider === 'all') {
            return true;
        }

        $configured = self::configuredProviders($settings, $registry);
        return !empty($configured[$provider]);
    }

    







    public static function configuredProviders(array $settings, $registry = null): array {
        $configured = [
            'all' => true,
            'widget' => (string)($settings['chat_status'] ?? '1') === '1',
            'telegram' => (string)($settings['chat_telegram_status'] ?? '0') === '1'
                && trim((string)($settings['chat_telegram_token'] ?? '')) !== '',
            'vk' => (string)($settings['chat_vk_status'] ?? '0') === '1'
                && trim((string)($settings['chat_vk_token'] ?? '')) !== '',
            'max-bot' => (string)($settings['chat_max_bot_status'] ?? '0') === '1'
                && trim((string)($settings['chat_max_bot_token'] ?? '')) !== '',
            'whatsapp-personal' => (string)($settings['chat_whatsapp_personal_status'] ?? '0') === '1',
            'avito' => (string)($settings['chat_avito_status'] ?? '0') === '1'
                && trim((string)($settings['chat_avito_client_id'] ?? '')) !== ''
                && trim((string)($settings['chat_avito_client_secret'] ?? '')) !== '',
            'youla' => (string)($settings['chat_youla_status'] ?? '0') === '1'
                && trim((string)($settings['chat_youla_app_id'] ?? '')) !== '',
            'wildberries' => false,
            'ozon' => false,
            'yandex_market' => false,
             
             
             
            'sms' => true,
            'email' => false,
        ];
        if (!$registry) {
            return $configured;
        }

        try {
            $db = $registry->get('db');
            $prefix = easychat_db_prefix();
            $channels = $db->query(
                "SELECT DISTINCT `provider` FROM `{$prefix}messenger_channels`
                 WHERE (`status` = '1' OR `status` = 'active')"
            );
            foreach ((array)($channels->rows ?? []) as $row) {
                $provider = self::normalize((string)($row['provider'] ?? ''));
                if (isset($configured[$provider])) {
                    $configured[$provider] = true;
                }
            }
        } catch (\Throwable $ignored) {
             
             
        }
        return $configured;
    }

    private static function normalize(string $provider): string {
        return strtolower(preg_replace('/[^a-z0-9_\-]/i', '', $provider));
    }
}
