<?php

if (! defined('ABSPATH')) {
    exit;
} class PufferGo_Global_Widgets
{
    public const OPTION_KEY = 'puffergo_global_widgets';

    public const WIDGET_SCHEMAS = array('float_contact' => array('label' => 'Float Contact Bar', 'default' => array('show_whatsapp' => true, 'show_wechat' => true, 'show_phone' => true, 'show_email' => true, 'show_back_to_top' => true, 'show_drag_handle' => true, 'whatsapp_message' => 'Hello! I am interested in your products.', 'tooltip_whatsapp' => 'WhatsApp', 'tooltip_wechat' => 'WeChat Inquiry', 'tooltip_phone' => 'Hotline', 'tooltip_email' => 'Email Us', 'copy_success_text' => 'Copied to Clipboard!', ), 'i18n_fields' => array('whatsapp_message', 'tooltip_whatsapp', 'tooltip_wechat', 'tooltip_phone', 'tooltip_email', 'copy_success_text', ), ), );

    public function __construct()
    {
        add_action('wp_enqueue_scripts', array($this, 'enqueue_assets'));
        add_action('wp_footer', array($this, 'render_widgets'));
    }

    public function enqueue_assets()
    {
        $enabled = array_filter(self::get_all_config(), fn ($w) => ! empty($w['enabled']));

        if (empty($enabled)) {
            return;
        } $plugin_url = plugin_dir_url(PUFFERGO_PLUGIN_FILE);
        $plugin_dir = plugin_dir_path(PUFFERGO_PLUGIN_FILE);
        $asset_file = $plugin_dir . 'build/widgets/index.asset.php';
        $version = PUFFERGO_CORE_VERSION;
        $deps = array();

        if (file_exists($asset_file)) {
            $asset = include $asset_file;
            $deps = $asset['dependencies'];
            $version = $asset['version'];
        } $css_file = $plugin_dir . 'build/widgets/style-index.css';

        if (file_exists($css_file)) {
            wp_enqueue_style('puffergo-widgets', $plugin_url . 'build/widgets/style-index.css', array(), $version);
        } $js_file = $plugin_dir . 'build/widgets/index.js';

        if (file_exists($js_file)) {
            wp_enqueue_script('puffergo-widgets', $plugin_url . 'build/widgets/index.js', $deps, $version, true);
        }
    }

    public function render_widgets()
    {
        $all_config = self::get_all_config();
        $lang = self::get_current_lang();

        foreach ($all_config as $key => $widget) {
            if (empty($widget['enabled'])) {
                continue;
            } $template = plugin_dir_path(PUFFERGO_PLUGIN_FILE) . 'php/widgets/' . str_replace('_', '-', $key) . '.php';

            if (! file_exists($template)) {
                continue;
            } $config = $widget['config'];

            if (! empty($widget['i18n'][ $lang ])) {
                $config = array_merge($config, $widget['i18n'][ $lang ]);
            } $args = self::build_template_args($key, $config);

            if (null === $args) {
                continue;
            } include $template;
        }
    }

    private static function build_template_args(string $key, array $config): ?array
    {
        switch ($key) {
            case 'float_contact': $contact = self::build_contact_data();

                if (empty($contact['email']) && empty($contact['phone']) && empty($contact['whatsapp']['url']) && empty($contact['wechat']['id'])) {
                    return null;
                }

return array('config' => $config, 'contact' => $contact);
            default: return array('config' => $config);
        }
    }

    public static function get_all_config(): array
    {
        $saved = (array) get_option(self::OPTION_KEY, array());
        $out = array();

        foreach (self::WIDGET_SCHEMAS as $key => $schema) {
            $entry = isset($saved[ $key ]) ? (array) $saved[ $key ] : array();
            $config = isset($entry['config']) && is_array($entry['config']) ? $entry['config'] : array();
            $out[ $key ] = array('enabled' => isset($entry['enabled']) ? (bool) $entry['enabled'] : true, 'config' => array_merge($schema['default'], $config), 'i18n' => isset($entry['i18n']) && is_array($entry['i18n']) ? $entry['i18n'] : array(), );
        }

return $out;
    }

    public static function save_all_config(array $data): void
    {
        update_option(self::OPTION_KEY, $data);
    }

    public static function build_contact_data(): array
    {
        $brand = puffergo_get_site_brand_identity();
        $contact = $brand['contact'];
        $whatsapp_url = '';
        $whatsapp_display = '';
        $wechat_id = '';
        $wechat_qr_url = '';

        foreach ((array) ($contact['channels'] ?? array()) as $ch) {
            $type = $ch['type'] ?? '';
            $value = trim((string) ($ch['value'] ?? ''));

            if ('' === $value) {
                continue;
            }

if ('WhatsApp' === $type) {
                if (stripos($value, 'http://') === 0) {
                    $value = 'https://' . substr($value, 7);
                } elseif (stripos($value, 'https://') !== 0) {
                    $value = preg_match('/^[0-9+\-\s()]+$/', $value) ? 'https://wa.me/' . preg_replace('/[^0-9]/', '', $value) : 'https://' . ltrim($value, '/');
                } $whatsapp_url = $value;
                $whatsapp_display = $value;
            } elseif ('WeChat' === $type) {
                $wechat_id = sanitize_text_field($value);
                $wechat_qr_url = esc_url(trim((string) ($ch['extra'] ?? '')));
            }
        }

return array('email' => $contact['email'] ?? '', 'phone' => $contact['phone'] ?? '', 'whatsapp' => array('url' => $whatsapp_url, 'display' => $whatsapp_display), 'wechat' => array('id' => $wechat_id, 'qr_url' => $wechat_qr_url), );
    }

    public static function get_current_lang(): string
    {
        $lang = PufferGo_Polylang::current_language();

        if ($lang) {
            return $lang;
        }

return str_replace('_', '-', get_locale());
    }
}
