<?php
/**
 * 💾 GUARDADOR DE CONFIGURACIÓN WHATSAPP
 * Herramienta para guardar configuración en la base de datos
 */

// Headers para mostrar errores
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<!DOCTYPE html><html><head><meta charset='UTF-8'>";
echo "<title>💾 Guardar Configuración WhatsApp</title>";
echo "<style>body{font-family:monospace;margin:20px;background:#000;color:#00ff00}";
echo ".ok{color:#00ff00}.error{color:#ff0040}.warning{color:#ffaa00}";
echo ".section{background:#111;padding:15px;margin:10px 0;border:1px solid #333}";
echo "input[type=text]{width:100%;padding:10px;background:#222;color:#fff;border:1px solid #555;margin:5px 0}";
echo "button{padding:10px 20px;background:#333;color:#fff;border:1px solid #555;cursor:pointer}";
echo "button:hover{background:#555}";
echo ".form-group{margin:15px 0}";
echo "</style></head><body>";

echo "<h1>💾 GUARDADOR DE CONFIGURACIÓN WHATSAPP</h1>";

// Cargar configuración
try {
    require_once 'config/config.php';
} catch (Exception $e) {
    echo "<div class='error'>❌ Error cargando configuración: " . htmlspecialchars($e->getMessage()) . "</div>";
    exit;
}

// Procesar formulario
if ($_POST) {
    echo "<div class='section'>";
    echo "<h2>💾 GUARDANDO EN BASE DE DATOS...</h2>";
    
    $config_updates = [
        'whatsapp_token' => trim($_POST['whatsapp_token'] ?? ''),
        'whatsapp_phone_number_id' => trim($_POST['phone_id'] ?? ''),
        'webhook_verify_token' => trim($_POST['webhook_token'] ?? ''),
        'whatsapp_api_url' => trim($_POST['api_url'] ?? 'https://graph.facebook.com/v22.0/')
    ];
    
    try {
        $pdo = new PDO(
            "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            ]
        );
        
        $updated = 0;
        $inserted = 0;
        
        foreach ($config_updates as $key => $value) {
            if (empty($value)) continue;
            
            // Verificar si ya existe
            $stmt = $pdo->prepare("SELECT id FROM system_config WHERE config_key = ?");
            $stmt->execute([$key]);
            
            if ($stmt->rowCount() > 0) {
                // Actualizar existente
                $stmt = $pdo->prepare("UPDATE system_config SET config_value = ?, updated_at = NOW() WHERE config_key = ?");
                $stmt->execute([$value, $key]);
                $updated++;
                echo "<div class='ok'>✅ Actualizado: $key</div>";
            } else {
                // Insertar nuevo
                $descriptions = [
                    'whatsapp_token' => 'Token de acceso de WhatsApp Business API',
                    'whatsapp_phone_number_id' => 'ID del número de teléfono de WhatsApp',
                    'webhook_verify_token' => 'Token de verificación para webhook',
                    'whatsapp_api_url' => 'URL base de la API de WhatsApp'
                ];
                
                $stmt = $pdo->prepare("INSERT INTO system_config (config_key, config_value, description) VALUES (?, ?, ?)");
                $stmt->execute([$key, $value, $descriptions[$key] ?? 'Configuración de WhatsApp']);
                $inserted++;
                echo "<div class='ok'>✅ Insertado: $key</div>";
            }
        }
        
        echo "<div class='ok'>📊 Total actualizados: $updated</div>";
        echo "<div class='ok'>📊 Total insertados: $inserted</div>";
        
        // Verificar que se guardó correctamente
        echo "<br><div class='warning'>🔄 Verificando configuración guardada...</div>";
        
        foreach ($config_updates as $key => $value) {
            if (empty($value)) continue;
            
            $stmt = $pdo->prepare("SELECT config_value FROM system_config WHERE config_key = ?");
            $stmt->execute([$key]);
            $row = $stmt->fetch();
            
            if ($row && $row['config_value'] === $value) {
                echo "<div class='ok'>✅ $key guardado correctamente</div>";
            } else {
                echo "<div class='error'>❌ $key NO se guardó correctamente</div>";
            }
        }
        
    } catch (PDOException $e) {
        echo "<div class='error'>❌ Error de base de datos: " . htmlspecialchars($e->getMessage()) . "</div>";
    }
    
    echo "</div>";
}

// Mostrar configuración actual
echo "<div class='section'>";
echo "<h2>⚙️ CONFIGURACIÓN ACTUAL</h2>";

try {
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
        DB_USER,
        DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
    
    $stmt = $pdo->query("SELECT config_key, config_value FROM system_config WHERE config_key IN ('whatsapp_token', 'whatsapp_phone_number_id', 'webhook_verify_token', 'whatsapp_api_url')");
    $current_config = [];
    while ($row = $stmt->fetch()) {
        $current_config[$row['config_key']] = $row['config_value'];
    }
    
    // Mostrar configuración
    $configs_to_show = [
        'whatsapp_token' => 'Token de WhatsApp',
        'whatsapp_phone_number_id' => 'Phone Number ID',
        'webhook_verify_token' => 'Webhook Verify Token',
        'whatsapp_api_url' => 'API URL'
    ];
    
    foreach ($configs_to_show as $key => $label) {
        if (isset($current_config[$key])) {
            $value = $current_config[$key];
            if (in_array($key, ['whatsapp_token', 'webhook_verify_token'])) {
                $display = substr($value, 0, 10) . '...' . substr($value, -10) . " (" . strlen($value) . " chars)";
            } else {
                $display = $value;
            }
            echo "<div class='ok'>✅ $label: $display</div>";
        } else {
            echo "<div class='error'>❌ $label: No configurado en BD</div>";
        }
    }
    
} catch (PDOException $e) {
    echo "<div class='error'>❌ Error consultando BD: " . htmlspecialchars($e->getMessage()) . "</div>";
}

echo "</div>";

// Formulario
echo "<div class='section'>";
echo "<h2>📝 ACTUALIZAR CONFIGURACIÓN</h2>";

echo "<form method='POST'>";

echo "<div class='form-group'>";
echo "<label style='color:#ffaa00'><strong>🔑 Token de WhatsApp Business API:</strong></label>";
echo "<input type='text' name='whatsapp_token' placeholder='EAAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'>";
echo "<div class='warning'>• Se guardará en la base de datos</div>";
echo "</div>";

echo "<div class='form-group'>";
echo "<label style='color:#ffaa00'><strong>📱 Phone Number ID:</strong></label>";
echo "<input type='text' name='phone_id' placeholder='1234567890123456'>";
echo "<div class='warning'>• ID numérico del teléfono</div>";
echo "</div>";

echo "<div class='form-group'>";
echo "<label style='color:#ffaa00'><strong>🔐 Webhook Verify Token:</strong></label>";
echo "<input type='text' name='webhook_token' placeholder='mi_token_secreto_123'>";
echo "<div class='warning'>• Token para verificar webhook</div>";
echo "</div>";

echo "<div class='form-group'>";
echo "<label style='color:#ffaa00'><strong>🌐 API URL:</strong></label>";
echo "<input type='text' name='api_url' value='https://graph.facebook.com/v22.0/' placeholder='https://graph.facebook.com/v22.0/'>";
echo "<div class='warning'>• URL base de la API de WhatsApp</div>";
echo "</div>";

echo "<div class='form-group'>";
echo "<button type='submit'>💾 Guardar en Base de Datos</button>";
echo "</div>";

echo "</form>";
echo "</div>";

// Test de las constantes actuales
echo "<div class='section'>";
echo "<h2>🔍 VALORES ACTUALES DE LAS CONSTANTES</h2>";

$constants_to_check = [
    'WHATSAPP_TOKEN' => 'Token actual en memoria',
    'WHATSAPP_PHONE_NUMBER_ID' => 'Phone ID actual en memoria',
    'WEBHOOK_VERIFY_TOKEN' => 'Webhook token actual en memoria',
    'WHATSAPP_API_URL' => 'API URL actual en memoria'
];

foreach ($constants_to_check as $const => $desc) {
    if (defined($const)) {
        $value = constant($const);
        if (in_array($const, ['WHATSAPP_TOKEN', 'WEBHOOK_VERIFY_TOKEN'])) {
            if (strlen($value) > 20) {
                $display = substr($value, 0, 10) . '...' . substr($value, -10);
            } else {
                $display = $value;
            }
        } else {
            $display = $value;
        }
        echo "<div class='ok'>✅ $desc: $display</div>";
    } else {
        echo "<div class='error'>❌ $desc: No definida</div>";
    }
}

echo "<div class='warning'><strong>NOTA:</strong> Después de guardar, recarga esta página para ver los nuevos valores</div>";

echo "</div>";

echo "</body></html>";
?>