<?php
// Purge report_archives based on retention in global_settings (default 5 years)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../core/db_connect.php';

try {
  $yrs = 5;
  try {
    $stmt = $conn_rbe->prepare("SELECT value FROM global_settings WHERE `key`='report_retention_years' LIMIT 1");
    $stmt->execute();
    $v = $stmt->fetchColumn();
    if ($v !== false && is_numeric($v)) { $yrs = max(1, (int)$v); }
  } catch (Throwable $e) { /* table optional */ }

  $cutoff = (new DateTimeImmutable())->modify(sprintf('-%d years', $yrs))->format('Y-m-d');
  $del = $conn_rbe->prepare('DELETE FROM report_archives WHERE period_end < ?');
  $del->execute([$cutoff]);
  echo sprintf("Purged archives before %s\n", $cutoff);
} catch (Throwable $e) {
  echo 'Error: ' . $e->getMessage();
}

?>

