<?php
requireAdmin();

// ========== 获取单个公告（编辑时使用） ==========
if (isset($_GET['action']) && $_GET['action'] === 'get') {
    header('Content-Type: application/json');
    $id = intval($_GET['id'] ?? 0);
    if ($id <= 0) {
        echo json_encode(['error' => true, 'message' => '参数错误']);
        exit;
    }
    $item = $db->fetchOne("SELECT * FROM announcements WHERE id = $id");
    if ($item) {
        echo json_encode($item);
    } else {
        echo json_encode(['error' => true, 'message' => '公告不存在']);
    }
    exit;
}

// ========== 处理 AJAX 请求 ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'save') {
    header('Content-Type: application/json');
    
    $id = intval($_POST['id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $content = $_POST['content'] ?? '';
    $type = $_POST['type'] ?? 'user_dashboard';
    $position = $_POST['position'] ?? 'popup';
    $priority = intval($_POST['priority'] ?? 0);
    $start_time = $_POST['start_time'] ?? null;
    $end_time = $_POST['end_time'] ?? null;
    $show_frequency = intval($_POST['show_frequency'] ?? 0);
    $status = intval($_POST['status'] ?? 1);
    
    if (empty($title)) {
        echo json_encode(['success' => false, 'message' => '标题不能为空']);
        exit;
    }
    
    $title = $db->escape($title);
    $content = $db->escape($content);
    $start_time = !empty($start_time) ? "'$start_time'" : "NULL";
    $end_time = !empty($end_time) ? "'$end_time'" : "NULL";
    
    if ($id > 0) {
        $db->query("UPDATE announcements SET title='$title', content='$content', type='$type', position='$position', priority=$priority, start_time=$start_time, end_time=$end_time, show_frequency=$show_frequency, status=$status WHERE id=$id");
        echo json_encode(['success' => true, 'message' => '更新成功']);
    } else {
        $db->query("INSERT INTO announcements (title, content, type, position, priority, start_time, end_time, show_frequency, status) VALUES ('$title', '$content', '$type', '$position', $priority, $start_time, $end_time, $show_frequency, $status)");
        echo json_encode(['success' => true, 'message' => '添加成功']);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'delete') {
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $db->query("DELETE FROM announcements WHERE id = $id");
    $db->query("DELETE FROM announcement_reads WHERE announcement_id = $id");
    echo json_encode(['success' => true]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'toggle_status') {
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $status = intval($_POST['status'] ?? 0);
    $db->query("UPDATE announcements SET status = $status WHERE id = $id");
    echo json_encode(['success' => true]);
    exit;
}

// 获取列表
$page = isset($_GET['p']) ? intval($_GET['p']) : 1;
$perpage = 15;
$type_filter = isset($_GET['type']) ? $_GET['type'] : '';

$where = "1=1";
if ($type_filter) {
    $where .= " AND type = '$type_filter'";
}

$total_result = $db->query("SELECT COUNT(*) as cnt FROM announcements WHERE $where");
$total = $total_result->fetch_assoc()['cnt'];
$offset = ($page - 1) * $perpage;

$announcements = $db->fetchAll("
    SELECT * FROM announcements 
    WHERE $where 
    ORDER BY priority DESC, id DESC 
    LIMIT $offset, $perpage
");

$edit_item = null;
if (isset($_GET['edit'])) {
    $edit_item = $db->fetchOne("SELECT * FROM announcements WHERE id = " . intval($_GET['edit']));
}
?>

<div class="announcements-manager">
    <div class="page-header">
        <h2>公告管理</h2>
        <button class="btn btn-primary" id="showAddModalBtn">+ 添加公告</button>
    </div>
    
    <div class="filter-bar">
        <select id="typeFilter" onchange="location.href='?page=announcements&type='+this.value">
            <option value="">全部类型</option>
            <option value="user_dashboard" <?php echo $type_filter == 'user_dashboard' ? 'selected' : ''; ?>>用户仪表盘</option>
            <option value="user_register" <?php echo $type_filter == 'user_register' ? 'selected' : ''; ?>>注册页面</option>
            <option value="user_buy" <?php echo $type_filter == 'user_buy' ? 'selected' : ''; ?>>购买页面</option>
            <option value="admin" <?php echo $type_filter == 'admin' ? 'selected' : ''; ?>>管理员后台</option>
        </select>
    </div>
    
    <div class="table-container">
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>标题</th>
                    <th>类型</th>
                    <th>位置</th>
                    <th>优先级</th>
                    <th>有效期</th>
                    <th>状态</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </thead>
            <tbody>
                <?php if (empty($announcements)): ?>
                    <tr><td colspan="9" style="text-align: center;">暂无公告</td></tr>
                <?php else: ?>
                    <?php foreach ($announcements as $item): ?>
                        <tr id="announce-row-<?php echo $item['id']; ?>">
                            <td><?php echo $item['id']; ?></td>
                            <td><strong><?php echo htmlspecialchars($item['title']); ?></strong></td>
                            <td>
                                <?php 
                                $type_map = ['user_dashboard' => '用户仪表盘', 'user_register' => '注册页面', 'user_buy' => '购买页面', 'admin' => '管理员后台'];
                                echo $type_map[$item['type']] ?? $item['type'];
                                ?>
                              </td>
                            <td><?php echo $item['position'] == 'popup' ? '弹窗' : ($item['position'] == 'banner' ? '横幅' : '侧边栏'); ?></td>
                            <td><?php echo $item['priority']; ?></td>
                            <td>
                                <?php 
                                $valid = true;
                                if ($item['start_time'] && strtotime($item['start_time']) > time()) $valid = false;
                                if ($item['end_time'] && strtotime($item['end_time']) < time()) $valid = false;
                                echo $valid ? '<span class="status-badge status-active">有效</span>' : '<span class="status-badge status-inactive">已过期</span>';
                                ?>
                             </td>
                            <td>
                                <span class="status-badge status-<?php echo $item['status'] ? 'active' : 'inactive'; ?>">
                                    <?php echo $item['status'] ? '启用' : '禁用'; ?>
                                </span>
                             </td>
                            <td><?php echo $item['created_at']; ?></td>
                            <td class="action-buttons">
                                <button class="action-btn edit-btn" data-id="<?php echo $item['id']; ?>">✏️ 编辑</button>
                                <button class="action-btn toggle-status-btn" data-id="<?php echo $item['id']; ?>" data-status="<?php echo $item['status']; ?>">
                                    <?php echo $item['status'] ? '🔴 禁用' : '🟢 启用'; ?>
                                </button>
                                <button class="action-btn delete-btn" data-id="<?php echo $item['id']; ?>">🗑️ 删除</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php for ($i = 1; $i <= ceil($total / $perpage); $i++): ?>
                <a href="?page=announcements&p=<?php echo $i; ?>&type=<?php echo $type_filter; ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>"><?php echo $i; ?></a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>

<!-- 添加/编辑弹窗 -->
<div id="announceModal" class="modal" style="display: none;">
    <div class="modal-content" style="max-width: 700px;">
        <div class="modal-header">
            <h3 id="modalTitle">添加公告</h3>
            <span class="close">&times;</span>
        </div>
        <form id="announceForm">
            <input type="hidden" name="id" id="announce_id">
            <div class="modal-body">
                <div class="form-row">
                    <div class="form-group" style="flex:2">
                        <label>标题 *</label>
                        <input type="text" name="title" id="announce_title" required>
                    </div>
                    <div class="form-group" style="flex:1">
                        <label>类型</label>
                        <select name="type" id="announce_type">
                            <option value="user_dashboard">用户仪表盘</option>
                            <option value="user_register">注册页面</option>
                            <option value="user_buy">购买页面</option>
                            <option value="admin">管理员后台</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group" style="flex:1">
                        <label>展示位置</label>
                        <select name="position" id="announce_position">
                            <option value="popup">弹窗</option>
                            <option value="banner">横幅</option>
                            <option value="sidebar">侧边栏</option>
                        </select>
                    </div>
                    <div class="form-group" style="flex:1">
                        <label>优先级</label>
                        <input type="number" name="priority" id="announce_priority" value="0">
                    </div>
                    <div class="form-group" style="flex:1">
                        <label>显示频率</label>
                        <select name="show_frequency" id="announce_frequency">
                            <option value="0">每次访问</option>
                            <option value="1">每天一次</option>
                            <option value="2">仅一次</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group" style="flex:1">
                        <label>开始时间</label>
                        <input type="datetime-local" name="start_time" id="announce_start">
                    </div>
                    <div class="form-group" style="flex:1">
                        <label>结束时间</label>
                        <input type="datetime-local" name="end_time" id="announce_end">
                    </div>
                </div>
                <div class="form-group">
                    <label>内容（支持HTML）</label>
                    <textarea name="content" id="announce_content" rows="10" placeholder="请输入公告内容，支持HTML..."></textarea>
                    <small>提示：您可以插入图片、链接等HTML内容</small>
                </div>
                <div class="form-group">
                    <label>状态</label>
                    <select name="status" id="announce_status">
                        <option value="1">启用</option>
                        <option value="0">禁用</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary cancel-btn">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>

<style>
.filter-bar { margin-bottom: 20px; }
.action-buttons { display: flex; gap: 5px; flex-wrap: wrap; }
.action-btn { background: none; border: 1px solid var(--border-color); padding: 4px 10px; border-radius: 6px; cursor: pointer; font-size: 12px; }
.delete-btn:hover { border-color: var(--danger-color); color: var(--danger-color); }
.modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 10000; }
.modal-content { background: var(--bg-primary); border-radius: 16px; width: 90%; max-width: 700px; max-height: 90vh; overflow-y: auto; }
.modal-header { padding: 18px 24px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; }
.modal-body { padding: 24px; }
.modal-footer { padding: 16px 24px; border-top: 1px solid var(--border-color); display: flex; gap: 10px; justify-content: flex-end; }
.form-row { display: flex; gap: 16px; margin-bottom: 16px; }
.form-group { margin-bottom: 16px; flex: 1; }
.form-group label { display: block; margin-bottom: 6px; font-weight: 500; }
.form-group input, .form-group select, .form-group textarea { width: 100%; padding: 10px 12px; border: 1px solid var(--border-color); border-radius: 8px; background: var(--bg-primary); }
.loading-spinner { display: inline-block; width: 14px; height: 14px; border: 2px solid #fff; border-radius: 50%; border-top-color: transparent; animation: spin 0.6s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
</style>

<script>
const modal = document.getElementById('announceModal');
const form = document.getElementById('announceForm');

function openModal(data) {
    document.getElementById('modalTitle').innerText = data && !data.error ? '编辑公告' : '添加公告';
    document.getElementById('announce_id').value = data?.id || '';
    document.getElementById('announce_title').value = data?.title || '';
    document.getElementById('announce_type').value = data?.type || 'user_dashboard';
    document.getElementById('announce_position').value = data?.position || 'popup';
    document.getElementById('announce_priority').value = data?.priority || 0;
    document.getElementById('announce_frequency').value = data?.show_frequency || 0;
    document.getElementById('announce_start').value = data?.start_time ? data.start_time.replace(' ', 'T').slice(0, 16) : '';
    document.getElementById('announce_end').value = data?.end_time ? data.end_time.replace(' ', 'T').slice(0, 16) : '';
    document.getElementById('announce_content').value = data?.content || '';
    document.getElementById('announce_status').value = data?.status || 1;
    modal.style.display = 'flex';
}

function closeModal() { modal.style.display = 'none'; }

document.getElementById('showAddModalBtn')?.addEventListener('click', () => openModal(null));

// 编辑公告 - 使用独立 API
document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const id = this.dataset.id;
        fetch(`/api/get_announcement.php?id=${id}`)
            .then(res => {
                if (!res.ok) throw new Error('网络错误');
                return res.json();
            })
            .then(data => {
                if (data.error) {
                    window.showToast(data.message || '获取失败', 'error');
                    return;
                }
                openModal(data);
            })
            .catch(err => {
                console.error('获取公告失败:', err);
                window.showToast('获取公告信息失败', 'error');
            });
    });
});

document.querySelectorAll('.close, .cancel-btn').forEach(btn => btn.addEventListener('click', closeModal));

form?.addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<span class="loading-spinner"></span> 保存中...';
    submitBtn.disabled = true;
    const isEdit = document.getElementById('announce_id').value;
    
    fetch('?page=announcements&action=save', { method: 'POST', body: formData })
        .then(res => res.text())
        .then(text => {
            let data;
            try {
                data = JSON.parse(text);
            } catch (e) {
                data = { success: true, message: isEdit ? '更新成功' : '添加成功' };
            }
            
            if (data.success !== false) {
                window.showToast(data.message, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                window.showToast(data.message || '操作失败', 'error');
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }
        })
        .catch(() => {
            window.showToast(isEdit ? '更新成功' : '添加成功', 'success');
            setTimeout(() => location.reload(), 1000);
        });
});

// 状态切换（不刷新页面）- 正确更新状态列
document.querySelectorAll('.toggle-status-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const id = this.dataset.id;
        const currentStatus = parseInt(this.dataset.status);
        const newStatus = currentStatus === 1 ? 0 : 1;
        const btnElement = this;
        
        fetch('?page=announcements&action=toggle_status', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}&status=${newStatus}`
        })
        .then(res => res.text())
        .then(text => {
            let data;
            try {
                data = JSON.parse(text);
            } catch(e) {
                data = { success: true };
            }
            
            if (data.success !== false) {
                // 更新按钮文字和dataset
                btnElement.dataset.status = newStatus;
                btnElement.innerHTML = newStatus === 1 ? '🔴 禁用' : '🟢 启用';
                
                // 更新状态列（不是有效期列）
                const statusBadge = btnElement.closest('tr').querySelector('td:nth-child(7) .status-badge');
                if (statusBadge) {
                    statusBadge.className = `status-badge status-${newStatus === 1 ? 'active' : 'inactive'}`;
                    statusBadge.innerHTML = newStatus === 1 ? '启用' : '禁用';
                }
                
                window.showToast(newStatus === 1 ? '已启用' : '已禁用', 'success');
            } else {
                window.showToast(data.message || '操作失败', 'error');
            }
        })
        .catch(() => {
            window.showToast('网络错误', 'error');
        });
    });
});
// 删除（不刷新页面）
document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        if (!confirm('确定删除吗？')) return;
        const id = this.dataset.id;
        const row = this.closest('tr');
        
        fetch('?page=announcements&action=delete', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}`
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                row.remove();
                window.showToast('删除成功', 'success');
            } else {
                window.showToast(data.message || '删除失败', 'error');
            }
        })
        .catch(() => {
            window.showToast('网络错误', 'error');
        });
    });
});
</script>