# Fix 2: save-config.php — use dm_set_global_secret (encrypted DB) instead of plain config.php
# Keep config.php write as fallback, but ALSO save to dm_settings encrypted

with open("public_html/supercerebro/api/save-config.php", "r") as f:
    content = f.read()

old_header = """<?php
header('Content-Type: application/json');
require_once dirname(__DIR__) . '/auth.php';
dm_require_admin();
dm_csrf_verify();"""

new_header = """<?php
header('Content-Type: application/json');
require_once dirname(__DIR__) . '/auth.php';
require_once dirname(__DIR__) . '/credentials.php';
dm_require_admin();
dm_csrf_verify();"""

if old_header in content:
    content = content.replace(old_header, new_header, 1)
    print("OK: credentials.php added to save-config.php")
else:
    print("ERROR: header anchor not found")

# Replace the file_put_contents block with encrypted DB save + config.php fallback
old_write = """// Generar archivo config.php
$php = "<?php\\n// DIMARK Brain - Configuración de APIs\\n// Generado automáticamente - NO subir a repositorios públicos\\n\\n";
foreach($existing as $key => $val) {
    $safe = addslashes($val);
    $php .= "define('{$key}', '{$safe}');\\n";
}
$php .= "\\n// Fin de configuración\\n";

$written = file_put_contents($config_file, $php);
if($written === false) {
    echo json_encode(['ok' => false, 'error' => 'No se pudo escribir config.php. Verifica permisos del directorio.']);
    exit;
}

echo json_encode(['ok' => true, 'message' => 'Configuración guardada.']);"""

new_write = """// 1. Guardar en BD cifrada (dm_settings) — método preferido
$saved_to_db = 0;
foreach($existing as $key => $val) {
    if (!empty($val) && dm_set_global_secret($key, $val)) $saved_to_db++;
}

// 2. También regenerar config.php como fallback (mantiene compatibilidad)
// Leer todos los secrets guardados para reconstruir el archivo completo
$php = "<?php\\n// DIMARK Brain - Configuración de APIs\\n// Generado automáticamente\\n\\n";
foreach($existing as $key => $val) {
    $safe = addslashes($val);
    $php .= "define('{$key}', '{$safe}');\\n";
}
$php .= "\\n// Fin de configuración\\n";
file_put_contents($config_file, $php);

echo json_encode(['ok' => true, 'message' => 'Configuración guardada.', 'db_saved' => $saved_to_db]);"""

if old_write in content:
    content = content.replace(old_write, new_write, 1)
    with open("public_html/supercerebro/api/save-config.php", "w") as f:
        f.write(content)
    print("OK: save-config.php now saves to encrypted DB + config.php fallback")
else:
    print("ERROR: write block not found")
    idx = content.find("// Generar archivo config.php")
    print("anchor idx:", idx)
