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

header('Content-Type: application/json');

// 检查登录状态
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

// 检查权限
$user = currentUser();
if ($user['role'] !== 'admin' && $user['role'] !== 'employee') {
    echo json_encode(['success' => false, 'message' => '权限不足']);
    exit;
}

// 获取参数
$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_sql = !empty($start_time) ? "'$start_time'" : "NULL";
$end_time_sql = !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_sql, 
        end_time=$end_time_sql, 
        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_sql, $end_time_sql, $show_frequency, $status)");
    echo json_encode(['success' => true, 'message' => '添加成功']);
}
exit;