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

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

$type = $_GET['type'] ?? '';
$user_id = $_SESSION['user_id'] ?? 0;

if (empty($type)) {
    echo json_encode(['success' => false, 'message' => '参数错误']);
    exit;
}

$now = date('Y-m-d H:i:s');
$today = date('Y-m-d');

// 获取有效公告
$announcements = $db->fetchAll("
    SELECT * FROM announcements 
    WHERE type = '$type' 
    AND status = 1 
    AND (start_time IS NULL OR start_time <= '$now')
    AND (end_time IS NULL OR end_time >= '$now')
    ORDER BY priority DESC, id DESC
");

$result = [];
foreach ($announcements as $item) {
    // 检查用户是否已读
    $read = $db->fetchOne("SELECT id FROM announcement_reads WHERE announcement_id = {$item['id']} AND user_id = $user_id");
    
    $show = true;
    if ($user_id > 0 && $read) {
        // 根据显示频率判断
        if ($item['show_frequency'] == 2) {
            $show = false; // 仅一次，已读过
        } elseif ($item['show_frequency'] == 1 && $read) {
            // 每天一次，检查今天是否已读
            $today_read = $db->fetchOne("SELECT id FROM announcement_reads WHERE announcement_id = {$item['id']} AND user_id = $user_id AND DATE(read_at) = '$today'");
            if ($today_read) $show = false;
        }
    }
    
    if ($show) {
        $result[] = $item;
    }
}

echo json_encode(['success' => true, 'data' => $result]);
?>