<?php
/**
 * 芋头CMS - 自定义变量
 */
$action = isset($_GET['action']) ? $_GET['action'] : 'list';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);
        $db->delete('custom_var', 'id = ?', [$id]);
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
    if ($action === 'save') {
        $var_name = trim($_POST['var_name'] ?? '');
        $var_key = trim($_POST['var_key'] ?? '');
        $var_type = trim($_POST['var_type'] ?? 'text');
        $var_value = $_POST['var_value'] ?? '';
        if (empty($var_name) || empty($var_key)) {
            echo '<script>alert("变量名和标识不能为空");history.back();</script>';
            exit;
        }
        $exists = $db->fetch("SELECT id FROM {$db->table('custom_var')} WHERE var_key = ?", [$var_key]);
        if ($exists) {
            $eid = intval($_POST['id'] ?? 0);
            if (!$eid || $exists['id'] != $eid) {
                echo '<script>alert("变量标识已存在");history.back();</script>';
                exit;
            }
        }
        $data = ['var_name'=>$var_name, 'var_key'=>$var_key, 'var_type'=>$var_type, 'var_value'=>$var_value];
        $id = intval($_POST['id'] ?? 0);
        if ($id > 0) {
            $db->update('custom_var', $data, 'id = ?', [$id]);
        } else {
            $data['create_time'] = time();
            $db->insert('custom_var', $data);
        }
        echo '<script>alert("保存成功");location.href="?act=custom_var"</script>';
        exit;
    }
}

if ($action === 'list') {
    $vars = $db->fetchAll("SELECT * FROM {$db->table('custom_var')} ORDER BY id ASC");
    $typeLabels = ['text'=>'单行文本', 'textarea'=>'多行文本', 'image'=>'图片'];
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg></div>
                <div>
                    <h1>自定义变量</h1>
                    <p style="font-size:12px;color:var(--gray-500);margin:0;">前台模板使用 {$custom.变量标识} 调用</p>
                </div>
            </div>
            <div class="page-actions">
                <a href="?act=custom_var&action=add" class="btn btn-primary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> 添加变量</a>
            </div>
        </div>
        <div class="content-card">
            <?php if (empty($vars)): ?>
            <div class="empty-state">
                <div class="empty-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg></div>
                <h3>暂无变量</h3>
                <p>添加自定义变量供前台模板调用</p>
                <a href="?act=custom_var&action=add" class="btn btn-primary">添加变量</a>
            </div>
            <?php else: ?>
            <table class="data-table">
                <thead>
                    <tr>
                        <th style="width:45px;">ID</th>
                        <th>变量名称</th>
                        <th>变量标识</th>
                        <th style="width:90px;">类型</th>
                        <th>变量值</th>
                        <th style="width:140px;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($vars as $item): ?>
                    <tr>
                        <td class="id-cell"><?php echo $item['id']; ?></td>
                        <td style="font-weight:500;"><?php echo htmlspecialchars($item['var_name']); ?></td>
                        <td><code id="tag_<?php echo $item['id']; ?>" style="background:var(--gray-100);padding:3px 8px;border-radius:4px;font-size:12px;">{$custom.<?php echo htmlspecialchars($item['var_key']); ?>}</code></td>
                        <td><span style="background:#f0fdf4;color:#16a34a;padding:2px 8px;border-radius:4px;font-size:11px;"><?php echo $typeLabels[$item['var_type']] ?? '单行文本'; ?></span></td>
                        <td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px;color:#64748b;" title="<?php echo htmlspecialchars($item['var_value']); ?>">
                            <?php if ($item['var_type'] === 'image' && !empty($item['var_value'])): ?>
                            <img src="<?php echo htmlspecialchars($item['var_value']); ?>" style="height:28px;border-radius:3px;vertical-align:middle;">
                            <?php else: ?>
                            <?php echo htmlspecialchars($item['var_value']); ?>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="btn-group">
                                <a href="?act=custom_var&action=edit&id=<?php echo $item['id']; ?>" class="btn btn-sm btn-primary"><svg style="width:12px;height:12px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg> 编辑</a>
                                <a href="javascript:delVar(<?php echo $item['id']; ?>);" class="btn btn-sm btn-danger"><svg style="width:12px;height:12px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg> 删除</a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>

            <!-- 调用说明 -->
            <div style="margin-top:24px;padding:20px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;">
                <div style="display:flex;align-items:center;gap:8px;margin-bottom:16px;">
                    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="#2563eb" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>
                    <span style="font-size:14px;font-weight:600;color:#1e293b;">自定义变量 · 调用说明</span>
                </div>


                <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
                    <!-- 左侧：模板用法 -->
                    <div>
                        <p style="font-size:13px;font-weight:600;color:#475569;margin:0 0 12px 0;">📝 模板中调用（支持所有前台模板）</p>
                        <div style="background:#1e293b;border-radius:8px;padding:14px;overflow-x:auto;">
                            <p style="margin:0 0 10px 0;font-size:12px;color:#94a3b8;">&#9654; 单行/多行文本变量</p>
                            <code style="font-size:12px;color:#f59e0b;display:block;margin-bottom:10px;">{$custom.变量标识}</code>
                            <p style="margin:0 0 10px 0;font-size:12px;color:#94a3b8;">&#9654; 图片变量（直接输出完整 &lt;img&gt; 标签）</p>
                            <code style="font-size:12px;color:#f59e0b;display:block;margin-bottom:10px;">{$custom.变量标识}</code>
                            <p style="margin:0 0 6px 0;font-size:12px;color:#94a3b8;">&#9654; 判断变量是否为空</p>
                            <code style="font-size:12px;color:#f59e0b;display:block;">&lt;if condition="\$custom['变量标识']"&gt;<br>&nbsp;&nbsp;...内容...<br>&lt;/if&gt;</code>
                        </div>
                    </div>
                    <!-- 右侧：模板示例 -->
                    <div>
                        <p style="font-size:13px;font-weight:600;color:#475569;margin:0 0 12px 0;">📋 使用示例</p>
                        <div style="background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:14px;overflow-x:auto;">
                            <p style="margin:0 0 8px 0;font-size:12px;color:#64748b;">调用单行文本：</p>
                            <code style="font-size:12px;color:#16a34a;display:block;margin-bottom:12px;">&#123;$custom.company_name&#125;</code>
                            <p style="margin:0 0 8px 0;font-size:12px;color:#64748b;">调用多行文本（公司简介）：</p>
                            <code style="font-size:12px;color:#16a34a;display:block;margin-bottom:12px;">&#123;$custom.intro&#125;</code>
                            <p style="margin:0 0 8px 0;font-size:12px;color:#64748b;">调用图片（Logo）：</p>
                            <code style="font-size:12px;color:#16a34a;display:block;margin-bottom:12px;">&lt;img src="&#123;$custom.logo&#125;"&gt;</code>
                            <p style="margin:0 0 4px 0;font-size:12px;color:#64748b;">条件判断：</p>
                            <code style="font-size:12px;color:#16a34a;display:block;">&lt;if condition="\$custom['hotline']"&gt;<br>&nbsp;&nbsp;电话：&#123;$custom.hotline&#125;<br>&lt;/if&gt;</code>
                        </div>
                    </div>
                </div>

                <!-- PHP标签说明 -->
                <div style="margin-top:16px;padding:14px;background:#fff;border:1px solid #e2e8f0;border-radius:8px;">
                    <p style="font-size:13px;font-weight:600;color:#475569;margin:0 0 10px 0;">💡 变量标识命名规范</p>
                    <ul style="margin:0;padding-left:18px;font-size:12px;color:#64748b;line-height:1.8;">
                        <li>只能包含 <strong>英文小写字母、数字、下划线</strong>，如 <code style="background:#f1f5f9;padding:1px 5px;border-radius:3px;">company_name</code>、<code style="background:#f1f5f9;padding:1px 5px;border-radius:3px;">hotline</code>、<code style="background:#f1f5f9;padding:1px 5px;border-radius:3px;">logo</code></li>
                        <li>不能以数字开头</li>
                        <li>建议使用有意义的英文命名，如 <code style="background:#f1f5f9;padding:1px 5px;border-radius:3px;">site_phone</code>（电话）、<code style="background:#f1f5f9;padding:1px 5px;border-radius:3px;">company_address</code>（地址）</li>
                        <li>修改标识后，前台模板中的调用标签也要同步修改</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    <script>
    function delVar(id) { if (confirm('确定删除？')) { fetch('?act=custom_var&action=delete', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id}).then(r=>r.json()).then(d=>{alert(d.msg);if(d.code==200)location.reload();}); } }
    </script>
    <?php
}

if ($action === 'add' || $action === 'edit') {
    $editData = ['id'=>'','var_name'=>'','var_key'=>'','var_type'=>'text','var_value'=>''];
    if ($action === 'edit' && isset($_GET['id'])) {
        $row = $db->fetch("SELECT * FROM {$db->table('custom_var')} WHERE id = ?", [intval($_GET['id'])]);
        if ($row) $editData = $row;
    }
    $isEdit = $action === 'edit';
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg></div>
                <div><h1><?php echo $isEdit ? '编辑变量' : '添加变量'; ?></h1><p style="font-size:12px;color:var(--gray-500);margin:0;">填写变量信息</p></div>
            </div>
            <div class="page-actions"><a href="?act=custom_var" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <form method="post" action="?act=custom_var&action=save">
            <input type="hidden" name="id" value="<?php echo $editData['id']; ?>">
            <div class="form-section">
                <div class="form-section-header"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg> 变量信息</div>
                <div class="form-section-body">
                    <div class="form-row">
                        <div class="form-group" style="flex:1;">
                            <label>变量名称 <span class="required">*</span></label>
                            <input type="text" name="var_name" class="form-control" value="<?php echo htmlspecialchars($editData['var_name']); ?>" placeholder="如：网站标题" required>
                        </div>
                        <div class="form-group" style="flex:1;">
                            <label>变量标识 <span class="required">*</span></label>
                            <input type="text" name="var_key" class="form-control" value="<?php echo htmlspecialchars($editData['var_key']); ?>" placeholder="如：site_title" <?php echo $isEdit ? 'readonly style="background:#f1f5f9;cursor:not-allowed;"' : ''; ?> required>
                            <?php if ($isEdit): ?><small style="color:#94a3b8;margin-top:4px;display:block;">标识不可修改</small><?php endif; ?>
                        </div>
                        <div class="form-group" style="flex:1;">
                            <label>表单类型 <span class="required">*</span></label>
                            <select name="var_type" id="varTypeSelect" class="form-control" onchange="onVarTypeChange()">
                                <option value="text" <?php echo ($editData['var_type'] ?? 'text') === 'text' ? 'selected' : ''; ?>>单行文本</option>
                                <option value="textarea" <?php echo ($editData['var_type'] ?? '') === 'textarea' ? 'selected' : ''; ?>>多行文本</option>
                                <option value="image" <?php echo ($editData['var_type'] ?? '') === 'image' ? 'selected' : ''; ?>>图片</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group" id="varValueGroup">
                        <label id="varValueLabel">变量值 <span class="required">*</span></label>
                        <input type="text" name="var_value" id="varValueInput" class="form-control" value="<?php echo htmlspecialchars($editData['var_value']); ?>" placeholder="如：芋头CMS官网" required>
                    </div>
                </div>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-success btn-lg">保存</button>
                <a href="?act=custom_var" class="btn btn-secondary btn-lg">取消</a>
            </div>
        </form>
    </div>
    <script>
    function onVarTypeChange() {
        var type = document.getElementById('varTypeSelect').value;
        var group = document.getElementById('varValueGroup');
        var label = document.getElementById('varValueLabel');
        var input = document.getElementById('varValueInput');
        if (type === 'textarea') {
            label.innerHTML = '变量值 <span class="required">*</span>';
            group.innerHTML = label.outerHTML + '<textarea name="var_value" id="varValueInput" class="form-control" rows="5" placeholder="请输入多行文本内容">' + (input ? input.value : '') + '</textarea>';
        } else if (type === 'image') {
            var curVal = input ? input.value : '';
            label.innerHTML = '变量值 <span class="required">*</span>';
            var previewHtml = curVal ? '<div style="margin-top:8px;"><img src="' + curVal + '" style="max-height:80px;border-radius:6px;"></div>' : '';
            group.innerHTML = label.outerHTML +
                '<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">' +
                '<input type="text" name="var_value" id="varValueInput" class="form-control" value="' + curVal + '" placeholder="图片URL或上传">' +
                '<button type="button" class="btn btn-secondary" onclick="uploadVarImage()">上传图片</button>' +
                '</div>' + previewHtml +
                '<input type="file" id="varImageFile" style="display:none;" accept="image/*" onchange="handleVarImageUpload(this)">';
        } else {
            label.innerHTML = '变量值 <span class="required">*</span>';
            group.innerHTML = label.outerHTML + '<input type="text" name="var_value" id="varValueInput" class="form-control" value="' + (input ? input.value : '') + '" placeholder="如：芋头CMS官网" required>';
        }
    }
    function uploadVarImage() { document.getElementById('varImageFile').click(); }
    function handleVarImageUpload(fileInput) {
        var file = fileInput.files[0];
        if (!file) return;
        var fd = new FormData();
        fd.append('file', file);
        fd.append('upload_type', 'image');
        fd.append('csrf_token', '<?php echo rawurlencode(getAdminCsrfToken()); ?>');
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=upload', true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                var res = JSON.parse(xhr.responseText);
                if (res.code === 200) {
                    var url = res.data && res.data.url ? res.data.url : res.url;
                    document.getElementById('varValueInput').value = url;
                    var group = document.getElementById('varValueGroup');
                    var existing = group.querySelector('img');
                    if (existing) existing.remove();
                    var img = document.createElement('img');
                    img.src = url;
                    img.style = 'max-height:80px;border-radius:6px;margin-top:8px;';
                    group.appendChild(img);
                } else {
                    alert(res.msg || '上传失败');
                }
            }
        };
        xhr.send(fd);
    }
    // 初始化
    (function() { onVarTypeChange(); })();
    </script>
    <?php
}
?>
