#!/usr/bin/env php
<?php
/**
 * Clean Temporary Files
 * Removes old temporary files from all temp directories
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/cache-manager.php';
require_once __DIR__ . '/../includes/session-manager.php';
require_once __DIR__ . '/../includes/upload-manager.php';
require_once __DIR__ . '/../includes/login-attempts.php';

$logFile = __DIR__ . '/../logs/cleanup.log';

function logMessage($message) {
    global $logFile;
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
    echo $message . "\n";
}

logMessage("=== Starting temporary files cleanup ===");

// Clean cache
$cache = getCache();
$cacheCleaned = $cache->clear();
logMessage("Cache cleaned: $cacheCleaned files deleted");

// Clean sessions
$session = getSession();
$sessionsCleaned = $session->cleanExpired();
logMessage("Expired sessions cleaned: $sessionsCleaned");

// Clean uploads
$upload = getUploadManager();
$uploadsCleaned = $upload->clean(86400); // 24 hours
logMessage("Temporary uploads cleaned: $uploadsCleaned files";

// Clean login attempts
$loginAttempts = getLoginAttempts();
$attemptsCleaned = $loginAttempts->clean(604800); // 7 days
logMessage("Old login attempts records cleaned: $attemptsCleaned");

// Get final statistics
$cacheStats = $cache->getStats();
$sessionStats = $session->getStats();
$uploadStats = $upload->getStats();
$attemptsStats = $loginAttempts->getStats();

logMessage("=== Cleanup Summary ===");
logMessage("Cache: {$cacheStats['total_files']} files, {$cacheStats['total_size_formatted']}");
logMessage("Sessions: {$sessionStats['active_sessions']} active sessions");
logMessage("Uploads: {$uploadStats['total_files']} files, {$uploadStats['total_size_formatted']}");
logMessage("Login attempts: {$attemptsStats['tracked_identifiers']} tracked");

logMessage("=== Cleanup completed ===");