<?php
require_once 'config.php';

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

if ($method === 'POST') {
    if (!isset($input['announcement_id']) || !isset($input['user_id']) || !isset($input['reaction'])) {
        jsonResponse(['error' => 'Missing required fields'], 400);
    }
    
    $pdo = getDB();
    
    $stmt = $pdo->prepare("SELECT * FROM announcement_reactions WHERE announcement_id = ? AND user_id = ?");
    $stmt->execute([$input['announcement_id'], $input['user_id']]);
    
    if ($stmt->fetch()) {
        $stmt = $pdo->prepare("UPDATE announcement_reactions SET reaction = ? WHERE announcement_id = ? AND user_id = ?");
        $stmt->execute([$input['reaction'], $input['announcement_id'], $input['user_id']]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO announcement_reactions (announcement_id, user_id, reaction) VALUES (?, ?, ?)");
        $stmt->execute([$input['announcement_id'], $input['user_id'], $input['reaction']]);
    }
    
    jsonResponse(['success' => true, 'message' => 'Reaction updated']);
}
?>