<?php
/**
 * TrackPro — Data Purge Cron Job
 * 
 * Deletes sessions and all related data older than the configured retention period.
 * Add to cPanel Cron Jobs:
 *   0 3 * * * php /home/youraccount/public_html/trackpro/cron/purge.php
 */

require_once __DIR__ . '/../includes/db.php';

$retentionDays = (int) getSetting('data_retention_days', 365);
if ($retentionDays <= 0) {
    echo "Data retention disabled (set to 0). Exiting.\n";
    exit;
}

$cutoff = date('Y-m-d H:i:s', strtotime("-{$retentionDays} days"));
$pdo = getDB();

try {
    // Get session IDs to delete
    $stmt = $pdo->prepare("SELECT id FROM sessions WHERE started_at < ?");
    $stmt->execute([$cutoff]);
    $ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

    if (empty($ids)) {
        echo "No sessions older than {$retentionDays} days. Nothing to purge.\n";
        exit;
    }

    $count = count($ids);
    $placeholders = implode(',', array_fill(0, $count, '?'));

    // Delete from all child tables (CASCADE should handle this, but being explicit)
    $tables = [
        'behavioral_data', 'risk_data', 'attribution_data', 'fingerprint_data',
        'browser_data', 'device_data', 'location_data', 'network_data',
        'consent_log'
    ];

    $pdo->beginTransaction();
    foreach ($tables as $table) {
        $pdo->prepare("DELETE FROM `{$table}` WHERE session_id IN ({$placeholders})")->execute($ids);
    }
    $pdo->prepare("DELETE FROM `sessions` WHERE id IN ({$placeholders})")->execute($ids);
    $pdo->commit();

    // Clean old audit logs (keep 90 days)
    $pdo->exec("DELETE FROM `audit_log` WHERE `created_at` < DATE_SUB(NOW(), INTERVAL 90 DAY)");

    echo "Purged {$count} sessions older than {$retentionDays} days.\n";
    auditLog('cron_purge', null, 'sessions', null, ['count' => $count, 'cutoff' => $cutoff]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo "Error: " . $e->getMessage() . "\n";
    error_log("TrackPro purge error: " . $e->getMessage());
}
