<?php
// api/events.php
require_once '../config/database.php';
header("Content-Type: application/json");

$method = $_SERVER['REQUEST_METHOD'];
$path_info = isset($_SERVER['PATH_INFO']) ? explode('/', trim($_SERVER['PATH_INFO'], '/')) : [];
$id = $path_info[0] ?? null;

$input = json_decode(file_get_contents("php://input"), true) ?? [];

try {
    if ($method === 'GET') {
        $stmt = $pdo->query("SELECT * FROM events ORDER BY created_at DESC");
        echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    } 
    elseif ($method === 'POST') {
        $sql = "INSERT INTO events (title, description, location, campus, speakers, event_date, status, is_active, image_url, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$input['title'], $input['description'] ?? null, $input['location'] ?? null, $input['campus'] ?? null, $input['speakers'] ?? null, $input['event_date'], $input['status'], $input['is_active'] ? 1 : 0, $input['image_url'] ?? null]);
        echo json_encode(["message" => "Event created", "id" => $pdo->lastInsertId()]);
    } 
    elseif ($method === 'PUT' && $id) {
        // Dynamic Update based on inputs
        $fields = []; $params = [];
        foreach ($input as $key => $value) {
            $fields[] = "$key = ?";
            $params[] = $value;
        }
        $params[] = $id;
        $sql = "UPDATE events SET " . implode(', ', $fields) . " WHERE id = ?";
        $pdo->prepare($sql)->execute($params);
        echo json_encode(["message" => "Event updated successfully"]);
    } 
    elseif ($method === 'DELETE' && $id) {
        $pdo->prepare("DELETE FROM events WHERE id = ?")->execute([$id]);
        echo json_encode(["status" => "success", "message" => "Event deleted successfully"]);
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["detail" => $e->getMessage()]);
}
?>