<?php
/**
 * Limpieza de registros antiguos de query_logs.
 * Elimina en lotes pequeños para no bloquear la tabla.
 *
 * Cron (root): 0 3 * * *  php /home/kuos/public_html/zerotrustdns.pcassi.ar/cleanup_cron.php
 */
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';

define('RETENTION_DAYS', 30);   // Días a conservar
define('BATCH_SIZE',     5000); // Filas por DELETE
define('MAX_BATCHES',    200);  // Máximo de lotes por ejecución (evita timeouts)

$log = function(string $msg) {
    $ts = date('[Y-m-d H:i:s]');
    if (PHP_SAPI === 'cli') echo $ts . ' ' . $msg . PHP_EOL;
    error_log('cleanup_cron: ' . $msg);
};

$pdo = db();
$cutoff = date('Y-m-d H:i:s', strtotime('-' . RETENTION_DAYS . ' days'));

$log("=== cleanup_cron iniciado — eliminando registros anteriores a $cutoff ===");

$totalDeleted = 0;
$batches = 0;

$stmt = $pdo->prepare(
    "DELETE FROM query_logs WHERE log_time < ? LIMIT " . BATCH_SIZE
);

do {
    $stmt->execute([$cutoff]);
    $deleted = $stmt->rowCount();
    $totalDeleted += $deleted;
    $batches++;

    if ($deleted > 0) {
        $log("  Lote $batches: $deleted filas eliminadas (total: $totalDeleted)");
    }

    if ($batches >= MAX_BATCHES) {
        $log("  Limite de lotes alcanzado ($MAX_BATCHES). Se continuará en la próxima ejecución.");
        break;
    }

    // Pequeña pausa entre lotes para no saturar el servidor
    if ($deleted === BATCH_SIZE) usleep(100000); // 100ms

} while ($deleted === BATCH_SIZE);

$log("=== cleanup_cron completado — $totalDeleted filas eliminadas en $batches lotes ===");
