<?php
/**
 * Cleanup script to delete events that are older than 7 days after their event date
 * This script should be run daily via cron job or scheduled task
 * 
 * Usage: php cleanup_expired_events.php
 * Or set up a cron job: 0 2 * * * /usr/bin/php /path/to/cleanup_expired_events.php
 */

require_once 'config.php';

$conn = getDBConnection();
$now = new DateTime();

// Get all events with event_date
$stmt = $conn->prepare("SELECT id, event_slug, event_date FROM events WHERE event_date IS NOT NULL");
$stmt->execute();
$result = $stmt->get_result();

$deleted_count = 0;
$errors = [];

while ($row = $result->fetch_assoc()) {
    $event_date = new DateTime($row['event_date']);
    $expiry_date = (clone $event_date)->modify('+7 days');
    
    // Check if expired (7 days after event_date)
    if ($expiry_date < $now) {
        $event_slug = $row['event_slug'];
        $event_id = $row['id'];
        
        // Delete event directory and files
        $event_dir = __DIR__ . '/events/' . $event_slug;
        if (is_dir($event_dir)) {
            $files = glob($event_dir . '/*');
            foreach ($files as $file) {
                if (is_file($file)) {
                    if (!unlink($file)) {
                        $errors[] = "Failed to delete file: $file";
                    }
                }
            }
            if (!rmdir($event_dir)) {
                $errors[] = "Failed to delete directory: $event_dir";
            }
        }
        
        // Delete from database
        $delete_stmt = $conn->prepare("DELETE FROM events WHERE id = ?");
        $delete_stmt->bind_param("i", $event_id);
        
        if ($delete_stmt->execute()) {
            $deleted_count++;
        } else {
            $errors[] = "Failed to delete event from database: $event_slug";
        }
        
        $delete_stmt->close();
    }
}

$stmt->close();
$conn->close();

// Output results
echo "Cleanup completed.\n";
echo "Deleted events: $deleted_count\n";

if (!empty($errors)) {
    echo "Errors encountered:\n";
    foreach ($errors as $error) {
        echo "  - $error\n";
    }
}

