<?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['title']) || !isset($input['event_date']) || !isset($input['created_by'])) {
        jsonResponse(['error' => 'Missing required fields'], 400);
    }
    
    $pdo = getDB();
    $stmt = $pdo->prepare("INSERT INTO events (group_id, title, description, event_date, created_by) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([
        $input['group_id'],
        $input['title'],
        $input['description'] ?? null,
        $input['event_date'],
        $input['created_by']
    ]);
    
    $eventId = $pdo->lastInsertId();
    jsonResponse(['success' => true, 'event_id' => $eventId], 201);
}

if ($method === 'GET') {
    if (!isset($_GET['group_id'])) {
        jsonResponse(['error' => 'Group ID required'], 400);
    }
    
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT e.*, u.first_name, u.last_name, u.username,
        (SELECT COUNT(*) FROM event_responses WHERE event_id = e.id AND status = 'present') as present_count,
        (SELECT COUNT(*) FROM event_responses WHERE event_id = e.id AND status = 'absent') as absent_count
        FROM events e 
        INNER JOIN users u ON e.created_by = u.id 
        WHERE e.group_id = ? 
        ORDER BY e.event_date ASC");
    $stmt->execute([$_GET['group_id']]);
    $events = $stmt->fetchAll();
    
    jsonResponse(['success' => true, 'events' => $events]);
}
?>