<?php
require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

if ($method === 'POST') {
    if (!isset($input['group_id']) || !isset($input['content']) || !isset($input['created_by'])) {
        jsonResponse(['error' => 'Missing required fields'], 400);
    }
    
    $pdo = getDB();
    $stmt = $pdo->prepare("INSERT INTO group_announcements (group_id, content, created_by) VALUES (?, ?, ?)");
    $stmt->execute([$input['group_id'], $input['content'], $input['created_by']]);
    
    $announcementId = $pdo->lastInsertId();
    jsonResponse(['success' => true, 'announcement_id' => $announcementId], 201);
}

if ($method === 'GET') {
    if (!isset($_GET['group_id'])) {
        jsonResponse(['error' => 'Group ID required'], 400);
    }
    
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT a.*, u.first_name, u.last_name, u.username, u.profile_photo, 
        (SELECT COUNT(*) FROM announcement_reactions WHERE announcement_id = a.id AND reaction = 'thumbs_up') as thumbs_up,
        (SELECT COUNT(*) FROM announcement_reactions WHERE announcement_id = a.id AND reaction = 'thumbs_down') as thumbs_down
        FROM group_announcements a 
        INNER JOIN users u ON a.created_by = u.id 
        WHERE a.group_id = ? 
        ORDER BY a.created_at DESC");
    $stmt->execute([$_GET['group_id']]);
    $announcements = $stmt->fetchAll();
    
    jsonResponse(['success' => true, 'announcements' => $announcements]);
}
?>