<?php
/**
 * 弹窗管理模块 — 图片改为上传 + 只在首页展示
 */
$db = getDB();
$popups = $db->query("SELECT * FROM popups ORDER BY sort_order DESC")->fetchAll();
?>

<div class="toolbar">
    <div class="toolbar-title">弹窗公告管理</div>
    <div class="toolbar-actions">
        <button class="btn-primary" onclick="showPopupModal()"><i class="fas fa-plus"></i> 新增弹窗</button>
    </div>
</div>

<div class="panel-card">
    <table class="data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>标题</th>
                <th>类型</th>
                <th>展示位置</th>
                <th>有效期</th>
                <th>状态</th>
                <th>排序</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($popups as $p): ?>
            <tr>
                <td><?php echo $p['id']; ?></td>
                <td><?php echo htmlspecialchars($p['title']); ?></td>
                <td><?php echo $p['popup_type'] == 1 ? '公告弹窗' : '图片弹窗'; ?></td>
                <td>首页</td>
                <td>
                    <?php
                    if ($p['start_time'] && $p['end_time']) {
                        echo substr($p['start_time'], 0, 10) . ' ~ ' . substr($p['end_time'], 0, 10);
                    } else {
                        echo '不限';
                    }
                    ?>
                </td>
                <td>
                    <span class="status-tag <?php echo $p['is_active'] ? 'active' : 'inactive'; ?>">
                        <?php echo $p['is_active'] ? '启用' : '禁用'; ?>
                    </span>
                </td>
                <td><?php echo $p['sort_order']; ?></td>
                <td>
                    <div class="table-actions">
                        <button class="btn-sm btn-edit" onclick="editPopup(<?php echo $p['id']; ?>)">编辑</button>
                        <button class="btn-sm <?php echo $p['is_active'] ? 'btn-del' : 'btn-edit'; ?>" onclick="togglePopup(<?php echo $p['id']; ?>)">
                            <?php echo $p['is_active'] ? '禁用' : '启用'; ?>
                        </button>
                        <button class="btn-sm btn-del" onclick="deletePopup(<?php echo $p['id']; ?>)">删除</button>
                    </div>
                </td>
            </tr>
        <?php endforeach; ?>
        <?php if (empty($popups)): ?>
            <tr><td colspan="8" style="text-align:center;color:#9ca3af;padding:32px;">暂无弹窗数据</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
</div>

<script>
function showPopupModal(id, title, content, image, type, start, end, active, sort) {
    id = id || 0;
    title = title || '';
    content = content || '';
    image = image || '';
    type = type || 1;
    start = start || '';
    end = end || '';
    active = active || 0;
    sort = sort || 0;
    var isEdit = id > 0;

    var body = '<div class="form-group">' +
        '<label class="form-label">弹窗标题</label>' +
        '<input class="form-input" id="popup_title" value="' + title + '" placeholder="如：系统公告">' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">弹窗类型</label>' +
        '<select class="form-select" id="popup_type">' +
        '<option value="1"' + (type == 1 ? ' selected' : '') + '>公告弹窗</option>' +
        '<option value="2"' + (type == 2 ? ' selected' : '') + '>图片弹窗</option>' +
        '</select>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">弹窗内容</label>' +
        '<textarea class="form-textarea" id="popup_content" placeholder="公告弹窗的文字内容">' + content + '</textarea>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">弹窗图片</label>' +
        '<div style="display:flex;align-items:center;gap:12px;">' +
        '<button class="btn-primary" onclick="uploadPopupImage()" style="font-size:13px;padding:6px 12px;"><i class="fas fa-upload"></i> 上传图片</button>' +
        '<input type="hidden" id="popup_image" value="' + image + '">' +
        '<span id="popup_image_name" style="font-size:13px;color:#6b7280;">' + (image ? '已上传' : '未上传') + '</span>' +
        '</div>' +
        (image ? '<div style="margin-top:8px;"><img src="' + image + '" style="max-width:200px;max-height:120px;border-radius:8px;border:1px solid #e5e7eb;"></div>' : '') +
        '<div class="form-hint">图片弹窗必须上传图片，仅支持 jpg/png 格式</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">展示位置</label>' +
        '<input class="form-input" value="首页" readonly style="background:#f3f4f6;cursor:not-allowed;">' +
        '<div class="form-hint">弹窗公告仅在首页展示</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">开始时间</label>' +
        '<input class="form-input" id="popup_start" type="datetime-local" value="' + start + '" step="60">' +
        '<div class="form-hint">精确到分钟即可，如 2024-06-15 10:00</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">结束时间</label>' +
        '<input class="form-input" id="popup_end" type="datetime-local" value="' + end + '" step="60">' +
        '<div class="form-hint">精确到分钟即可，如 2024-06-15 18:00</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">启用状态</label>' +
        '<label class="switch"><input type="checkbox" id="popup_active" ' + (active ? 'checked' : '') + '><span class="slider"></span></label>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">排序权重</label>' +
        '<input class="form-input" id="popup_sort" type="number" value="' + sort + '">' +
        '</div>';

    showModal(isEdit ? '编辑弹窗' : '新增弹窗', body,
        '<button class="btn-secondary" onclick="closeModal()">取消</button>' +
        '<button class="btn-primary" onclick="savePopup(' + id + ')">保存</button>');
}

// 上传弹窗图片
function uploadPopupImage() {
    var input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/jpeg,image/png';
    input.onchange = function(e) {
        var file = e.target.files[0];
        if (!file) return;
        if (file.size > 2 * 1024 * 1024) {
            showToast('图片大小不能超过2MB', 'error');
            return;
        }
        var formData = new FormData();
        formData.append('action', 'upload_image');
        formData.append('file', file);
        formData.append('type', 'popup');

        fetch('<?php echo SITE_URL; ?>/admin/api.php', {
            method: 'POST',
            body: formData
        })
        .then(function(res) {
            return res.text().then(function(text) {
                try { return JSON.parse(text); }
                catch(e) { throw new Error('服务器响应异常'); }
            });
        })
        .then(function(result) {
            if (result.code === 1) {
                document.getElementById('popup_image').value = result.data.url;
                document.getElementById('popup_image_name').textContent = '已上传: ' + file.name;
                showToast('图片上传成功', 'success');
            } else {
                showToast(result.msg || '上传失败', 'error');
            }
        })
        .catch(function(err) {
            showToast(err.message || '上传失败', 'error');
        });
    };
    input.click();
}

function editPopup(id) {
    apiRequest('get_popup', {id: id}, function(res) {
        if (res.code === 1) {
            var d = res.data;
            var startVal = d.start_time ? d.start_time.substring(0, 16) : '';
            var endVal = d.end_time ? d.end_time.substring(0, 16) : '';
            showPopupModal(d.id, d.title, d.content, d.image, d.popup_type, startVal, endVal, d.is_active, d.sort_order);
        } else {
            showToast(res.msg, 'error');
        }
    });
}

function savePopup(id) {
    var title = document.getElementById('popup_title').value;
    var content = document.getElementById('popup_content').value;
    var image = document.getElementById('popup_image').value;
    var type = document.getElementById('popup_type').value;
    var start = document.getElementById('popup_start').value;
    var end = document.getElementById('popup_end').value;
    var active = document.getElementById('popup_active').checked ? 1 : 0;
    var sort = document.getElementById('popup_sort').value;

    if (!title) { showToast('请输入弹窗标题', 'error'); return; }
    if (type == 2 && !image) { showToast('图片弹窗必须上传图片', 'error'); return; }

    apiRequest(id > 0 ? 'update_popup' : 'create_popup', {
        id: id, title: title, content: content, image: image,
        popup_type: type, show_pages: 'home', start_time: start, end_time: end,
        is_active: active, sort_order: sort
    }, function(res) {
        if (res.code === 1) {
            showToast(res.msg, 'success');
            setTimeout(function() { location.reload(); }, 500);
        } else {
            showToast(res.msg, 'error');
        }
    });
}

function togglePopup(id) {
    apiRequest('toggle_popup', {id: id}, function(res) {
        if (res.code === 1) {
            showToast(res.msg, 'success');
            setTimeout(function() { location.reload(); }, 500);
        } else {
            showToast(res.msg, 'error');
        }
    });
}

function deletePopup(id) {
    window._deletePopupId = id;
    confirmAction('确认删除该弹窗？', 'doDeletePopup');
}

function doDeletePopup() {
    apiRequest('delete_popup', {id: window._deletePopupId}, function(res) {
        if (res.code === 1) {
            showToast(res.msg, 'success');
            setTimeout(function() { location.reload(); }, 500);
        } else {
            showToast(res.msg, 'error');
        }
    });
}
</script>
