<?php
/**
 * Eliminar plantillas que no funcionan de la base de datos
 */

require_once 'config/config.php';

header('Content-Type: text/plain; charset=utf-8');

try {
    $db = Database::getInstance();
    
    echo "=== ELIMINAR PLANTILLAS QUE NO FUNCIONAN ===\n\n";
    
    // Mostrar plantillas actuales
    echo "📋 Plantillas actuales en la BD:\n";
    $stmt = $db->query("SELECT id, template_name, language_code, status FROM message_templates ORDER BY template_name");
    $templates = $stmt->fetchAll();
    
    foreach ($templates as $template) {
        echo "• ID: {$template['id']} - {$template['template_name']} ({$template['language_code']}) - {$template['status']}\n";
    }
    
    echo "\n🗑️ Eliminando plantillas que no funcionan...\n";
    
    // Eliminar plantillas que no funcionan
    $templatesToDelete = [
        'welcome_user',
        'jaspers_market_plain_text_v1'
    ];
    
    foreach ($templatesToDelete as $templateName) {
        $stmt = $db->query(
            "DELETE FROM message_templates WHERE template_name = ?",
            [$templateName]
        );
        
        $affectedRows = $stmt->rowCount();
        echo "• Eliminada '{$templateName}': {$affectedRows} registro(s) afectado(s)\n";
    }
    
    echo "\n✅ Plantillas restantes en la BD:\n";
    $stmt = $db->query("SELECT id, template_name, language_code, status FROM message_templates ORDER BY template_name");
    $remainingTemplates = $stmt->fetchAll();
    
    if (empty($remainingTemplates)) {
        echo "❌ No hay plantillas restantes\n";
        echo "\n💡 Sugerencia: Agrega la plantilla 'hello_world' que funciona:\n";
        
        // Agregar plantilla hello_world que sabemos que funciona
        $db->query(
            "INSERT INTO message_templates (template_name, language_code, status, body_text, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())",
            ['hello_world', 'en_US', 'approved', 'Hello World! This is a test message.']
        );
        echo "✅ Agregada plantilla 'hello_world' (en_US) que funciona correctamente\n";
        
        // Mostrar plantillas finales
        $stmt = $db->query("SELECT id, template_name, language_code, status FROM message_templates ORDER BY template_name");
        $finalTemplates = $stmt->fetchAll();
        
        echo "\n📋 Plantillas finales:\n";
        foreach ($finalTemplates as $template) {
            echo "• ID: {$template['id']} - {$template['template_name']} ({$template['language_code']}) - {$template['status']}\n";
        }
    } else {
        foreach ($remainingTemplates as $template) {
            echo "• ID: {$template['id']} - {$template['template_name']} ({$template['language_code']}) - {$template['status']}\n";
        }
    }
    
    echo "\n🎉 Limpieza completada exitosamente\n";
    
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}
?>