#!/usr/bin/env php
<?php
/**
 * Log Rotation Script
 * Rotates and compresses old log files
 * Cron job: Daily at midnight
 */

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

$logDir = __DIR__ . '/../logs/';
$logger = new Logger($logDir);

echo "Starting log rotation...\n";

$logFiles = ['errors.log', 'access.log', 'ai.log', 'cron.log'];

foreach ($logFiles as $logFile) {
    $fullPath = $logDir . $logFile;
    
    if (!file_exists($fullPath)) {
        continue;
    }
    
    $size = filesize($fullPath);
    
    // Rotate if larger than 10MB
    if ($size > 10 * 1024 * 1024) {
        $backupName = $logDir . $logFile . '.' . date('Y-m-d') . '.bak';
        rename($fullPath, $backupName);
        
        // Compress
        if (function_exists('gzopen')) {
            $gzFile = $backupName . '.gz';
            $gz = gzopen($gzFile, 'w9');
            gzwrite($gz, file_get_contents($backupName));
            gzclose($gz);
            unlink($backupName);
            echo "Rotated and compressed: $logFile (" . formatFileSize($size) . ")\n";
        } else {
            echo "Rotated: $logFile (" . formatFileSize($size) . ")\n";
        }
    }
}

// Delete logs older than 30 days
$backups = glob($logDir . "*.bak*");
foreach ($backups as $backup) {
    if (filemtime($backup) < time() - 30 * 86400) {
        unlink($backup);
        echo "Deleted old backup: " . basename($backup) . "\n";
    }
}

echo "Log rotation completed.\n";