<?php
/**
 * Cleanup Expired Tokens Script
 * Removes expired password reset tokens and logs cleanup activity
 */

require_once 'config.php';

echo "<h2>Password Reset Token Cleanup</h2>";
echo "<p>Cleaning up expired password reset tokens...</p>";

// Function to log cleanup activity
function logCleanupActivity($message, $count = 0) {
    $logMessage = date('Y-m-d H:i:s') . " - " . $message . ($count > 0 ? " (Count: $count)" : "") . "\n";
    file_put_contents('logs/token_cleanup.log', $logMessage, FILE_APPEND | LOCK_EX);
    echo "<p style='color: blue;'>ℹ " . htmlspecialchars($message) . ($count > 0 ? " (Count: $count)" : "") . "</p>";
}

try {
    // Clean up expired tokens
    $expiredQuery = "DELETE FROM password_reset_tokens WHERE expires_at < NOW()";
    $expiredResult = mysqli_query($conn, $expiredQuery);
    $expiredCount = mysqli_affected_rows($conn);
    
    if ($expiredResult) {
        logCleanupActivity("Expired tokens cleaned up", $expiredCount);
    } else {
        logCleanupActivity("Failed to clean expired tokens: " . mysqli_error($conn));
    }
    
    // Clean up used tokens older than 1 hour
    $usedQuery = "DELETE FROM password_reset_tokens WHERE used_at IS NOT NULL AND created_at < DATE_SUB(NOW(), INTERVAL 1 HOUR)";
    $usedResult = mysqli_query($conn, $usedQuery);
    $usedCount = mysqli_affected_rows($conn);
    
    if ($usedResult) {
        logCleanupActivity("Used tokens cleaned up", $usedCount);
    } else {
        logCleanupActivity("Failed to clean used tokens: " . mysqli_error($conn));
    }
    
    // Clean up tokens with max attempts reached
    $maxAttemptsQuery = "DELETE FROM password_reset_tokens WHERE attempts >= max_attempts";
    $maxAttemptsResult = mysqli_query($conn, $maxAttemptsQuery);
    $maxAttemptsCount = mysqli_affected_rows($conn);
    
    if ($maxAttemptsResult) {
        logCleanupActivity("Max attempts tokens cleaned up", $maxAttemptsCount);
    } else {
        logCleanupActivity("Failed to clean max attempts tokens: " . mysqli_error($conn));
    }
    
    // Get current token statistics
    $statsQuery = "SELECT 
        COUNT(*) as total_tokens,
        COUNT(CASE WHEN expires_at > NOW() AND used_at IS NULL THEN 1 END) as active_tokens,
        COUNT(CASE WHEN used_at IS NOT NULL THEN 1 END) as used_tokens,
        COUNT(CASE WHEN attempts >= max_attempts THEN 1 END) as max_attempts_tokens
    FROM password_reset_tokens";
    
    $statsResult = mysqli_query($conn, $statsQuery);
    if ($statsResult) {
        $stats = mysqli_fetch_assoc($statsResult);
        logCleanupActivity("Token Statistics - Total: {$stats['total_tokens']}, Active: {$stats['active_tokens']}, Used: {$stats['used_tokens']}, Max Attempts: {$stats['max_attempts_tokens']}");
    }
    
    $totalCleaned = $expiredCount + $usedCount + $maxAttemptsCount;
    
    if ($totalCleaned > 0) {
        echo "<p style='color: green;'>✓ Cleanup completed successfully! Removed $totalCleaned tokens.</p>";
    } else {
        echo "<p style='color: blue;'>ℹ No tokens needed cleanup.</p>";
    }
    
} catch (Exception $e) {
    $errorMessage = "Cleanup failed: " . $e->getMessage();
    logCleanupActivity($errorMessage);
    echo "<p style='color: red;'>✗ " . htmlspecialchars($errorMessage) . "</p>";
}

echo "<hr>";
echo "<h3>Security Measures Implemented:</h3>";
echo "<ul>";
echo "<li>✓ Automatic cleanup of expired tokens (15 minutes)</li>";
echo "<li>✓ Cleanup of used tokens after 1 hour</li>";
echo "<li>✓ Cleanup of tokens with max attempts reached</li>";
echo "<li>✓ Activity logging for audit trail</li>";
echo "<li>✓ Token statistics monitoring</li>";
echo "</ul>";

echo "<p><strong>Recommendation:</strong> Set up a cron job to run this script every 30 minutes:</p>";
echo "<code>*/30 * * * * /usr/bin/php " . __DIR__ . "/cleanup_expired_tokens.php</code>";
?>
