<?php
header('Content-Type: application/json');
require_once __DIR__ . '/db/config.php';

$bni_group_id = isset($_GET['bni_group_id']) ? (int)$_GET['bni_group_id'] : 0;
$offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 2;

if ($bni_group_id === 0) {
    echo json_encode(['error' => 'Invalid BNI Group ID']);
    exit;
}

try {
    $pdo = db();

    $sql = "
        SELECT ce.*, bg.name as group_name
        FROM calendar_events ce
        JOIN calendar_event_groups ceg ON ce.id = ceg.calendar_event_id
        JOIN bni_groups bg ON ceg.bni_group_id = bg.id
        WHERE ceg.bni_group_id = :bni_group_id
          AND ce.start_datetime > NOW()
        ORDER BY ce.start_datetime ASC
        LIMIT :limit OFFSET :offset
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':bni_group_id', $bni_group_id, PDO::PARAM_INT);
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    $events = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($events);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
