<?php
require_once __DIR__ . '/../MPHX/common.php';

if (!is_admin_login()) {
    header('Location: /admin/login.php');
    exit;
}

$egn = isset($_GET['egn']) ? $_GET['egn'] : '';
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>公告管理 - 宝塔主机管理系统</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/all.min.css">
    <link rel="stylesheet" href="css/style.css?v=2026040501">
</head>
<body>
    <?php
    // 生成CSRF Token
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    $csrf_token = $_SESSION['csrf_token'];
    ?>
    <input type="hidden" id="csrf_token" value="<?php echo $csrf_token; ?>">
    <div class="content-area">
        <div class="card">
            <h3><i class="fas fa-bullhorn"></i> 发布公告</h3>
            <form id="announcementForm">
                <input type="hidden" name="edit_id" id="edit_id" value="">
                <div class="form-group">
                    <label for="title">公告标题</label>
                    <input type="text" name="title" id="title" class="form-control" placeholder="请输入公告标题" required>
                </div>
                <div class="form-group">
                    <label for="target_type">目标用户</label>
                    <select name="target_type" id="target_type" class="form-control" onchange="toggleTargetSelect()">
                        <option value="all">所有用户</option>
                        <option value="bt_server">指定IP（宝塔服务器）</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="category">公告分类</label>
                    <select name="category" id="category" class="form-control">
                        <option value="general">通用公告</option>
                        <option value="maintenance">维护公告</option>
                        <option value="update">更新公告</option>
                        <option value="important">重要公告</option>
                        <option value="activity">活动公告</option>
                    </select>
                </div>
                <div class="form-group" id="target_bt_div" style="display: none;">
                    <label for="target_bt">选择宝塔服务器</label>
                    <select name="target_bt" id="target_bt" class="form-control">
                        <option value="">请选择宝塔服务器</option>
                        <?php
                        $bts = $DB->query("SELECT * FROM `bt` ORDER BY ip");
                        while ($bt = $DB->fetch($bts)) {
                            echo '<option value="' . $bt['id'] . '">' . htmlspecialchars($bt['ip']) . ' (' . htmlspecialchars($bt['czzt']) . ')</option>';
                        }
                        ?>
                    </select>
                    <small>该宝塔服务器下的所有用户都将收到此公告</small>
                </div>
                <div class="form-group">
                    <label for="content">公告内容</label>
                    <textarea name="content" id="content" rows="6" class="form-control" placeholder="请输入公告内容" required></textarea>
                </div>
                <div class="form-group">
                    <label>公告状态</label>
                    <div style="display: flex; align-items: center; gap: 8px;">
                        <input type="checkbox" id="is_active" name="is_active" checked style="width: auto;">
                        <label for="is_active" style="margin: 0; font-weight: 400;">立即发布</label>
                    </div>
                </div>
                <button type="button" class="btn btn-primary" id="submitBtn" onclick="publishAnnouncement(this)">
                    <i class="fas fa-paper-plane"></i> 发布公告
                </button>
                <button type="button" class="btn btn-secondary" id="cancelBtn" onclick="resetForm()" style="display: none; margin-left: 10px;">
                    <i class="fas fa-times"></i> 取消编辑
                </button>
            </form>
        </div>

        <div class="card" style="margin-top: 20px;">
            <h3><i class="fas fa-list"></i> 公告列表</h3>
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>标题</th>
                            <th>分类</th>
                            <th>目标用户类型</th>
                            <th>目标用户</th>
                            <th>已读/未读</th>
                            <th>发布时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="announcementList">
                        <?php
                        // 获取公告数据 - 只获取公告模板（user_id=0）
                        $notifications = $DB->query("SELECT * FROM `notifications` WHERE type='announcement' AND user_id=0 ORDER BY `create_time` DESC LIMIT 50");
                        while ($notif = $DB->fetch($notifications)) {
                            $notif_id = $notif['id'];
                            $title = $notif['title'];
                            $content = $notif['content'];
                            $target_type = isset($notif['target_type']) ? $notif['target_type'] : 'all';
                            $target_bt = isset($notif['target_bt']) ? intval($notif['target_bt']) : 0;
                            
                            // 根据target_type获取目标用户数
                            if ($target_type == 'bt_server' && $target_bt > 0) {
                                $zj_result = $DB->query("SELECT id FROM `zj` WHERE btid=" . $target_bt);
                                $total_users = $DB->num_rows($zj_result);
                                // 获取宝塔服务器IP
                                $bt_info = $DB->get_row("SELECT ip FROM `bt` WHERE id=" . $target_bt);
                                $target_display = isset($bt_info['ip']) ? htmlspecialchars($bt_info['ip']) : '指定用户';
                            } else {
                                $zj_result = $DB->query("SELECT id FROM `zj`");
                                $total_users = $DB->num_rows($zj_result);
                                $target_display = '所有用户';
                            }
                            
                            // 计算已读和未读人数 - 通过title+content匹配所有用户记录（排除模板user_id=0）
                            $read_result = $DB->query("SELECT id FROM `notifications` WHERE title='" . addslashes($title) . "' AND content='" . addslashes($content) . "' AND is_read=1 AND user_id > 0");
                            $read_count = $DB->num_rows($read_result);
                            $unread_result = $DB->query("SELECT id FROM `notifications` WHERE title='" . addslashes($title) . "' AND content='" . addslashes($content) . "' AND is_read=0 AND user_id > 0");
                            $unread_count = $DB->num_rows($unread_result);
                            
                            // 分类映射
                            $category_map = array(
                                'general' => '<span class="badge badge-info">通用</span>',
                                'maintenance' => '<span class="badge badge-warning">维护</span>',
                                'update' => '<span class="badge badge-primary">更新</span>',
                                'important' => '<span class="badge badge-danger">重要</span>',
                                'activity' => '<span class="badge badge-success">活动</span>'
                            );
                            $category_display = isset($category_map[$notif['category']]) ? $category_map[$notif['category']] : '<span class="badge badge-secondary">'.htmlspecialchars($notif['category']).'</span>';
                        ?>
                        <tr>
                            <td><?php echo intval($notif_id); ?></td>
                            <td><?php echo htmlspecialchars($notif['title']); ?></td>
                            <td><?php echo $category_display; ?></td>
                            <td><?php echo $target_type == 'bt_server' ? '指定服务器' : '所有用户'; ?></td>
                            <td><?php echo $target_display; ?></td>
                            <td>
                                <span class="badge badge-success">已读: <?php echo $read_count; ?></span>
                                <span class="badge badge-warning" style="margin-left: 5px;">未读: <?php echo $unread_count; ?></span>
                                <br><small style="color: #999;">共 <?php echo $total_users; ?> 人</small>
                            </td>
                            <td><?php echo htmlspecialchars($notif['create_time']); ?></td>
                            <td>
                                <button class="btn btn-primary btn-sm edit-btn" data-id="<?php echo $notif_id; ?>" data-title="<?php echo htmlspecialchars($notif['title'], ENT_QUOTES); ?>" data-content="<?php echo htmlspecialchars($notif['content'], ENT_QUOTES); ?>" data-category="<?php echo htmlspecialchars($notif['category']); ?>">
                                    <i class="fas fa-edit"></i> 编辑
                                </button>
                                <button class="btn btn-danger btn-sm delete-btn" data-id="<?php echo $notif_id; ?>" data-title="<?php echo htmlspecialchars($notif['title'], ENT_QUOTES); ?>" data-content="<?php echo htmlspecialchars($notif['content'], ENT_QUOTES); ?>" data-btn="this">
                                    <i class="fas fa-trash-alt"></i> 删除
                                </button>
                            </td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 编辑公告模态框 -->
    <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel">编辑公告</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="editForm">
                        <input type="hidden" name="edit_id" id="edit_id" value="">
                        <div class="form-group">
                            <label for="edit_title">公告标题</label>
                            <input type="text" name="edit_title" id="edit_title" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label for="edit_category">公告分类</label>
                            <select name="edit_category" id="edit_category" class="form-control">
                                <option value="general">通用公告</option>
                                <option value="maintenance">维护公告</option>
                                <option value="update">更新公告</option>
                                <option value="important">重要公告</option>
                                <option value="activity">活动公告</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="edit_content">公告内容</label>
                            <textarea name="edit_content" id="edit_content" rows="5" class="form-control" required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="saveEditAnnouncement()">保存修改</button>
                </div>
            </div>
        </div>
    </div>

    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/bootstrap.bundle.min.js"></script>
    <script>
    function toggleTargetSelect() {
        var targetType = $('#target_type').val();
        if (targetType == 'bt_server') {
            $('#target_bt_div').show();
        } else {
            $('#target_bt_div').hide();
        }
    }

    function resetForm() {
        $('#announcementForm')[0].reset();
        $('#edit_id').val('');
        $('#submitBtn').html('<i class="fas fa-paper-plane"></i> 发布公告');
        $('#cancelBtn').hide();
    }

    function publishAnnouncement(btn) {
        var title = $('#title').val();
        var content = $('#content').val();
        var category = $('#category').val();
        var targetType = $('#target_type').val();
        var targetBt = $('#target_bt').val();
        var isActive = $('#is_active').is(':checked') ? 'true' : 'false';
        var csrfToken = $('#csrf_token').val();

        if (!title || !content) {
            alert('请填写公告标题和内容');
            return;
        }

        if (targetType == 'bt_server' && !targetBt) {
            alert('请选择宝塔服务器');
            return;
        }

        var $btn = $(btn);
        var originalText = $btn.html();
        $btn.addClass('btn-loading').prop('disabled', true);

        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: {
                egn: 'publish_announcement',
                title: title,
                content: content,
                category: category,
                target_type: targetType,
                target_bt: targetBt,
                is_active: isActive,
                csrf_token: csrfToken
            },
            dataType: 'json',
            success: function(data) {
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                alert(data.msg);
                if (data.code == 1) {
                    location.reload();
                }
            },
            error: function() {
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                alert('操作失败，请重试');
            }
        });
    }

    $(document).ready(function() {
        // 编辑按钮点击事件
        $(document).on('click', '.edit-btn', function() {
            var id = $(this).data('id');
            var title = $(this).data('title');
            var content = $(this).data('content');
            var category = $(this).data('category') || 'general';
            $('#edit_id').val(id);
            $('#edit_title').val(title);
            $('#edit_category').val(category);
            $('#edit_content').val(content);
            $('#editModal').modal('show');
        });

        // 删除按钮点击事件
        $(document).on('click', '.delete-btn', function() {
            var id = $(this).data('id');
            var title = $(this).data('title');
            var content = $(this).data('content');
            var btn = this;
            var csrfToken = $('#csrf_token').val();
            
            if (!confirm('确定要删除这个公告吗？删除后所有用户都将看不到此公告。')) {
                return;
            }

            var $btn = $(btn);
            var originalText = $btn.html();
            $btn.addClass('btn-loading').prop('disabled', true);

            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {
                    egn: 'delete_announcement',
                    id: id,
                    title: title,
                    content: content,
                    csrf_token: csrfToken
                },
                dataType: 'json',
                success: function(data) {
                    $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    alert(data.msg);
                    if (data.code == 1) {
                        location.reload();
                    }
                },
                error: function() {
                    $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    alert('操作失败，请重试');
                }
            });
        });
    });

    function editAnnouncement(data) {
        $('#edit_id').val(data.id);
        $('#edit_title').val(data.title);
        $('#edit_content').val(data.content);
        $('#editModal').modal('show');
    }

    function saveEditAnnouncement() {
        var id = $('#edit_id').val();
        var title = $('#edit_title').val();
        var category = $('#edit_category').val();
        var content = $('#edit_content').val();
        var csrfToken = $('#csrf_token').val();

        if (!title || !content) {
            alert('请填写公告标题和内容');
            return;
        }

        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: {
                egn: 'edit_announcement',
                id: id,
                title: title,
                category: category,
                content: content,
                csrf_token: csrfToken
            },
            dataType: 'json',
            success: function(data) {
                alert(data.msg);
                if (data.code == 1) {
                    $('#editModal').modal('hide');
                    location.reload();
                }
            },
            error: function() {
                alert('操作失败，请重试');
            }
        });
    }

    </script>
</body>
</html>
