<?php
/**
 * Cleanup Expired Sessions
 * 
 * This script should be run periodically (via cron job) to clean up expired sessions
 * Recommended: Run daily at midnight
 * 
 * Cron example: 0 0 * * * /usr/bin/php /path/to/cleanup_sessions.php
 */

require_once '../config/database.php';
require_once '../includes/functions.php';

try {
    $conn = getDBConnection();
    
    // Delete expired sessions
    $stmt = $conn->prepare("DELETE FROM user_sessions WHERE expires_at < NOW()");
    $stmt->execute();
    $deletedCount = $stmt->rowCount();
    
    // Log the cleanup
    $message = "Session cleanup completed. Deleted $deletedCount expired session(s).";
    logActivity($message);
    
    // Output for cron logs
    echo date('Y-m-d H:i:s') . " - $message\n";
    
    // Also clean up old activity logs (optional - keep last 90 days)
    $stmt = $conn->prepare("DELETE FROM activity_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 90 DAY)");
    $stmt->execute();
    $deletedLogs = $stmt->rowCount();
    
    if ($deletedLogs > 0) {
        echo date('Y-m-d H:i:s') . " - Deleted $deletedLogs old activity log(s).\n";
    }
    
    exit(0);
    
} catch (PDOException $e) {
    $error = "Session cleanup error: " . $e->getMessage();
    logError($error);
    echo date('Y-m-d H:i:s') . " - ERROR: $error\n";
    exit(1);
}
