<?php
// Define the path where you want to save the log file
$logFilePath = 'log.log';

// Define the username and password for authentication
$validUsername = 'symbol';
$validPassword = 'NHJ+a=Jqq+z46q?-';

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if the request has valid authentication credentials
    if (
        isset($_SERVER['PHP_AUTH_USER']) &&
        isset($_SERVER['PHP_AUTH_PW']) &&
        $_SERVER['PHP_AUTH_USER'] === $validUsername &&
        $_SERVER['PHP_AUTH_PW'] === $validPassword
    ) {
        // Check if the request has a body
        $requestBody = file_get_contents('php://input');
        if (!empty($requestBody)) {
            $requestContent = $requestBody;
            
            // Decode the content of the request
            $xmlContent = substr(urldecode($requestContent),8);

            // Load XML string
            $xmlParse = simplexml_load_string($xmlContent);
            
            // Check if XML was parsed successfully
            if ($xmlParse === false) {
                echo 'Error parsing XML';
            }
            
            // Loop through each ProductQuantity element
            foreach ($xmlParse->ProductQuantity as $product) {
                $productCode = (string) $product->ProductCode;
                $quantity = (int) $product->Quantity;
                
                $pcsPerUnit = 1000;
                $quantityInUnit = $quantity / $pcsPerUnit;
            
                // Display the product quantities
                file_put_contents($logFilePath, 'SKU: ' . $productCode . ' | Készlet: ' . $quantityInUnit . PHP_EOL, FILE_APPEND);
            }

            // Send a response
            echo 'XML data saved successfully.';
        } else {
            // Send an error response
            header('HTTP/1.1 400 Bad Request');
            echo 'No XML data found in the request body.';
        }
    } else {
        // Send an error response
        header('WWW-Authenticate: Basic realm="Restricted Area"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Authentication required.';
        exit;
    }
} else {
    // Send an error response
    header('HTTP/1.1 405 Method Not Allowed');
    echo 'Only POST requests are allowed.';
}
?>