<?php
ob_start();
require_once __DIR__ . '/../../config.php';

if (!isAdmin()) {
    header('Location: /m/');
    exit;
}

$message = '';
$error = '';

// 处理保存（添加/编辑）
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save') {
    $id = intval($_POST['id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
$type = $_POST['type'] ?? 'user_dashboard';    $position = $_POST['position'] ?? 'banner';
    $priority = intval($_POST['priority'] ?? 0);
    $status = intval($_POST['status'] ?? 1);
    
    if (empty($title) || empty($content)) {
        $error = '标题和内容不能为空';
    } else {
        if ($id > 0) {
            $db->query("UPDATE announcements SET title='$title', content='$content', type='$type', position='$position', priority=$priority, status=$status WHERE id=$id");
            $message = '公告更新成功';
        } else {
            $db->query("INSERT INTO announcements (title, content, type, position, priority, status) VALUES ('$title', '$content', '$type', '$position', $priority, $status)");
            $message = '公告发布成功';
        }
    }
}

// 切换状态
if (isset($_GET['toggle']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $status = intval($_GET['toggle']);
    $db->query("UPDATE announcements SET status = $status WHERE id = $id");
    header('Location: ?page=announcements');
    exit;
}

// 删除公告
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $db->query("DELETE FROM announcements WHERE id = $id");
    header('Location: ?page=announcements');
    exit;
}

// 获取编辑数据
$edit_item = null;
if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $edit_item = $db->fetchOne("SELECT * FROM announcements WHERE id = $edit_id");
}

// 获取公告列表
$type_filter = $_GET['type'] ?? '';
$where = "1=1";
if ($type_filter) {
    $where .= " AND type = '$type_filter'";
}

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

$stats = [
    'total' => $db->fetchOne("SELECT COUNT(*) as cnt FROM announcements")['cnt'],
    'active' => $db->fetchOne("SELECT COUNT(*) as cnt FROM announcements WHERE status = 1")['cnt'],
];

// 类型映射
$type_map = [
    'user_dashboard' => ['name' => '控制台', 'color' => '667eea'],
    'user_register' => ['name' => '注册页面', 'color' => '10b981'],
    'user_buy' => ['name' => '购买页面', 'color' => 'f59e0b'],
    'admin' => ['name' => '管理员后台', 'color' => '8b5cf6'],
];
?>

<?php if ($message): ?>
<div class="card" style="background: #d1fae5; color: #065f46;">
    <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="18" height="18" alt=""> <?php echo $message; ?>
</div>
<?php endif; ?>

<?php if ($error): ?>
<div class="card" style="background: #fef2f2; color: #991b1b;">
    <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="18" height="18" alt=""> <?php echo $error; ?>
</div>
<?php endif; ?>

<?php if ($edit_item || isset($_GET['add'])): ?>
<!-- 添加/编辑表单 -->
<div class="card">
    <h3 style="margin-bottom: 16px; display: flex; align-items: center; gap: 8px;">
        <img src="https://api.iconify.design/mdi:<?php echo $edit_item ? 'pencil' : 'plus'; ?>.svg?color=%23667eea" width="20" height="20" alt="">
        <?php echo $edit_item ? '编辑公告' : '发布公告'; ?>
    </h3>
    
    <form method="POST">
        <input type="hidden" name="action" value="save">
        <input type="hidden" name="id" value="<?php echo $edit_item['id'] ?? 0; ?>">
        
        <div style="margin-bottom: 16px;">
            <label style="display: block; margin-bottom: 6px; font-weight: 500;">标题 *</label>
            <input type="text" name="title" value="<?php echo htmlspecialchars($edit_item['title'] ?? ''); ?>" required 
                   style="width:100%; padding:12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px;" placeholder="请输入公告标题">
        </div>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 16px;">
            <div>
                <label style="display: block; margin-bottom: 6px; font-weight: 500;">类型</label>
<select name="type" style="width:100%; padding:12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px;">
    <option value="user_dashboard" <?php echo (isset($edit_item['type']) && $edit_item['type'] == 'user_dashboard') ? 'selected' : ''; ?>>控制台</option>
    <option value="user_register" <?php echo (isset($edit_item['type']) && $edit_item['type'] == 'user_register') ? 'selected' : ''; ?>>注册页面</option>
    <option value="user_buy" <?php echo (isset($edit_item['type']) && $edit_item['type'] == 'user_buy') ? 'selected' : ''; ?>>购买页面</option>
    <option value="admin" <?php echo (isset($edit_item['type']) && $edit_item['type'] == 'admin') ? 'selected' : ''; ?>>管理员后台</option>
</select>            </div>
            <div>
                <label style="display: block; margin-bottom: 6px; font-weight: 500;">位置</label>
                <select name="position" style="width:100%; padding:12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px;">
                    <option value="banner" <?php echo (isset($edit_item['position']) && $edit_item['position'] == 'banner') ? 'selected' : ''; ?>>横幅</option>
                    <option value="popup" <?php echo (isset($edit_item['position']) && $edit_item['position'] == 'popup') ? 'selected' : ''; ?>>弹窗</option>
                    <option value="sidebar" <?php echo (isset($edit_item['position']) && $edit_item['position'] == 'sidebar') ? 'selected' : ''; ?>>侧边栏</option>
                </select>
            </div>
        </div>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 16px;">
            <div>
                <label style="display: block; margin-bottom: 6px; font-weight: 500;">优先级</label>
                <input type="number" name="priority" value="<?php echo $edit_item['priority'] ?? 0; ?>" 
                       style="width:100%; padding:12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px;">
            </div>
            <div>
                <label style="display: block; margin-bottom: 6px; font-weight: 500;">状态</label>
                <select name="status" style="width:100%; padding:12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px;">
                    <option value="1" <?php echo (isset($edit_item['status']) && $edit_item['status'] == 1) ? 'selected' : ''; ?>>启用</option>
                    <option value="0" <?php echo (isset($edit_item['status']) && $edit_item['status'] == 0) ? 'selected' : ''; ?>>禁用</option>
                </select>
            </div>
        </div>
        
        <div style="margin-bottom: 16px;">
            <label style="display: block; margin-bottom: 6px; font-weight: 500;">内容 *</label>
            <textarea name="content" rows="6" required 
                      style="width:100%; padding:12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px; resize:vertical;" placeholder="支持HTML标签"><?php echo htmlspecialchars($edit_item['content'] ?? ''); ?></textarea>
        </div>
        
        <div style="display: flex; gap: 10px;">
            <button type="submit" class="btn btn-primary" style="flex:1;">
                <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="18" height="18" alt="">
                保存
            </button>
            <a href="?page=announcements" class="btn" style="flex:1; background:#f5f5f5; text-align:center; text-decoration:none; color:#666;">
                <img src="https://api.iconify.design/mdi:close.svg?color=%23666" width="18" height="18" alt="">
                取消
            </a>
        </div>
    </form>
</div>

<?php else: ?>
<!-- 发布按钮和统计 -->
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
    <div style="display: flex; gap: 8px;">
        <div class="card" style="padding: 8px 16px; text-align: center;">
            <div style="font-size: 18px; font-weight: 700;"><?php echo $stats['total']; ?></div>
            <div style="font-size: 11px; color: #999;">总数</div>
        </div>
        <div class="card" style="padding: 8px 16px; text-align: center;">
            <div style="font-size: 18px; font-weight: 700; color: #10b981;"><?php echo $stats['active']; ?></div>
            <div style="font-size: 11px; color: #999;">已启用</div>
        </div>
    </div>
    <a href="?page=announcements&add=1" class="btn btn-primary">
        <img src="https://api.iconify.design/mdi:plus.svg?color=white" width="18" height="18" alt="">
        发布公告
    </a>
</div>

<div style="display: flex; gap: 8px; margin-bottom: 16px;">
    <a href="?page=announcements" class="btn" style="flex:1; background:<?php echo $type_filter==''?'#667eea':'#f5f5f5'; ?>; color:<?php echo $type_filter==''?'white':'#666'; ?>;">全部</a>
    <a href="?page=announcements&type=user_dashboard" class="btn" style="flex:1; background:<?php echo $type_filter=='user_dashboard'?'#667eea':'#f5f5f5'; ?>; color:<?php echo $type_filter=='user_dashboard'?'white':'#666'; ?>;">控制台</a>
    <a href="?page=announcements&type=user_register" class="btn" style="flex:1; background:<?php echo $type_filter=='user_register'?'#667eea':'#f5f5f5'; ?>; color:<?php echo $type_filter=='user_register'?'white':'#666'; ?>;">注册页</a>
    <a href="?page=announcements&type=user_buy" class="btn" style="flex:1; background:<?php echo $type_filter=='user_buy'?'#667eea':'#f5f5f5'; ?>; color:<?php echo $type_filter=='user_buy'?'white':'#666'; ?>;">购买页</a>
</div>

<!-- 公告列表 -->
<?php foreach ($announcements as $item): ?>
<div class="card">
    <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px;">
        <div style="display: flex; align-items: center; gap: 8px;">
            <span style="font-weight: 600;"><?php echo htmlspecialchars($item['title']); ?></span>
            <span style="background: #<?php echo $type_map[$item['type']]['color'] ?? '667eea'; ?>15; color: #<?php echo $type_map[$item['type']]['color'] ?? '667eea'; ?>; padding: 2px 8px; border-radius: 20px; font-size: 11px;">
                <?php echo $type_map[$item['type']]['name'] ?? $item['type']; ?>
            </span>
        </div>
        <span style="padding: 4px 10px; border-radius: 20px; font-size: 12px;
                     <?php echo $item['status'] ? 'background:#d1fae5;color:#065f46;' : 'background:#fee2e2;color:#991b1b;'; ?>">
            <?php echo $item['status'] ? '启用' : '禁用'; ?>
        </span>
    </div>
    
    <p style="font-size: 13px; color: #666; margin-bottom: 10px; line-height: 1.5;">
        <?php echo strip_tags(mb_substr($item['content'], 0, 80)); ?>...
    </p>
    
    <div style="display: flex; gap: 8px; font-size: 12px; color: #999; margin-bottom: 12px;">
        <span>位置: <?php echo $item['position'] == 'banner' ? '横幅' : ($item['position'] == 'popup' ? '弹窗' : '侧边栏'); ?></span>
        <span>优先级: <?php echo $item['priority']; ?></span>
        <span><?php echo date('m-d H:i', strtotime($item['created_at'])); ?></span>
    </div>
    
    <div style="display: flex; gap: 8px;">
        <a href="?page=announcements&edit=<?php echo $item['id']; ?>" style="flex:1; text-align: center; padding: 8px; background: #f5f5f5; border-radius: 8px; text-decoration: none; color: #666;">
            <img src="https://api.iconify.design/mdi:pencil.svg?color=%23666" width="16" height="16" alt=""> 编辑
        </a>
        <a href="?page=announcements&toggle=<?php echo $item['status'] ? 0 : 1; ?>&id=<?php echo $item['id']; ?>" style="flex:1; text-align: center; padding: 8px; background: #f5f5f5; border-radius: 8px; text-decoration: none; color: #666;">
            <?php if ($item['status']): ?>
                <img src="https://api.iconify.design/mdi:eye-off.svg?color=%23ef4444" width="16" height="16" alt=""> 禁用
            <?php else: ?>
                <img src="https://api.iconify.design/mdi:eye.svg?color=%2310b981" width="16" height="16" alt=""> 启用
            <?php endif; ?>
        </a>
        <a href="?page=announcements&delete=<?php echo $item['id']; ?>" onclick="return confirm('确定删除？')" style="flex:1; text-align: center; padding: 8px; background: #fef2f2; border-radius: 8px; text-decoration: none; color: #ef4444;">
            <img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="16" height="16" alt=""> 删除
        </a>
    </div>
</div>
<?php endforeach; ?>

<?php if (empty($announcements)): ?>
<div class="card" style="text-align: center; padding: 40px;">
    <img src="https://api.iconify.design/mdi:bullhorn-outline.svg?color=%23999" width="48" height="48" alt="">
    <p style="color: #999;">暂无公告</p>
</div>
<?php endif; ?>

<?php endif; ?>