<?php
require_once ROOT_PATH . 'core/lib/online_service.php';

$siteRows = $db->fetchAll("SELECT config_key, config_value FROM {$db->table('config')} WHERE config_key IN ('site_name','site_phone')");
$siteInfo = [];
foreach ($siteRows as $row) {
    $siteInfo[$row['config_key']] = $row['config_value'];
}
$service = cmsOnlineServiceLoad($db, $siteInfo);
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireAdminCsrfToken();
    $labels = is_array($_POST['qq_label'] ?? null) ? $_POST['qq_label'] : [];
    $numbers = is_array($_POST['qq_number'] ?? null) ? $_POST['qq_number'] : [];
    $qqItems = [];
    $rowCount = min(max(count($labels), count($numbers)), 6);
    for ($i = 0; $i < $rowCount; $i++) {
        $number = preg_replace('/\D+/', '', (string) ($numbers[$i] ?? ''));
        if ($number !== '' && !preg_match('/^\d{5,12}$/', $number)) {
            $error = 'QQ 号码应为 5 至 12 位数字';
            break;
        }
        $qqItems[] = ['label' => $labels[$i] ?? '', 'number' => $number];
    }

    $qrcode = trim((string) ($_POST['wechat_qrcode'] ?? $service['wechat_qrcode']));
    if (!empty($_POST['remove_qrcode'])) {
        $qrcode = '';
    }
    if ($error === '') {
        try {
            $uploaded = cmsOnlineServiceUploadQrcode($_FILES['qrcode_file'] ?? []);
            if ($uploaded !== '') {
                $qrcode = $uploaded;
            }
        } catch (RuntimeException $e) {
            $error = $e->getMessage();
        }
    }

    $phone = trim((string) ($_POST['phone'] ?? ''));
    $hasQq = count(array_filter($qqItems, function ($item) { return $item['number'] !== ''; })) > 0;
    if ($error === '' && isset($_POST['enabled']) && !$hasQq && $qrcode === '' && $phone === '') {
        $error = '启用前请至少配置 QQ、微信二维码或服务热线中的一项';
    }

    if ($error === '') {
        cmsOnlineServiceSave($db, [
            'enabled' => isset($_POST['enabled']) ? 1 : 0,
            'title' => $_POST['title'] ?? '',
            'subtitle' => $_POST['subtitle'] ?? '',
            'theme' => $_POST['theme'] ?? 'enterprise',
            'position' => $_POST['position'] ?? 'right',
            'phone' => $phone,
            'support_hours' => $_POST['support_hours'] ?? '',
            'wechat_label' => $_POST['wechat_label'] ?? '',
            'wechat_qrcode' => $qrcode,
            'qq_items' => $qqItems,
        ], $siteInfo);
        echo '<script>alert("在线客服设置已保存");location.href="?act=online_service";</script>';
        exit;
    }
    $service = cmsOnlineServiceNormalize([
        'enabled' => isset($_POST['enabled']), 'title' => $_POST['title'] ?? '', 'subtitle' => $_POST['subtitle'] ?? '', 'theme' => $_POST['theme'] ?? 'enterprise',
        'position' => $_POST['position'] ?? 'right', 'phone' => $phone, 'support_hours' => $_POST['support_hours'] ?? '',
        'wechat_label' => $_POST['wechat_label'] ?? '', 'wechat_qrcode' => $qrcode, 'qq_items' => $qqItems,
    ], $siteInfo);
}

while (count($service['qq_items']) < 2) {
    $service['qq_items'][] = ['label' => '', 'number' => '', 'url' => ''];
}
$e = function ($value) { return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8'); };
?>
<style>
.service-settings{--s-primary:#2563eb;--s-line:#e2e8f0;--s-muted:#64748b}.service-settings .service-card{overflow:hidden;margin-bottom:14px;border:1px solid var(--s-line);border-radius:8px;background:#fff}.service-settings .service-card__head{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid var(--s-line);background:#f8fafc}.service-settings .service-card__head h2{margin:0;font-size:15px}.service-settings .service-card__body{padding:18px}.service-settings .service-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px 16px}.service-settings .service-span{grid-column:1/-1}.service-settings .service-enable{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:16px;border:1px solid #dbeafe;border-radius:8px;background:#f8fbff}.service-settings .service-enable strong,.service-settings .service-enable small{display:block}.service-settings .service-enable small{margin-top:4px;color:var(--s-muted)}.service-switch{position:relative;width:48px;height:26px;flex:0 0 auto}.service-switch input{position:absolute;opacity:0}.service-switch span{display:block;width:100%;height:100%;border-radius:999px;background:#cbd5e1;cursor:pointer;transition:.18s}.service-switch span:after{position:absolute;top:3px;left:3px;width:20px;height:20px;border-radius:50%;background:#fff;box-shadow:0 1px 3px rgba(15,23,42,.25);content:"";transition:.18s}.service-switch input:checked+span{background:var(--s-primary)}.service-switch input:checked+span:after{transform:translateX(22px)}.service-switch input:focus-visible+span{outline:3px solid rgba(37,99,235,.18);outline-offset:2px}.service-settings .qq-list{display:grid;gap:10px}.service-settings .qq-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) 38px;gap:10px}.service-settings .qq-remove{border:1px solid #fecaca;border-radius:6px;background:#fff7f7;color:#dc2626;font-size:20px;cursor:pointer}.service-settings .service-note{margin:9px 0 0;color:#94a3b8;font-size:12px}.service-settings .qr-layout{display:grid;grid-template-columns:150px minmax(0,1fr);gap:18px;align-items:start}.service-settings .qr-preview{display:grid;width:150px;height:150px;place-items:center;overflow:hidden;border:1px solid var(--s-line);border-radius:8px;background:#f8fafc;color:#94a3b8}.service-settings .qr-preview img{width:100%;height:100%;padding:8px;object-fit:contain}.service-settings .service-error{margin-bottom:14px;padding:12px 15px;border:1px solid #fecaca;border-radius:8px;background:#fff7f7;color:#b91c1c}.service-settings .service-actions{display:grid;grid-template-columns:1fr 1fr;gap:10px;position:sticky;bottom:0;padding-top:4px}.service-settings .service-actions .btn{justify-content:center}.service-preview-tip{font-size:12px;color:var(--s-muted)}
.service-themes{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}.service-theme{position:relative;display:block;cursor:pointer}.service-theme>input{position:absolute;opacity:0}.service-theme__card{display:block;overflow:hidden;border:1px solid var(--s-line);border-radius:9px;background:#fff;transition:border-color .18s ease,box-shadow .18s ease,transform .18s ease}.service-theme:hover .service-theme__card{transform:translateY(-2px)}.service-theme>input:checked+.service-theme__card{border-color:var(--s-primary);box-shadow:0 0 0 3px rgba(37,99,235,.12)}.service-theme>input:focus-visible+.service-theme__card{outline:3px solid rgba(37,99,235,.18);outline-offset:3px}.service-theme__preview{display:block;height:104px;padding:12px;background:#f1f5f9}.service-theme__mini{display:block;width:82px;margin-left:auto;overflow:hidden;border-radius:7px;background:#fff;box-shadow:0 7px 18px rgba(15,23,42,.13)}.service-theme__mini i{display:block}.service-theme__mini-head{height:25px;background:#2563eb}.service-theme__mini-row{height:15px;margin:7px;border-radius:4px;background:#eff6ff}.service-theme__mini-foot{height:22px;background:#f8fafc}.service-theme__meta{display:flex;align-items:center;justify-content:space-between;padding:10px 11px}.service-theme__meta>span:first-child{display:block}.service-theme__meta strong,.service-theme__meta small{display:block}.service-theme__meta strong{font-size:13px}.service-theme__meta small{margin-top:2px;color:#94a3b8;font-size:11px}.service-theme__check{display:grid!important;width:18px;height:18px;place-items:center;border:1px solid #cbd5e1;border-radius:50%;color:transparent;font-size:11px}.service-theme>input:checked+.service-theme__card .service-theme__check{border-color:var(--s-primary);background:var(--s-primary);color:#fff}.service-theme--minimal .service-theme__preview{background:#fff}.service-theme--minimal .service-theme__mini{border:1px solid #d9dde5;box-shadow:0 4px 12px rgba(15,23,42,.07)}.service-theme--minimal .service-theme__mini-head{background:#fff;border-bottom:1px solid #e5e7eb}.service-theme--minimal .service-theme__mini-row{background:#f3f4f6}.service-theme--obsidian .service-theme__preview{background:#20242c}.service-theme--obsidian .service-theme__mini{background:#15181e;box-shadow:0 8px 20px rgba(0,0,0,.3)}.service-theme--obsidian .service-theme__mini-head{background:#0b0d11;border-bottom:1px solid #343944}.service-theme--obsidian .service-theme__mini-row{background:#292e38}.service-theme--obsidian .service-theme__mini-foot{background:#1c2028}.service-theme--fresh .service-theme__preview{background:#edf8f2}.service-theme--fresh .service-theme__mini-head{background:#16845b}.service-theme--fresh .service-theme__mini-row{background:#e4f5ec}.service-theme--fresh .service-theme__mini-foot{background:#f3faf6}
@media(max-width:1000px){.service-themes{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:760px){.service-settings .service-grid{grid-template-columns:1fr}.service-settings .service-span{grid-column:auto}.service-settings .qq-row{grid-template-columns:1fr 1fr 38px}.service-settings .qr-layout{grid-template-columns:1fr}.service-settings .service-actions{grid-template-columns:1fr}}@media(max-width:520px){.service-themes{grid-template-columns:1fr}}
</style>
<div class="page-container fade-in service-settings">
    <div class="page-header"><div class="page-title"><div class="page-icon"><i class="fa fa-comments-o"></i></div><div><h1>在线客服</h1><p>统一配置前台悬浮客服面板，开启后立即在网站前台显示。</p></div></div></div>
    <?php if ($error !== ''): ?><div class="service-error"><?php echo $e($error); ?></div><?php endif; ?>
    <form method="post" enctype="multipart/form-data" id="serviceForm">
        <section class="service-card"><div class="service-card__head"><h2>客服插件设置</h2><span class="service-preview-tip">关闭时前台不加载任何客服内容</span></div><div class="service-card__body service-grid">
            <div class="service-enable service-span"><div><strong>启用在线客服</strong><small>启用后固定显示在网站前台，移动端自动折叠。</small></div><label class="service-switch"><input type="checkbox" name="enabled" value="1"<?php echo $service['enabled'] ? ' checked' : ''; ?>><span></span></label></div>
            <div class="form-group service-span"><label>面板样式</label><div class="service-themes">
                <?php foreach (['enterprise' => ['企业蓝','专业稳重'], 'minimal' => ['极简白','克制通透'], 'obsidian' => ['曜石黑','高端深色'], 'fresh' => ['清新绿','亲和自然']] as $themeKey => $themeInfo): ?>
                <label class="service-theme service-theme--<?php echo $themeKey; ?>"><input type="radio" name="theme" value="<?php echo $themeKey; ?>"<?php echo ($service['theme'] ?? 'enterprise') === $themeKey ? ' checked' : ''; ?>><span class="service-theme__card"><span class="service-theme__preview"><span class="service-theme__mini"><i class="service-theme__mini-head"></i><i class="service-theme__mini-row"></i><i class="service-theme__mini-row"></i><i class="service-theme__mini-foot"></i></span></span><span class="service-theme__meta"><span><strong><?php echo $themeInfo[0]; ?></strong><small><?php echo $themeInfo[1]; ?></small></span><span class="service-theme__check">✓</span></span></span></label>
                <?php endforeach; ?>
            </div></div>
            <div class="form-group"><label>面板标题</label><input class="form-control" name="title" maxlength="30" value="<?php echo $e($service['title']); ?>"></div>
            <div class="form-group"><label>在线状态文案</label><input class="form-control" name="subtitle" maxlength="40" value="<?php echo $e($service['subtitle']); ?>"></div>
            <div class="form-group"><label>服务热线</label><input class="form-control" name="phone" maxlength="32" value="<?php echo $e($service['phone']); ?>" placeholder="如：400-888-8888"></div>
            <div class="form-group"><label>服务时间</label><input class="form-control" name="support_hours" maxlength="80" value="<?php echo $e($service['support_hours']); ?>"></div>
            <div class="form-group service-span"><label>显示位置</label><select class="form-control" name="position"><option value="right"<?php echo $service['position'] === 'right' ? ' selected' : ''; ?>>网页右侧</option><option value="left"<?php echo $service['position'] === 'left' ? ' selected' : ''; ?>>网页左侧</option></select></div>
        </div></section>

        <section class="service-card"><div class="service-card__head"><h2>QQ 客服</h2><button type="button" class="btn btn-primary" id="addQq">添加 QQ 客服</button></div><div class="service-card__body"><div class="qq-list" id="qqList">
            <?php foreach ($service['qq_items'] as $item): ?><div class="qq-row"><input class="form-control" name="qq_label[]" maxlength="30" value="<?php echo $e($item['label'] ?? ''); ?>" placeholder="客服名称"><input class="form-control" name="qq_number[]" inputmode="numeric" maxlength="12" value="<?php echo $e($item['number'] ?? ''); ?>" placeholder="QQ号码"><button type="button" class="qq-remove" aria-label="删除该客服">×</button></div><?php endforeach; ?>
        </div><p class="service-note">最多添加 6 个 QQ 客服；未填写号码的项目不会在前台生成链接。</p></div></section>

        <section class="service-card"><div class="service-card__head"><h2>微信客服</h2></div><div class="service-card__body service-grid"><div class="form-group service-span"><label>微信客服名称</label><input class="form-control" name="wechat_label" maxlength="30" value="<?php echo $e($service['wechat_label']); ?>"></div><div class="qr-layout service-span"><div class="qr-preview" id="qrPreview"><?php if ($service['wechat_qrcode'] !== ''): ?><img src="<?php echo $e($service['wechat_qrcode']); ?>" alt="当前微信二维码"><?php else: ?><span>暂无二维码</span><?php endif; ?></div><div><input type="hidden" name="wechat_qrcode" value="<?php echo $e($service['wechat_qrcode']); ?>"><input class="form-control" type="file" name="qrcode_file" id="qrcodeFile" accept="image/jpeg,image/png,image/gif,image/webp"><p class="service-note">支持 JPG、PNG、GIF、WEBP，最大 5MB，建议上传正方形二维码。</p><?php if ($service['wechat_qrcode'] !== ''): ?><label style="display:inline-flex;gap:7px;align-items:center;margin-top:14px"><input type="checkbox" name="remove_qrcode" value="1"> 删除当前二维码</label><?php endif; ?></div></div></div></section>
        <div class="service-actions"><button type="submit" class="btn btn-primary btn-lg">保存客服设置</button><a class="btn btn-secondary btn-lg" href="/" target="_blank" rel="noopener">打开前台查看</a></div>
    </form>
</div>
<script>
(function(){var list=document.getElementById('qqList'),add=document.getElementById('addQq');function bind(row){row.querySelector('.qq-remove').addEventListener('click',function(){if(list.children.length>1)row.remove();else row.querySelectorAll('input').forEach(function(input){input.value=''})})}Array.prototype.forEach.call(list.children,bind);add.addEventListener('click',function(){if(list.children.length>=6){alert('最多添加 6 个 QQ 客服');return}var row=document.createElement('div');row.className='qq-row';row.innerHTML='<input class="form-control" name="qq_label[]" maxlength="30" placeholder="客服名称"><input class="form-control" name="qq_number[]" inputmode="numeric" maxlength="12" placeholder="QQ号码"><button type="button" class="qq-remove" aria-label="删除该客服">×</button>';list.appendChild(row);bind(row);row.querySelector('input').focus()});document.getElementById('qrcodeFile').addEventListener('change',function(){var file=this.files&&this.files[0];if(!file)return;var preview=document.getElementById('qrPreview'),reader=new FileReader();reader.onload=function(event){preview.innerHTML='<img src="'+event.target.result+'" alt="待上传二维码预览">'};reader.readAsDataURL(file)})}());
</script>
