<?php

/**
 * Retrieves and sanitizes the query string from the server request.
 * 
 * @return string|null The query string or null if not found.
 */
function getServerQueryString()
{
    // Check if QUERY_STRING is available and sanitize it
    if (isset($_SERVER['QUERY_STRING'])) {
        return filter_var($_SERVER['QUERY_STRING'], FILTER_SANITIZE_STRING);
    }

    // Check for query string in the REQUEST_URI
    if (isset($_SERVER['REQUEST_URI'])) {
        $query = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
        return filter_var($query, FILTER_SANITIZE_STRING);
    }

    return null;
}

// Retrieve and sanitize the query string
$queryString = getServerQueryString();

// Ensure that $queryString is not null before processing
if ($queryString) {
    $cssFiles = array_map('trim', explode(',', $queryString));
} else {
    $cssFiles = [];
}

$css = '';

// Loop through CSS files and aggregate their content
foreach ($cssFiles as $cssFile) {
    $cssFile = basename($cssFile); // Prevent directory traversal
    $filePath = 'css/' . $cssFile . '.css';

    if (file_exists($filePath)) {
        $css .= file_get_contents($filePath);
    }
}

// Enable GZip encoding
if (!ob_start("ob_gzhandler")) {
    ob_start();
}

// Enable caching
header('Cache-Control: public');
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT');

// Set the MIME type
header('Content-Type: text/css');

// Minify and output the CSS
$css = preg_replace('/\s*\/\*.*?\*\//s', '', $css); // Remove comments
$css = preg_replace('/\s+/', ' ', $css); // Remove extra whitespace
$css = preg_replace('/\s*([{};])\s*/', '$1', $css); // Remove extra spaces around braces and semicolons

echo $css;

?>
