<?php
/**
 * Endpoint para limpiar archivos de log
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

try {
    $logDir = __DIR__ . '/logs';
    $clearedFiles = 0;
    
    if (is_dir($logDir)) {
        $iterator = new DirectoryIterator($logDir);
        
        foreach ($iterator as $file) {
            if ($file->isFile() && $file->getExtension() === 'log') {
                $filePath = $file->getPathname();
                
                // Crear backup antes de limpiar
                $backupPath = $filePath . '.backup.' . date('Y-m-d_H-i-s');
                copy($filePath, $backupPath);
                
                // Limpiar el archivo (no eliminarlo, solo vaciarlo)
                file_put_contents($filePath, '');
                $clearedFiles++;
            }
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => "Se limpiaron $clearedFiles archivos de log",
        'cleared_files' => $clearedFiles
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error limpiando logs: ' . $e->getMessage()
    ]);
}
?>