<?php
include('inc/check_login.php');
include('inc/db.php');

// 🔹 Pfad zum Backup-Ordner (relativ zum Projekt)
$backup_dir = __DIR__ . '/backups/';
$backup_url = 'backups/'; // öffentliche URL

// Prüfen, ob Ordner existiert
if (!is_dir($backup_dir)) {
    mkdir($backup_dir, 0755, true);
}

// PDF-Dateien holen
$files = [];
if ($handle = opendir($backup_dir)) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry !== '.' && $entry !== '..' && pathinfo($entry, PATHINFO_EXTENSION) === 'pdf') {
            $full_path = $backup_dir . $entry;
            $files[] = [
                'name' => $entry,
                'size' => filesize($full_path),
                'mtime' => filemtime($full_path)
            ];
        }
    }
    closedir($handle);

    // 🔸 Sortieren nach Datum im Dateinamen: DoMiLi_Backup_YYYY-MM[_x].pdf
    usort($files, function ($a, $b) {
        // Extrahiere YYYY-MM aus dem Dateinamen (ohne .pdf)
        $nameA = pathinfo($a['name'], PATHINFO_FILENAME);
        $nameB = pathinfo($b['name'], PATHINFO_FILENAME);

        // Regex: Suche nach 4 Ziffern, Bindestrich, 2 Ziffern
        $dateA = null;
        $dateB = null;
        if (preg_match('/(\d{4}-\d{2})/', $nameA, $matchesA)) {
            $dateA = $matchesA[1];
        }
        if (preg_match('/(\d{4}-\d{2})/', $nameB, $matchesB)) {
            $dateB = $matchesB[1];
        }

        // Wenn kein Datum gefunden: ans Ende schieben
        if ($dateA === null && $dateB === null) return 0;
        if ($dateA === null) return 1;  // A hinter B
        if ($dateB === null) return -1; // B hinter A

        // Absteigend sortieren: neuestes zuerst → "2025-07" > "2025-02"
        return $dateB <=> $dateA;
    });
}

require_once 'inc/header.php';
?>

<div class="container mt-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0">PDF-Backups</h2>
        <a href="index.php" class="btn btn-sm btn-outline-secondary">Zurück</a>
    </div>

    <?php if (empty($files)): ?>
        <div class="alert alert-info">
            <span class="material-symbols-outlined align-text-bottom me-2">info</span>
            Keine PDF-Backups gefunden.
        </div>
    <?php else: ?>
        <div class="card shadow">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Datei</th>
                                <th>Datum</th>
                                <th class="d-none d-md-table-cell">Größe</th>
                                <th class="text-end">Aktion</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($files as $file): ?>
                                <tr>
                                    <td style="white-space: nowrap;">
                                        <div class="d-flex align-items-center" style="min-height: 1.4rem;">
                                            <span class="material-symbols-outlined text-info me-2" style="font-size: 1.1em; line-height: 1; flex-shrink: 0;">picture_as_pdf</span>
                                            <span class="fw-medium text-break" style="font-size: 0.92rem; line-height: 1.3; min-width: 0; white-space: normal;">
                                                <?= htmlspecialchars(pathinfo($file['name'], PATHINFO_FILENAME)) ?>
                                            </span>
                                        </div>
                                    </td>
                                    <td><?= date('d.m.y', $file['mtime']) ?></td>
                                    <td class="d-none d-md-table-cell"><?= number_format($file['size'] / 1024, 1, ',', '.') ?> KB</td>
                                    <td class="text-end pe-4">
                                        <a href="<?= htmlspecialchars($backup_url . $file['name']) ?>" target="_blank" class="text-secondary" title="PDF öffnen oder herunterladen">
                                            <span class="material-icons">download</span>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <div class="mt-4 p-3 bg-light rounded">
        <h5 class="mb-3">Hinweis</h5>
        <p class="mb-0">
            Diese PDFs werden manuell oder automatisch erstellt (z. B. über <code>export.php</code>).
            Sie dienen als Archiv und können nicht über diese Oberfläche gelöscht werden.
        </p>
    </div>
</div>

<?php include('inc/footer.php'); ?>