#!/usr/bin/env bash
# Atualiza SOMENTE o texto do shortcode no widget Elementor (não apaga o restante da página).
# Uso no VPS: bash scripts/wp-shortcode-embed-planos.sh [post_id]
set -euo pipefail

WP="${WP_ROOT:-/home/nolapiscom/public_html/wp}"
POST_ID="${1:-221}"
SHORTCODE='[nolapis_planos]'

cd "$WP"

echo "==> Post $POST_ID — verificar Elementor"
php /usr/local/bin/wp --allow-root post meta get "$POST_ID" _elementor_data --format=json 2>/dev/null | head -c 200 || true
echo ""

LEN=$(php /usr/local/bin/wp --allow-root post meta get "$POST_ID" _elementor_data 2>/dev/null | wc -c)
if [ "${LEN:-0}" -lt 500 ]; then
  echo ""
  echo "AVISO: _elementor_data muito pequeno — a página pode ter sido substituída só pelo shortcode."
  echo "Restaure no WordPress: Elementor → editar página Planos → ícone Histórico (revisões) → versão anterior."
  echo "Depois de restaurar, rode este script de novo."
  exit 1
fi

echo "==> Substituir shortcode no JSON Elementor (sem apagar outros widgets)"
php /usr/local/bin/wp --allow-root eval "
\$id = (int) '$POST_ID';
\$raw = get_post_meta(\$id, '_elementor_data', true);
if (! is_string(\$raw) || \$raw === '') {
    echo \"Sem _elementor_data\\n\";
    exit(1);
}
\$needle = '[nolapis_planos';
if (! str_contains(\$raw, \$needle)) {
    echo \"Nenhum shortcode nolapis_planos encontrado. Adicione um widget Shortcode no Elementor com: $SHORTCODE\\n\";
    exit(1);
}
\$updated = preg_replace(
    '/\[nolapis_planos[^\]]*\]/',
    '$SHORTCODE',
    \$raw
);
if (\$updated === \$raw) {
    echo \"Shortcode já está em modo embed.\\n\";
} else {
    update_post_meta(\$id, '_elementor_data', wp_slash(\$updated));
    echo \"Shortcode atualizado para: $SHORTCODE\\n\";
}
delete_post_meta(\$id, '_elementor_css');
"

php /usr/local/bin/wp --allow-root transient delete --all 2>/dev/null || true
php /usr/local/bin/wp --allow-root elementor flush-css 2>/dev/null || true

echo "Pronto. Confira https://nolapis.com.br/wp/planos/"
