<?php
// Allow CORS

// Include the reusable CORS handler
require_once __DIR__ . '/cors.php';


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

require_once __DIR__ . '/db.php'; // Make sure this sets $pdo


$data = json_decode(file_get_contents('php://input'), true);

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        $stmt = $pdo->query("SELECT * FROM announcements ORDER BY created_at DESC");
        echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
        break;

    case 'POST':
        $title = $data['title'] ?? '';
        $message = $data['message'] ?? '';

        if (!$title || !$message) {
            http_response_code(400);
            echo json_encode(['error' => 'Title and message are required']);
            exit;
        }

        $stmt = $pdo->prepare("INSERT INTO announcements (title, message) VALUES (?, ?)");
        $stmt->execute([$title, $message]);

        echo json_encode(['success' => true, 'id' => $pdo->lastInsertId()]);
        break;

    case 'DELETE': {
      // Get the ID from query string
      parse_str(file_get_contents('php://input'), $data);
      $id = $data['id'] ?? null;
    
      if (!$id) {
        http_response_code(400);
        echo json_encode(['error' => 'ID is required for deletion']);
        exit;
      }
    
      $stmt = $pdo->prepare("DELETE FROM announcements WHERE id = ?");
      $stmt->execute([$id]);
    
      echo json_encode(['success' => true]);
      exit;
    }
    

    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
}
