<?php
header('Content-Type: application/json');

require_once 'db_config.php';
require_once 'Logger.php';

// API Key Überprüfung
if (!isset($_SERVER['HTTP_X_API_KEY']) || $_SERVER['HTTP_X_API_KEY'] !== API_KEY) {
    http_response_code(401);
    die(json_encode(['error' => 'Unauthorized']));
}

// Nur POST-Methode erlauben
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die(json_encode(['error' => 'Method not allowed']));
}

// JSON-Daten aus dem Request-Body lesen
$input = json_decode(file_get_contents('php://input'), true);

// Validierung der Eingabedaten
if (!isset($input['level']) || !isset($input['message'])) {
    http_response_code(400);
    die(json_encode(['error' => 'Missing required fields']));
}

try {
    // Datenbankverbindung herstellen
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME,
        DB_USER,
        DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    $logger = new Logger($pdo);

    // Log-Eintrag erstellen
    $result = $logger->log(
        $input['level'],
        $input['message'],
        $input['source'] ?? '',
        $input['additional_info'] ?? null
    );

    if ($result) {
        echo json_encode(['success' => true, 'message' => 'Log entry created']);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to create log entry']);
    }

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