<?php

if (!function_exists('cmsOnlineServiceDefaults')) {
    function cmsOnlineServiceDefaults(array $site = [])
    {
        return [
            'enabled' => 0,
            'title' => trim((string) ($site['site_name'] ?? '网站在线客服')),
            'subtitle' => '专业顾问在线',
            'theme' => 'enterprise',
            'position' => 'right',
            'phone' => trim((string) ($site['site_phone'] ?? '')),
            'support_hours' => '周一至周六 09:00 - 18:00',
            'wechat_label' => '微信客服',
            'wechat_qrcode' => '',
            'qq_items' => [
                ['label' => '业务客服', 'number' => ''],
                ['label' => '售后客服', 'number' => ''],
            ],
        ];
    }
}

if (!function_exists('cmsOnlineServiceText')) {
    function cmsOnlineServiceText($value, $maxLength)
    {
        $value = trim(strip_tags((string) $value));
        return function_exists('mb_substr')
            ? mb_substr($value, 0, $maxLength, 'UTF-8')
            : substr($value, 0, $maxLength);
    }
}

if (!function_exists('cmsOnlineServiceNormalize')) {
    function cmsOnlineServiceNormalize($config, array $site = [])
    {
        $config = array_merge(cmsOnlineServiceDefaults($site), is_array($config) ? $config : []);
        $qrcode = trim((string) ($config['wechat_qrcode'] ?? ''));
        if ($qrcode !== '' && !preg_match('#^/uploads/online-service/[a-zA-Z0-9_./-]+$#', $qrcode)) {
            $qrcode = '';
        }

        $qqItems = [];
        foreach (array_slice((array) ($config['qq_items'] ?? []), 0, 6) as $item) {
            if (!is_array($item)) {
                continue;
            }
            $label = cmsOnlineServiceText($item['label'] ?? '', 30);
            $number = substr(preg_replace('/\D+/', '', (string) ($item['number'] ?? '')), 0, 12);
            if ($label === '' && $number === '') {
                continue;
            }
            $qqItems[] = [
                'label' => $label !== '' ? $label : 'QQ客服',
                'number' => $number,
                'url' => $number !== '' ? 'https://wpa.qq.com/msgrd?v=3&uin=' . rawurlencode($number) . '&site=qq&menu=yes' : '',
            ];
        }

        $themes = ['enterprise', 'minimal', 'obsidian', 'fresh'];
        $theme = in_array((string) ($config['theme'] ?? ''), $themes, true) ? (string) $config['theme'] : 'enterprise';

        return [
            'enabled' => !empty($config['enabled']) ? 1 : 0,
            'title' => cmsOnlineServiceText($config['title'] ?? '', 30),
            'subtitle' => cmsOnlineServiceText($config['subtitle'] ?? '', 40),
            'theme' => $theme,
            'position' => ($config['position'] ?? '') === 'left' ? 'left' : 'right',
            'phone' => cmsOnlineServiceText($config['phone'] ?? '', 32),
            'support_hours' => cmsOnlineServiceText($config['support_hours'] ?? '', 80),
            'wechat_label' => cmsOnlineServiceText($config['wechat_label'] ?? '', 30),
            'wechat_qrcode' => $qrcode,
            'qq_items' => $qqItems,
        ];
    }
}

if (!function_exists('cmsOnlineServiceLoad')) {
    function cmsOnlineServiceLoad($db, array $site = [])
    {
        try {
            $row = $db->fetch("SELECT config_value FROM {$db->table('config')} WHERE config_key = ? LIMIT 1", ['online_service']);
            $saved = $row ? json_decode((string) $row['config_value'], true) : [];
            return cmsOnlineServiceNormalize($saved, $site);
        } catch (Exception $e) {
            return cmsOnlineServiceNormalize([], $site);
        }
    }
}

if (!function_exists('cmsOnlineServiceSave')) {
    function cmsOnlineServiceSave($db, array $config, array $site = [])
    {
        $config = cmsOnlineServiceNormalize($config, $site);
        $data = [
            'config_value' => json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'config_type' => 'json',
            'config_group' => 'basic',
        ];
        $exists = $db->fetch("SELECT id FROM {$db->table('config')} WHERE config_key = ? LIMIT 1", ['online_service']);
        if ($exists) {
            $db->update('config', $data, 'config_key = ?', ['online_service']);
        } else {
            $data['config_key'] = 'online_service';
            $db->insert('config', $data);
        }
        return $config;
    }
}

if (!function_exists('cmsOnlineServiceUploadQrcode')) {
    function cmsOnlineServiceUploadQrcode($file)
    {
        if (!is_array($file) || intval($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
            return '';
        }
        if (intval($file['error']) !== UPLOAD_ERR_OK) {
            throw new RuntimeException('二维码上传失败，请重新选择图片');
        }
        if (intval($file['size'] ?? 0) > 5 * 1024 * 1024) {
            throw new RuntimeException('二维码图片不能超过 5MB');
        }

        $imageInfo = function_exists('getimagesize') ? @getimagesize($file['tmp_name']) : false;
        $mime = $imageInfo['mime'] ?? '';
        $extensions = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp'];
        if (!isset($extensions[$mime])) {
            throw new RuntimeException('二维码仅支持 JPG、PNG、GIF 或 WEBP 图片');
        }

        $month = date('Ym');
        $uploadDir = dirname(__DIR__, 2) . '/uploads/online-service/' . $month . '/';
        if (!is_dir($uploadDir) && !@mkdir($uploadDir, 0755, true)) {
            throw new RuntimeException('二维码上传目录创建失败');
        }
        $fileName = 'service_' . date('YmdHis') . '_' . substr(md5(uniqid('', true)), 0, 12) . '.' . $extensions[$mime];
        if (!@move_uploaded_file($file['tmp_name'], $uploadDir . $fileName)) {
            throw new RuntimeException('二维码图片保存失败');
        }
        return '/uploads/online-service/' . $month . '/' . $fileName;
    }
}

if (!function_exists('cmsOnlineServiceRender')) {
    function cmsOnlineServiceRender(array $config, $preview = false)
    {
        if (empty($config['enabled']) && !$preview) {
            return '';
        }
        $qqItems = array_values(array_filter((array) ($config['qq_items'] ?? []), function ($item) use ($preview) {
            return is_array($item) && ($preview || !empty($item['url']));
        }));
        $showWechat = !empty($config['wechat_qrcode']) || $preview;
        $e = function ($value) {
            return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
        };
        ob_start();
        ?>
        <link rel="stylesheet" href="/public/css/online-service.css?v=<?php echo @filemtime(dirname(__DIR__, 2) . '/public/css/online-service.css'); ?>">
        <aside class="cms-service cms-service--<?php echo $config['position'] === 'left' ? 'left' : 'right'; ?> cms-service--theme-<?php echo $e($config['theme'] ?? 'enterprise'); ?>" data-cms-online-service data-service-theme="<?php echo $e($config['theme'] ?? 'enterprise'); ?>">
            <button class="cms-service__launcher" type="button" aria-expanded="true" aria-controls="cms-online-service-panel" aria-label="打开在线客服">
                <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 13v-1a7 7 0 0 1 14 0v1M5 13H4a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h2v-6H5Zm14 0h1a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2h-2v-6h1Zm-1 6c0 1.1-.9 2-2 2h-3"/></svg>
                <span>在线咨询</span>
            </button>
            <div class="cms-service__panel" id="cms-online-service-panel" role="complementary" aria-label="在线客服">
                <header class="cms-service__header">
                    <span class="cms-service__brand" aria-hidden="true">客</span>
                    <span class="cms-service__heading"><strong><?php echo $e($config['title']); ?></strong><small><i></i><?php echo $e($config['subtitle']); ?></small></span>
                    <button class="cms-service__close" type="button" aria-label="收起在线客服">×</button>
                </header>
                <?php if ($qqItems): ?><div class="cms-service__channels">
                    <?php foreach ($qqItems as $item): $url = trim((string) ($item['url'] ?? '')); ?>
                        <?php if ($url !== ''): ?><a class="cms-service__channel" href="<?php echo $e($url); ?>" target="_blank" rel="noopener noreferrer"><?php else: ?><span class="cms-service__channel is-disabled"><?php endif; ?>
                            <b>QQ</b><span><strong><?php echo $e($item['label'] ?? 'QQ客服'); ?></strong><small><?php echo $url !== '' ? '点击发起咨询' : '账号待配置'; ?></small></span><em>›</em>
                        <?php echo $url !== '' ? '</a>' : '</span>'; ?>
                    <?php endforeach; ?>
                </div><?php endif; ?>
                <?php if ($showWechat): ?><section class="cms-service__wechat">
                    <div class="cms-service__section-title"><b>微</b><span><strong><?php echo $e($config['wechat_label']); ?></strong><small>扫码添加专属顾问</small></span></div>
                    <?php if (!empty($config['wechat_qrcode'])): ?><img src="<?php echo $e($config['wechat_qrcode']); ?>" alt="微信客服二维码"><?php else: ?><div class="cms-service__qrcode-empty"><span>二维码待上传</span></div><?php endif; ?>
                </section><?php endif; ?>
                <?php if ($config['phone'] !== '' || $config['support_hours'] !== ''): ?><footer class="cms-service__footer">
                    <?php if ($config['phone'] !== ''): ?><a href="tel:<?php echo $e(preg_replace('/[^0-9+\-]/', '', $config['phone'])); ?>"><span>服务热线</span><strong><?php echo $e($config['phone']); ?></strong></a><?php endif; ?>
                    <?php if ($config['support_hours'] !== ''): ?><p><?php echo $e($config['support_hours']); ?></p><?php endif; ?>
                </footer><?php endif; ?>
            </div>
        </aside>
        <script src="/public/js/online-service.js?v=<?php echo @filemtime(dirname(__DIR__, 2) . '/public/js/online-service.js'); ?>" defer></script>
        <?php
        return ob_get_clean();
    }
}

if (!function_exists('cmsInjectOnlineService')) {
    function cmsInjectOnlineService($html, $widgetHtml)
    {
        if ($widgetHtml === '' || stripos((string) $html, 'data-cms-online-service') !== false) {
            return $html;
        }
        return stripos((string) $html, '</body>') !== false
            ? preg_replace('/<\/body>/i', $widgetHtml . '</body>', $html, 1)
            : $html . $widgetHtml;
    }
}
