<?php
/**
 * API - Limpiar logs del sistema
 * Fecha: 13 de enero de 2026
 */

require_once '../config/config.php';

// Verificar autenticación
requireAuthentication();

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, DELETE');
header('Access-Control-Allow-Headers: Content-Type');

// Solo permitir POST o DELETE
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && $_SERVER['REQUEST_METHOD'] !== 'DELETE') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Método no permitido']);
    exit;
}

try {
    $db = Database::getInstance();
    
    // Obtener tipo de logs a limpiar (opcional)
    $input = json_decode(file_get_contents('php://input'), true);
    $type = $input['type'] ?? 'all'; // 'all', 'webhook', 'system'
    
    $deletedCount = 0;
    $tablesCleared = [];
    
    // Verificar qué tablas existen
    $existingTables = $db->fetchAll("SHOW TABLES");
    $tableNames = array_column($existingTables, 'Tables_in_' . DB_NAME);
    
    switch ($type) {
        case 'webhook':
            if (in_array('webhook_logs', $tableNames)) {
                $result = $db->execute("DELETE FROM webhook_logs");
                $deletedCount += $db->fetchAll("SELECT ROW_COUNT() as count")[0]['count'] ?? 0;
                $tablesCleared[] = 'webhook_logs';
            }
            break;
            
        case 'system':
            if (in_array('system_logs', $tableNames)) {
                $result = $db->execute("DELETE FROM system_logs");
                $deletedCount += $db->fetchAll("SELECT ROW_COUNT() as count")[0]['count'] ?? 0;
                $tablesCleared[] = 'system_logs';
            }
            if (in_array('application_logs', $tableNames)) {
                $result = $db->execute("DELETE FROM application_logs");
                $deletedCount += $db->fetchAll("SELECT ROW_COUNT() as count")[0]['count'] ?? 0;
                $tablesCleared[] = 'application_logs';
            }
            break;
            
        case 'all':
        default:
            // Limpiar todas las tablas de logs
            if (in_array('webhook_logs', $tableNames)) {
                $countBefore = $db->fetch("SELECT COUNT(*) as count FROM webhook_logs")['count'] ?? 0;
                $db->execute("DELETE FROM webhook_logs");
                $deletedCount += $countBefore;
                $tablesCleared[] = 'webhook_logs';
            }
            
            if (in_array('system_logs', $tableNames)) {
                $countBefore = $db->fetch("SELECT COUNT(*) as count FROM system_logs")['count'] ?? 0;
                $db->execute("DELETE FROM system_logs");
                $deletedCount += $countBefore;
                $tablesCleared[] = 'system_logs';
            }
            
            if (in_array('application_logs', $tableNames)) {
                $countBefore = $db->fetch("SELECT COUNT(*) as count FROM application_logs")['count'] ?? 0;
                $db->execute("DELETE FROM application_logs");
                $deletedCount += $countBefore;
                $tablesCleared[] = 'application_logs';
            }
            break;
    }
    
    // Registrar acción
    $user = $_SESSION['user'] ?? null;
    $userId = $user['id'] ?? null;
    $username = $user['username'] ?? 'sistema';
    
    error_log("Logs limpiados por usuario: {$username}. Tipo: {$type}. Registros eliminados: {$deletedCount}");
    
    echo json_encode([
        'success' => true,
        'message' => 'Logs limpiados correctamente',
        'deleted_count' => $deletedCount,
        'tables_cleared' => $tablesCleared,
        'type' => $type
    ]);
    
} catch (Exception $e) {
    error_log("Error en clear_logs.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
        'debug' => DEBUG_MODE ? $e->getTraceAsString() : null
    ]);
}
?>
