<?php
declare(strict_types=1);
require_once __DIR__ . "/../includes/auth.php";
require_once __DIR__ . "/../includes/helpers.php";
requireAuth();

$storageRoot = __DIR__ . "/produced";
if (!is_dir($storageRoot)) {
    @mkdir($storageRoot, 0777, true);
}

$projectRoot = realpath(__DIR__ . "/..");
if (!is_string($projectRoot) || $projectRoot === "") {
    $projectRoot = dirname(__DIR__);
}

function storagePathToUrl(string $absolutePath, string $projectRoot): string
{
    $absolutePath = str_replace("\\", "/", $absolutePath);
    $projectRoot = rtrim(str_replace("\\", "/", $projectRoot), "/");

    if (!str_starts_with($absolutePath, $projectRoot)) {
        return "#";
    }

    $relative = ltrim(substr($absolutePath, strlen($projectRoot)), "/");
    if ($relative === "") {
        return "#";
    }

    $segments = explode("/", $relative);
    $encoded = array_map(static fn (string $part): string => rawurlencode($part), $segments);

    return "/PIS/" . implode("/", $encoded);
}

function collectDateModules(string $datePath, string $projectRoot): array
{
    $moduleBase = rtrim($datePath, "\\/") . DIRECTORY_SEPARATOR . "par-module";
    if (!is_dir($moduleBase)) {
        return [];
    }

    $entries = @scandir($moduleBase) ?: [];
    $modules = [];
    foreach ($entries as $entry) {
        if ($entry === "." || $entry === "..") {
            continue;
        }

        $entryPath = $moduleBase . DIRECTORY_SEPARATOR . $entry;
        if (!is_dir($entryPath)) {
            continue;
        }

        $files = glob($entryPath . DIRECTORY_SEPARATOR . "*.html") ?: [];
        sort($files, SORT_NATURAL | SORT_FLAG_CASE);

        $fileItems = [];
        foreach ($files as $filePath) {
            $fileItems[] = [
                "name" => basename($filePath),
                "url" => storagePathToUrl($filePath, $projectRoot),
            ];
        }

        $modules[] = [
            "title" => $entry,
            "count" => count($fileItems),
            "files" => $fileItems,
        ];
    }

    usort($modules, static fn (array $a, array $b): int => strcasecmp($a["title"], $b["title"]));
    return $modules;
}

$dates = [];
$rootEntries = @scandir($storageRoot) ?: [];
foreach ($rootEntries as $entry) {
    if ($entry === "." || $entry === "..") {
        continue;
    }

    $entryPath = $storageRoot . DIRECTORY_SEPARATOR . $entry;
    if (!is_dir($entryPath)) {
        continue;
    }

    if (preg_match("/^\\d{4}-\\d{2}-\\d{2}$/", $entry) === 1) {
        $dates[] = $entry;
    }
}

rsort($dates, SORT_STRING);

$selectedDate = trim((string) ($_GET["date"] ?? ""));
if ($selectedDate === "" && $dates !== []) {
    $selectedDate = $dates[0];
}
if ($selectedDate !== "" && !in_array($selectedDate, $dates, true)) {
    $selectedDate = $dates[0] ?? "";
}

$moduleItems = [];

if ($selectedDate !== "") {
    $datePath = $storageRoot . DIRECTORY_SEPARATOR . $selectedDate;
    $moduleItems = collectDateModules($datePath, $projectRoot);
}

require_once __DIR__ . "/../includes/header.php";
?>
<h2>Stockage des attestations</h2>
<p>Copies sauvegardees automatiquement lors de la generation, classees par date de production.</p>

<?php if ($dates === []): ?>
    <p class="message">Aucune copie sauvegardee pour le moment.</p>
<?php else: ?>
    <form method="GET" action="/PIS/attestations/list.php">
        <select name="date">
            <?php foreach ($dates as $dateItem): ?>
                <option value="<?= htmlspecialchars($dateItem) ?>" <?= $dateItem === $selectedDate ? "selected" : "" ?>>
                    <?= htmlspecialchars($dateItem) ?>
                </option>
            <?php endforeach; ?>
        </select>
        <button type="submit">Afficher</button>
    </form>

    <h3>Date de production: <?= htmlspecialchars($selectedDate) ?></h3>
    <?php if ($moduleItems !== []): ?>
        <div class="module-list-wrapper">
            <h4>Modules de formation</h4>
            <ul class="module-list">
                <?php foreach ($moduleItems as $module): ?>
                    <li>
                        <strong><?= htmlspecialchars((string) $module["title"]) ?></strong>
                        (<?= (int) $module["count"] ?> attestation<?= $module["count"] === 1 ? "" : "s" ?>)
                        <?php if ($module["files"] !== []): ?>
                            <ul class="module-files">
                                <?php foreach ($module["files"] as $file): ?>
                                    <li>
                                        <?= htmlspecialchars((string) $file["name"]) ?>
                                        <a href="<?= htmlspecialchars((string) $file["url"]) ?>" target="_blank" rel="noopener">Ouvrir</a>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($moduleItems === []): ?>
        <p>Aucune copie pour cette date.</p>
    <?php endif; ?>

<?php endif; ?>

<?php require_once __DIR__ . "/../includes/footer.php"; ?>
