<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("HTTP/1.1 401 Unauthorized");
    exit();
}

require_once 'db/config.php';

if (isset($_GET['id'])) {
    $event_id = $_GET['id'];
    $pdo = db();
    $stmt = $pdo->prepare("
        SELECT c.*, t.name as type_name, GROUP_CONCAT(g.id) as group_ids
        FROM calendar_events c 
        LEFT JOIN event_types t ON c.event_type_id = t.id
        LEFT JOIN calendar_event_groups ceg ON c.id = ceg.calendar_event_id
        LEFT JOIN bni_groups g ON ceg.bni_group_id = g.id
        WHERE c.id = ?
        GROUP BY c.id
    ");
    $stmt->execute([$event_id]);
    $event = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($event) {
        if ($event['group_ids']) {
            $event['group_ids'] = explode(',', $event['group_ids']);
        } else {
            $event['group_ids'] = [];
        }

        header('Content-Type: application/json');
        echo json_encode($event);
    } else {
        header("HTTP/1.1 404 Not Found");
    }
} else {
    header("HTTP/1.1 400 Bad Request");
}
