<?php
// Sprawdź czy żądanie to POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo 'Metoda niedozwolona';
    exit;
}

// Pobierz surowe dane POST
$rawData = file_get_contents('php://input');

// Sprawdź czy dane nie są puste
if (empty($rawData)) {
    http_response_code(400);
    echo 'Brak danych';
    exit;
}

// Funkcja do sprawdzania czy XML jest ucięty
function isXMLTruncated($xmlData) {
    $reasons = [];
    
    // Sprawdź czy XML jest poprawny syntaktycznie
    libxml_use_internal_errors(true);
    libxml_clear_errors();
    
    $dom = new DOMDocument();
    if (!$dom->loadXML($xmlData)) {
        $errors = libxml_get_errors();
        foreach ($errors as $error) {
            $reasons[] = "Parse error line {$error->line}: " . trim($error->message);
        }
        return $reasons;
    }
    
    // Sprawdź czy XML kończy się poprawnie
    $trimmed = trim($xmlData);
    if (!preg_match('/<\/\w+>\s*$/', $trimmed)) {
        $reasons[] = "XML does not end with proper closing tag";
    }
    
    // Sprawdź czy ostatnie znaki wyglądają na przerwane
    if (preg_match('/[^>]\s*$/', $trimmed)) {
        $lastChars = substr($trimmed, -10);
        if (!preg_match('/>\s*$/', $lastChars)) {
            $reasons[] = "XML appears to end abruptly: '" . $lastChars . "'";
        }
    }
    
    return $reasons;
}

// Sprawdź czy XML jest ucięty
$truncationReasons = isXMLTruncated($rawData);

// Zapisz plik TYLKO jeśli XML jest ucięty
if (!empty($truncationReasons)) {
    $expectedLength = $_SERVER['CONTENT_LENGTH'] ?? 0;
    $receivedLength = strlen($rawData);
    $timestamp = date('Y-m-d H:i:s');
    $fileTimestamp = date('YmdHis') . '-' . substr(microtime(), 2, 6);
    
    // Nazwy plików
    $fileName = "TRUNCATED-{$fileTimestamp}.xml";
    $logFileName = "TRUNCATED-{$fileTimestamp}.log";
    
    // Ścieżki
    $filePath = __DIR__ . '/gha/' . $fileName;
    $logPath = __DIR__ . '/gha/' . $logFileName;
    
    // Zapisz uszkodzony XML
    file_put_contents($filePath, $rawData);
    
    // Przygotuj dane do loga
    $logData = [
        "[$timestamp] === TRUNCATED XML DETECTED ===",
        "[$timestamp] File: $fileName",
        "[$timestamp] Expected Length: $expectedLength bytes",
        "[$timestamp] Received Length: $receivedLength bytes",
        "[$timestamp] Missing: " . ($expectedLength - $receivedLength) . " bytes",
        "[$timestamp] Truncation Reasons:"
    ];
    
    foreach ($truncationReasons as $reason) {
        $logData[] = "[$timestamp]   - $reason";
    }
    
    $logData[] = "[$timestamp] Last 100 chars: '" . substr($rawData, -100) . "'";
    $logData[] = "[$timestamp] === END ===";
    $logData[] = "";
    
    // Zapisz log
    file_put_contents($logPath, implode("\n", $logData) . "\n", FILE_APPEND | LOCK_EX);
    
    // Wyślij do głównego loga
    error_log("Truncated XML detected: $fileName (expected: $expectedLength, received: $receivedLength)");
}

// Zwróć sukces
http_response_code(200);
echo 'OK';
?>
