<?php
// backend/cleanup_activity_logs.php — Alte Activity-Logs bereinigen
require_once 'config.php';
requireBackendAccess();

if (!isAdmin()) {
    header('Location: index.php');
    exit;
}

// AJAX-Handler für Vorschau (vor jeglichem Output)
if (isset($_GET['preview_days']) && is_numeric($_GET['preview_days'])) {
    $pd  = max(7, (int)$_GET['preview_days']);
    $cnt = $db->selectOne(
        "SELECT COUNT(*) as c FROM activity_log WHERE created_at < datetime('now', '-' || ? || ' days')",
        [$pd]
    )['c'] ?? 0;
    header('Content-Type: application/json');
    echo json_encode(['count' => $cnt]);
    exit;
}

$message = '';
$error   = '';
$days    = max(7, (int)($_POST['days'] ?? 90));

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm'])) {
    validateRequest();
    try {
        $count = $db->selectOne(
            "SELECT COUNT(*) as c FROM activity_log WHERE created_at < datetime('now', '-' || ? || ' days')",
            [$days]
        )['c'] ?? 0;

        $db->execute(
            "DELETE FROM activity_log WHERE created_at < datetime('now', '-' || ? || ' days')",
            [$days]
        );

        Security::logSecurityEvent('activity_log_cleanup', [
            'deleted'         => $count,
            'older_than_days' => $days,
            'by'              => $_SESSION['username'] ?? '?'
        ]);

        $message = "✅ $count Einträge älter als $days Tage wurden gelöscht.";

    } catch (Exception $e) {
        $error = 'Fehler beim Bereinigen: ' . $e->getMessage();
    }
}

// Statistik
try {
    $total   = $db->selectOne("SELECT COUNT(*) as c FROM activity_log")['c'] ?? 0;
    $oldest  = $db->selectOne("SELECT MIN(created_at) as d FROM activity_log")['d'] ?? null;
    $preview = $db->selectOne(
        "SELECT COUNT(*) as c FROM activity_log WHERE created_at < datetime('now', '-' || ? || ' days')",
        [$days]
    )['c'] ?? 0;
} catch (Exception $e) {
    $total = 0; $oldest = null; $preview = 0;
}

include 'layout/header.php';
?>

<div class="backend-content">
    <h1>🗑️ Activity-Log bereinigen</h1>

    <?php if ($message): ?>
    <div style="background:#d4edda;border:1px solid #c3e6cb;border-radius:8px;padding:14px 18px;margin-bottom:20px;color:#155724;">
        <?php echo htmlspecialchars($message); ?>
    </div>
    <?php endif; ?>

    <?php if ($error): ?>
    <div style="background:#f8d7da;border:1px solid #f5c6cb;border-radius:8px;padding:14px 18px;margin-bottom:20px;color:#721c24;">
        <?php echo htmlspecialchars($error); ?>
    </div>
    <?php endif; ?>

    <!-- Statistik -->
    <div style="display:flex;gap:16px;flex-wrap:wrap;margin-bottom:24px;">
        <div style="background:white;border:1px solid #dee2e6;border-radius:10px;padding:16px 24px;text-align:center;min-width:140px;">
            <div style="font-size:28px;font-weight:700;color:#2c3e50;"><?php echo number_format($total); ?></div>
            <div style="font-size:12px;color:#888;">Einträge gesamt</div>
        </div>
        <div style="background:white;border:1px solid #dee2e6;border-radius:10px;padding:16px 24px;text-align:center;min-width:140px;">
            <div style="font-size:28px;font-weight:700;color:#e74c3c;"><?php echo number_format($preview); ?></div>
            <div style="font-size:12px;color:#888;">Werden gelöscht (<?php echo $days; ?> Tage)</div>
        </div>
        <?php if ($oldest): ?>
        <div style="background:white;border:1px solid #dee2e6;border-radius:10px;padding:16px 24px;text-align:center;min-width:140px;">
            <div style="font-size:16px;font-weight:700;color:#2c3e50;"><?php echo date('d.m.Y', strtotime($oldest)); ?></div>
            <div style="font-size:12px;color:#888;">Ältester Eintrag</div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Formular -->
    <div style="background:white;border:1px solid #dee2e6;border-radius:12px;padding:24px;max-width:480px;">
        <h3 style="margin-bottom:16px;color:#2c3e50;">Einträge löschen</h3>
        <form method="POST" action=""
              onsubmit="return confirm('Wirklich ' + document.getElementById('preview_count').textContent + ' Einträge löschen? Diese Aktion kann nicht rückgängig gemacht werden.')">
            <?php echo Security::getCSRFInput(); ?>
            <div style="margin-bottom:16px;">
                <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">
                    Einträge älter als … Tage löschen
                </label>
                <select name="days" id="daysSelect"
                        style="width:100%;padding:10px;border:1px solid #d1d5db;border-radius:8px;font-size:14px;"
                        onchange="updatePreview(this.value)">
                    <option value="30"  <?php echo $days==30  ?'selected':''; ?>>30 Tage</option>
                    <option value="60"  <?php echo $days==60  ?'selected':''; ?>>60 Tage</option>
                    <option value="90"  <?php echo $days==90  ?'selected':''; ?>>90 Tage (empfohlen)</option>
                    <option value="180" <?php echo $days==180 ?'selected':''; ?>>180 Tage</option>
                    <option value="365" <?php echo $days==365 ?'selected':''; ?>>1 Jahr</option>
                </select>
            </div>
            <div style="background:#fff3cd;border:1px solid #ffc107;border-radius:8px;padding:12px 16px;margin-bottom:16px;font-size:13px;color:#856404;">
                ⚠️ Es werden <strong><span id="preview_count"><?php echo $preview; ?></span></strong>
                Einträge unwiderruflich gelöscht.
            </div>
            <div style="display:flex;gap:10px;">
                <button type="submit" name="confirm" value="1"
                        style="padding:11px 24px;background:#e74c3c;color:white;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;">
                    🗑️ Jetzt bereinigen
                </button>
                <a href="activity_log.php"
                   style="padding:11px 20px;background:white;border:1px solid #d1d5db;border-radius:8px;font-size:14px;color:#374151;text-decoration:none;">
                    ← Zurück
                </a>
            </div>
        </form>
    </div>
</div>

<script>
function updatePreview(days) {
    fetch('cleanup_activity_logs.php?preview_days=' + days)
        .then(r => r.json())
        .then(data => { document.getElementById('preview_count').textContent = data.count; })
        .catch(() => {});
}
</script>

<?php include 'layout/footer.php'; ?>
