<?php
// workers/cleanup.php – Rensar gamla loggposter och optimerar databasen
// Kör via cron en gång per dygn:
//   0 3 * * * php /var/www/radio/workers/cleanup.php

require __DIR__ . '/../config/config.php';

$db = new PDO('sqlite:' . DB_PATH);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Behåll bara 90 dagars spellogg
$stmt = $db->prepare("DELETE FROM play_log WHERE started_at < datetime('now', '-90 days')");
$stmt->execute();
$deleted = $db->changes() ?? $stmt->rowCount();
echo date('Y-m-d H:i:s') . " Raderade $deleted gamla loggposter\n";

// Vacuumera för att frigöra diskutrymme
$db->exec("VACUUM");
echo date('Y-m-d H:i:s') . " VACUUM klar\n";

// Rensa stale cache-filer
$files = glob(CACHE_PATH . '*.json');
$cacheDeleted = 0;
foreach ($files as $f) {
    if (filemtime($f) < time() - 3600) {
        unlink($f);
        $cacheDeleted++;
    }
}
echo date('Y-m-d H:i:s') . " Raderade $cacheDeleted stale cache-filer\n";

echo date('Y-m-d H:i:s') . " Städning klar\n";
