<?php

/**
 * Echo <link rel="stylesheet"> tags for every *.css file in the templates folder.
 *
 * @param string $templatesDirFs  Filesystem path to templates dir, e.g. __DIR__ . '/templates'
 * @param string $templatesDirUrl URL path to templates dir, e.g. '/templates'
 */
function echoTemplateCssLinks(string $templatesDirFs, string $templatesDirUrl = '/templates'): void
{
    $templatesDirFs = rtrim($templatesDirFs, DIRECTORY_SEPARATOR);
    $templatesDirUrl = rtrim($templatesDirUrl, '/');

    if (!is_dir($templatesDirFs)) {
        return;
    }

    $files = glob($templatesDirFs . DIRECTORY_SEPARATOR . '*.css');
    if ($files === false) {
        return;
    }

    sort($files, SORT_NATURAL | SORT_FLAG_CASE);

    foreach ($files as $filePath) {
        $fileName = basename($filePath);

        if (!preg_match('/^[a-zA-Z0-9_.-]+\.css$/', $fileName)) {
            continue;
        }

        $href = $templatesDirUrl . '/' . rawurlencode($fileName);
        echo '<link rel="stylesheet" href="' . htmlspecialchars($href, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">' . "\n";
    }
}